diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/tests/experimental/test_utils.py b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/experimental/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b498d19eb05ab00ce809d0c3cb04384a2ab697f9 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/experimental/test_utils.py @@ -0,0 +1,160 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +from datasets import Dataset, load_dataset +from transformers import AutoTokenizer + +from trl.experimental.utils import DataCollatorForChatML, truncate_dataset + +from ..testing_utils import TrlTestCase + + +class TestDataCollatorForChatML(TrlTestCase): + def setup_method(self): + # Initialize the tokenizer + self.tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5") + if self.tokenizer.pad_token is None: + self.tokenizer.pad_token = self.tokenizer.eos_token + + # Define token IDs + self.bos_token_id = self.tokenizer.bos_token_id if self.tokenizer.bos_token_id is not None else 1 + self.eos_token_id = self.tokenizer.eos_token_id if self.tokenizer.eos_token_id is not None else 2 + # Token ID for "true", the last assistant's response in the example: + self.ignore_index = -100 + self.max_length = 1024 + self.messages_key = "messages" + + # Example input + dataset = load_dataset("trl-internal-testing/zen", "conversational_language_modeling", split="train") + self.examples = dataset.to_list() + + # Initialize the data collator + self.collator = DataCollatorForChatML( + tokenizer=self.tokenizer, + max_length=self.max_length, + ignore_index=self.ignore_index, + ) + + def test_data_collator_for_chatml(self): + # Process the data + data = self.collator(self.examples) + + # Verify basic shapes and types + assert "input_ids" in data + assert "attention_mask" in data + assert "labels" in data + assert "prompts" in data + assert "prompt_attention_mask" in data + + # Decode input_ids and labels for verification + input_ids = data["input_ids"][0].tolist() + labels = data["labels"][0].tolist() + prompt_only = data["prompts"][0].tolist() + + # Get the last assistant's response for comparison + last_message = self.examples[0][self.messages_key][-1] + assert last_message["role"] == "assistant", "Last message should be from assistant" + last_assistant_response = last_message["content"] + + # Verify that input_ids contain both prompt and response + decoded_input = self.tokenizer.decode(input_ids) + assert last_assistant_response in decoded_input, "Input should contain assistant's response" + + # Verify that prompts only contain the conversation up to the last response + decoded_prompt = self.tokenizer.decode(prompt_only) + assert last_assistant_response not in decoded_prompt, "Prompt should not contain assistant's response" + + # Verify labels are -100 for non-assistant parts + prompt_length = len(prompt_only) + assert all(label == self.ignore_index for label in labels[:prompt_length]), ( + "Labels should be ignore_index for prompt tokens" + ) + + # Verify labels match assistant response after prompt + # Add a filter to remove any trailing tokens after the first <|im_end|> + last_assistant_response_with_end = last_assistant_response + self.tokenizer.eos_token + last_assistant_response_tokens = self.tokenizer.encode( + last_assistant_response_with_end, add_special_tokens=False + ) + + response_labels = [] + for label in labels[prompt_length:]: + if label == self.ignore_index: + continue + response_labels.append(label) + if label == self.tokenizer.convert_tokens_to_ids("<|im_end|>"): + break + assert response_labels == last_assistant_response_tokens, "Labels should match assistant response tokens" + + # Verify there isn't a generation prompt at the end + generation_prompt = "<|im_start|>assistant" + assert not decoded_input.strip().endswith(generation_prompt), ( + f"Input should not end with generation prompt '{generation_prompt}'" + ) + + assert response_labels == last_assistant_response_tokens, "Labels should match assistant response tokens" + + +class TestTruncateExamples(TrlTestCase): + def test_with_dataset(self): + examples = { + "input_ids": [[1, 2, 3], [4, 5, 6, 7], [8]], + "attention_mask": [[0, 1, 1], [0, 0, 1, 1], [1]], + } + dataset = Dataset.from_dict(examples) + dataset = dataset.with_format("numpy", dtype="float32") + format = dataset.format + max_length = 2 + expected_output = { + "input_ids": [[1, 2], [4, 5], [8]], + "attention_mask": [[0, 1], [0, 0], [1]], + } + dataset = truncate_dataset(dataset, max_length) + assert dataset.to_dict() == expected_output + assert format == dataset.format + + def test_with_iterable_dataset(self): + examples = { + "input_ids": [[1, 2, 3], [4, 5, 6, 7], [8]], + "attention_mask": [[0, 1, 1], [0, 0, 1, 1], [1]], + } + dataset = Dataset.from_dict(examples).to_iterable_dataset() + dataset = dataset.with_format("numpy") + formatting = dataset._formatting + max_length = 2 + expected_output = { + "input_ids": [[1, 2], [4, 5], [8]], + "attention_mask": [[0, 1], [0, 0], [1]], + } + dataset = truncate_dataset(dataset, max_length) + num_examples = len(examples[next(iter(examples))]) + assert next(iter(dataset.with_format(None).batch(batch_size=num_examples))) == expected_output + assert formatting == dataset._formatting + + def test_with_extra_column(self): + examples = { + "input_ids": [[1, 2, 3], [4, 5, 6, 7], [8]], + "attention_mask": [[0, 1, 1], [0, 0, 1, 1], [1]], + "my_column": ["a", "b", "c"], + } + dataset = Dataset.from_dict(examples) + max_length = 2 + expected_output = { + "input_ids": [[1, 2], [4, 5], [8]], + "attention_mask": [[0, 1], [0, 0], [1]], + "my_column": ["a", "b", "c"], + } + dataset = truncate_dataset(dataset, max_length) + assert dataset.to_dict() == expected_output diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/tests/experimental/test_xpo_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/experimental/test_xpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..2c81e1f7c474c731899321b09405c0ee9c0e6954 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/experimental/test_xpo_trainer.py @@ -0,0 +1,143 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pytest +from datasets import load_dataset +from transformers import AutoModelForCausalLM, AutoModelForSequenceClassification, AutoTokenizer +from transformers.utils import is_peft_available + +from trl.experimental.xpo import XPOConfig, XPOTrainer + +from ..testing_utils import TrlTestCase, require_peft + + +if is_peft_available(): + from peft import LoraConfig, get_peft_model + + +@pytest.mark.low_priority +class TestXPOTrainer(TrlTestCase): + def setup_method(self): + self.model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" + self.model = AutoModelForCausalLM.from_pretrained(self.model_id, dtype="float32") + self.ref_model = AutoModelForCausalLM.from_pretrained(self.model_id) + self.reward_model = AutoModelForSequenceClassification.from_pretrained(self.model_id, num_labels=1) + self.tokenizer = AutoTokenizer.from_pretrained(self.model_id) + self.tokenizer.pad_token = self.tokenizer.eos_token + + @pytest.mark.parametrize("config_name", ["standard_prompt_only", "conversational_prompt_only"]) + def test_xpo_trainer_training(self, config_name): + training_args = XPOConfig( + output_dir=self.tmp_dir, + per_device_train_batch_size=2, + max_steps=3, + remove_unused_columns=False, + gradient_accumulation_steps=1, + learning_rate=9e-1, + report_to="none", + ) + dataset = load_dataset("trl-internal-testing/zen", config_name, split="train") + + trainer = XPOTrainer( + model=self.model, + ref_model=self.ref_model, + reward_funcs=self.reward_model, + args=training_args, + processing_class=self.tokenizer, + train_dataset=dataset, + ) + + trainer.train() + + assert "train_loss" in trainer.state.log_history[-1] + + @require_peft + def test_train_with_peft(self): + lora_config = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM") + training_args = XPOConfig( + output_dir=self.tmp_dir, + per_device_train_batch_size=2, + max_steps=3, + learning_rate=5.0e-7, + report_to="none", + ) + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + trainer = XPOTrainer( + model=self.model, + reward_funcs=self.reward_model, + args=training_args, + processing_class=self.tokenizer, + train_dataset=dataset, + peft_config=lora_config, + ) + + trainer.train() + + assert "train_loss" in trainer.state.log_history[-1] + + @require_peft + def test_train_with_peft_and_ref_model(self): + lora_config = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM") + training_args = XPOConfig( + output_dir=self.tmp_dir, + per_device_train_batch_size=2, + max_steps=3, + learning_rate=5.0e-7, + report_to="none", + ) + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + trainer = XPOTrainer( + model=self.model, + ref_model=self.ref_model, + reward_funcs=self.reward_model, + args=training_args, + processing_class=self.tokenizer, + train_dataset=dataset, + peft_config=lora_config, + ) + + trainer.train() + + assert "train_loss" in trainer.state.log_history[-1] + + @require_peft + def test_train_pre_pefted_model_implicit_ref(self): + lora_config = LoraConfig(r=8, lora_alpha=16, lora_dropout=0.1, bias="none", task_type="CAUSAL_LM") + peft_model_instance = get_peft_model(self.model, lora_config) + + training_args = XPOConfig( + output_dir=self.tmp_dir, + per_device_train_batch_size=1, + max_steps=2, + learning_rate=5.0e-7, + eval_strategy="no", + report_to="none", + remove_unused_columns=False, + ) + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + trainer = XPOTrainer( + model=peft_model_instance, + ref_model=None, + reward_funcs=self.reward_model, # Using reward_model to ensure _generate_completions is used as expected + args=training_args, + processing_class=self.tokenizer, + train_dataset=dataset, + ) + + trainer.train() + + assert "train_loss" in trainer.state.log_history[-1] diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/tests/invariant/README.md b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/invariant/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6bb9d5e7809b51db3d6d411515dcec6a193810bc --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/invariant/README.md @@ -0,0 +1,57 @@ +# Training invariant tests + +Catches silent training bugs that don't fail unit tests but shift the training trajectory. Runs on real models, opt-in only. + +## How it works + +Configs are grouped into **equivalence classes**: configs in the same class must produce the same trajectory (e.g. PDB=1×GAS=8 must equal PDB=8×GAS=1, FA2 must equal eager). Each class has one **canonical** config (the first one) that owns the class's reference snapshot. Every config in the class — canonical included — is asserted to match the saved reference. This catches both invariant breakage (a non-canonical config drifting away from the canonical's pinned trajectory) and numerical regressions (the canonical itself drifting from its committed snapshot across versions). + +Recording the references is a separate concern from testing them, so it's a separate entry point (`python tests/invariant/test_invariant.py`). + +Each config is a `trl ` CLI invocation with a fixed set of args. The harness shells out (`subprocess.run(["trl", method, ...])`), the CLI runs end to end, writes `trainer_state.json` to its `--output_dir`, and the harness parses the `log_history` into a `Trajectory`. + +This means the suite tests the actual user-facing entry point, not the Python API. Catches CLI-only bugs (arg parsing, defaults, dispatch) for free. Distributed runs are an additive change: prepend `accelerate launch --config_file .yaml` to the same command. + +## Scope (initial) + +- Trainers: `trl sft`, `trl dpo` +- Model: `Qwen/Qwen2.5-0.5B-Instruct` (pinned revision) +- Equivalence classes: + - `sft`: `sft_default` (canonical), `sft_pdb1_gas8` (gradient accumulation), `sft_attn_fa2_kernels` (FA2 via kernels) + - `dpo`: `dpo_default` (canonical), `dpo_pdb1_gas8` (gradient accumulation) +- Single GPU, fp32, fixed seed, ~50 optimizer steps. + +Other axes (sharding, DDP, more trainers) are deferred and will be additive. + +## Trajectory + +Per optimizer step: `loss`, `grad_norm`. One JSON per equivalence class in `references/` (`sft.json`, `dpo.json`): + +```json +{ + "config": {"name": "sft_default", "method": "sft", "args": {...}}, + "env": {"accelerate": "...", "torch": "...", "transformers": "...", "trl": "...", "gpu": "H100-80GB"}, + "steps": [{"step": 1, "loss": 1.234, "grad_norm": 0.567}, ...] +} +``` + +## Comparison + +Scalar series with absolute tolerance + zero-mean-residual. The residual check is what flags bugs like GAS-dropping — they show up as a one-sided systematic shift in the loss curve, not as point-wise outliers. + +## Hardware + +Reference snapshots are recorded on **H100 80GB** (pinned in `references/env.lock`). + +## Running + +```bash +# test +pytest tests/invariant/ -m invariant + +# record references +python tests/invariant/test_invariant.py # all classes +python tests/invariant/test_invariant.py sft # one class +``` + +Snapshot updates must be justified in the PR description. diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/tests/invariant/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/invariant/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3d26f4482fe3969b6de2b51bd1f85fc16dad6a65 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/invariant/__init__.py @@ -0,0 +1,14 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/tests/invariant/references/dpo.json b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/invariant/references/dpo.json new file mode 100644 index 0000000000000000000000000000000000000000..b13ed4133bc29f799b936d06624e52c73ddad6cb --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/invariant/references/dpo.json @@ -0,0 +1,280 @@ +{ + "config": { + "name": "dpo_default", + "method": "dpo", + "args": { + "model_name_or_path": "Qwen/Qwen2.5-0.5B-Instruct", + "model_revision": "7ae557604adf67be50417f59c2c2f167def9a775", + "attn_implementation": "eager", + "dataset_name": "trl-lib/ultrafeedback_binarized", + "max_steps": "50", + "max_length": "512", + "logging_steps": "1", + "report_to": "none", + "seed": "42", + "data_seed": "42", + "full_determinism": "True", + "bf16": "False" + } + }, + "env": { + "accelerate": "1.13.0", + "torch": "2.10.0+cu128", + "transformers": "5.10.0.dev0", + "trl": "f4e94c0c10654ab57b94e7cd8096ed4f12246e03", + "python": "3.13.13", + "gpu": "NVIDIA H100 80GB HBM3" + }, + "steps": [ + { + "step": 1, + "loss": 0.6931471824645996, + "grad_norm": 157.25071716308594 + }, + { + "step": 2, + "loss": 0.6901174783706665, + "grad_norm": 108.38384246826172 + }, + { + "step": 3, + "loss": 0.6326549053192139, + "grad_norm": 140.2856903076172 + }, + { + "step": 4, + "loss": 0.7054474353790283, + "grad_norm": 151.10508728027344 + }, + { + "step": 5, + "loss": 0.7342866063117981, + "grad_norm": 157.84791564941406 + }, + { + "step": 6, + "loss": 0.6869831085205078, + "grad_norm": 137.7687530517578 + }, + { + "step": 7, + "loss": 0.7037957906723022, + "grad_norm": 130.58058166503906 + }, + { + "step": 8, + "loss": 0.671793520450592, + "grad_norm": 164.77792358398438 + }, + { + "step": 9, + "loss": 0.6760100722312927, + "grad_norm": 102.67815399169922 + }, + { + "step": 10, + "loss": 0.6628016233444214, + "grad_norm": 123.41923522949219 + }, + { + "step": 11, + "loss": 0.6634430885314941, + "grad_norm": 83.91616821289062 + }, + { + "step": 12, + "loss": 0.7321300506591797, + "grad_norm": 161.53366088867188 + }, + { + "step": 13, + "loss": 0.7024844884872437, + "grad_norm": 150.16744995117188 + }, + { + "step": 14, + "loss": 0.6837225556373596, + "grad_norm": 123.26526641845703 + }, + { + "step": 15, + "loss": 0.7167133092880249, + "grad_norm": 133.57534790039062 + }, + { + "step": 16, + "loss": 0.6835181713104248, + "grad_norm": 124.6922378540039 + }, + { + "step": 17, + "loss": 0.6272522211074829, + "grad_norm": 100.10560607910156 + }, + { + "step": 18, + "loss": 0.8025375604629517, + "grad_norm": 198.8187713623047 + }, + { + "step": 19, + "loss": 0.7497490048408508, + "grad_norm": 136.41639709472656 + }, + { + "step": 20, + "loss": 0.7327032089233398, + "grad_norm": 135.1873016357422 + }, + { + "step": 21, + "loss": 0.8468657732009888, + "grad_norm": 183.79238891601562 + }, + { + "step": 22, + "loss": 0.6504813432693481, + "grad_norm": 119.43262481689453 + }, + { + "step": 23, + "loss": 0.8200190663337708, + "grad_norm": 221.7334747314453 + }, + { + "step": 24, + "loss": 0.6116989850997925, + "grad_norm": 134.1520233154297 + }, + { + "step": 25, + "loss": 0.715190052986145, + "grad_norm": 160.9645538330078 + }, + { + "step": 26, + "loss": 0.78664231300354, + "grad_norm": 173.35397338867188 + }, + { + "step": 27, + "loss": 0.627922534942627, + "grad_norm": 118.79180145263672 + }, + { + "step": 28, + "loss": 0.6171221733093262, + "grad_norm": 143.510986328125 + }, + { + "step": 29, + "loss": 0.7258801460266113, + "grad_norm": 166.77137756347656 + }, + { + "step": 30, + "loss": 0.6643164157867432, + "grad_norm": 109.94638061523438 + }, + { + "step": 31, + "loss": 0.8424814343452454, + "grad_norm": 155.43392944335938 + }, + { + "step": 32, + "loss": 0.6372821927070618, + "grad_norm": 165.25477600097656 + }, + { + "step": 33, + "loss": 0.6878336668014526, + "grad_norm": 132.20591735839844 + }, + { + "step": 34, + "loss": 0.7095304131507874, + "grad_norm": 168.26194763183594 + }, + { + "step": 35, + "loss": 0.6994724273681641, + "grad_norm": 126.31066131591797 + }, + { + "step": 36, + "loss": 0.6479494571685791, + "grad_norm": 162.87469482421875 + }, + { + "step": 37, + "loss": 0.7106008529663086, + "grad_norm": 142.19422912597656 + }, + { + "step": 38, + "loss": 0.6147706508636475, + "grad_norm": 124.1236343383789 + }, + { + "step": 39, + "loss": 0.6274570226669312, + "grad_norm": 97.5869369506836 + }, + { + "step": 40, + "loss": 0.5677652359008789, + "grad_norm": 99.20594787597656 + }, + { + "step": 41, + "loss": 0.5417441129684448, + "grad_norm": 136.53424072265625 + }, + { + "step": 42, + "loss": 0.6146669983863831, + "grad_norm": 117.05335998535156 + }, + { + "step": 43, + "loss": 0.5652309656143188, + "grad_norm": 141.68212890625 + }, + { + "step": 44, + "loss": 0.6843374967575073, + "grad_norm": 123.86646270751953 + }, + { + "step": 45, + "loss": 0.700664758682251, + "grad_norm": 176.58290100097656 + }, + { + "step": 46, + "loss": 0.627228856086731, + "grad_norm": 93.38623046875 + }, + { + "step": 47, + "loss": 0.6068558096885681, + "grad_norm": 144.66879272460938 + }, + { + "step": 48, + "loss": 0.7041699886322021, + "grad_norm": 147.3819122314453 + }, + { + "step": 49, + "loss": 0.6936260461807251, + "grad_norm": 114.99978637695312 + }, + { + "step": 50, + "loss": 0.8024596571922302, + "grad_norm": 156.8375244140625 + } + ] +} \ No newline at end of file diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/tests/invariant/references/sft.json b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/invariant/references/sft.json new file mode 100644 index 0000000000000000000000000000000000000000..f0d292b6d878793470222cebc553eb1a39cb7672 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/invariant/references/sft.json @@ -0,0 +1,280 @@ +{ + "config": { + "name": "sft_default", + "method": "sft", + "args": { + "model_name_or_path": "Qwen/Qwen2.5-0.5B-Instruct", + "model_revision": "7ae557604adf67be50417f59c2c2f167def9a775", + "attn_implementation": "eager", + "dataset_name": "trl-lib/Capybara", + "max_steps": "50", + "max_length": "512", + "logging_steps": "1", + "report_to": "none", + "seed": "42", + "data_seed": "42", + "full_determinism": "True", + "bf16": "False" + } + }, + "env": { + "accelerate": "1.13.0", + "torch": "2.10.0+cu128", + "transformers": "5.10.0.dev0", + "trl": "f4e94c0c10654ab57b94e7cd8096ed4f12246e03", + "python": "3.13.13", + "gpu": "NVIDIA H100 80GB HBM3" + }, + "steps": [ + { + "step": 1, + "loss": 2.3842217922210693, + "grad_norm": 28.170888900756836 + }, + { + "step": 2, + "loss": 1.4120551347732544, + "grad_norm": 16.11708641052246 + }, + { + "step": 3, + "loss": 1.6543627977371216, + "grad_norm": 9.521869659423828 + }, + { + "step": 4, + "loss": 1.548227071762085, + "grad_norm": 9.530509948730469 + }, + { + "step": 5, + "loss": 1.3084965944290161, + "grad_norm": 13.43132209777832 + }, + { + "step": 6, + "loss": 1.4568636417388916, + "grad_norm": 11.567093849182129 + }, + { + "step": 7, + "loss": 1.6642777919769287, + "grad_norm": 8.233135223388672 + }, + { + "step": 8, + "loss": 1.6268576383590698, + "grad_norm": 6.363206386566162 + }, + { + "step": 9, + "loss": 1.5339726209640503, + "grad_norm": 6.955142974853516 + }, + { + "step": 10, + "loss": 1.547467827796936, + "grad_norm": 5.978666305541992 + }, + { + "step": 11, + "loss": 1.7950178384780884, + "grad_norm": 7.241233825683594 + }, + { + "step": 12, + "loss": 1.8137775659561157, + "grad_norm": 8.63271713256836 + }, + { + "step": 13, + "loss": 1.3856267929077148, + "grad_norm": 6.400929927825928 + }, + { + "step": 14, + "loss": 1.3795125484466553, + "grad_norm": 6.382791996002197 + }, + { + "step": 15, + "loss": 1.3708516359329224, + "grad_norm": 6.692564010620117 + }, + { + "step": 16, + "loss": 1.8075040578842163, + "grad_norm": 7.801014423370361 + }, + { + "step": 17, + "loss": 1.254800796508789, + "grad_norm": 5.860067367553711 + }, + { + "step": 18, + "loss": 1.6014561653137207, + "grad_norm": 7.397754669189453 + }, + { + "step": 19, + "loss": 1.5693073272705078, + "grad_norm": 6.078225612640381 + }, + { + "step": 20, + "loss": 1.2925223112106323, + "grad_norm": 6.285624027252197 + }, + { + "step": 21, + "loss": 1.261284589767456, + "grad_norm": 5.98115348815918 + }, + { + "step": 22, + "loss": 1.016650676727295, + "grad_norm": 6.040045261383057 + }, + { + "step": 23, + "loss": 1.222269058227539, + "grad_norm": 6.034141540527344 + }, + { + "step": 24, + "loss": 1.45418381690979, + "grad_norm": 6.263362407684326 + }, + { + "step": 25, + "loss": 1.23504638671875, + "grad_norm": 5.99455451965332 + }, + { + "step": 26, + "loss": 1.2722694873809814, + "grad_norm": 5.834524631500244 + }, + { + "step": 27, + "loss": 2.2606589794158936, + "grad_norm": 7.2228522300720215 + }, + { + "step": 28, + "loss": 1.4542038440704346, + "grad_norm": 6.190547466278076 + }, + { + "step": 29, + "loss": 1.3753437995910645, + "grad_norm": 5.7064290046691895 + }, + { + "step": 30, + "loss": 1.0842117071151733, + "grad_norm": 6.300862789154053 + }, + { + "step": 31, + "loss": 1.6317358016967773, + "grad_norm": 6.022386074066162 + }, + { + "step": 32, + "loss": 1.4107545614242554, + "grad_norm": 6.697302341461182 + }, + { + "step": 33, + "loss": 1.5427740812301636, + "grad_norm": 6.703666687011719 + }, + { + "step": 34, + "loss": 1.0882741212844849, + "grad_norm": 6.260556697845459 + }, + { + "step": 35, + "loss": 2.1459619998931885, + "grad_norm": 6.938933849334717 + }, + { + "step": 36, + "loss": 1.7524574995040894, + "grad_norm": 6.392754554748535 + }, + { + "step": 37, + "loss": 1.558825135231018, + "grad_norm": 7.106125831604004 + }, + { + "step": 38, + "loss": 1.5750346183776855, + "grad_norm": 6.705704689025879 + }, + { + "step": 39, + "loss": 1.0681045055389404, + "grad_norm": 5.93332576751709 + }, + { + "step": 40, + "loss": 1.4508510828018188, + "grad_norm": 6.193344593048096 + }, + { + "step": 41, + "loss": 1.5779269933700562, + "grad_norm": 6.469877243041992 + }, + { + "step": 42, + "loss": 1.2731173038482666, + "grad_norm": 6.590377330780029 + }, + { + "step": 43, + "loss": 1.34458327293396, + "grad_norm": 5.618240833282471 + }, + { + "step": 44, + "loss": 1.5110447406768799, + "grad_norm": 5.829492092132568 + }, + { + "step": 45, + "loss": 1.9833546876907349, + "grad_norm": 6.42317533493042 + }, + { + "step": 46, + "loss": 2.0645744800567627, + "grad_norm": 7.079426288604736 + }, + { + "step": 47, + "loss": 1.0404279232025146, + "grad_norm": 5.035366535186768 + }, + { + "step": 48, + "loss": 1.3794283866882324, + "grad_norm": 5.685641288757324 + }, + { + "step": 49, + "loss": 1.4115599393844604, + "grad_norm": 6.172175407409668 + }, + { + "step": 50, + "loss": 1.3042362928390503, + "grad_norm": 5.568996906280518 + } + ] +} \ No newline at end of file diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/tests/invariant/references/sft_fa2.json b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/invariant/references/sft_fa2.json new file mode 100644 index 0000000000000000000000000000000000000000..ef554a958e2cbdc5d02c5e3775e7a8d8b24f3b4e --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/invariant/references/sft_fa2.json @@ -0,0 +1,281 @@ +{ + "config": { + "name": "sft_fa2", + "method": "sft", + "args": { + "model_name_or_path": "Qwen/Qwen2.5-0.5B-Instruct", + "model_revision": "7ae557604adf67be50417f59c2c2f167def9a775", + "attn_implementation": "kernels-community/flash-attn2", + "dataset_name": "trl-lib/Capybara", + "max_steps": "50", + "max_length": "None", + "logging_steps": "1", + "report_to": "none", + "seed": "42", + "data_seed": "42", + "full_determinism": "True", + "bf16": "True", + "per_device_train_batch_size": "2" + } + }, + "env": { + "accelerate": "1.13.0", + "torch": "2.10.0+cu128", + "transformers": "5.10.0.dev0", + "trl": "f4e94c0c10654ab57b94e7cd8096ed4f12246e03", + "python": "3.13.13", + "gpu": "NVIDIA H100 80GB HBM3" + }, + "steps": [ + { + "step": 1, + "loss": 2.0777087211608887, + "grad_norm": 23.311853408813477 + }, + { + "step": 2, + "loss": 1.5351684093475342, + "grad_norm": 18.663341522216797 + }, + { + "step": 3, + "loss": 1.3684718608856201, + "grad_norm": 15.328994750976562 + }, + { + "step": 4, + "loss": 2.432941198348999, + "grad_norm": 10.522828102111816 + }, + { + "step": 5, + "loss": 1.482237458229065, + "grad_norm": 14.26174259185791 + }, + { + "step": 6, + "loss": 1.205272912979126, + "grad_norm": 9.654252052307129 + }, + { + "step": 7, + "loss": 1.4993977546691895, + "grad_norm": 9.16186237335205 + }, + { + "step": 8, + "loss": 1.3386749029159546, + "grad_norm": 9.539480209350586 + }, + { + "step": 9, + "loss": 1.7551285028457642, + "grad_norm": 8.458740234375 + }, + { + "step": 10, + "loss": 1.6139777898788452, + "grad_norm": 47.66611099243164 + }, + { + "step": 11, + "loss": 1.3058594465255737, + "grad_norm": 7.0746378898620605 + }, + { + "step": 12, + "loss": 1.4825245141983032, + "grad_norm": 7.372246265411377 + }, + { + "step": 13, + "loss": 1.0571527481079102, + "grad_norm": 9.301342010498047 + }, + { + "step": 14, + "loss": 1.2916768789291382, + "grad_norm": 6.207754135131836 + }, + { + "step": 15, + "loss": 1.3111194372177124, + "grad_norm": 9.410601615905762 + }, + { + "step": 16, + "loss": 1.5206763744354248, + "grad_norm": 9.227742195129395 + }, + { + "step": 17, + "loss": 1.580748438835144, + "grad_norm": 14.178001403808594 + }, + { + "step": 18, + "loss": 0.7333115935325623, + "grad_norm": 12.217166900634766 + }, + { + "step": 19, + "loss": 1.6668834686279297, + "grad_norm": 6.052151679992676 + }, + { + "step": 20, + "loss": 1.0880261659622192, + "grad_norm": 9.590500831604004 + }, + { + "step": 21, + "loss": 1.147664189338684, + "grad_norm": 8.589299201965332 + }, + { + "step": 22, + "loss": 1.0658481121063232, + "grad_norm": 6.9600419998168945 + }, + { + "step": 23, + "loss": 1.3873035907745361, + "grad_norm": 9.590429306030273 + }, + { + "step": 24, + "loss": 1.890312671661377, + "grad_norm": 19.884483337402344 + }, + { + "step": 25, + "loss": 1.9729206562042236, + "grad_norm": 7.790271759033203 + }, + { + "step": 26, + "loss": 2.0644829273223877, + "grad_norm": 6.620902061462402 + }, + { + "step": 27, + "loss": 0.6783545613288879, + "grad_norm": 5.400845527648926 + }, + { + "step": 28, + "loss": 1.4178911447525024, + "grad_norm": 11.719703674316406 + }, + { + "step": 29, + "loss": 2.0086207389831543, + "grad_norm": 8.36505126953125 + }, + { + "step": 30, + "loss": 1.5915957689285278, + "grad_norm": 7.866483688354492 + }, + { + "step": 31, + "loss": 1.4387072324752808, + "grad_norm": 6.462050914764404 + }, + { + "step": 32, + "loss": 1.1696559190750122, + "grad_norm": 7.273270606994629 + }, + { + "step": 33, + "loss": 1.8873889446258545, + "grad_norm": 16.88315773010254 + }, + { + "step": 34, + "loss": 1.742367148399353, + "grad_norm": 10.79595947265625 + }, + { + "step": 35, + "loss": 1.484022617340088, + "grad_norm": 7.354922294616699 + }, + { + "step": 36, + "loss": 1.209019422531128, + "grad_norm": 9.22113037109375 + }, + { + "step": 37, + "loss": 1.4977227449417114, + "grad_norm": 6.676819801330566 + }, + { + "step": 38, + "loss": 1.186678409576416, + "grad_norm": 6.483543395996094 + }, + { + "step": 39, + "loss": 1.463419795036316, + "grad_norm": 8.406513214111328 + }, + { + "step": 40, + "loss": 1.892924427986145, + "grad_norm": 6.2646484375 + }, + { + "step": 41, + "loss": 1.6282488107681274, + "grad_norm": 8.783570289611816 + }, + { + "step": 42, + "loss": 1.6034563779830933, + "grad_norm": 8.478983879089355 + }, + { + "step": 43, + "loss": 1.4728147983551025, + "grad_norm": 8.578154563903809 + }, + { + "step": 44, + "loss": 2.4027509689331055, + "grad_norm": 8.874027252197266 + }, + { + "step": 45, + "loss": 2.154872179031372, + "grad_norm": 8.062206268310547 + }, + { + "step": 46, + "loss": 1.3577312231063843, + "grad_norm": 8.476325035095215 + }, + { + "step": 47, + "loss": 1.2283380031585693, + "grad_norm": 24.45260238647461 + }, + { + "step": 48, + "loss": 1.87751305103302, + "grad_norm": 6.911473274230957 + }, + { + "step": 49, + "loss": 0.6943105459213257, + "grad_norm": 7.364080905914307 + }, + { + "step": 50, + "loss": 0.9754929542541504, + "grad_norm": 12.101676940917969 + } + ] +} \ No newline at end of file diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/tests/invariant/test_invariant.py b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/invariant/test_invariant.py new file mode 100644 index 0000000000000000000000000000000000000000..77987daa188f8ecaccb0aa98d6a64743a3c8466e --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/invariant/test_invariant.py @@ -0,0 +1,296 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +import os +import platform +import subprocess +import sys +import tempfile +from dataclasses import asdict, dataclass +from pathlib import Path + +import accelerate +import pytest +import torch +import transformers + + +MODEL = "Qwen/Qwen2.5-0.5B-Instruct" +MODEL_REVISION = "7ae557604adf67be50417f59c2c2f167def9a775" + +SFT_DATASET = "trl-lib/Capybara" +DPO_DATASET = "trl-lib/ultrafeedback_binarized" + +REFERENCES_DIR = Path(__file__).parent / "references" + +NUM_STEPS = 50 +SEED = 42 +MAX_LENGTH = 512 + + +def _trl_commit() -> str: + """Return the current trl commit SHA (with `-dirty` suffix if the working tree has uncommitted changes). + + Assumes the suite is run from a `pip install -e .` checkout — the only intended setup. + """ + cwd = Path(__file__).parent + sha = subprocess.run( + ["git", "-C", str(cwd), "rev-parse", "HEAD"], capture_output=True, text=True, check=True + ).stdout.strip() + dirty = subprocess.run( + ["git", "-C", str(cwd), "status", "--porcelain"], capture_output=True, text=True, check=True + ).stdout.strip() + return f"{sha}-dirty" if dirty else sha + + +def env_snapshot() -> dict: + return { + "accelerate": accelerate.__version__, + "torch": torch.__version__, + "transformers": transformers.__version__, + "trl": _trl_commit(), + "python": platform.python_version(), + "gpu": torch.cuda.get_device_name(0) if torch.cuda.is_available() else "cpu", + } + + +@dataclass +class StepRecord: + step: int + loss: float + grad_norm: float + + +@dataclass +class Trajectory: + config: dict + env: dict + steps: list[StepRecord] + + +@dataclass +class CorrectnessConfig: + name: str + method: str # "sft" | "dpo" + args: dict[str, str] + num_processes: int = 1 + + def cli_args(self) -> list[str]: + out: list[str] = [] + for k, v in self.args.items(): + out.extend([f"--{k}", v]) + return out + + +def run(config: CorrectnessConfig) -> Trajectory: + """Invoke the trl CLI as a subprocess; parse its trainer_state.json into a Trajectory.""" + with tempfile.TemporaryDirectory() as tmpdir: + cmd = ["trl", config.method] + cmd += ["--num_processes", str(config.num_processes)] + cmd += ["--output_dir", tmpdir, *config.cli_args()] + env = {**os.environ, "CUDA_VISIBLE_DEVICES": ",".join(str(i) for i in range(config.num_processes))} + subprocess.run(cmd, check=True, env=env) + + state_paths = list(Path(tmpdir).glob("**/trainer_state.json")) + if not state_paths: + raise RuntimeError(f"trainer_state.json not produced in {tmpdir}") + state = json.loads(state_paths[0].read_text()) + + steps = [ + StepRecord( + step=int(log["step"]), + loss=float(log["loss"]), + grad_norm=float(log["grad_norm"]), + ) + for log in state["log_history"] + if "loss" in log # skip eval and final-summary entries + ] + + return Trajectory( + config={"name": config.name, "method": config.method, "args": config.args}, + env=env_snapshot(), + steps=steps, + ) + + +def save(trajectory: Trajectory, path: Path) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(asdict(trajectory), indent=2)) + + +def load(path: Path) -> Trajectory: + data = json.loads(path.read_text()) + return Trajectory( + config=data["config"], + env=data["env"], + steps=[StepRecord(**s) for s in data["steps"]], + ) + + +def compare_scalars(a: Trajectory, b: Trajectory, tol: dict[str, float], residual_tol: dict[str, float]) -> list[str]: + """Compare scalar series (loss, grad_norm). `tol` and `residual_tol` are per-field dicts keyed by `'loss'` and + `'grad_norm'`.""" + errors: list[str] = [] + if len(a.steps) != len(b.steps): + return [f"length mismatch: {len(a.steps)} vs {len(b.steps)}"] + + for field in ("loss", "grad_norm"): + sa = [getattr(s, field) for s in a.steps] + sb = [getattr(s, field) for s in b.steps] + diffs = [x - y for x, y in zip(sa, sb, strict=False)] + max_abs = max(abs(d) for d in diffs) + if max_abs > tol[field]: + i = max(range(len(diffs)), key=lambda k: abs(diffs[k])) + step = a.steps[i].step + errors.append( + f"{field}: max |Δ|={max_abs:.3e} at step {step} (a={sa[i]:.6e}, b={sb[i]:.6e}, tol={tol[field]:.1e})" + ) + + mean = sum(diffs) / len(diffs) + if abs(mean) > residual_tol[field]: + errors.append(f"{field}: systematic drift, mean Δ={mean:.3e} (tol={residual_tol[field]:.1e})") + + return errors + + +def _build( + name: str, method: str, dataset: str, attn: str = "eager", num_processes: int = 1, **overrides +) -> CorrectnessConfig: + args: dict[str, str] = { + "model_name_or_path": MODEL, + "model_revision": MODEL_REVISION, + "attn_implementation": attn, + "dataset_name": dataset, + "max_steps": str(NUM_STEPS), + "max_length": str(MAX_LENGTH), + "logging_steps": "1", + "report_to": "none", + "seed": str(SEED), + "data_seed": str(SEED), + "full_determinism": "True", + # Force pure fp32 training for maximal determinism and to avoid bfloat16-induced divergences. + "bf16": "False", + } + args.update({k: str(v) for k, v in overrides.items()}) + return CorrectnessConfig(name=name, method=method, args=args, num_processes=num_processes) + + +# Equivalence classes: each maps to a `members` list plus per-field `tol` (max |Δ|) and `residual_tol` (mean Δ) +# dicts. The first member is the canonical config — it owns the class's reference snapshot and is the only one +# re-recorded under `--update-references`. Every other member is asserted to match that snapshot. +# Tuning tip: run `python tests/invariant/test_invariant.py --report` to see actual Δs and set tolerances +# to ~1.5–2× the observed noise. +EQUIVALENCE_CLASSES: dict[str, dict] = { + "sft": { + "tol": {"loss": 1e-3, "grad_norm": 1e-1}, + "residual_tol": {"loss": 1e-5, "grad_norm": 1e-3}, + "members": [ + _build("sft_default", "sft", SFT_DATASET), + _build("sft_pdb1_gas8", "sft", SFT_DATASET, per_device_train_batch_size=1, gradient_accumulation_steps=8), + _build("sft_no_grad_ckpt", "sft", SFT_DATASET, gradient_checkpointing=False), + _build("sft_ddp2", "sft", SFT_DATASET, per_device_train_batch_size=4, num_processes=2), + ], + }, + "sft_fa2": { + # Loss is much tighter than grad_norm under FA2+bf16 (grad_norm absorbs bf16 + FA varlen kernel noise). + # See https://github.com/huggingface/trl/pull/5842#issuecomment-4539190615 + "tol": {"loss": 1.5e-2, "grad_norm": 1.0}, + "residual_tol": {"loss": 1e-4, "grad_norm": 5e-2}, + "members": [ + _build( + "sft_fa2", + "sft", + SFT_DATASET, + attn="kernels-community/flash-attn2", # to avoid cross-contamination between samples when padding_free=True + bf16=True, # required for FA2 kernels, which are bfloat16-only + max_length=None, # Required when padding_free=True + per_device_train_batch_size=2, + ), + _build( + "sft_fa2_padfree", + "sft", + SFT_DATASET, + attn="kernels-community/flash-attn2", # to avoid cross-contamination between samples when padding_free=True + bf16=True, # required for FA2 kernels, which are bfloat16-only + max_length=None, # Required when padding_free=True + per_device_train_batch_size=2, + padding_free=True, + ), + ], + }, + "dpo": { + "tol": {"loss": 1e-4, "grad_norm": 1e-2}, + "residual_tol": {"loss": 1e-5, "grad_norm": 1e-3}, + "members": [ + _build("dpo_default", "dpo", DPO_DATASET), + _build("dpo_pdb1_gas8", "dpo", DPO_DATASET, per_device_train_batch_size=1, gradient_accumulation_steps=8), + _build("dpo_no_grad_ckpt", "dpo", DPO_DATASET, gradient_checkpointing=False), + _build("dpo_ddp2", "dpo", DPO_DATASET, per_device_train_batch_size=4, num_processes=2), + ], + }, +} + + +_ALL = [(klass, c) for klass, ec in EQUIVALENCE_CLASSES.items() for c in ec["members"]] + + +@pytest.mark.invariant +@pytest.mark.parametrize("klass,config", _ALL, ids=[c.name for _, c in _ALL]) +def test_invariant(klass, config): + ref_path = REFERENCES_DIR / f"{klass}.json" + if not ref_path.exists(): + pytest.fail(f"no reference at {ref_path}; record it with `python {Path(__file__).name}`") + + if config.num_processes > 1 and torch.cuda.device_count() < config.num_processes: + pytest.skip(f"requires {config.num_processes} GPUs, got {torch.cuda.device_count()}") + + trajectory = run(config) + reference = load(ref_path) + ec = EQUIVALENCE_CLASSES[klass] + errors = compare_scalars(trajectory, reference, tol=ec["tol"], residual_tol=ec["residual_tol"]) + assert not errors, f"'{config.name}' diverges from class '{klass}' reference:\n " + "\n ".join(errors) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Record canonical reference trajectories for the invariant tests.") + parser.add_argument( + "klass", + nargs="*", + choices=list(EQUIVALENCE_CLASSES), + help="Equivalence class(es) to record. Default: all.", + ) + parser.add_argument( + "--allow-dirty", + action="store_true", + help="Allow recording from a dirty working tree (snapshot will pin an irreproducible state).", + ) + cli_args = parser.parse_args() + + if _trl_commit().endswith("-dirty") and not cli_args.allow_dirty: + sys.exit( + "Refusing to record from a dirty working tree: the snapshot would pin a state that can't be " + "reproduced from a commit SHA. Commit your changes first, or pass --allow-dirty to override." + ) + + classes = cli_args.klass or list(EQUIVALENCE_CLASSES) + for klass in classes: + canonical = EQUIVALENCE_CLASSES[klass]["members"][0] + print(f"recording '{klass}' from canonical config '{canonical.name}'") # noqa: T201 + trajectory = run(canonical) + ref_path = REFERENCES_DIR / f"{klass}.json" + save(trajectory, ref_path) + print(f" → {ref_path}") # noqa: T201 diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/tests/tasksmith_behavior.py b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/tasksmith_behavior.py new file mode 100644 index 0000000000000000000000000000000000000000..096df3a94e1f084103e45368438d9c9dc346c2f0 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/tasksmith_behavior.py @@ -0,0 +1,201 @@ +"""Offline numerical contracts and real tiny-trainer integration for GMPO.""" +from collections import defaultdict +from types import SimpleNamespace + +import pytest +import torch + + +class LogitTable(torch.nn.Module): + def __init__(self): + super().__init__() + values = torch.tensor([ + [[0.0, 0.3, -0.1, 0.4, 0.2, -0.4, 0.1], [0.0, 0.2, 0.7, -0.2, 0.5, 0.1, -0.1], + [0.4, -0.5, 0.1, 0.6, 0.9, 0.2, -0.1], [0.3, 0.2, 0.1, 0.4, 0.5, -0.2, 0.0], + [0.1, 0.3, -0.2, 0.8, 0.0, 0.1, -0.3]], + [[0.5, 0.2, -0.5, 0.4, 0.1, -0.3, 0.7], [1.3, -0.3, 0.7, -0.2, 0.4, 0.2, 0.0], + [2.1, -0.3, 0.0, 0.2, -0.5, 0.1, -0.1], [0.0, 0.1, 0.2, 0.4, 0.3, 0.5, -0.2], + [0.4, 0.2, 0.1, 0.3, -0.4, 0.0, -0.2]], + ], dtype=torch.float64) + self.logits = torch.nn.Parameter(values) + + def forward(self, input_ids, attention_mask, use_cache=False): + assert input_ids.shape == attention_mask.shape == (2, 5) + return SimpleNamespace(logits=self.logits + 0.0) + + +def _logps(logits, completion_ids): + log_probs = logits[:, -4:-1].log_softmax(-1) + return log_probs.gather(-1, completion_ids.unsqueeze(-1)).squeeze(-1) + + +def _fixture(beta=0.0, entropy_quantile=1.0, train=True, accumulation=1): + from trl.experimental.gmpo import GMPOTrainer + model = LogitTable() + model.train(train) + trainer = object.__new__(GMPOTrainer) + trainer.model = model + trainer.temperature = 1.0 + trainer.model_kwarg_keys = {"input_ids", "attention_mask", "use_cache"} + trainer.epsilon_low, trainer.epsilon_high = 0.4, 0.25 + trainer.beta, trainer.top_entropy_quantile = beta, entropy_quantile + trainer.current_gradient_accumulation_steps = accumulation + trainer.accelerator = SimpleNamespace(gather=lambda value: value, pad_across_processes=lambda value, **kwargs: value, + num_processes=1, is_main_process=True) + trainer._metrics = {"train": defaultdict(list), "eval": defaultdict(list)} + inputs = { + "prompt_ids": torch.tensor([[1, 2], [2, 1]]), "prompt_mask": torch.ones(2, 2, dtype=torch.long), + "completion_ids": torch.tensor([[3, 4, 5], [4, 3, 2]]), + "completion_mask": torch.tensor([[1, 1, 0], [1, 1, 1]]), + "advantages": torch.tensor([1.5, -0.8], dtype=torch.float64), + } + current = _logps(model.logits.detach(), inputs["completion_ids"]) + # Positive/negative advantages encounter both clipped and unclipped directions. + inputs["old_per_token_logps"] = current - torch.tensor([[0.8, -0.7, 5.0], [-0.8, 0.7, 0.1]]) + inputs["ref_per_token_logps"] = current + torch.tensor([[0.2, -0.3, 2.0], [0.4, -0.2, 0.15]]) + return trainer, model, inputs + + +def _expected(logits, inputs, *, beta=0.0, keep=None, accumulation=1): + """Sequence-wise ratio-space calculation independent of the vectorized implementation.""" + current = _logps(logits, inputs["completion_ids"]) + previous = inputs.get("old_per_token_logps", current.detach()) + full_mask = inputs["completion_mask"].bool() + if "tool_mask" in inputs: + full_mask &= inputs["tool_mask"].bool() + selected = full_mask if keep is None else full_mask & keep + losses = [] + for row in range(2): + advantage = inputs["advantages"][row] + ratios = [] + for col in range(3): + if selected[row, col]: + ratio = (current[row, col] - previous[row, col]).exp() + limit = torch.exp(current.new_tensor(0.25 if advantage > 0 else -0.4)) + ratios.append(torch.minimum(ratio, limit) if advantage > 0 else torch.maximum(ratio, limit)) + weight = torch.stack(ratios).prod().pow(1.0 / len(ratios)) if ratios else current.new_tensor(1.0) + loss = -advantage * weight + if beta: + terms = [torch.exp(inputs["ref_per_token_logps"][row, col] - current[row, col]) + - (inputs["ref_per_token_logps"][row, col] - current[row, col]) - 1 + for col in range(3) if full_mask[row, col]] + loss = loss + beta * (torch.stack(terms).mean() if terms else current.new_tensor(0.0)) + losses.append(loss) + return torch.stack(losses).mean() / accumulation + + +def _compare(trainer, model, inputs, *, beta=0.0, keep=None, accumulation=1): + expected_logits = model.logits.detach().clone().requires_grad_() + expected = _expected(expected_logits, inputs, beta=beta, keep=keep, accumulation=accumulation) + actual = trainer._compute_loss(model, inputs) + torch.testing.assert_close(actual, expected, rtol=1e-8, atol=1e-8) + actual.backward() + expected.backward() + assert model.logits.grad is not None and model.logits.grad.abs().sum() > 0 + torch.testing.assert_close(model.logits.grad, expected_logits.grad, rtol=1e-7, atol=1e-8) + + +def test_log_space_defaults_on_cpu(tmp_path): + from trl.experimental.gmpo import GMPOConfig + args = GMPOConfig(str(tmp_path), use_cpu=True, bf16=False, fp16=False, report_to="none") + assert args.epsilon == 0.4 and args.epsilon_high is None + + +def test_geometric_mean_sign_aware_clipping_values_and_gradients(): + trainer, model, inputs = _fixture() + _compare(trainer, model, inputs) + + +def test_tool_and_completion_masks_exclude_tokens_from_values_and_gradients(): + trainer, model, inputs = _fixture() + inputs["tool_mask"] = torch.tensor([[1, 0, 1], [1, 1, 0]]) + _compare(trainer, model, inputs) + assert model.logits.grad[0, 2:4].count_nonzero() == 0 + assert model.logits.grad[1, 3].count_nonzero() == 0 + + +def test_sequence_averaged_kl_and_train_accumulation(): + trainer, model, inputs = _fixture(beta=0.3, accumulation=3) + _compare(trainer, model, inputs, beta=0.3, accumulation=3) + assert trainer._metrics["train"]["kl"] + + +def test_eval_does_not_divide_by_training_accumulation(): + trainer, model, inputs = _fixture(train=False, accumulation=3) + _compare(trainer, model, inputs) + + +def test_old_logps_default_detaches_without_losing_policy_gradient(): + trainer, model, inputs = _fixture() + del inputs["old_per_token_logps"] + _compare(trainer, model, inputs) + + +def test_high_entropy_selection_changes_geometric_mean_not_kl_mask(): + trainer, model, inputs = _fixture(beta=0.2, entropy_quantile=0.4) + probabilities = model.logits.detach()[:, -4:-1].softmax(-1) + entropy = -(probabilities * probabilities.log()).sum(-1) + active = inputs["completion_mask"].bool() + threshold = entropy[active].quantile(0.6) + keep = entropy >= threshold + assert 0 < (active & keep).sum() < active.sum() + _compare(trainer, model, inputs, beta=0.2, keep=keep) + + +def test_empty_completion_masks_are_finite_with_zero_policy_gradient(): + trainer, model, inputs = _fixture(beta=0.3) + inputs["completion_mask"].zero_() + actual = trainer._compute_loss(model, inputs) + torch.testing.assert_close(actual, -inputs["advantages"].mean()) + actual.backward() + assert torch.isfinite(actual) and model.logits.grad.count_nonzero() == 0 + + +@pytest.mark.parametrize("conversational", [False, True]) +def test_local_tiny_trainer_updates_policy(conversational, tmp_path): + from datasets import Dataset + from tokenizers import Tokenizer + from tokenizers.models import WordLevel + from tokenizers.pre_tokenizers import Whitespace + from transformers import LlamaConfig, LlamaForCausalLM, PreTrainedTokenizerFast + from trl.experimental.gmpo import GMPOConfig, GMPOTrainer + + torch.manual_seed(31) + torch.set_num_threads(1) + vocab = {"[PAD]": 0, "[UNK]": 1, "[EOS]": 2, "hello": 3, "red": 4, "blue": 5, "green": 6, "answer": 7} + backend = Tokenizer(WordLevel(vocab, unk_token="[UNK]")) + backend.pre_tokenizer = Whitespace() + tokenizer = PreTrainedTokenizerFast(tokenizer_object=backend, pad_token="[PAD]", unk_token="[UNK]", eos_token="[EOS]") + tokenizer.chat_template = "{% for message in messages %}{{ message['content'] }} {% endfor %}" + model = LlamaForCausalLM(LlamaConfig(vocab_size=8, hidden_size=16, intermediate_size=32, + num_hidden_layers=1, num_attention_heads=2, num_key_value_heads=2, max_position_embeddings=32, + bos_token_id=1, eos_token_id=2, pad_token_id=0, attention_dropout=0.0)) + # The inherited beta>0 path reloads its reference from the policy's model ID. + # Give it a local checkpoint instead of an empty or remote model identifier. + checkpoint = tmp_path / "initial-model" + model.save_pretrained(checkpoint) + model = LlamaForCausalLM.from_pretrained(checkpoint) + prompt = [{"role": "user", "content": "hello"}] if conversational else "hello" + dataset = Dataset.from_list([{"prompt": prompt} for _ in range(4)]) + + def rewards(completions, **kwargs): + return [float(index % 2) for index in range(len(completions))] + + def rollout(prompts, trainer): + # Deterministic rollout input; the real trainer still computes loss/backprop/optimizer updates. + count = len(prompts) + return {"prompt_ids": [[3] for _ in range(count)], + "completion_ids": [[4, 5, 2] if i % 2 == 0 else [6, 7, 2] for i in range(count)], + "logprobs": [[-2.0] * 3 for _ in range(count)]} + + args = GMPOConfig(str(tmp_path), use_cpu=True, bf16=False, fp16=False, + gradient_checkpointing=False, per_device_train_batch_size=2, num_generations=2, + max_steps=2, max_completion_length=3, num_iterations=2, learning_rate=0.01, + report_to="none", save_strategy="no", logging_steps=1, disable_tqdm=True, + beta=0.1 if conversational else 0.0) + trainer = GMPOTrainer(model, rewards, args=args, train_dataset=dataset, + processing_class=tokenizer, rollout_func=rollout) + before = {name: value.detach().clone() for name, value in model.named_parameters()} + outcome = trainer.train() + assert trainer.state.global_step == 2 and torch.isfinite(torch.tensor(outcome.training_loss)) + assert any(not torch.equal(before[name], value.detach()) for name, value in model.named_parameters()) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_activation_offloading.py b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_activation_offloading.py new file mode 100644 index 0000000000000000000000000000000000000000..5f2f6a03b4bb78911a64e08db2775094fd896edb --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_activation_offloading.py @@ -0,0 +1,237 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch +from torch import nn +from transformers import AutoModelForCausalLM +from transformers.testing_utils import torch_device +from transformers.utils import is_peft_available + +from trl.models.activation_offloading import NoOpManager, OffloadActivations + +from .testing_utils import TrlTestCase, require_peft, require_torch_accelerator + + +if is_peft_available(): + from peft import LoraConfig, get_peft_model + + +class TestActivationOffloading(TrlTestCase): + @require_torch_accelerator + @require_peft + def test_offloading_with_peft_models(self) -> None: + """Test that activation offloading works with PEFT models.""" + model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" + model = AutoModelForCausalLM.from_pretrained(model_id).to(torch_device) + peft_config = LoraConfig( + lora_alpha=16, + lora_dropout=0.1, + r=8, + bias="none", + task_type="CAUSAL_LM", + ) + + model = get_peft_model(model, peft_config) + inp = torch.randint(0, 100, (2, 10), device=torch_device) + + # First forward-backward pass without offloading + torch.manual_seed(42) + loss = model(inp, labels=inp).loss + loss.backward() + + # Store gradients - only from trainable parameters + grads_original = [] + for name, param in model.named_parameters(): + if param.requires_grad and param.grad is not None: + grads_original.append((name, param.grad.clone())) + + # Reset gradients + for p in model.parameters(): + if p.grad is not None: + p.grad = None + + # Second forward-backward pass with offloading + torch.manual_seed(42) + with OffloadActivations(): + loss_c = model(inp, labels=inp).loss + loss_c.backward() + + # Compare gradients - only trainable parameters + for name_orig, grad_orig in grads_original: + for name_param, param in model.named_parameters(): + if name_param == name_orig and param.requires_grad and param.grad is not None: + ( + torch.testing.assert_close(grad_orig, param.grad, rtol=1e-4, atol=1e-5), + (f"Gradient mismatch for {name_orig}"), + ) + + @require_torch_accelerator + def test_noop_manager_with_offloading(self): + model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" + model = AutoModelForCausalLM.from_pretrained(model_id).to(torch_device) + inp = torch.randint(0, 100, (2, 10), device=torch_device) + + # Run with offloading but disable for specific section + with OffloadActivations(): + # First forward-backward with normal offloading + torch.manual_seed(42) + out1 = model(inp, labels=inp) + out1.loss.backward() + grads1 = [p.grad.clone() for p in model.parameters()] + + # Reset grads + for p in model.parameters(): + p.grad = None + + # Second forward-backward with NoOpManager + with NoOpManager(): + torch.manual_seed(42) + out2 = model(inp, labels=inp) + out2.loss.backward() + + grads2 = [p.grad.clone() for p in model.parameters()] + + # Gradients should match as NoOpManager should have prevented offloading + for g1, g2 in zip(grads1, grads2, strict=True): + torch.testing.assert_close(g1, g2, rtol=1e-4, atol=1e-5) + + @require_torch_accelerator + def test_min_offload_size(self): + """Test that tensors smaller than min_offload_size aren't offloaded""" + model = nn.Sequential( + nn.Linear(5, 5), # Small layer that shouldn't be offloaded + nn.Linear(5, 1000), # Large layer that should be offloaded + ).to(torch_device) + + inp = torch.randn(2, 5, device=torch_device) + + with OffloadActivations(min_offload_size=1000): + out = model(inp) + out.sum().backward() + + # The test passes if no errors occur, as we're mainly testing + # that the logic handles both offloaded and non-offloaded tensors + + @require_torch_accelerator + def test_real_hf_model(self): + """Test with an actual HuggingFace model""" + model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" + model = AutoModelForCausalLM.from_pretrained(model_id).to(torch_device) + + # Create small input + inp = torch.randint(0, 100, (2, 10), device=torch_device) + + # Baseline without offloading + torch.manual_seed(42) + out1 = model(inp, labels=inp).loss + out1.backward() + grads1 = [p.grad.clone() for p in model.parameters()] + + # Reset grads + for p in model.parameters(): + p.grad = None + + # With offloading + with OffloadActivations(): + torch.manual_seed(42) + out2 = model(inp, labels=inp).loss + out2.backward() + + grads2 = [p.grad.clone() for p in model.parameters()] + + # Check outputs and gradients match + torch.testing.assert_close(out1, out2) + for g1, g2 in zip(grads1, grads2, strict=True): + torch.testing.assert_close(g1, g2) + + @require_torch_accelerator + def test_tensor_deduplication(self): + """Test that deduplication works correctly for tensors sharing storage""" + + class ModelWithViews(nn.Module): + def __init__(self): + super().__init__() + self.linear = nn.Linear(100, 100) + + def forward(self, x): + out = self.linear(x) + view1 = out.view(-1) + view2 = out.transpose(0, 1) + return view1.sum() + view2.sum() + + model = ModelWithViews().to(torch_device) + offload_ctx = OffloadActivations(min_offload_size=1) + offload_ctx.update_model_params(model) + + x = torch.randn(10, 100, device=torch_device, requires_grad=True) + with offload_ctx: + loss = model(x) + + total_tensor_ids = offload_ctx.tensor_id + assert total_tensor_ids > 0, "Should have created tensor IDs" + + # modified=True means offloaded to CPU, modified=False means kept on GPU (deduplicated) + deduplicated_count = sum(1 for _, modified, _, _, _ in offload_ctx.tracker.values() if not modified) + offloaded_count = sum(1 for _, modified, _, _, _ in offload_ctx.tracker.values() if modified) + + assert offloaded_count > 0, "Should have offloaded at least one tensor" + assert deduplicated_count > 0, "Should have deduplicated at least one tensor (view)" + + unique_storages_offloaded = len(offload_ctx.storage_to_tensor_id) + assert unique_storages_offloaded < total_tensor_ids, ( + f"Deduplication should result in fewer storages ({unique_storages_offloaded}) " + f"than total tensors ({total_tensor_ids})" + ) + + loss.backward() + + @require_torch_accelerator + def test_stale_tracker_state_is_cleared_between_forwards(self): + """Test that tensors from unused graph branches don't accumulate across steps.""" + + class ModelWithUnusedBranch(nn.Module): + def __init__(self): + super().__init__() + self.used = nn.Linear(8, 8) + self.unused = nn.Linear(8, 8) + + def forward(self, x): + return self.used(x).sum(), self.unused(x).sum() + + model = ModelWithUnusedBranch().to(torch_device) + offload_ctx = OffloadActivations(use_pin_memory=False, use_streams=False, min_offload_size=1) + offload_ctx.update_model_params(model) + inp = torch.randn(4, 8, device=torch_device) + + tracker_counts = [] + for _ in range(3): + model.zero_grad(set_to_none=True) + with offload_ctx: + loss, _ = model(inp) + loss.backward() + tracker_counts.append(len(offload_ctx.tracker)) + + assert tracker_counts == [tracker_counts[0]] * len(tracker_counts) + + @require_torch_accelerator + def test_parameter_filtering(self): + """Test that model parameters are filtered during offloading""" + model = nn.Sequential(nn.Linear(10, 20), nn.Linear(20, 10)).to(torch_device) + offload_ctx = OffloadActivations() + offload_ctx.update_model_params(model) + + assert len(offload_ctx.param_storages) > 0, "Should have tracked parameter storages" + + param_ptrs = {p.data.untyped_storage().data_ptr() for p in model.parameters()} + assert offload_ctx.param_storages == param_ptrs, "Tracked storages should match parameter storages" diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_callbacks.py b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_callbacks.py new file mode 100644 index 0000000000000000000000000000000000000000..ef2aa71d81644f11b5963974d3f5f849334a93fd --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_callbacks.py @@ -0,0 +1,238 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +import os +from unittest.mock import call, patch + +from datasets import load_dataset +from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig, Trainer, TrainingArguments + +from trl import BEMACallback, LogCompletionsCallback + +from .testing_utils import TrlTestCase, require_comet, require_wandb + + +class TestLogCompletionsCallback(TrlTestCase): + def setup_method(self): + self.model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5") + self.tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5") + self.tokenizer.pad_token = self.tokenizer.eos_token + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only") + dataset["train"] = dataset["train"].select(range(8)) + + def tokenize_function(examples): + out = self.tokenizer(examples["prompt"], padding="max_length", max_length=16, truncation=True) + out["labels"] = out["input_ids"].copy() + return out + + self.dataset = dataset.map(tokenize_function, batched=True) + + self.generation_config = GenerationConfig(max_length=32) + + @require_wandb + def test_basic_wandb(self): + import wandb + + training_args = TrainingArguments( + output_dir=self.tmp_dir, + eval_strategy="steps", + eval_steps=2, # evaluate every 2 steps + per_device_train_batch_size=2, # 8 samples in total so 4 batches of 2 per epoch + per_device_eval_batch_size=2, + report_to="wandb", + ) + trainer = Trainer( + model=self.model, + args=training_args, + train_dataset=self.dataset["train"], + eval_dataset=self.dataset["test"], + processing_class=self.tokenizer, + ) + completions_callback = LogCompletionsCallback(trainer, self.generation_config, num_prompts=2) + trainer.add_callback(completions_callback) + trainer.train() + + # Get the current run + completions_path = wandb.run.summary.completions["path"] + json_path = os.path.join(wandb.run.dir, completions_path) + with open(json_path) as f: + completions = json.load(f) + + # Check that the columns are correct + assert "step" in completions["columns"] + assert "prompt" in completions["columns"] + assert "completion" in completions["columns"] + + # Check that the prompt is in the log + assert self.dataset["test"][0]["prompt"] in completions["data"][0] + + @require_comet + def test_basic_comet(self): + import comet_ml + + training_args = TrainingArguments( + output_dir=self.tmp_dir, + eval_strategy="steps", + eval_steps=2, # evaluate every 2 steps + per_device_train_batch_size=2, # 8 samples in total so 4 batches of 2 per epoch + per_device_eval_batch_size=2, + report_to="comet_ml", + ) + trainer = Trainer( + model=self.model, + args=training_args, + train_dataset=self.dataset["train"], + eval_dataset=self.dataset["test"], + processing_class=self.tokenizer, + ) + completions_callback = LogCompletionsCallback(trainer, self.generation_config, num_prompts=2) + trainer.add_callback(completions_callback) + trainer.train() + + # close experiment to make sure all pending data are flushed + experiment = comet_ml.get_running_experiment() + assert experiment is not None + experiment.end() + + # get experiment assets and check that all required tables was logged + steps = len(self.dataset["train"]) + len(self.dataset["test"]) + tables_logged = int(steps / 2) + 1 # +1 to include zero step + + api_experiment = comet_ml.APIExperiment(previous_experiment=experiment.id) + tables = api_experiment.get_asset_list("dataframe") + assert tables is not None + assert len(tables) == tables_logged + assert all(table["fileName"] == "completions.csv" for table in tables) + + +class TestBEMACallback(TrlTestCase): + def setup_method(self): + self.model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5") + self.tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5") + self.tokenizer.pad_token = self.tokenizer.eos_token + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling") + + def tokenize_function(examples, tokenizer): + out = tokenizer(examples["text"], padding="max_length", max_length=17) + out["labels"] = out["input_ids"].copy() + return out + + self.dataset = dataset.map( + tokenize_function, fn_kwargs={"tokenizer": self.tokenizer}, remove_columns=["text"], batched=True + ) + + def test_model_saved(self): + """Test that BEMACallback saves the BEMA model.""" + training_args = TrainingArguments(output_dir=self.tmp_dir, report_to="none") + bema_callback = BEMACallback(update_freq=2) + trainer = Trainer( + model=self.model, + args=training_args, + train_dataset=self.dataset["train"], + processing_class=self.tokenizer, + callbacks=[bema_callback], + ) + trainer.train() + + # Check that the BEMA model was saved and can be loaded + bema_path = os.path.join(self.tmp_dir, "bema") + assert os.path.isdir(bema_path), "BEMA directory was not created" + AutoModelForCausalLM.from_pretrained(bema_path) + + def test_update_frequency_0(self): + """Test that BEMA callback respects the update frequency.""" + training_args = TrainingArguments(output_dir=self.tmp_dir, report_to="none") + bema_callback = BEMACallback(update_freq=2) + + with patch.object(bema_callback, "_update_bema_weights") as mock_update: + trainer = Trainer( + model=self.model, + args=training_args, + train_dataset=self.dataset["train"], + processing_class=self.tokenizer, + callbacks=[bema_callback], + ) + + trainer.train() + + # Total 9 steps (17 samples, batch size 8, 3 epochs). + # BEMA starts after step 0 and updates every 2 steps → updates at 2, 4, 5, 8 + assert mock_update.call_args_list == [call(2), call(4), call(6), call(8)] + + def test_update_frequency_1(self): + """Test that BEMA callback respects the update frequency.""" + training_args = TrainingArguments(output_dir=self.tmp_dir, report_to="none") + bema_callback = BEMACallback(update_freq=3) + + with patch.object(bema_callback, "_update_bema_weights") as mock_update: + trainer = Trainer( + model=self.model, + args=training_args, + train_dataset=self.dataset["train"], + processing_class=self.tokenizer, + callbacks=[bema_callback], + ) + + trainer.train() + + # Total 9 steps (17 samples, batch size 8, 3 epochs). + # BEMA starts after step 0 and updates every 3 steps → updates at 3, 6, 9 + assert mock_update.call_args_list == [call(3), call(6), call(9)] + + def test_update_frequency_2(self): + """Test that BEMA callback respects the update frequency.""" + training_args = TrainingArguments(output_dir=self.tmp_dir, report_to="none") + bema_callback = BEMACallback(update_freq=2, update_after=3) + + with patch.object(bema_callback, "_update_bema_weights") as mock_update: + trainer = Trainer( + model=self.model, + args=training_args, + train_dataset=self.dataset["train"], + processing_class=self.tokenizer, + callbacks=[bema_callback], + ) + + trainer.train() + + # Total 9 steps (17 samples, batch size 8, 3 epochs). + # BEMA starts after step 3 and updates every 2 steps → updates at 5, 7, 9 + assert mock_update.call_args_list == [call(5), call(7), call(9)] + + def test_no_bema(self): + """Test that BEMACallback works without BEMA updates.""" + training_args = TrainingArguments(output_dir=self.tmp_dir, report_to="none") + bema_callback = BEMACallback(update_freq=2, bias_power=0.0) + trainer = Trainer( + model=self.model, + args=training_args, + train_dataset=self.dataset["train"], + processing_class=self.tokenizer, + callbacks=[bema_callback], + ) + trainer.train() + + def test_no_ema(self): + """Test that BEMACallback works without EMA updates.""" + training_args = TrainingArguments(output_dir=self.tmp_dir, report_to="none") + bema_callback = BEMACallback(update_freq=2, ema_power=0.0) + trainer = Trainer( + model=self.model, + args=training_args, + train_dataset=self.dataset["train"], + processing_class=self.tokenizer, + callbacks=[bema_callback], + ) + trainer.train() diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_chat_template_utils.py b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_chat_template_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f6245ab2b327301be9971d45f1171f1c67b1dcc7 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_chat_template_utils.py @@ -0,0 +1,1255 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import copy +import textwrap + +import pytest +import transformers +from packaging.version import Version +from transformers import AutoModelForCausalLM, AutoModelForSequenceClassification, AutoProcessor, AutoTokenizer + +from trl import clone_chat_template +from trl.chat_template_utils import ( + add_response_schema, + get_training_chat_template, + is_chat_template_prefix_preserving, + is_chat_template_stop_token_trained, + parse_response, + supports_tool_calling, +) +from trl.data_utils import prepare_multimodal_messages + +from .testing_utils import TrlTestCase, require_jmespath, require_vision + + +class TestCloneChatTemplate(TrlTestCase): + def test_clone(self): + # This tokenizer doesn't have a chat_template by default + tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-BloomForCausalLM") + model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-BloomForCausalLM") + # This one has a chat_template by default + source = "trl-internal-testing/tiny-Qwen3ForCausalLM" + _, modified_tokenizer, _ = clone_chat_template(model, tokenizer, source) + + # Check if special tokens are correctly set + assert modified_tokenizer.eos_token == "<|im_end|>" + + def test_clone_with_resize(self): + # This tokenizer doesn't have a chat_template by default + tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-BloomForCausalLM") + model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-BloomForCausalLM") + # This one has a chat_template by default + source = "trl-internal-testing/tiny-Qwen3ForCausalLM" + modified_model, modified_tokenizer, _ = clone_chat_template( + model, tokenizer, source, resize_to_multiple_of=123 + ) + + # Check that the input embeddings have been resized to a multiple of 123 + assert (modified_model.vocab_size % 123) == 0 + # Check that the input embeddings size matches the tokenizer vocabulary size + assert model.vocab_size == len(modified_tokenizer.vocab) + + def test_clone_with_resize_and_extra_tokens_already_in_vocab(self): + # This tokenizer doesn't have a chat_template by default + tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-BloomForCausalLM") + model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-BloomForCausalLM") + # This one has a chat_template by default + source = "trl-internal-testing/tiny-Qwen3ForCausalLM" + # This will add , , ... to the tokenizer + modified_model, modified_tokenizer, _ = clone_chat_template( + model, tokenizer, source, resize_to_multiple_of=123 + ) + # Try if we can resize a tokenizer that already has extra these extra tokens + modified_model, modified_tokenizer, _ = clone_chat_template( + modified_model, modified_tokenizer, source, resize_to_multiple_of=124 + ) + + # Check that the input embeddings have been resized to a multiple of 123 + assert (modified_model.vocab_size % 124) == 0 + # Check that the input embeddings size matches the tokenizer vocabulary size + assert model.vocab_size == len(modified_tokenizer.vocab) + + def test_apply_new_chat_template(self): + # This tokenizer doesn't have a chat_template by default + tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-BloomForCausalLM") + model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-BloomForCausalLM") + # This one has a chat_template by default + source = "trl-internal-testing/tiny-Qwen3ForCausalLM" + _, modified_tokenizer, _ = clone_chat_template(model, tokenizer, source) + messages = [ + {"role": "system", "content": "You are helpful"}, + {"role": "user", "content": "Hello"}, + {"role": "assistant", "content": "Hi, how can I help you?"}, + ] + prompt = modified_tokenizer.apply_chat_template(messages, tokenize=False) + + assert ( + prompt + == "<|im_start|>system\nYou are helpful<|im_end|>\n<|im_start|>user\nHello<|im_end|>\n<|im_start|>assistant\n\n\n\n\nHi, how can I help you?<|im_end|>\n" + ) + + def test_clone_with_sequence_classification_model(self): + # This tokenizer doesn't have a chat_template by default + tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-GptNeoXForSequenceClassification") + model = AutoModelForSequenceClassification.from_pretrained( + "trl-internal-testing/tiny-GptNeoXForSequenceClassification" + ) + # This one has a chat_template by default + source = "trl-internal-testing/tiny-Qwen3ForCausalLM" + _, modified_tokenizer, _ = clone_chat_template(model, tokenizer, source) + + # Check if special tokens are correctly set + assert modified_tokenizer.eos_token == "<|im_end|>" + + +@pytest.mark.xfail( + condition=Version(transformers.__version__) < Version("5.0.0"), + reason="Response parsing is not supported in transformers versions below 5.0.0", + strict=True, +) +@require_jmespath +class TestAddResponseSchema: + @pytest.mark.parametrize( + "tokenizer_name", + [ + pytest.param("trl-internal-testing/tiny-Glm4MoeForCausalLM", id="glm4moe"), + pytest.param( + "trl-internal-testing/tiny-GptOssForCausalLM", + id="gptoss", + marks=pytest.mark.xfail( + Version(transformers.__version__) < Version("5.5.0"), + reason="Upstream bug in response parsing (see #5753; fixed in transformers#45166)", + strict=True, + ), + ), + pytest.param("trl-internal-testing/tiny-LlamaForCausalLM-3.1", id="llama3.1"), + pytest.param("trl-internal-testing/tiny-LlamaForCausalLM-3.2", id="llama3.2"), + pytest.param( + "trl-internal-testing/tiny-NemotronHForCausalLM-nano", + id="nemotron_3_nano", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.3.0"), + reason="Nemotron 3 tokenizer requires transformers>=5.3.0", + ), + ), + pytest.param( + "trl-internal-testing/tiny-NemotronHForCausalLM-super", + id="nemotron_3_super", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.3.0"), + reason="Nemotron 3 tokenizer requires transformers>=5.3.0", + ), + ), + pytest.param( + "trl-internal-testing/tiny-NemotronHForCausalLM-ultra", + id="nemotron_3_ultra", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.3.0"), + reason="Nemotron 3 tokenizer requires transformers>=5.3.0", + ), + ), + pytest.param("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", id="qwen2.5"), + pytest.param("trl-internal-testing/tiny-Qwen3MoeForCausalLM", id="qwen3"), + pytest.param("trl-internal-testing/tiny-Qwen3ForCausalLM-Instruct-2507", id="qwen3_instruct_2507"), + ], + ) + def test_add_response_schema(self, tokenizer_name): + tokenizer = AutoTokenizer.from_pretrained(tokenizer_name) + tokenizer = add_response_schema(tokenizer) + messages = [ + {"role": "user", "content": "What is 3*4?"}, + { + "role": "assistant", + "tool_calls": [{"type": "function", "function": {"name": "multiply", "arguments": {"a": 3, "b": 4}}}], + }, + ] + prefix = tokenizer.apply_chat_template(messages[:1], tokenize=False, add_generation_prompt=True) + text = tokenizer.apply_chat_template(messages, tokenize=False) + response = text[len(prefix) :] + # Here, we just test that the parsing doesn't raise an error. + # The correctness of the parsing is tested in TestParseResponse + tokenizer.parse_response(response) + + @pytest.mark.parametrize( + "processor_name", + [ + pytest.param("trl-internal-testing/tiny-Qwen3VLForConditionalGeneration", id="qwen3_vl"), + pytest.param("trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-NoThink", id="qwen35-nothink"), + pytest.param("trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-Think", id="qwen35-think"), + pytest.param("trl-internal-testing/tiny-Qwen3_5MoeForConditionalGeneration-3.6", id="qwen36"), + ], + ) + def test_add_response_schema_vlm(self, processor_name): + # For VLM processors, `add_response_schema` must set the schema on the inner tokenizer, since + # `parse_response` is a tokenizer method that reads `self.response_schema` from the tokenizer instance. + processor = AutoProcessor.from_pretrained(processor_name) + processor = add_response_schema(processor) + assert processor.tokenizer.response_schema is not None + messages = [ + {"role": "user", "content": [{"type": "text", "text": "What is 3*4?"}]}, + { + "role": "assistant", + # "content" is required here because VLM processors crash on tokenize=True without it + # (KeyError in processing_utils.py). See huggingface/transformers#45290. + "content": [{"type": "text", "text": ""}], + "tool_calls": [{"type": "function", "function": {"name": "multiply", "arguments": {"a": 3, "b": 4}}}], + }, + ] + prefix = processor.apply_chat_template(messages[:1], tokenize=False, add_generation_prompt=True) + text = processor.apply_chat_template(messages, tokenize=False) + response = text[len(prefix) :] + # Here, we just test that the parsing doesn't raise an error. + # The correctness of the parsing is tested in TestParseResponse + processor.tokenizer.parse_response(response) + + +class TestSupportsToolCalling: + @pytest.mark.parametrize( + "model_id", + [ + pytest.param("trl-internal-testing/tiny-DeepseekV3ForCausalLM", id="deepseekv3"), + pytest.param("trl-internal-testing/tiny-DeepseekV3ForCausalLM-0528", id="deepseekv3-0528"), + pytest.param( + "trl-internal-testing/tiny-Gemma4ForConditionalGeneration", + id="gemma4", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.5.0"), + reason="Gemma4 models were introduced in transformers-5.5.0", + ), + ), + pytest.param( + "trl-internal-testing/tiny-Glm4MoeForCausalLM", + id="glm4moe", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.0.0"), + reason="GLM4 tokenizer requires transformers>=5.0.0", + ), + ), + pytest.param("trl-internal-testing/tiny-GptOssForCausalLM", id="gptoss"), + pytest.param("trl-internal-testing/tiny-LlamaForCausalLM-3.1", id="llama3.1"), + pytest.param("trl-internal-testing/tiny-LlamaForCausalLM-3.2", id="llama3.2"), + pytest.param( + "trl-internal-testing/tiny-NemotronHForCausalLM-nano", + id="nemotron_3_nano", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.3.0"), + reason="Nemotron 3 tokenizer requires transformers>=5.3.0", + ), + ), + pytest.param( + "trl-internal-testing/tiny-NemotronHForCausalLM-super", + id="nemotron_3_super", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.3.0"), + reason="Nemotron 3 tokenizer requires transformers>=5.3.0", + ), + ), + pytest.param( + "trl-internal-testing/tiny-NemotronHForCausalLM-ultra", + id="nemotron_3_ultra", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.3.0"), + reason="Nemotron 3 tokenizer requires transformers>=5.3.0", + ), + ), + pytest.param("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", id="qwen2.5"), + pytest.param("trl-internal-testing/tiny-Qwen3ForCausalLM", id="qwen3"), + pytest.param("trl-internal-testing/tiny-Qwen3ForCausalLM-Instruct-2507", id="qwen3_instruct_2507"), + pytest.param("trl-internal-testing/tiny-Qwen3MoeForCausalLM", id="qwen3moe"), + pytest.param( + "trl-internal-testing/tiny-Qwen3VLForConditionalGeneration", + id="qwen3_vl", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("4.57.0"), + reason="Qwen3-VL was introduced in transformers-4.57.0", + ), + ), + pytest.param( + "trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-NoThink", + id="qwen35-nothink", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.0.0"), + reason="Qwen3.5 tokenizer requires transformers>=5.0.0", + ), + ), + pytest.param( + "trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-Think", + id="qwen35-think", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.0.0"), + reason="Qwen3.5 tokenizer requires transformers>=5.0.0", + ), + ), + pytest.param( + "trl-internal-testing/tiny-Qwen3_5MoeForConditionalGeneration-3.6", + id="qwen36", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.0.0"), + reason="Qwen3.5 tokenizer requires transformers>=5.0.0", + ), + ), + ], + ) + def test_supports_tool_calling(self, model_id): + tokenizer = AutoTokenizer.from_pretrained(model_id) + assert supports_tool_calling(tokenizer) is True + + @pytest.mark.parametrize( + "model_id", + [ + # No chat template + pytest.param("trl-internal-testing/tiny-BartModel", id="bart"), + pytest.param("trl-internal-testing/tiny-BloomForCausalLM", id="bloom"), + pytest.param("trl-internal-testing/tiny-GPT2LMHeadModel", id="gpt2"), + pytest.param("trl-internal-testing/tiny-GPTNeoXForCausalLM", id="gptneox"), + pytest.param("trl-internal-testing/tiny-GptNeoXForSequenceClassification", id="gptneox-seq"), + pytest.param("trl-internal-testing/tiny-OPTForCausalLM", id="opt"), + pytest.param("trl-internal-testing/tiny-T5ForConditionalGeneration", id="t5"), + # TemplateError: rejects tool role sequence + pytest.param("trl-internal-testing/tiny-CohereForCausalLM", id="cohere"), + pytest.param("trl-internal-testing/tiny-FalconMambaForCausalLM", id="falconmamba"), + pytest.param("trl-internal-testing/tiny-GemmaForCausalLM", id="gemma"), + pytest.param("trl-internal-testing/tiny-Gemma2ForCausalLM", id="gemma2"), + pytest.param("trl-internal-testing/tiny-Gemma3ForConditionalGeneration", id="gemma3"), + pytest.param("trl-internal-testing/tiny-Idefics2ForConditionalGeneration", id="idefics2"), + pytest.param("trl-internal-testing/tiny-Idefics3ForConditionalGeneration", id="idefics3"), + pytest.param("trl-internal-testing/tiny-LlavaNextForConditionalGeneration", id="llava_next"), + pytest.param("trl-internal-testing/tiny-MistralForCausalLM-0.1", id="mistral0.1"), + pytest.param("trl-internal-testing/tiny-MistralForCausalLM-0.2", id="mistral0.2"), + pytest.param("trl-internal-testing/tiny-SmolVLMForConditionalGeneration", id="smolvlm"), + # Silently drops both tool_calls and tool messages + pytest.param("trl-internal-testing/tiny-Cohere2ForCausalLM", id="cohere2"), + pytest.param("trl-internal-testing/tiny-LlavaForConditionalGeneration", id="llava"), + # Olmo3 uses a bespoke function-calling schema (a `functions`/`function_calls` string on the + # message plus an `environment` role) instead of the standard `tools`/`tool_calls`/`tool` + # interface, so a standard tool-calling conversation is silently dropped. + pytest.param( + "trl-internal-testing/tiny-Olmo3ForCausalLM", + id="olmo3", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("4.57.0"), + reason="Olmo 3 was introduced in transformers>=4.57.0", + ), + ), + pytest.param("trl-internal-testing/tiny-Phi3ForCausalLM-3", id="phi3"), + pytest.param("trl-internal-testing/tiny-Phi3ForCausalLM-3.5", id="phi3.5"), + # Renders tool message content as plain text but drops assistant tool_calls + pytest.param("trl-internal-testing/tiny-LlamaForCausalLM-3", id="llama3"), + pytest.param("trl-internal-testing/tiny-Qwen2VLForConditionalGeneration", id="qwen2_vl"), + pytest.param("trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration", id="qwen2.5_vl"), + ], + ) + def test_does_not_support_tool_calling(self, model_id): + tokenizer = AutoTokenizer.from_pretrained(model_id) + assert supports_tool_calling(tokenizer) is False + + +class TestIsChatTemplatePrefixPreserving: + def test_prefix_preserving_template(self): + tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen3MoeForCausalLM") + # docstyle-ignore + tokenizer.chat_template = textwrap.dedent(r""" + {%- for message in messages %} + + {%- if message.role == 'user' %} + {{- '<|im_start|>user\n' + message.content + '<|im_end|>\n' }} + {%- elif message.role == 'assistant' %} + {{- '<|im_start|>assistant\n' + message.content }} + {%- if message.tool_calls %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '' + tool_call.name + '' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == 'tool' %} + {{- '<|im_start|>tool\n' + message.content + '<|im_end|>\n' }} + {%- endif %} + + {%- endfor %} + + {%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} + {%- endif %}""") + assert is_chat_template_prefix_preserving(tokenizer) is True + + def test_non_prefix_preserving_template(self): + tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen3MoeForCausalLM") + # The following template is quite typical of models like Qwen3 and GPT-OSS, where the thinking part (even + # empty) is only present for last assistant message, which makes it non-prefix-preserving: appending a tool + # message changes the earlier output. + # docstyle-ignore + tokenizer.chat_template = textwrap.dedent(r""" + {%- if messages[0].role == 'system' %} + {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }} + {%- endif %} + {%- set ns = namespace(last_query_index=messages|length - 1) %} + {%- for message in messages[::-1] %} + {%- set index = (messages|length - 1) - loop.index0 %} + {%- if message.role == "user" and message.content is string %} + {%- set ns.last_query_index = index %} + {%- break %} + {%- endif %} + {%- endfor %} + {%- for message in messages %} + {%- set content = message.content if message.content is string else '' %} + {%- if message.role == "user" or (message.role == "system" and not loop.first) %} + {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>\n' }} + {%- elif message.role == "assistant" %} + {%- set reasoning_content = '' %} + {%- if message.reasoning_content is string %} + {%- set reasoning_content = message.reasoning_content %} + {%- else %} + {%- if '' in content %} + {%- set reasoning_content = content.split('')[0].rstrip('\n').split('')[-1].lstrip('\n') %} + {%- set content = content.split('')[-1].lstrip('\n') %} + {%- endif %} + {%- endif %} + {%- if loop.index0 > ns.last_query_index %} + {%- if loop.last or (not loop.last and reasoning_content) %} + {{- '<|im_start|>' + message.role + '\n\n' + reasoning_content.strip('\n') + '\n\n\n' + content.lstrip('\n') }} + {%- else %} + {{- '<|im_start|>' + message.role + '\n' + content }} + {%- endif %} + {%- else %} + {{- '<|im_start|>' + message.role + '\n' + content }} + {%- endif %} + {%- if message.tool_calls %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '' + tool_call.name + '' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {{- '<|im_start|>tool\n' + content + '<|im_end|>\n' }} + {%- endif %} + {%- endfor %} + {%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} + {%- if enable_thinking is defined and enable_thinking is false %} + {{- '\n\n\n\n' }} + {%- endif %} + {%- endif %}""") + assert is_chat_template_prefix_preserving(tokenizer) is False + + @require_vision + def test_prefix_preserving_template_processor(self): + processor = AutoProcessor.from_pretrained("trl-internal-testing/tiny-Qwen3VLForConditionalGeneration") + # Simple prefix-preserving template that mirrors how Qwen-VL templates emit image tokens: a list-of-blocks + # content is iterated, and `{"type": "image"}` blocks are rendered as `<|vision_start|><|image_pad|><|vision_end|>`. + # docstyle-ignore + processor.chat_template = textwrap.dedent(r""" + {%- for message in messages %} + + {%- if message.role == 'user' %} + {{- '<|im_start|>user\n' }} + {%- if message.content is string %} + {{- message.content }} + {%- else %} + {%- for content in message.content %} + {%- if content.type == 'image' or 'image' in content %} + {{- '<|vision_start|><|image_pad|><|vision_end|>' }} + {%- elif 'text' in content %} + {{- content.text }} + {%- endif %} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == 'assistant' %} + {{- '<|im_start|>assistant\n' }} + {%- if message.content is string %} + {{- message.content }} + {%- else %} + {%- for content in message.content %} + {%- if 'text' in content %} + {{- content.text }} + {%- endif %} + {%- endfor %} + {%- endif %} + {%- if message.tool_calls %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '' + tool_call.name + '' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == 'tool' %} + {{- '<|im_start|>tool\n' }} + {%- if message.content is string %} + {{- message.content }} + {%- else %} + {%- for content in message.content %} + {%- if 'text' in content %} + {{- content.text }} + {%- endif %} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- endif %} + + {%- endfor %} + + {%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} + {%- endif %}""") + assert is_chat_template_prefix_preserving(processor) is True + + +class TestIsChatTemplateStopTokenTrained: + def test_stop_token_trained(self): + tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen3MoeForCausalLM") + # The assistant turn is closed by <|im_end|> inside the generation span, so the end-of-turn token is masked + # in and the model is trained to stop. + # docstyle-ignore + tokenizer.chat_template = textwrap.dedent(r""" + {%- for message in messages %} + {%- if message.role == 'user' %} + {{- '<|im_start|>user\n' + message.content + '<|im_end|>\n' }} + {%- elif message.role == 'assistant' %} + {{- '<|im_start|>assistant\n' }} + {%- generation %}{{- message.content + '<|im_end|>' }}{%- endgeneration %} + {{- '\n' }} + {%- endif %} + {%- endfor %} + {%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} + {%- endif %}""") + assert is_chat_template_stop_token_trained(tokenizer) is True + + def test_stop_token_not_trained(self): + tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen3MoeForCausalLM") + # GLM-style: the assistant's end-of-turn token is emitted as the prefix of the following message, so the + # generation span covers content only and the model is never trained to stop. + # docstyle-ignore + tokenizer.chat_template = textwrap.dedent(r""" + {%- for message in messages %} + {%- if message.role == 'user' %} + {{- '<|im_start|>user\n' + message.content + '<|im_end|>\n' }} + {%- elif message.role == 'assistant' %} + {{- '<|im_start|>assistant\n' }} + {%- generation %}{{- message.content }}{%- endgeneration %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- endfor %} + {%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} + {%- endif %}""") + assert is_chat_template_stop_token_trained(tokenizer) is False + + def test_template_error_returns_false(self): + tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen3MoeForCausalLM") + tokenizer.chat_template = "{{ raise_exception('probe rejected') }}" + assert is_chat_template_stop_token_trained(tokenizer) is False + + +@pytest.mark.parametrize( + "tokenizer_name", + [ + pytest.param("trl-internal-testing/tiny-CohereForCausalLM", id="cohere"), + pytest.param("trl-internal-testing/tiny-Cohere2ForCausalLM", id="cohere2"), + pytest.param("trl-internal-testing/tiny-DeepseekV3ForCausalLM", id="deepseekv3"), + pytest.param("trl-internal-testing/tiny-GemmaForCausalLM", id="gemma"), + pytest.param("trl-internal-testing/tiny-Gemma2ForCausalLM", id="gemma2"), + pytest.param("trl-internal-testing/tiny-Gemma3ForConditionalGeneration", id="gemma3", marks=require_vision), + pytest.param( + "trl-internal-testing/tiny-Glm4MoeForCausalLM", + id="glm4moe", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.0.0"), + reason="GLM4 tokenizer requires transformers>=5.0.0", + ), + ), + pytest.param("trl-internal-testing/tiny-GptOssForCausalLM", id="gptoss"), + pytest.param("trl-internal-testing/tiny-LlamaForCausalLM-3", id="llama3"), + pytest.param("trl-internal-testing/tiny-LlavaForConditionalGeneration", id="llava", marks=require_vision), + pytest.param( + "trl-internal-testing/tiny-LlavaNextForConditionalGeneration", id="llava_next", marks=require_vision + ), + pytest.param( + "trl-internal-testing/tiny-NemotronHForCausalLM-nano", + id="nemotron_3_nano", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.3.0"), + reason="Nemotron 3 tokenizer requires transformers>=5.3.0", + ), + ), + pytest.param( + "trl-internal-testing/tiny-NemotronHForCausalLM-super", + id="nemotron_3_super", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.3.0"), + reason="Nemotron 3 tokenizer requires transformers>=5.3.0", + ), + ), + pytest.param( + "trl-internal-testing/tiny-NemotronHForCausalLM-ultra", + id="nemotron_3_ultra", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.3.0"), + reason="Nemotron 3 tokenizer requires transformers>=5.3.0", + ), + ), + pytest.param("trl-internal-testing/tiny-Phi3ForCausalLM-3", id="phi3"), + pytest.param("trl-internal-testing/tiny-Phi3ForCausalLM-3.5", id="phi3.5"), + pytest.param("trl-internal-testing/tiny-Qwen2VLForConditionalGeneration", id="qwen2_vl", marks=require_vision), + pytest.param("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", id="qwen2.5"), + pytest.param( + "trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration", id="qwen2.5_vl", marks=require_vision + ), + pytest.param("trl-internal-testing/tiny-Qwen3MoeForCausalLM", id="qwen3"), + pytest.param("trl-internal-testing/tiny-Qwen3ForCausalLM-Instruct-2507", id="qwen3_instruct_2507"), + pytest.param( + "trl-internal-testing/tiny-Qwen3VLForConditionalGeneration", + id="qwen3_vl", + marks=[ + require_vision, + pytest.mark.skipif( + Version(transformers.__version__) < Version("4.57.0"), + reason="Qwen3-VL was introduced in transformers-4.57.0", + ), + ], + ), + pytest.param( + "trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-NoThink", + id="qwen35-nothink", + marks=[ + require_vision, + pytest.mark.skipif( + Version(transformers.__version__) < Version("5.0.0"), + reason="Qwen3.5 tokenizer requires transformers>=5.0.0", + ), + ], + ), + pytest.param( + "trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-Think", + id="qwen35-think", + marks=[ + require_vision, + pytest.mark.skipif( + Version(transformers.__version__) < Version("5.0.0"), + reason="Qwen3.5 tokenizer requires transformers>=5.0.0", + ), + ], + ), + pytest.param( + "trl-internal-testing/tiny-Qwen3_5MoeForConditionalGeneration-3.6", + id="qwen36", + marks=[ + require_vision, + pytest.mark.skipif( + Version(transformers.__version__) < Version("5.0.0"), + reason="Qwen3.5 tokenizer requires transformers>=5.0.0", + ), + ], + ), + ], +) +class TestGetTrainingChatTemplate: + def _load(self, model_name): + if "ForCausalLM" in model_name: + self.is_vlm = False + processing_class = AutoTokenizer.from_pretrained(model_name) + elif "ForConditionalGeneration" in model_name: + self.is_vlm = True + processing_class = AutoProcessor.from_pretrained(model_name) + + return processing_class + + def test_new_chat_template_is_prefix_preserving(self, tokenizer_name): + tokenizer = self._load(tokenizer_name) + new_chat_template = get_training_chat_template(tokenizer) + if new_chat_template is not None: + tokenizer.chat_template = new_chat_template + # Prefix-preservation is only meaningful for templates that actually support tool messages — the check + # itself renders one. Skip the assertion for tool-less templates (e.g. Gemma). + if not supports_tool_calling(tokenizer): + pytest.skip("Template does not support tool calling; prefix-preservation check is not applicable.") + assert is_chat_template_prefix_preserving(tokenizer) is True + + def test_new_chat_template_trains_stop_token(self, tokenizer_name, request): + if tokenizer_name in ( + "trl-internal-testing/tiny-LlavaForConditionalGeneration", + "trl-internal-testing/tiny-LlavaNextForConditionalGeneration", + ): + reason = f"{tokenizer_name}: the processor returns an all-zero assistant tokens mask" + request.node.add_marker(pytest.mark.xfail(strict=False, reason=reason)) + tokenizer = self._load(tokenizer_name) + new_chat_template = get_training_chat_template(tokenizer) + assert is_chat_template_stop_token_trained(tokenizer, chat_template=new_chat_template) is True + + def test_behavior_unchanged_single_user_no_generation_prompt(self, tokenizer_name): + tokenizer = self._load(tokenizer_name) + messages = [{"role": "user", "content": "What color is the sky?"}] + if self.is_vlm: + messages = prepare_multimodal_messages(messages) + + before = tokenizer.apply_chat_template(messages, tokenize=False) + new_chat_template = get_training_chat_template(tokenizer) + after = tokenizer.apply_chat_template(messages, tokenize=False, chat_template=new_chat_template) + assert before == after + + def test_behavior_unchanged_single_user_with_generation_prompt(self, tokenizer_name): + tokenizer = self._load(tokenizer_name) + messages = [{"role": "user", "content": "What color is the sky?"}] + if self.is_vlm: + messages = prepare_multimodal_messages(messages) + + before = tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=False) + new_chat_template = get_training_chat_template(tokenizer) + after = tokenizer.apply_chat_template( + messages, + tokenize=False, + add_generation_prompt=True, + chat_template=new_chat_template, + ) + assert before == after + + def test_behavior_unchanged_single_user_and_final_assistant_plain_content(self, tokenizer_name): + tokenizer = self._load(tokenizer_name) + messages = [ + {"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is blue."}, + ] + if self.is_vlm: + messages = prepare_multimodal_messages(messages) + + before = tokenizer.apply_chat_template(messages, tokenize=False) + new_chat_template = get_training_chat_template(tokenizer) + after = tokenizer.apply_chat_template(messages, tokenize=False, chat_template=new_chat_template) + if tokenizer_name == "trl-internal-testing/tiny-Glm4MoeForCausalLM": + # GLM's native template doesn't terminate an assistant turn with an end-of-turn token; the turn is ended + # by the following message's role marker. The training template appends that terminator to the final + # assistant turn so the stop token is trained — here the `<|user|>` that would open the next turn. + assert after == before + "<|user|>" + else: + assert before == after + + def test_behavior_unchanged_final_assistant_with_reasoning_content(self, tokenizer_name): + tokenizer = self._load(tokenizer_name) + messages = [ + {"role": "user", "content": "What color is the sky?"}, + { + "role": "assistant", + "content": "It is blue.", + "reasoning_content": "The sky appears blue due to Rayleigh scattering.", + }, + ] + if self.is_vlm: + messages = prepare_multimodal_messages(messages) + + before = tokenizer.apply_chat_template(messages, tokenize=False) + new_chat_template = get_training_chat_template(tokenizer) + after = tokenizer.apply_chat_template(messages, tokenize=False, chat_template=new_chat_template) + if tokenizer_name == "trl-internal-testing/tiny-Glm4MoeForCausalLM": + # GLM's native template doesn't terminate an assistant turn with an end-of-turn token; the turn is ended + # by the following message's role marker. The training template appends that terminator to the final + # assistant turn so the stop token is trained — here the `<|user|>` that would open the next turn. + assert after == before + "<|user|>" + else: + assert before == after + + def test_behavior_unchanged_final_assistant_with_existing_think_tags(self, tokenizer_name): + tokenizer = self._load(tokenizer_name) + messages = [ + {"role": "user", "content": "What color is the sky?"}, + { + "role": "assistant", + "content": "\nThe sky scatters shorter wavelengths.\n\n\nIt is blue.", + }, + ] + if self.is_vlm: + messages = prepare_multimodal_messages(messages) + + before = tokenizer.apply_chat_template(messages, tokenize=False) + new_chat_template = get_training_chat_template(tokenizer) + after = tokenizer.apply_chat_template(messages, tokenize=False, chat_template=new_chat_template) + if tokenizer_name == "trl-internal-testing/tiny-Glm4MoeForCausalLM": + # GLM's native template doesn't terminate an assistant turn with an end-of-turn token; the turn is ended + # by the following message's role marker. The training template appends that terminator to the final + # assistant turn so the stop token is trained — here the `<|user|>` that would open the next turn. + assert after == before + "<|user|>" + else: + assert before == after + + def test_behavior_unchanged_assistant_with_tool_calls(self, tokenizer_name): + tokenizer = self._load(tokenizer_name) + tool_calls = [{"type": "function", "function": {"name": "multiply", "arguments": {"a": 3, "b": 4}}}] + messages = [ + {"role": "user", "content": "Multiply 3 by 4."}, + {"role": "assistant", "content": "I will call a tool.", "tool_calls": tool_calls}, + ] + if self.is_vlm: + messages = prepare_multimodal_messages(messages) + + messages_before = copy.deepcopy(messages) + if tokenizer_name == "trl-internal-testing/tiny-DeepseekV3ForCausalLM": + # Best-effort fallback for templates that reject dict args (e.g. DeepSeek-V3). This is a chat template + # bug (see transformers#45419), and the training chat template fixes it to avoid blocking users. + messages_before[1]["tool_calls"][0]["function"]["arguments"] = '{"a": 3, "b": 4}' + + before = tokenizer.apply_chat_template(messages_before, tokenize=False) + new_chat_template = get_training_chat_template(tokenizer) + after = tokenizer.apply_chat_template(messages, tokenize=False, chat_template=new_chat_template) + if tokenizer_name == "trl-internal-testing/tiny-Glm4MoeForCausalLM": + # GLM's native template doesn't terminate an assistant turn with an end-of-turn token; the turn is ended + # by the following message's role marker. The training template appends that terminator to the final + # assistant turn so the stop token is trained — here `<|observation|>`, which closes a tool call. + assert after == before + "<|observation|>" + else: + assert before == after + + def test_behavior_unchanged_with_tools_with_and_without_system_message(self, tokenizer_name): + tokenizer = self._load(tokenizer_name) + tools = [ + { + "type": "function", + "function": { + "name": "multiply", + "description": "Multiply two numbers.", + "parameters": { + "type": "object", + "properties": { + "a": {"type": "number"}, + "b": {"type": "number"}, + }, + "required": ["a", "b"], + }, + }, + } + ] + messages = [{"role": "user", "content": "Multiply 3 by 4."}] + if self.is_vlm: + messages = prepare_multimodal_messages(messages) + + before = tokenizer.apply_chat_template(messages, tokenize=False, tools=tools) + new_chat_template = get_training_chat_template(tokenizer) + after = tokenizer.apply_chat_template(messages, tokenize=False, tools=tools, chat_template=new_chat_template) + assert before == after + + def test_behavior_unchanged_with_tools_with_system_message(self, tokenizer_name): + tokenizer = self._load(tokenizer_name) + if not supports_tool_calling(tokenizer): + pytest.skip("Template does not support tool calling; skipping tool_calls test.") + tools = [ + { + "type": "function", + "function": { + "name": "multiply", + "description": "Multiply two numbers.", + "parameters": { + "type": "object", + "properties": {"a": {"type": "number"}, "b": {"type": "number"}}, + "required": ["a", "b"], + }, + }, + } + ] + messages = [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Multiply 3 by 4."}, + ] + if self.is_vlm: + messages = prepare_multimodal_messages(messages) + + before = tokenizer.apply_chat_template(messages, tokenize=False, tools=tools) + new_chat_template = get_training_chat_template(tokenizer) + after = tokenizer.apply_chat_template(messages, tokenize=False, tools=tools, chat_template=new_chat_template) + assert before == after + + def test_behavior_unchanged_generation_prompt_with_enable_thinking_false(self, tokenizer_name): + tokenizer = self._load(tokenizer_name) + messages = [{"role": "user", "content": "What color is the sky?"}] + if self.is_vlm: + messages = prepare_multimodal_messages(messages) + + before = tokenizer.apply_chat_template( + messages, tokenize=False, add_generation_prompt=True, enable_thinking=False + ) + new_chat_template = get_training_chat_template(tokenizer) + after = tokenizer.apply_chat_template( + messages, + tokenize=False, + add_generation_prompt=True, + enable_thinking=False, + chat_template=new_chat_template, + ) + assert before == after + + def test_assistant_masks(self, tokenizer_name, request): + if tokenizer_name == "trl-internal-testing/tiny-LlavaForConditionalGeneration": + request.node.add_marker( + pytest.mark.xfail( + reason="Llava's official chat template `{% generation %}` markers don't yield assistant masks " + "through the processor path. It is not a supported training template.", + strict=True, + ) + ) + tokenizer = self._load(tokenizer_name) + messages = [ + {"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is blue."}, + ] + if self.is_vlm: + messages = prepare_multimodal_messages(messages) + + chat_template = get_training_chat_template(tokenizer) + result = tokenizer.apply_chat_template( + messages, chat_template=chat_template, return_assistant_tokens_mask=True, return_dict=True, tokenize=True + ) + masks = result["assistant_masks"] + if self.is_vlm: # VLM processors return batched output + masks = masks[0] + assert 1 in masks + # The first tokens (user turn) should not be masked + assert masks[0] == 0 + # The last tokens (assistant turn ending with <|im_end|>) should be masked + assert masks[-1] == 1 + + def test_assistant_masks_multi_turn(self, tokenizer_name, request): + if tokenizer_name == "trl-internal-testing/tiny-LlavaForConditionalGeneration": + request.node.add_marker( + pytest.mark.xfail( + reason="Llava's official chat template `{% generation %}` markers don't yield assistant masks " + "through the processor path. It is not a supported training template.", + strict=True, + ) + ) + tokenizer = self._load(tokenizer_name) + messages = [ + {"role": "user", "content": "Hi"}, + {"role": "assistant", "content": "Hello!"}, + {"role": "user", "content": "Bye"}, + {"role": "assistant", "content": "Goodbye!"}, + ] + if self.is_vlm: + messages = prepare_multimodal_messages(messages) + + chat_template = get_training_chat_template(tokenizer) + result = tokenizer.apply_chat_template( + messages, chat_template=chat_template, return_assistant_tokens_mask=True, return_dict=True, tokenize=True + ) + masks = result["assistant_masks"] + if self.is_vlm: # VLM processors return batched output + masks = masks[0] + # Should have two masked regions (two assistant turns): 0→1, 1→0, 0→1 + transitions = sum(1 for i in range(1, len(masks)) if masks[i] != masks[i - 1]) + assert transitions == 3 + + +@pytest.mark.parametrize( + "model_name", + [ + pytest.param("trl-internal-testing/tiny-Glm4MoeForCausalLM", id="glm4moe"), + pytest.param("trl-internal-testing/tiny-GptOssForCausalLM", id="gptoss"), + pytest.param("trl-internal-testing/tiny-LlamaForCausalLM-3.1", id="llama3.1"), + pytest.param("trl-internal-testing/tiny-LlamaForCausalLM-3.2", id="llama3.2"), + pytest.param( + "trl-internal-testing/tiny-NemotronHForCausalLM-nano", + id="nemotron_3_nano", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.3.0"), + reason="Nemotron 3 tokenizer requires transformers>=5.3.0", + ), + ), + pytest.param( + "trl-internal-testing/tiny-NemotronHForCausalLM-super", + id="nemotron_3_super", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.3.0"), + reason="Nemotron 3 tokenizer requires transformers>=5.3.0", + ), + ), + pytest.param( + "trl-internal-testing/tiny-NemotronHForCausalLM-ultra", + id="nemotron_3_ultra", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.3.0"), + reason="Nemotron 3 tokenizer requires transformers>=5.3.0", + ), + ), + pytest.param("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", id="qwen2.5"), + pytest.param("trl-internal-testing/tiny-Qwen3MoeForCausalLM", id="qwen3"), + pytest.param("trl-internal-testing/tiny-Qwen3ForCausalLM-Instruct-2507", id="qwen3_instruct_2507"), + pytest.param("trl-internal-testing/tiny-Qwen3VLForConditionalGeneration", id="qwen3_vl"), + pytest.param("trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-NoThink", id="qwen35-nothink"), + pytest.param("trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-Think", id="qwen35-think"), + pytest.param("trl-internal-testing/tiny-Qwen3_5MoeForConditionalGeneration-3.6", id="qwen36"), + pytest.param( + "trl-internal-testing/tiny-Gemma4ForConditionalGeneration", + id="gemma4", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.5.0"), + reason="Gemma4 models were introduced in transformers-5.5.0", + ), + ), + ], +) +@pytest.mark.xfail( + condition=Version(transformers.__version__) < Version("5.0.0"), + reason="Response parsing is not supported in transformers versions below 5.0.0", + strict=True, +) +@require_jmespath +class TestParseResponse: + def _load(self, model_name): + if "ForCausalLM" in model_name: + self.is_vlm = False + processing_class = AutoTokenizer.from_pretrained(model_name) + response_schema = getattr(processing_class, "response_schema", None) + elif "ForConditionalGeneration" in model_name: + self.is_vlm = True + processing_class = AutoProcessor.from_pretrained(model_name) + response_schema = getattr(processing_class.tokenizer, "response_schema", None) + + if response_schema is None: + processing_class = add_response_schema(processing_class) + + return processing_class + + def test_parse_response(self, model_name): + if model_name in ("trl-internal-testing/tiny-GptOssForCausalLM",) and Version( + transformers.__version__ + ) < Version("5.5.0"): + pytest.skip("Upstream bug in response parsing (see #5753; fixed in transformers#45166)") + processing_class = self._load(model_name) + messages = [ + {"role": "user", "content": "What is 3*4?"}, + {"role": "assistant", "content": "12"}, + ] + expected = messages[-1] + messages = prepare_multimodal_messages(messages) if self.is_vlm else messages + prefix = processing_class.apply_chat_template( + messages[:1], add_generation_prompt=True, tokenize=True, return_dict=True + ).input_ids + text = processing_class.apply_chat_template(messages, tokenize=True, return_dict=True).input_ids + if self.is_vlm: # VLM processors return batched output + prefix = prefix[0] + text = text[0] + response = text[len(prefix) :] + tokenizer = processing_class.tokenizer if self.is_vlm else processing_class + parsed = parse_response(tokenizer, response) + assert parsed == expected + + def test_parse_response_with_reasoning_content(self, model_name): + if model_name in ( + "trl-internal-testing/tiny-Gemma4ForConditionalGeneration", + "trl-internal-testing/tiny-GptOssForCausalLM", + "trl-internal-testing/tiny-LlamaForCausalLM-3.1", + "trl-internal-testing/tiny-LlamaForCausalLM-3.2", + "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + "trl-internal-testing/tiny-Qwen3ForCausalLM-Instruct-2507", + "trl-internal-testing/tiny-Qwen3VLForConditionalGeneration", + ): + pytest.skip("This tokenizer doesn't support inline reasoning_content.") + + processing_class = self._load(model_name) + messages = [ + {"role": "user", "content": "What is 3*4?"}, + {"role": "assistant", "reasoning_content": "Hmmm.", "content": "12"}, + ] + expected = messages[-1] + messages = prepare_multimodal_messages(messages) if self.is_vlm else messages + # enable_thinking=True is required here because the Qwen3.5 NoThink fixture disables thinking by default + # for the generation prompt. + prefix = processing_class.apply_chat_template( + messages[:1], add_generation_prompt=True, enable_thinking=True, tokenize=True, return_dict=True + ).input_ids + text = processing_class.apply_chat_template(messages, tokenize=True, return_dict=True).input_ids + if self.is_vlm: # VLM processors return batched output + prefix = prefix[0] + text = text[0] + response = text[len(prefix) :] + tokenizer = processing_class.tokenizer if self.is_vlm else processing_class + parsed = parse_response(tokenizer, response) + assert parsed == expected + + def test_parse_response_tool_call(self, model_name): + if model_name in ( + "trl-internal-testing/tiny-GptOssForCausalLM", + "trl-internal-testing/tiny-LlamaForCausalLM-3.1", + "trl-internal-testing/tiny-LlamaForCausalLM-3.2", + ) and Version(transformers.__version__) < Version("5.5.0"): + pytest.skip("Upstream bug in response parsing (see #5753; fixed in transformers#45166)") + processing_class = self._load(model_name) + tool_calls = [{"type": "function", "function": {"name": "multiply", "arguments": {"a": 3, "b": 4}}}] + messages = [ + {"role": "user", "content": "What is 3*4?"}, + { + "role": "assistant", + # "content" is required here because VLM processors crash on tokenize=True without it + # (KeyError in processing_utils.py). See huggingface/transformers#45290. + "content": "", + "tool_calls": tool_calls, + }, + ] + expected = messages[-1] + messages = prepare_multimodal_messages(messages) if self.is_vlm else messages + prefix = processing_class.apply_chat_template( + messages[:1], add_generation_prompt=True, tokenize=True, return_dict=True + ).input_ids + text = processing_class.apply_chat_template(messages, tokenize=True, return_dict=True).input_ids + if self.is_vlm: # VLM processors return batched output + prefix = prefix[0] + text = text[0] + response = text[len(prefix) :] + tokenizer = processing_class.tokenizer if self.is_vlm else processing_class + parsed = parse_response(tokenizer, response) + assert parsed == expected + + def test_parse_response_tool_call_with_content(self, model_name): + if model_name in ( + "trl-internal-testing/tiny-LlamaForCausalLM-3.1", + "trl-internal-testing/tiny-LlamaForCausalLM-3.2", + ): + pytest.skip("Llama 3.1 / 3.2 templates only allow a single tool call per assistant turn, with no content.") + if model_name in ("trl-internal-testing/tiny-GptOssForCausalLM",) and Version( + transformers.__version__ + ) < Version("5.5.0"): + pytest.skip("Upstream bug in response parsing (see #5753; fixed in transformers#45166)") + processing_class = self._load(model_name) + tool_calls = [{"type": "function", "function": {"name": "multiply", "arguments": {"a": 3, "b": 4}}}] + messages = [ + {"role": "user", "content": "What is 3*4?"}, + {"role": "assistant", "content": "Let's call the tool.", "tool_calls": tool_calls}, + ] + expected = messages[-1] + messages = prepare_multimodal_messages(messages) if self.is_vlm else messages + prefix = processing_class.apply_chat_template( + messages[:1], add_generation_prompt=True, tokenize=True, return_dict=True + ).input_ids + text = processing_class.apply_chat_template(messages, tokenize=True, return_dict=True).input_ids + if self.is_vlm: # VLM processors return batched output + prefix = prefix[0] + text = text[0] + response = text[len(prefix) :] + tokenizer = processing_class.tokenizer if self.is_vlm else processing_class + parsed = parse_response(tokenizer, response) + assert parsed == expected + + def test_parse_response_tool_call_without_arguments(self, model_name): + if model_name in ("trl-internal-testing/tiny-GptOssForCausalLM",) and Version( + transformers.__version__ + ) < Version("5.5.0"): + pytest.skip("Upstream bug in response parsing (see #5753; fixed in transformers#45166)") + processing_class = self._load(model_name) + tool_calls = [{"type": "function", "function": {"name": "ping", "arguments": {}}}] + messages = [ + {"role": "user", "content": "Ping the service."}, + { + "role": "assistant", + # "content" is required here because VLM processors crash on tokenize=True without it + # (KeyError in processing_utils.py). See huggingface/transformers#45290. + "content": "", + "tool_calls": tool_calls, + }, + ] + expected = messages[-1] + messages = prepare_multimodal_messages(messages) if self.is_vlm else messages + prefix = processing_class.apply_chat_template( + messages[:1], add_generation_prompt=True, tokenize=True, return_dict=True + ).input_ids + text = processing_class.apply_chat_template(messages, tokenize=True, return_dict=True).input_ids + if self.is_vlm: # VLM processors return batched output + prefix = prefix[0] + text = text[0] + response = text[len(prefix) :] + tokenizer = processing_class.tokenizer if self.is_vlm else processing_class + parsed = parse_response(tokenizer, response) + assert parsed == expected + + def test_parse_response_multiple_tool_calls(self, model_name): + if model_name in ( + "trl-internal-testing/tiny-GptOssForCausalLM", + "trl-internal-testing/tiny-LlamaForCausalLM-3.1", + "trl-internal-testing/tiny-LlamaForCausalLM-3.2", + ): + pytest.skip("This template only renders one tool call per assistant message.") + processing_class = self._load(model_name) + tool_calls = [ + {"type": "function", "function": {"name": "multiply", "arguments": {"a": 3, "b": 4}}}, + {"type": "function", "function": {"name": "addition", "arguments": {"a": 4, "b": 3}}}, + ] + messages = [ + {"role": "user", "content": "What is 3*4?"}, + { + "role": "assistant", + # "content" is required here because VLM processors crash on tokenize=True without it + # (KeyError in processing_utils.py). See huggingface/transformers#45290. + "content": "", + "tool_calls": tool_calls, + }, + ] + expected = messages[-1] + messages = prepare_multimodal_messages(messages) if self.is_vlm else messages + prefix = processing_class.apply_chat_template( + messages[:1], add_generation_prompt=True, tokenize=True, return_dict=True + ).input_ids + text = processing_class.apply_chat_template(messages, tokenize=True, return_dict=True).input_ids + if self.is_vlm: # VLM processors return batched output + prefix = prefix[0] + text = text[0] + response = text[len(prefix) :] + tokenizer = processing_class.tokenizer if self.is_vlm else processing_class + parsed = parse_response(tokenizer, response) + assert parsed == expected + + def test_parse_response_malformed_tool_call(self, model_name): + if model_name != "trl-internal-testing/tiny-Qwen3MoeForCausalLM": + pytest.skip("For simplicity, we only test the malformed tool call case on one tokenizer.") + processing_class = self._load(model_name) + text = '\n{"name": "multiply", "arguments": {"a": 3, "b": 4}\n<|im_end|>' + assistant_text = processing_class(text)["input_ids"] + parsed = parse_response(processing_class, assistant_text) + expected = { + "role": "assistant", + "content": '\n{"name": "multiply", "arguments": {"a": 3, "b": 4}\n', + } + + assert parsed == expected + + def test_parse_response_truncated(self, model_name): + processing_class = self._load(model_name) + # Here we use 2 tool calls as it seems to be a more common source of failure when truncated. + # Llama 3.1 / 3.2 templates only allow a single tool call per assistant turn, so fall back to one. + tool_calls = [{"type": "function", "function": {"name": "multiply", "arguments": {"a": 3, "b": 4}}}] + if model_name not in ( + "trl-internal-testing/tiny-LlamaForCausalLM-3.1", + "trl-internal-testing/tiny-LlamaForCausalLM-3.2", + ): + tool_calls.append({"type": "function", "function": {"name": "addition", "arguments": {"a": 4, "b": 3}}}) + messages = [ + {"role": "user", "content": "What is 3*4?"}, + {"role": "assistant", "content": "", "tool_calls": tool_calls}, + ] + messages = prepare_multimodal_messages(messages) if self.is_vlm else messages + prefix = processing_class.apply_chat_template( + messages[:1], add_generation_prompt=True, tokenize=True, return_dict=True + ).input_ids + text = processing_class.apply_chat_template(messages, tokenize=True, return_dict=True).input_ids + if self.is_vlm: # VLM processors return batched output + prefix = prefix[0] + text = text[0] + response = text[len(prefix) :] + tokenizer = processing_class.tokenizer if self.is_vlm else processing_class + # Truncate the response mid-tool-call and just check that parsing doesn't crash. + for end in range(1, len(response)): + parse_response(tokenizer, response[:end]) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_cli.py b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..30c75cddca413fb9ffcace4d238a07ffcf7031ed --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_cli.py @@ -0,0 +1,140 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +from io import StringIO +from unittest.mock import patch + +import pytest +import yaml + +from .testing_utils import TrlTestCase + + +@pytest.mark.parametrize("command", ["dpo", "grpo", "kto", "reward", "rloo", "sft"]) +def test_help_no_type_error(command): + # Regression test for https://github.com/huggingface/trl/issues/5099: + # TrainingArguments help strings with unescaped "%" caused TypeError in argparse. + from trl.cli import main + + with pytest.raises(SystemExit) as exc_info: + with patch("sys.argv", ["trl", command, "--help"]), patch("sys.stdout", new_callable=StringIO): + main() + assert exc_info.value.code == 0 + + +class TestCLI(TrlTestCase): + def test_dpo(self): + from trl.cli import main + + command = f"trl dpo --output_dir {self.tmp_dir} --model_name_or_path trl-internal-testing/tiny-Qwen2ForCausalLM-2.5 --dataset_name trl-internal-testing/zen --dataset_config standard_preference --report_to none" + with patch("sys.argv", command.split(" ")): + main() + + def test_dpo_multiple_loss_types(self): + from trl.cli import main + + command = f"trl dpo --output_dir {self.tmp_dir} --model_name_or_path trl-internal-testing/tiny-Qwen2ForCausalLM-2.5 --dataset_name trl-internal-testing/zen --dataset_config standard_preference --report_to none --loss_type sigmoid bco_pair --loss_weights 1.0 0.5" + with patch("sys.argv", command.split(" ")): + main() + + @patch("sys.stdout", new_callable=StringIO) + def test_env(self, mock_stdout): + from trl.cli import main + + command = "trl env" + with patch("sys.argv", command.split(" ")): + main() + assert "TRL version: " in mock_stdout.getvalue().strip() + + def test_grpo(self): + from trl.cli import main + + command = f"trl grpo --output_dir {self.tmp_dir} --model_name_or_path trl-internal-testing/tiny-Qwen2ForCausalLM-2.5 --reward_model_name_or_path trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5 --dataset_name trl-internal-testing/zen --dataset_config standard_prompt_only --num_generations 4 --max_completion_length 32 --report_to none" + with patch("sys.argv", command.split(" ")): + main() + + def test_kto(self): + from trl.cli import main + + command = f"trl kto --output_dir {self.tmp_dir} --model_name_or_path trl-internal-testing/tiny-Qwen2ForCausalLM-2.5 --dataset_name trl-internal-testing/zen --dataset_config standard_unpaired_preference --report_to none" + with patch("sys.argv", command.split(" ")): + main() + + def test_reward(self): + from trl.cli import main + + command = f"trl reward --output_dir {self.tmp_dir} --model_name_or_path trl-internal-testing/tiny-Qwen2ForCausalLM-2.5 --dataset_name trl-internal-testing/zen --dataset_config standard_implicit_prompt_preference --report_to none" + with patch("sys.argv", command.split(" ")): + main() + + def test_rloo(self): + from trl.cli import main + + command = f"trl rloo --output_dir {self.tmp_dir} --model_name_or_path trl-internal-testing/tiny-Qwen2ForCausalLM-2.5 --reward_model_name_or_path trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5 --dataset_name trl-internal-testing/zen --dataset_config standard_prompt_only --num_generations 2 --max_completion_length 32 --report_to none" + with patch("sys.argv", command.split(" ")): + main() + + def test_sft(self): + from trl.cli import main + + command = f"trl sft --output_dir {self.tmp_dir} --model_name_or_path trl-internal-testing/tiny-Qwen2ForCausalLM-2.5 --dataset_name trl-internal-testing/zen --dataset_config standard_language_modeling --report_to none" + with patch("sys.argv", command.split(" ")): + main() + + def test_sft_config_file(self): + from trl.cli import main + + output_dir = os.path.join(self.tmp_dir, "output") + + # Create a temporary config file + config_path = os.path.join(self.tmp_dir, "config.yaml") + config_content = { + "model_name_or_path": "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + "dataset_name": "trl-internal-testing/zen", + "dataset_config": "standard_language_modeling", + "report_to": "none", + "output_dir": output_dir, + "lr_scheduler_type": "cosine_with_restarts", + } + with open(config_path, "w") as config_file: + yaml.dump(config_content, config_file) + + # Test the CLI with config file + command = f"trl sft --config {config_path}" + with patch("sys.argv", command.split(" ")): + main() + + # Verify that output directory was created + assert os.path.exists(output_dir) + + def test_vllm_serve_config_file(self): + """ + Test `trl vllm-serve --config config.yaml` must not raise "the following arguments are required: --model" when + the required field is satisfied by the config file rather than the command line. + """ + from trl.cli import main + + config_path = os.path.join(self.tmp_dir, "config.yaml") + with open(config_path, "w") as f: + yaml.dump({"model": "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"}, f) + + # Patch the actual function that `VllmServeCommand.run` imports as `vllm_serve_main` + with patch("trl.scripts.vllm_serve.main") as mock_serve: + with patch("sys.argv", ["trl", "vllm-serve", "--config", config_path]): + main() + + mock_serve.assert_called_once() + script_args = mock_serve.call_args.args[0] + assert script_args.model == "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_cli_utils.py b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_cli_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..cabb8f38bd2234ca3e698e01e0664b83a51f0813 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_cli_utils.py @@ -0,0 +1,426 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import tempfile +from dataclasses import dataclass +from unittest.mock import mock_open, patch + +import pytest +from datasets import DatasetDict, load_dataset + +from trl import DatasetMixtureConfig, TrlParser, get_dataset +from trl.scripts.utils import DatasetConfig + +from .testing_utils import TrlTestCase + + +@dataclass +class MyDataclass: + arg1: int + arg2: str = "default" + + +@dataclass +class InvalidDataclass: + config: str # This should raise an error in the TrlParser + + +class TestTrlParser(TrlTestCase): + def test_init_without_config_field(self): + """Test initialization without 'config' field in the dataclasses.""" + parser = TrlParser(dataclass_types=[MyDataclass]) + assert isinstance(parser, TrlParser) + + def test_init_with_config_field(self): + """Test initialization with a 'config' field in the dataclass (should raise ValueError).""" + with pytest.raises(ValueError, match="has a field named 'config'"): + TrlParser(dataclass_types=[InvalidDataclass]) + + @patch("builtins.open", mock_open(read_data="env:\n VAR1: value1\n VAR2: value2\narg1: 2")) + @patch("yaml.safe_load") + @patch("os.environ", new_callable=dict) # Mock os.environ as a dictionary + def test_parse_args_and_config_with_valid_config(self, mock_environ, mock_yaml_load): + """Test parse_args_and_config method with valid arguments and config.""" + mock_yaml_load.return_value = {"env": {"VAR1": "value1", "VAR2": "value2"}, "arg1": 2} + + parser = TrlParser(dataclass_types=[MyDataclass]) + + args = ["--arg2", "value", "--config", "config.yaml"] # don't set arg1 to test default value + + # Simulate the config being loaded and environment variables being set + result_args = parser.parse_args_and_config(args) + + # Set the environment variables using the mock + mock_environ["VAR1"] = "value1" + mock_environ["VAR2"] = "value2" + + # Ensure that the environment variables were set correctly + assert mock_environ.get("VAR1") == "value1" + assert mock_environ.get("VAR2") == "value2" + + # Check the parsed arguments + assert len(result_args) == 1 + assert isinstance(result_args[0], MyDataclass) + assert result_args[0].arg1 == 2 + assert result_args[0].arg2 == "value" + + @patch("builtins.open", mock_open(read_data="arg1: 2")) + @patch("yaml.safe_load") + def test_parse_args_and_arg_override_config(self, mock_yaml_load): + """Test parse_args_and_config method and check that arguments override the config.""" + mock_yaml_load.return_value = {"arg1": 2} # this arg is meant to be overridden + + parser = TrlParser(dataclass_types=[MyDataclass]) + + args = ["--arg1", "3", "--config", "config.yaml"] # override arg1 default with 3 + + # Simulate the config being loaded and arguments being passed + result_args = parser.parse_args_and_config(args) + + # Check the parsed arguments + assert len(result_args) == 1 + assert isinstance(result_args[0], MyDataclass) + assert result_args[0].arg1 == 3 + + @patch("builtins.open", mock_open(read_data="env: not_a_dict")) + @patch("yaml.safe_load") + def test_parse_args_and_config_with_invalid_env(self, mock_yaml_load): + """Test parse_args_and_config method when the 'env' field is not a dictionary.""" + mock_yaml_load.return_value = {"env": "not_a_dict"} + + parser = TrlParser(dataclass_types=[MyDataclass]) + + args = ["--arg1", "2", "--arg2", "value", "--config", "config.yaml"] + + with pytest.raises(ValueError, match="`env` field should be a dict in the YAML file."): + parser.parse_args_and_config(args) + + def test_parse_args_and_config_without_config(self): + """Test parse_args_and_config without the `--config` argument.""" + parser = TrlParser(dataclass_types=[MyDataclass]) + + args = ["--arg1", "2", "--arg2", "value"] + + # Simulate no config, just parse args normally + result_args = parser.parse_args_and_config(args) + + # Check that the arguments are parsed as is + assert len(result_args) == 1 + assert isinstance(result_args[0], MyDataclass) + assert result_args[0].arg1 == 2 + assert result_args[0].arg2 == "value" + + def test_set_defaults_with_config(self): + """Test set_defaults_with_config updates the defaults.""" + parser = TrlParser(dataclass_types=[MyDataclass]) + + # Update defaults + parser.set_defaults_with_config(arg1=42) + + # Ensure the default value is updated + result_args = parser.parse_args_and_config([]) + assert len(result_args) == 1 + assert isinstance(result_args[0], MyDataclass) + assert result_args[0].arg1 == 42 + + def test_parse_args_and_config_with_remaining_strings(self): + parser = TrlParser(dataclass_types=[MyDataclass]) + + args = ["--arg1", "2", "--arg2", "value", "remaining"] + + # Simulate no config, just parse args normally + result_args = parser.parse_args_and_config(args, return_remaining_strings=True) + + # Check that the arguments are parsed as is + assert len(result_args) == 2 + assert isinstance(result_args[0], MyDataclass) + assert result_args[0].arg1 == 2 + assert result_args[0].arg2 == "value" + assert result_args[1] == ["remaining"] + + @patch("builtins.open", mock_open(read_data="remaining_string_in_config: abc")) + @patch("yaml.safe_load") + def test_parse_args_and_config_with_remaining_strings_in_config_and_args(self, mock_yaml_load): + mock_yaml_load.return_value = {"remaining_string_in_config": "abc"} + + parser = TrlParser(dataclass_types=[MyDataclass]) + + args = ["--arg1", "2", "--remaining_string_in_args", "def", "--config", "config.yaml"] + + # Simulate the config being loaded and arguments being passed + result_args = parser.parse_args_and_config(args, return_remaining_strings=True) + + # Check that the arguments are parsed as is + assert len(result_args) == 2 + assert isinstance(result_args[0], MyDataclass) + assert result_args[0].arg1 == 2 + assert result_args[1] == ["--remaining_string_in_config", "abc", "--remaining_string_in_args", "def"] + + @patch("builtins.open", mock_open(read_data="arg1: 2\narg2: config_value")) + @patch("yaml.safe_load") + def test_subparsers_with_config_defaults(self, mock_yaml_load): + """Test that config defaults are applied to all subparsers.""" + mock_yaml_load.return_value = {"arg1": 2, "arg2": "config_value"} + + # Create the main parser + parser = TrlParser() + + # Add subparsers + subparsers = parser.add_subparsers(dest="command", parser_class=TrlParser) + + # Create a subparser for a specific command + subparsers.add_parser("subcommand", dataclass_types=[MyDataclass]) + + # Parse with config file + args = ["subcommand", "--config", "config.yaml"] + result_args = parser.parse_args_and_config(args) + + # Check main parser arguments + assert len(result_args) == 1 + + # Check that config values were applied to the subparser + assert result_args[0].arg1 == 2 # Default from config + assert result_args[0].arg2 == "config_value" # Default from config + + @patch("builtins.open", mock_open(read_data="arg1: 2\narg2: config_value")) + @patch("yaml.safe_load") + def test_subparsers_with_config_defaults_and_arg_override(self, mock_yaml_load): + """Test that config defaults are applied to all subparsers.""" + mock_yaml_load.return_value = {"arg1": 2, "arg2": "config_value"} + + # Create the main parser + parser = TrlParser() + + # Add subparsers + subparsers = parser.add_subparsers(dest="command", parser_class=TrlParser) + + # Create a subparser for a specific command + subparsers.add_parser("subcommand", dataclass_types=[MyDataclass]) + + # Test with command line arguments overriding config + args = ["subcommand", "--arg1", "3", "--config", "config.yaml"] + result_args = parser.parse_args_and_config(args) + + # Command line arguments should override config + assert result_args[0].arg1 == 3 + assert result_args[0].arg2 == "config_value" # Still from config + + @patch("builtins.open", mock_open(read_data="arg1: 2\nthis_arg_does_not_exist: config_value")) + @patch("yaml.safe_load") + def test_subparsers_with_config_defaults_and_arg_override_wrong_name(self, mock_yaml_load): + """Test that config defaults are applied to all subparsers.""" + mock_yaml_load.return_value = {"arg1": 2, "this_arg_does_not_exist": "config_value"} + + # Create the main parser + parser = TrlParser() + + # Add subparsers + subparsers = parser.add_subparsers(dest="command", parser_class=TrlParser) + + # Create a subparser for a specific command + subparsers.add_parser("subcommand", dataclass_types=[MyDataclass]) + + # Test with command line arguments overriding config + args = ["subcommand", "--arg1", "3", "--config", "config.yaml"] + with pytest.raises(ValueError): + parser.parse_args_and_config(args) + + parser.parse_args_and_config(args, fail_with_unknown_args=False) + + @patch("builtins.open", mock_open(read_data="arg1: 2\narg2: config_value")) + @patch("yaml.safe_load") + def test_subparsers_multiple_with_config_defaults(self, mock_yaml_load): + """Test that config defaults are applied to all subparsers.""" + mock_yaml_load.return_value = {"arg1": 2, "arg2": "config_value"} + + # Create the main parser + parser = TrlParser() + + # Add subparsers + subparsers = parser.add_subparsers(dest="command", parser_class=TrlParser) + + # Create a subparser for a specific command + subparsers.add_parser("subcommand0", dataclass_types=[MyDataclass]) + subparsers.add_parser("subcommand1", dataclass_types=[MyDataclass]) + + for idx in range(2): + # Parse with config file + args = [f"subcommand{idx}", "--config", "config.yaml"] + result_args = parser.parse_args_and_config(args) + + # Check main parser arguments + assert len(result_args) == 1 + + # Check that config values were applied to the subparser + assert result_args[0].arg1 == 2 # Default from config + assert result_args[0].arg2 == "config_value" # Default from config + + +class TestGetDataset: + def test_single_dataset_with_config(self): + mixture_config = DatasetMixtureConfig( + datasets=[DatasetConfig(path="trl-internal-testing/zen", name="standard_language_modeling")] + ) + result = get_dataset(mixture_config) + expected = load_dataset("trl-internal-testing/zen", "standard_language_modeling") + assert expected["train"][:] == result["train"][:] + + def test_single_dataset_preference_config(self): + mixture_config = DatasetMixtureConfig( + datasets=[DatasetConfig(path="trl-internal-testing/zen", name="standard_preference")] + ) + result = get_dataset(mixture_config) + expected = load_dataset("trl-internal-testing/zen", "standard_preference") + assert expected["train"][:] == result["train"][:] + + def test_single_dataset_streaming(self): + mixture_config = DatasetMixtureConfig( + datasets=[DatasetConfig(path="trl-internal-testing/zen", name="standard_language_modeling")], + streaming=True, + ) + result = get_dataset(mixture_config) + expected = load_dataset("trl-internal-testing/zen", "standard_language_modeling") + assert expected["train"].to_list() == list(result["train"]) + + def test_dataset_mixture_basic(self): + dataset_config1 = DatasetConfig( + path="trl-internal-testing/zen", name="standard_prompt_completion", split="train", columns=["prompt"] + ) + dataset_config2 = DatasetConfig( + path="trl-internal-testing/zen", name="standard_preference", split="train", columns=["prompt"] + ) + mixture_config = DatasetMixtureConfig(datasets=[dataset_config1, dataset_config2]) + result = get_dataset(mixture_config) + assert isinstance(result, DatasetDict) + assert "train" in result + train_dataset = result["train"] + assert train_dataset.column_names == ["prompt"] + prompts = train_dataset["prompt"] + expected_first_half = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") + assert prompts[: len(prompts) // 2] == expected_first_half["prompt"] + expected_second_half = load_dataset("trl-internal-testing/zen", "standard_prompt_completion", split="train") + assert prompts[len(prompts) // 2 :] == expected_second_half["prompt"] + + def test_dataset_mixture_with_weights(self): + dataset_config1 = DatasetConfig( + path="trl-internal-testing/zen", name="standard_prompt_completion", split="train[:50%]", columns=["prompt"] + ) + dataset_config2 = DatasetConfig( + path="trl-internal-testing/zen", name="standard_preference", split="train[:50%]", columns=["prompt"] + ) + mixture_config = DatasetMixtureConfig(datasets=[dataset_config1, dataset_config2]) + result = get_dataset(mixture_config) + assert isinstance(result, DatasetDict) + assert "train" in result + train_dataset = result["train"] + assert train_dataset.column_names == ["prompt"] + prompts = train_dataset["prompt"] + expected_first_half = load_dataset("trl-internal-testing/zen", "standard_preference", split="train[:50%]") + assert prompts[: len(prompts) // 2] == expected_first_half["prompt"] + expected_second_half = load_dataset( + "trl-internal-testing/zen", "standard_prompt_completion", split="train[:50%]" + ) + assert prompts[len(prompts) // 2 :] == expected_second_half["prompt"] + + def test_dataset_mixture_with_test_split(self): + mixture_config = DatasetMixtureConfig( + datasets=[DatasetConfig(path="trl-internal-testing/zen", name="standard_language_modeling")], + test_split_size=2, + ) + result = get_dataset(mixture_config) + assert isinstance(result, DatasetDict) + assert "train" in result + assert "test" in result + assert len(result["train"]) == 15 + assert len(result["test"]) == 2 + + def test_empty_dataset_mixture_raises_error(self): + mixture_config = DatasetMixtureConfig(datasets=[]) + + with pytest.raises(ValueError, match="No datasets were loaded"): + get_dataset(mixture_config) + + def test_mixture_multiple_different_configs(self): + dataset_config1 = DatasetConfig( + path="trl-internal-testing/zen", name="conversational_preference", split="train", columns=["prompt"] + ) + dataset_config2 = DatasetConfig( + path="trl-internal-testing/zen", name="conversational_prompt_only", split="test" + ) + mixture_config = DatasetMixtureConfig(datasets=[dataset_config1, dataset_config2]) + result = get_dataset(mixture_config) + assert isinstance(result, DatasetDict) + assert "train" in result + assert len(result["train"]) > 0 + + def test_trlparser_parses_yaml_config_correctly(self): + # Prepare YAML content exactly like your example + # docstyle-ignore + yaml_content = """ + datasets: + - path: trl-internal-testing/zen + name: standard_prompt_only + - path: trl-internal-testing/zen + name: standard_preference + columns: + - prompt + """ + + # Write YAML to a temporary file + with tempfile.NamedTemporaryFile("w+", suffix=".yaml") as tmpfile: + tmpfile.write(yaml_content) + tmpfile.flush() + parser = TrlParser((DatasetMixtureConfig,)) + args = parser.parse_args_and_config(args=["--config", tmpfile.name])[0] + + # Assert that we got DatasetMixtureConfig instance + assert isinstance(args, DatasetMixtureConfig) + + # Assert datasets list length + assert len(args.datasets) == 2 + + # Check first dataset + dataset_config1 = args.datasets[0] + assert isinstance(dataset_config1, DatasetConfig) + assert dataset_config1.path == "trl-internal-testing/zen" + assert dataset_config1.name == "standard_prompt_only" + assert dataset_config1.columns is None # No columns specified + + # Check second dataset + dataset_config2 = args.datasets[1] + assert isinstance(dataset_config2, DatasetConfig) + assert dataset_config2.path == "trl-internal-testing/zen" + assert dataset_config2.name == "standard_preference" + assert dataset_config2.columns == ["prompt"] # Columns specified + + def test_trlparser_parses_yaml_and_loads_dataset(self): + # Prepare YAML content exactly like your example + # docstyle-ignore + yaml_content = """ + datasets: + - path: trl-internal-testing/zen + name: standard_language_modeling + """ + + # Write YAML to a temporary file + with tempfile.NamedTemporaryFile("w+", suffix=".yaml") as tmpfile: + tmpfile.write(yaml_content) + tmpfile.flush() + parser = TrlParser((DatasetMixtureConfig,)) + args = parser.parse_args_and_config(args=["--config", tmpfile.name])[0] + + # Load the dataset using get_dataset + result = get_dataset(args) + expected = load_dataset("trl-internal-testing/zen", "standard_language_modeling") + assert expected["train"][:] == result["train"][:] diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_data_utils.py b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_data_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..341ff337583f0205edd621134a56c4d515056d48 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_data_utils.py @@ -0,0 +1,1335 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import copy +import textwrap +from time import strftime + +import pytest +import transformers +from datasets import Dataset, DatasetDict +from packaging.version import Version +from transformers import AutoProcessor, AutoTokenizer, is_vision_available + +from trl.data_utils import ( + apply_chat_template, + extract_prompt, + is_conversational, + is_conversational_from_value, + maybe_apply_chat_template, + maybe_convert_to_chatml, + maybe_extract_prompt, + maybe_unpair_preference_dataset, + pack_dataset, + prepare_multimodal_messages, + prepare_multimodal_messages_vllm, + unpair_preference_dataset, +) + +from .testing_utils import TrlTestCase, require_vision + + +if is_vision_available(): + from PIL import Image + + +@require_vision +class TestPrepareMultimodalMessages: + def test_basic_user_assistant_conversation(self): + """Test basic conversation with user and assistant messages.""" + messages = [ + {"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is blue."}, + ] + image = Image.new("RGB", (10, 10), color="blue") + messages = prepare_multimodal_messages(messages, images=[image]) + + expected = [ + { + "role": "user", + "content": [{"type": "image", "image": image}, {"type": "text", "text": "What color is the sky?"}], + }, + { + "role": "assistant", + "content": [{"type": "text", "text": "It is blue."}], + }, + ] + + assert messages == expected + + def test_first_user_message_gets_image(self): + """Test that only the first user message gets an image.""" + messages = [ + {"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is blue."}, + {"role": "user", "content": "How about the grass?"}, + ] + + image = Image.new("RGB", (10, 10), color="blue") + messages = prepare_multimodal_messages(messages, images=[image]) + + expected = [ + { + "role": "user", + "content": [{"type": "image", "image": image}, {"type": "text", "text": "What color is the sky?"}], + }, + { + "role": "assistant", + "content": [{"type": "text", "text": "It is blue."}], + }, + { + "role": "user", + "content": [{"type": "text", "text": "How about the grass?"}], + }, + ] + + assert messages == expected + + def test_multiple_images(self): + """Test that multiple images are added to the first user message.""" + messages = [ + {"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is blue."}, + ] + images = [Image.new("RGB", (10, 10), color=color) for color in ["red", "green", "blue"]] + messages = prepare_multimodal_messages(messages, images=images) + + expected = [ + { + "role": "user", + "content": [ + {"type": "image", "image": images[0]}, + {"type": "image", "image": images[1]}, + {"type": "image", "image": images[2]}, + {"type": "text", "text": "What color is the sky?"}, + ], + }, + { + "role": "assistant", + "content": [{"type": "text", "text": "It is blue."}], + }, + ] + + assert messages == expected + + def test_system_message_transformation(self): + """Test that system messages are properly transformed.""" + messages = [ + {"role": "system", "content": "You are a helpful assistant"}, + {"role": "user", "content": "What color is the sky?"}, + ] + + image = Image.new("RGB", (10, 10), color="blue") + messages = prepare_multimodal_messages(messages, images=[image]) + + expected = [ + { + "role": "system", + "content": [{"type": "text", "text": "You are a helpful assistant"}], + }, + { + "role": "user", + "content": [{"type": "image", "image": image}, {"type": "text", "text": "What color is the sky?"}], + }, + ] + + assert messages == expected + + def test_already_prepared_messages_unchanged(self): + """Test that messages with list content are not modified.""" + messages = [ + {"role": "system", "content": [{"type": "text", "text": "You are a helpful assistant"}]}, + {"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What color is the sky?"}]}, + {"role": "assistant", "content": [{"type": "text", "text": "It is blue."}]}, + ] + + image = Image.new("RGB", (10, 10), color="blue") + messages = prepare_multimodal_messages(messages, images=[image]) + + expected = [ + { + "role": "system", + "content": [{"type": "text", "text": "You are a helpful assistant"}], + }, + { + "role": "user", + "content": [{"type": "image", "image": image}, {"type": "text", "text": "What color is the sky?"}], + }, + { + "role": "assistant", + "content": [{"type": "text", "text": "It is blue."}], + }, + ] + + assert messages == expected + + def test_mixed_prepared_and_unprepared_messages(self): + """Test handling of mixed prepared and unprepared messages.""" + messages = [ + {"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": [{"type": "text", "text": "It is blue."}]}, + {"role": "user", "content": "What about the grass?"}, + ] + + image = Image.new("RGB", (10, 10), color="blue") + messages = prepare_multimodal_messages(messages, images=[image]) + + expected = [ + { + "role": "user", + "content": [{"type": "image", "image": image}, {"type": "text", "text": "What color is the sky?"}], + }, + { + "role": "assistant", + "content": [{"type": "text", "text": "It is blue."}], + }, + { + "role": "user", + "content": [{"type": "text", "text": "What about the grass?"}], + }, + ] + + assert messages == expected + + def test_message_with_tool_calling_turns(self): + """Test that both the assistant tool call and the tool role turns messages are properly transformed.""" + messages = [ + {"role": "user", "content": "What's the weather like in New York?"}, + { + "role": "assistant", + "tool_calls": [ + { + "type": "tool", + "function": {"name": "get_current_weather", "arguments": {"location": "New York"}}, + } + ], + }, + {"role": "tool", "name": "get_current_weather", "content": "22.0"}, + {"role": "assistant", "content": "The current weather in New York is 22.0 degrees Celsius."}, + ] + + messages = prepare_multimodal_messages(messages) + + expected = [ + { + "role": "user", + "content": [{"type": "text", "text": "What's the weather like in New York?"}], + }, + { + "role": "assistant", + "tool_calls": [ + { + "type": "tool", + "function": {"name": "get_current_weather", "arguments": {"location": "New York"}}, + } + ], + }, + {"role": "tool", "name": "get_current_weather", "content": [{"type": "text", "text": "22.0"}]}, + { + "role": "assistant", + "content": [{"type": "text", "text": "The current weather in New York is 22.0 degrees Celsius."}], + }, + ] + + assert messages == expected + + def test_prepared_image_blocks_without_new_images(self): + """Test that existing image payloads are preserved when no new images are provided.""" + image = Image.new("RGB", (10, 10), color="blue") + messages = [ + { + "role": "user", + "content": [{"type": "image", "image": image}, {"type": "text", "text": "What color is the sky?"}], + }, + {"role": "assistant", "content": "It is blue."}, + ] + + messages = prepare_multimodal_messages(messages) + + expected = [ + { + "role": "user", + "content": [{"type": "image", "image": image}, {"type": "text", "text": "What color is the sky?"}], + }, + {"role": "assistant", "content": [{"type": "text", "text": "It is blue."}]}, + ] + + assert messages == expected + + +@require_vision +class TestPrepareMultimodalMessagesVLLM: + def test_single_image_conversion(self): + messages = [ + { + "role": "user", + "content": [ + {"type": "image", "image": Image.new("RGB", (10, 10), color="blue")}, + {"type": "text", "text": "What color is the sky?"}, + ], + } + ] + + result = prepare_multimodal_messages_vllm(messages) + + # Original should remain unchanged (deepcopy test) + assert messages[0]["content"][0]["type"] == "image" + + # Converted version should have correct structure + assert result[0]["content"][0]["type"] == "image_pil" + assert "image_pil" in result[0]["content"][0] + assert "image" not in result[0]["content"][0] + assert isinstance(result[0]["content"][0]["image_pil"], Image.Image) + assert result[0]["content"][1]["type"] == "text" + + def test_mixed_content_conversion(self): + messages = [ + { + "role": "user", + "content": [ + {"type": "text", "text": "What color is the sky?"}, + {"type": "image", "image": Image.new("RGB", (10, 10), color="blue")}, + ], + } + ] + + result = prepare_multimodal_messages_vllm(messages) + + # The image part should be converted, text should be unchanged + assert result[0]["content"][0]["type"] == "text" + assert result[0]["content"][1]["type"] == "image_pil" + + def test_no_images(self): + messages = [{"role": "user", "content": [{"type": "text", "text": "What color is the sky?"}]}] + + result = prepare_multimodal_messages_vllm(messages) + + # Should be identical since there are no images + assert result == messages + # And a deepcopy — not the same object + assert result is not messages + assert result[0] is not messages[0] + + def test_multiple_messages(self): + messages = [ + { + "role": "user", + "content": [ + {"type": "text", "text": "What color is the sky?"}, + {"type": "image", "image": Image.new("RGB", (10, 10), color="blue")}, + ], + }, + { + "role": "assistant", + "content": [{"type": "text", "text": "It is blue."}], + }, + ] + + result = prepare_multimodal_messages_vllm(messages) + + assert result[0]["content"][1]["type"] == "image_pil" + assert result[1]["content"][0]["type"] == "text" + assert result[1]["content"][0]["text"] == "It is blue." + + def test_deepcopy_integrity(self): + messages = [ + { + "role": "user", + "content": [ + {"type": "text", "text": "What color is the sky?"}, + {"type": "image", "image": Image.new("RGB", (10, 10), color="blue")}, + ], + }, + ] + original = copy.deepcopy(messages) + + _ = prepare_multimodal_messages_vllm(messages) + + # Original should not be mutated + assert messages == original + + +class TestIsConversational(TrlTestCase): + # fmt: off + conversational_examples = [ + { # Language modeling + "messages": [ + {"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is blue."}, + ], + }, + { # Prompt-only + "prompt": [{"role": "user", "content": "What color is the sky?"}], + }, + { # Prompt-completion + "prompt": [{"role": "user", "content": "What color is the sky?"}], + "completion": [{"role": "assistant", "content": "It is blue."}], + }, + { # Preference + "prompt": [{"role": "user", "content": "What color is the sky?"}], + "chosen": [{"role": "assistant", "content": "It is blue."}], + "rejected": [{"role": "assistant", "content": "It is green."}], + }, + { # Preference with implicit prompt + "chosen": [ + {"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is blue."}, + ], + "rejected": [ + {"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is green."}, + ], + }, + { # Preference with tool calls + "prompt": [{"role": "user", "content": "What color is the sky?"}], + "chosen": [ + {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "get_color", "arguments": {"what": "sky"}}}]}, + {"role": "tool", "name": "get_color", "content": "blue"}, + {"role": "assistant", "content": "It is blue."}, + ], + "rejected": [ + {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "get_color", "arguments": {"what": "tree"}}}]}, + {"role": "tool", "name": "get_color", "content": "green"}, + {"role": "assistant", "content": "It is green."}, + ], + "tools": [ + { + "type": "function", + "function": { + "description": "Gets the color.", + "name": "get_color", + "parameters": {"properties": {"what": {"description": "What to get the color of.", "type": "string"}}, "required": ["what"], "type": "object"}, + "return": {"description": "The color.", "type": "string"}, + }, + }, + ], + }, + { # Unpaired preference + "prompt": [{"role": "user", "content": "What color is the sky?"}], + "completion": [{"role": "assistant", "content": "It is blue."}], + "label": True, + }, + { # Language modeling with harmony + "messages": [ + {"role": "system", "content": "Respond in a friendly manner."}, + {"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "thinking": "The user asks the color of the sky...", "content": "It is blue."}, + ], + }, + { # Prompt-only with harmony + "prompt": [ + {"role": "system", "content": "Respond in a friendly manner."}, + {"role": "user", "content": "What color is the sky?"}, + ], + }, + { # Prompt-completion with harmony + "prompt": [ + {"role": "system", "content": "Respond in a friendly manner."}, + {"role": "user", "content": "What color is the sky?"}, + ], + "completion": [ + {"role": "assistant", "thinking": "The user asks the color of the sky...", "content": "It is blue."}, + ], + }, + { # Preference with harmony + "prompt": [ + {"role": "system", "content": "Respond in a friendly manner."}, + {"role": "user", "content": "What color is the sky?"}, + ], + "chosen": [ + {"role": "assistant", "thinking": "The user asks the color of the sky...", "content": "It is blue."}, + ], + "rejected": [ + {"role": "assistant", "thinking": "The user asks the color of the tree...", "content": "It is green."}, + ], + }, + { # Preference with implicit prompt and harmony + "chosen": [ + {"role": "system", "content": "Respond in a friendly manner."}, + {"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "thinking": "The user asks the color of the sky...", "content": "It is blue."}, + ], + "rejected": [ + {"role": "system", "content": "Respond in a friendly manner."}, + {"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "thinking": "The user asks the color of the tree...", "content": "It is green."}, + ], + }, + { # Unpaired preference with harmony + "prompt": [ + {"role": "system", "content": "Respond in a friendly manner."}, + {"role": "user", "content": "What color is the sky?"}, + ], + "completion": [ + {"role": "assistant", "thinking": "The user asks the color of the sky...", "content": "It is blue."}, + ], + "label": True, + }, + ] + # fmt: on + + non_conversational_examples = [ + {"prompt": "The sky is", "completion": " blue."}, + {"text": "The sky is blue."}, + {"prompt": "The sky is"}, + {"prompt": "The sky is", "chosen": " blue.", "rejected": " green."}, + {"prompt": "The sky is", "completion": " blue.", "label": True}, + ] + + @pytest.mark.parametrize("example", conversational_examples) + def test_conversational(self, example): + assert is_conversational(example) + + @pytest.mark.parametrize("example", non_conversational_examples) + def test_non_conversational(self, example): + assert not is_conversational(example) + + +class TestIsConversationalFromValue(TrlTestCase): + def test_positive_1(self): + example = { + "conversations": [ + {"from": "user", "value": "What color is the sky?"}, + {"from": "assistant", "value": "It is blue."}, + ], + } + assert is_conversational_from_value(example) + + def test_negative_1(self): + example = { + "messages": [ + {"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is blue."}, + ], + } + assert not is_conversational_from_value(example) + + def test_negative_2(self): + example = {"text": "The sky is blue."} + assert not is_conversational_from_value(example) + + +class TestApplyChatTemplate(TrlTestCase): + tokenizers = [ + "trl-internal-testing/tiny-CohereForCausalLM", + "trl-internal-testing/tiny-Cohere2ForCausalLM", + "trl-internal-testing/tiny-DeepseekV3ForCausalLM", + "trl-internal-testing/tiny-DeepseekV3ForCausalLM-0528", + "trl-internal-testing/tiny-FalconMambaForCausalLM", + "trl-internal-testing/tiny-Gemma2ForCausalLM", + "trl-internal-testing/tiny-GemmaForCausalLM", + "trl-internal-testing/tiny-GptOssForCausalLM", + pytest.param( + "trl-internal-testing/tiny-Glm4MoeForCausalLM", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.0.0"), + reason="GLM4 tokenizer requires transformers>=5.0.0", + ), + ), + "trl-internal-testing/tiny-LlamaForCausalLM-3.1", + "trl-internal-testing/tiny-LlamaForCausalLM-3.2", + "trl-internal-testing/tiny-LlamaForCausalLM-3", + "trl-internal-testing/tiny-MistralForCausalLM-0.1", + "trl-internal-testing/tiny-MistralForCausalLM-0.2", + pytest.param( + "trl-internal-testing/tiny-NemotronHForCausalLM-nano", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.3.0"), + reason="Nemotron 3 tokenizer requires transformers>=5.3.0", + ), + ), + pytest.param( + "trl-internal-testing/tiny-NemotronHForCausalLM-super", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.3.0"), + reason="Nemotron 3 tokenizer requires transformers>=5.3.0", + ), + ), + pytest.param( + "trl-internal-testing/tiny-NemotronHForCausalLM-ultra", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.3.0"), + reason="Nemotron 3 tokenizer requires transformers>=5.3.0", + ), + ), + pytest.param( + "trl-internal-testing/tiny-Olmo3ForCausalLM", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("4.57.0"), + reason="Olmo 3 requires transformers>=4.57.0", + ), + ), + "trl-internal-testing/tiny-Phi3ForCausalLM-3", + "trl-internal-testing/tiny-Phi3ForCausalLM-3.5", + "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + "trl-internal-testing/tiny-Qwen3ForCausalLM", + "trl-internal-testing/tiny-Qwen3ForCausalLM-Instruct-2507", + pytest.param( + "trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-NoThink", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.0.0"), + reason="Qwen3.5 tokenizer requires transformers>=5.0.0", + ), + ), + pytest.param( + "trl-internal-testing/tiny-Qwen3_5MoeForConditionalGeneration-3.6", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.0.0"), + reason="Qwen3.5 tokenizer requires transformers>=5.0.0", + ), + ), + ] + + conversational_examples = [ + { # Language modeling + "messages": [ + {"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is blue."}, + ], + }, + { # Prompt-only + "prompt": [{"role": "user", "content": "What color is the sky?"}], + }, + { # Prompt-completion + "prompt": [{"role": "user", "content": "What color is the sky?"}], + "completion": [{"role": "assistant", "content": "It is blue."}], + }, + { # Preference + "prompt": [{"role": "user", "content": "What color is the sky?"}], + "chosen": [{"role": "assistant", "content": "It is blue."}], + "rejected": [{"role": "assistant", "content": "It is green."}], + }, + { # Preference with implicit prompt + "chosen": [ + {"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is blue."}, + ], + "rejected": [ + {"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is green."}, + ], + }, + { # Unpaired preference + "prompt": [{"role": "user", "content": "What color is the sky?"}], + "completion": [{"role": "assistant", "content": "It is blue."}], + "label": True, + }, + ] + + non_conversational_examples = [ + {"text": "The sky is blue."}, # Language modeling + {"prompt": "The sky is"}, # Prompt-only + {"prompt": "The sky is", "completion": " blue."}, # Prompt-completion + {"prompt": "The sky is", "chosen": " blue.", "rejected": " green."}, # Preference + {"chosen": "The sky is blue.", "rejected": "The sky is green."}, # Preference with implicit prompt + {"prompt": "The sky is", "completion": " blue.", "label": True}, # Unpaired preference + ] + + @pytest.mark.parametrize("example", conversational_examples) + @pytest.mark.parametrize("tokenizer_id", tokenizers) + def test_apply_chat_template(self, tokenizer_id, example): + tokenizer = AutoTokenizer.from_pretrained(tokenizer_id) + result = apply_chat_template(example, tokenizer) + + # Checking if the result is a dictionary + assert isinstance(result, dict) + + # The chat template should be applied to the following keys + for key in ["prompt", "chosen", "rejected", "completion"]: + if key in example: + assert key in result + assert isinstance(result[key], str) + + # Exception for messages, the key is "text" once the chat template is applied + if "messages" in example: + assert "text" in result + assert isinstance(result["text"], str) + + # The label should be kept + if "label" in example: + assert "label" in result + assert isinstance(result["label"], bool) + assert result["label"] == example["label"] + + # both conversational and non-conversational examples + @pytest.mark.parametrize("example", conversational_examples + non_conversational_examples) + @pytest.mark.parametrize("tokenizer_id", tokenizers) + def test_maybe_apply_chat_template(self, tokenizer_id, example): + tokenizer = AutoTokenizer.from_pretrained(tokenizer_id) + result = maybe_apply_chat_template(example, tokenizer) + + # Checking if the result is a dictionary + assert isinstance(result, dict) + + # The chat template should be applied to the following keys + for key in ["prompt", "chosen", "rejected", "completion"]: + if key in example: + assert key in result + assert isinstance(result[key], str) + + # Exception for messages, the key is "text" once the chat template is applied + if "messages" in example: + assert "text" in result + assert isinstance(result["text"], str) + + # The label should be kept + if "label" in example: + assert "label" in result + assert isinstance(result["label"], bool) + assert result["label"] == example["label"] + + def test_apply_chat_template_with_chat_template_kwargs(self): + tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen3ForCausalLM") + + example = { + "prompt": [{"role": "user", "content": "What color is the sky?"}], + # with this tokenizer, when you pass enable_thinking=False, it will add "\n\n\n\n" + "chat_template_kwargs": {"enable_thinking": False}, + } + result = apply_chat_template(example, tokenizer) + + # docstyle-ignore + expected = textwrap.dedent("""\ + <|im_start|>user + What color is the sky?<|im_end|> + <|im_start|>assistant + + + + + """) + + assert result["prompt"] == expected + + def test_apply_chat_template_with_tools(self): + tokenizer = AutoProcessor.from_pretrained("trl-internal-testing/tiny-LlamaForCausalLM-3.2") + + # Define dummy test tools + def get_current_temperature(location: str): + """ + Gets the temperature at a given location. + + Args: + location: The location to get the temperature for + """ + return 22.0 + + # Define test case + test_case = { + "prompt": [ + {"content": "What's the temperature in London?", "role": "user"}, + ] + } + # Test with tools + result_with_tools = apply_chat_template(test_case, tokenizer, tools=[get_current_temperature]) + + # Verify tools are included in the output + assert "get_current_temperature" in result_with_tools["prompt"] + + # Test without tools + result_without_tools = apply_chat_template(test_case, tokenizer, tools=None) + + # Verify tools are not included in the output + assert "get_current_temperature" not in result_without_tools["prompt"] + + +class TestApplyChatTemplateHarmony(TrlTestCase): + def test_language_modeling(self): + messages = { + "messages": [ + {"role": "system", "content": "Respond in a friendly manner."}, + {"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "thinking": "The user asks the color of the sky...", "content": "It is blue."}, + ], + } + output = apply_chat_template( + messages, + processing_class=AutoTokenizer.from_pretrained("trl-internal-testing/tiny-GptOssForCausalLM"), + reasoning_effort="low", + model_identity="You are HuggingGPT.", + ) + + # docstyle-ignore + expected = textwrap.dedent(f"""\ + <|start|>system<|message|>You are HuggingGPT. + Knowledge cutoff: 2024-06 + Current date: {strftime("%Y-%m-%d")} + + Reasoning: low + + # Valid channels: analysis, commentary, final. Channel must be included for every message.<|end|><|start|>developer<|message|># Instructions + + Respond in a friendly manner. + + <|end|><|start|>user<|message|>What color is the sky?<|end|><|start|>assistant<|channel|>analysis<|message|>The user asks the color of the sky...<|end|><|start|>assistant<|channel|>final<|message|>It is blue.<|return|>""") + + assert output["text"] == expected + + def test_prompt_only(self): + messages = { + "prompt": [ + {"role": "system", "content": "Respond in a friendly manner."}, + {"role": "user", "content": "What color is the sky?"}, + ], + } + output = apply_chat_template( + messages, + processing_class=AutoTokenizer.from_pretrained("trl-internal-testing/tiny-GptOssForCausalLM"), + reasoning_effort="low", + model_identity="You are HuggingGPT.", + ) + + # docstyle-ignore + expected = textwrap.dedent(f"""\ + <|start|>system<|message|>You are HuggingGPT. + Knowledge cutoff: 2024-06 + Current date: {strftime("%Y-%m-%d")} + + Reasoning: low + + # Valid channels: analysis, commentary, final. Channel must be included for every message.<|end|><|start|>developer<|message|># Instructions + + Respond in a friendly manner. + + <|end|><|start|>user<|message|>What color is the sky?<|end|><|start|>assistant""") + + assert output["prompt"] == expected + + def test_prompt_completion(self): + messages = { + "prompt": [ + {"role": "system", "content": "Respond in a friendly manner."}, + {"role": "user", "content": "What color is the sky?"}, + ], + "completion": [ + {"role": "assistant", "thinking": "The user asks the color of the sky...", "content": "It is blue."}, + ], + } + output = apply_chat_template( + messages, + processing_class=AutoTokenizer.from_pretrained("trl-internal-testing/tiny-GptOssForCausalLM"), + reasoning_effort="low", + model_identity="You are HuggingGPT.", + ) + + # docstyle-ignore + expected_prompt = textwrap.dedent(f"""\ + <|start|>system<|message|>You are HuggingGPT. + Knowledge cutoff: 2024-06 + Current date: {strftime("%Y-%m-%d")} + + Reasoning: low + + # Valid channels: analysis, commentary, final. Channel must be included for every message.<|end|><|start|>developer<|message|># Instructions + + Respond in a friendly manner. + + <|end|><|start|>user<|message|>What color is the sky?<|end|><|start|>assistant""") + expected_completion = "<|channel|>analysis<|message|>The user asks the color of the sky...<|end|><|start|>assistant<|channel|>final<|message|>It is blue.<|return|>" + + assert output["prompt"] == expected_prompt + assert output["completion"] == expected_completion + + def test_preference(self): + messages = { + "prompt": [ + {"role": "system", "content": "Respond in a friendly manner."}, + {"role": "user", "content": "What color is the sky?"}, + ], + "chosen": [ + {"role": "assistant", "thinking": "The user asks the color of the sky...", "content": "It is blue."}, + ], + "rejected": [ + {"role": "assistant", "thinking": "The user asks the color of the tree...", "content": "It is green."}, + ], + } + output = apply_chat_template( + messages, + processing_class=AutoTokenizer.from_pretrained("trl-internal-testing/tiny-GptOssForCausalLM"), + reasoning_effort="low", + model_identity="You are HuggingGPT.", + ) + + # docstyle-ignore + expected_prompt = textwrap.dedent(f"""\ + <|start|>system<|message|>You are HuggingGPT. + Knowledge cutoff: 2024-06 + Current date: {strftime("%Y-%m-%d")} + + Reasoning: low + + # Valid channels: analysis, commentary, final. Channel must be included for every message.<|end|><|start|>developer<|message|># Instructions + + Respond in a friendly manner. + + <|end|><|start|>user<|message|>What color is the sky?<|end|><|start|>assistant""") + expected_chosen = "<|channel|>analysis<|message|>The user asks the color of the sky...<|end|><|start|>assistant<|channel|>final<|message|>It is blue.<|return|>" + expected_rejected = "<|channel|>analysis<|message|>The user asks the color of the tree...<|end|><|start|>assistant<|channel|>final<|message|>It is green.<|return|>" + + assert output["prompt"] == expected_prompt + assert output["chosen"] == expected_chosen + assert output["rejected"] == expected_rejected + + def test_preference_with_implicit_prompt(self): + messages = { + "chosen": [ + {"role": "system", "content": "Respond in a friendly manner."}, + {"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "thinking": "The user asks the color of the sky...", "content": "It is blue."}, + ], + "rejected": [ + {"role": "system", "content": "Respond in a friendly manner."}, + {"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "thinking": "The user asks the color of the tree...", "content": "It is green."}, + ], + } + output = apply_chat_template( + messages, + processing_class=AutoTokenizer.from_pretrained("trl-internal-testing/tiny-GptOssForCausalLM"), + reasoning_effort="low", + model_identity="You are HuggingGPT.", + ) + + # docstyle-ignore + expected_chosen = textwrap.dedent(f"""\ + <|start|>system<|message|>You are HuggingGPT. + Knowledge cutoff: 2024-06 + Current date: {strftime("%Y-%m-%d")} + + Reasoning: low + + # Valid channels: analysis, commentary, final. Channel must be included for every message.<|end|><|start|>developer<|message|># Instructions + + Respond in a friendly manner. + + <|end|><|start|>user<|message|>What color is the sky?<|end|><|start|>assistant<|channel|>analysis<|message|>The user asks the color of the sky...<|end|><|start|>assistant<|channel|>final<|message|>It is blue.<|return|>""") + + # docstyle-ignore + expected_rejected = textwrap.dedent(f"""\ + <|start|>system<|message|>You are HuggingGPT. + Knowledge cutoff: 2024-06 + Current date: {strftime("%Y-%m-%d")} + + Reasoning: low + + # Valid channels: analysis, commentary, final. Channel must be included for every message.<|end|><|start|>developer<|message|># Instructions + + Respond in a friendly manner. + + <|end|><|start|>user<|message|>What color is the sky?<|end|><|start|>assistant<|channel|>analysis<|message|>The user asks the color of the tree...<|end|><|start|>assistant<|channel|>final<|message|>It is green.<|return|>""") + + assert output["chosen"] == expected_chosen + assert output["rejected"] == expected_rejected + + def test_unpaired_preference(self): + messages = { + "prompt": [ + {"role": "system", "content": "Respond in a friendly manner."}, + {"role": "user", "content": "What color is the sky?"}, + ], + "completion": [ + {"role": "assistant", "thinking": "The user asks the color of the sky...", "content": "It is blue."}, + ], + "label": True, + } + output = apply_chat_template( + messages, + processing_class=AutoTokenizer.from_pretrained("trl-internal-testing/tiny-GptOssForCausalLM"), + reasoning_effort="low", + model_identity="You are HuggingGPT.", + ) + + # docstyle-ignore + expected_prompt = textwrap.dedent(f"""\ + <|start|>system<|message|>You are HuggingGPT. + Knowledge cutoff: 2024-06 + Current date: {strftime("%Y-%m-%d")} + + Reasoning: low + + # Valid channels: analysis, commentary, final. Channel must be included for every message.<|end|><|start|>developer<|message|># Instructions + + Respond in a friendly manner. + + <|end|><|start|>user<|message|>What color is the sky?<|end|><|start|>assistant""") + expected_completion = "<|channel|>analysis<|message|>The user asks the color of the sky...<|end|><|start|>assistant<|channel|>final<|message|>It is blue.<|return|>" + + assert output["prompt"] == expected_prompt + assert output["completion"] == expected_completion + assert output["label"] + + +class TestUnpairPreferenceDataset(TrlTestCase): + paired_dataset = Dataset.from_dict( + { + "prompt": ["The sky is", "The sun is"], + "chosen": [" blue.", " in the sky."], + "rejected": [" green.", " in the sea."], + } + ) + + unpaired_dataset = Dataset.from_dict( + { + "prompt": ["The sky is", "The sun is", "The sky is", "The sun is"], + "completion": [" blue.", " in the sky.", " green.", " in the sea."], + "label": [True, True, False, False], + } + ) + + def test_unpair_preference_dataset(self): + # Test that a paired dataset is correctly converted to unpaired + unpaired_dataset = unpair_preference_dataset(self.paired_dataset) + assert unpaired_dataset.to_dict() == self.unpaired_dataset.to_dict(), ( + "The paired dataset should be converted to unpaired." + ) + + def test_unpair_preference_dataset_extra_columns(self): + # Test that extra columns are dropped (not causing a length mismatch error) + paired_dataset = Dataset.from_dict( + { + "prompt": ["The sky is", "The sun is"], + "chosen": [" blue.", " in the sky."], + "rejected": [" green.", " in the sea."], + "extra": [1, 2], + } + ) + unpaired_dataset = unpair_preference_dataset(paired_dataset) + assert unpaired_dataset.to_dict() == self.unpaired_dataset.to_dict() + + def test_unpair_preference_dataset_iterable(self): + # Test that an IterableDataset with extra columns is correctly unpaired + paired_dataset = self.paired_dataset.to_iterable_dataset() + unpaired_dataset = unpair_preference_dataset(paired_dataset) + assert list(unpaired_dataset) == [ + dict(zip(self.unpaired_dataset.column_names, vals, strict=False)) + for vals in zip(*self.unpaired_dataset.to_dict().values(), strict=False) + ] + + def test_unpair_preference_dataset_iterable_extra_columns(self): + # Test that an IterableDataset with extra columns drops them without error + paired_iterable = Dataset.from_dict( + { + "prompt": ["The sky is", "The sun is"], + "chosen": [" blue.", " in the sky."], + "rejected": [" green.", " in the sea."], + "extra": [1, 2], + } + ).to_iterable_dataset() + unpaired_dataset = unpair_preference_dataset(paired_iterable) + assert list(unpaired_dataset) == [ + dict(zip(self.unpaired_dataset.column_names, vals, strict=False)) + for vals in zip(*self.unpaired_dataset.to_dict().values(), strict=False) + ] + + def test_unpair_preference_dataset_dict(self): + # Test that a paired dataset dict is correctly converted to unpaired + paired_dataset_dict = DatasetDict({"abc": self.paired_dataset}) + unpaired_dataset_dict = unpair_preference_dataset(paired_dataset_dict) + assert unpaired_dataset_dict["abc"].to_dict() == self.unpaired_dataset.to_dict(), ( + "The paired dataset should be converted to unpaired." + ) + + def test_maybe_unpair_preference_dataset(self): + # Test that a paired dataset is correctly converted to unpaired with maybe_unpair_preference_dataset + unpaired_dataset = maybe_unpair_preference_dataset(self.paired_dataset) + assert unpaired_dataset.to_dict() == self.unpaired_dataset.to_dict(), ( + "The paired dataset should be converted to unpaired." + ) + + def test_maybe_unpair_preference_dataset_dict(self): + # Test that a paired dataset dict is correctly converted to unpaired with maybe_unpair_preference_dataset + paired_dataset_dict = DatasetDict({"abc": self.paired_dataset}) + unpaired_dataset_dict = maybe_unpair_preference_dataset(paired_dataset_dict) + assert unpaired_dataset_dict["abc"].to_dict() == self.unpaired_dataset.to_dict(), ( + "The paired dataset should be converted to unpaired." + ) + + def test_maybe_unpair_preference_dataset_already_paired(self): + # Test that a paired dataset remains unchanged with maybe_unpair_preference_dataset + unpaired_dataset = maybe_unpair_preference_dataset(self.unpaired_dataset) + assert unpaired_dataset.to_dict() == self.unpaired_dataset.to_dict(), ( + "The unpaired dataset should remain unchanged." + ) + + def test_maybe_unpair_preference_dataset_dict_already_paired(self): + # Test that a paired dataset dict remains unchanged with maybe_unpair_preference_dataset + unpaired_dataset_dict = maybe_unpair_preference_dataset(DatasetDict({"abc": self.unpaired_dataset})) + assert unpaired_dataset_dict["abc"].to_dict() == self.unpaired_dataset.to_dict(), ( + "The unpaired dataset should remain unchanged." + ) + + +class TestExtractPrompt(TrlTestCase): + example_implicit_prompt_conversational = { + "chosen": [ + {"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is blue."}, + ], + "rejected": [ + {"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is green."}, + ], + } + + example_explicit_prompt_conversational = { + "prompt": [ + {"role": "user", "content": "What color is the sky?"}, + ], + "chosen": [ + {"role": "assistant", "content": "It is blue."}, + ], + "rejected": [ + {"role": "assistant", "content": "It is green."}, + ], + } + + example_implicit_prompt_standard = { + "chosen": "The sky is blue.", + "rejected": "The sky is green.", + } + + example_explicit_prompt_standard = { + "prompt": "The sky is", + "chosen": " blue.", + "rejected": " green.", + } + + def test_extract_prompt_conversational(self): + # Test that the prompt is correctly extracted from the dataset + example_extracted_prompt = extract_prompt(self.example_implicit_prompt_conversational) + assert example_extracted_prompt == self.example_explicit_prompt_conversational, ( + "The prompt is not correctly extracted from the dataset." + ) + + def test_maybe_extract_prompt_conversational(self): + # Test that the prompt is correctly extracted from the dataset with maybe_extract_prompt + example_extracted_prompt = maybe_extract_prompt(self.example_implicit_prompt_conversational) + assert example_extracted_prompt == self.example_explicit_prompt_conversational, ( + "The prompt is not correctly extracted from the dataset." + ) + + def test_maybe_extract_prompt_conversational_already_explicit(self): + # Test that the prompt remains unchanged with maybe_extract_prompt + example_extracted_prompt = maybe_extract_prompt(self.example_explicit_prompt_conversational) + assert example_extracted_prompt == self.example_explicit_prompt_conversational, ( + "The prompt should remain unchanged." + ) + + def test_extract_prompt_standard(self): + # Test that the prompt is correctly extracted from the dataset + example_extracted_prompt = extract_prompt(self.example_implicit_prompt_standard) + assert example_extracted_prompt == self.example_explicit_prompt_standard, ( + "The prompt is not correctly extracted from the dataset." + ) + + def test_maybe_extract_prompt_standard(self): + # Test that the prompt is correctly extracted from the dataset with maybe_extract_prompt + example_extracted_prompt = maybe_extract_prompt(self.example_implicit_prompt_standard) + assert example_extracted_prompt == self.example_explicit_prompt_standard, ( + "The prompt is not correctly extracted from the dataset." + ) + + def test_maybe_extract_prompt_standard_already_explicit(self): + # Test that the prompt remains unchanged with maybe_extract_prompt + example_extracted_prompt = maybe_extract_prompt(self.example_explicit_prompt_standard) + assert example_extracted_prompt == self.example_explicit_prompt_standard, "The prompt should remain unchanged." + + +class TestPackDatasetWrapped(TrlTestCase): + def test_with_dataset(self): + examples = { + "input_ids": [[1, 2, 3], [4, 5, 6, 7], [8]], + "attention_mask": [[0, 1, 1], [0, 0, 1, 1], [1]], + } + dataset = Dataset.from_dict(examples) + dataset = dataset.with_format("numpy", dtype="float32") + format = dataset.format + seq_length = 3 + expected_output = { + "input_ids": [[1, 2, 3], [4, 5, 6], [7, 8]], + "attention_mask": [[0, 1, 1], [0, 0, 1], [1, 1]], + } + dataset = pack_dataset(dataset, seq_length, strategy="wrapped") + assert dataset.to_dict() == expected_output + assert format == dataset.format + + def test_with_iterable_dataset(self): + examples = { + "input_ids": [[1, 2, 3], [4, 5, 6, 7], [8]], + "attention_mask": [[0, 1, 1], [0, 0, 1, 1], [1]], + } + dataset = Dataset.from_dict(examples).to_iterable_dataset() + dataset = dataset.with_format("numpy") + formatting = dataset._formatting + seq_length = 3 + expected_output = { + "input_ids": [[1, 2, 3], [4, 5, 6], [7, 8]], + "attention_mask": [[0, 1, 1], [0, 0, 1], [1, 1]], + } + dataset = pack_dataset(dataset, seq_length, strategy="wrapped") + num_examples = len(examples[next(iter(examples))]) + assert next(iter(dataset.with_format(None).batch(batch_size=num_examples))) == expected_output + assert formatting == dataset._formatting + + +class TestPackDatasetBfd(TrlTestCase): + def test_with_dataset(self): + examples = { + "input_ids": [[1, 2, 3], [4, 5, 6, 7], [8]], + } + dataset = Dataset.from_dict(examples) + dataset = dataset.with_format("numpy", dtype="float32") + format = dataset.format + seq_length = 4 + expected_output = { + "input_ids": [[4, 5, 6, 7], [1, 2, 3, 8]], + "seq_lengths": [[4], [3, 1]], + } + dataset = pack_dataset(dataset, seq_length, strategy="bfd") + expected_format = dataset.format + assert dataset.to_dict() == expected_output + assert "seq_lengths" in expected_format["columns"] + expected_format["columns"].remove("seq_lengths") + assert format == dataset.format + + def test_with_iterable_dataset(self): + examples = { + "input_ids": [[1, 2, 3], [4, 5, 6, 7], [8]], + } + dataset = Dataset.from_dict(examples).to_iterable_dataset() + dataset = dataset.with_format("numpy") + formatting = dataset._formatting + seq_length = 4 + expected_output = { + "input_ids": [[4, 5, 6, 7], [1, 2, 3, 8]], + "seq_lengths": [[4], [3, 1]], + } + dataset = pack_dataset(dataset, seq_length, strategy="bfd") + num_examples = len(examples[next(iter(examples))]) + assert next(iter(dataset.with_format(None).batch(batch_size=num_examples))) == expected_output + assert formatting == dataset._formatting + + def test_with_overlong_0(self): + examples = { + "input_ids": [[1, 2, 3, 4, 5], [6, 7], [8, 9, 10, 11], [12]], + } + dataset = Dataset.from_dict(examples) + seq_length = 4 + expected_output = { + "input_ids": [[1, 2, 3, 4], [8, 9, 10, 11], [6, 7, 5, 12]], + "seq_lengths": [[4], [4], [2, 1, 1]], + } + dataset = pack_dataset(dataset, seq_length, strategy="bfd_split") + assert dataset.to_dict() == expected_output + + def test_with_overlong_two_coluns(self): + examples = { + "col1": [[1, -2, 3, -4, 5, -6], [7, -8, 9], [-10, 11, -12], [13, -14, 15, -16]], + "col2": [[-1, 2, -3, 4, -5, 6], [-7, 8, -9], [10, -11, 12], [-13, 14, -15, 16]], + } + dataset = Dataset.from_dict(examples) + seq_length = 4 + expected_output = { + "col1": [[1, -2, 3, -4], [13, -14, 15, -16], [7, -8, 9], [-10, 11, -12], [5, -6]], + "col2": [[-1, 2, -3, 4], [-13, 14, -15, 16], [-7, 8, -9], [10, -11, 12], [-5, 6]], + "seq_lengths": [[4], [4], [3], [3], [2]], + } + dataset = pack_dataset(dataset, seq_length, strategy="bfd_split") + assert dataset.to_dict() == expected_output + + def test_with_non_power_of_2(self): + examples = { + "input_ids": [[1, 2, 3, 4, 5], [6], [7, 8, 9, 10], [11, 12, 13]], + } + dataset = Dataset.from_dict(examples) + seq_length = 5 + expected_output = { + "input_ids": [[1, 2, 3, 4, 5], [7, 8, 9, 10, 6], [11, 12, 13]], + "seq_lengths": [[5], [4, 1], [3]], + } + dataset = pack_dataset(dataset, seq_length, strategy="bfd_split") + assert dataset.to_dict() == expected_output + + def test_default_no_split(self): + """Test default 'bfd' strategy for SFT datasets (truncates overflow).""" + examples = { + "input_ids": [[1, 2, 3, 4, 5], [6, 7], [8, 9, 10, 11], [12]], + } + dataset = Dataset.from_dict(examples) + seq_length = 4 + # With default 'bfd' strategy, overflow tokens are discarded + expected_output = { + "input_ids": [[1, 2, 3, 4], [8, 9, 10, 11], [6, 7, 12]], + "seq_lengths": [[4], [4], [2, 1]], + } + dataset = pack_dataset(dataset, seq_length, strategy="bfd") + assert dataset.to_dict() == expected_output + + def test_with_empty_sequences(self): + examples = { + "input_ids": [[1, 2], [], [3, 4, 5], [], [6]], + } + dataset = Dataset.from_dict(examples) + seq_length = 4 + expected_output = { + "input_ids": [[3, 4, 5, 6], [1, 2]], + "seq_lengths": [[3, 1], [2]], + } + dataset = pack_dataset(dataset, seq_length, strategy="bfd_split") + assert dataset.to_dict() == expected_output + + +class TestMaybeConvertToChatML(TrlTestCase): + def test_with_conversations_key(self): + # Particular case where the key is "conversations": we rename it to "messages" + example = { + "conversations": [ + {"from": "user", "value": "What color is the sky?"}, + {"from": "assistant", "value": "It is blue."}, + ] + } + expected_output = { + "messages": [ + {"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is blue."}, + ] + } + assert maybe_convert_to_chatml(example) == expected_output + + def test_without_conversations_key(self): + # Same as before, but we don't rename the keys + example = { + "prompt": [{"from": "user", "value": "What color is the sky?"}], + "completion": [{"from": "assistant", "value": "It is blue."}], + } + expected_output = { + "prompt": [{"role": "user", "content": "What color is the sky?"}], + "completion": [{"role": "assistant", "content": "It is blue."}], + } + assert maybe_convert_to_chatml(example) == expected_output + + def test_not_conversional(self): + # When not needed, the example should remain unchanged + example = {"text": "The sky is blue."} + assert maybe_convert_to_chatml(example) == example + + def test_already_chatml(self): + # When the example is already in ChatML format, it should remain unchanged + example = { + "messages": [ + {"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is blue."}, + ] + } + assert maybe_convert_to_chatml(example) == example diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_dpo_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_dpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..1e52f8b76dab527ac916db44a0b78c8e3b90ab51 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_dpo_trainer.py @@ -0,0 +1,1286 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pytest +import torch +import transformers +from datasets import load_dataset +from packaging.version import Version +from packaging.version import parse as parse_version +from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig +from transformers.testing_utils import torch_device +from transformers.utils import is_peft_available + +from trl import DPOConfig, DPOTrainer +from trl.trainer.dpo_trainer import DataCollatorForPreference, DataCollatorForVisionPreference + +from .testing_utils import ( + TrlTestCase, + is_ampere_or_newer, + require_bitsandbytes, + require_kernels, + require_liger_kernel, + require_peft, + require_vision, +) + + +if is_peft_available(): + from peft import LoraConfig, get_peft_model + + +class TestDataCollatorForPreference(TrlTestCase): + def test_padding_and_masks(self): + collator = DataCollatorForPreference(pad_token_id=0) + examples = [ + {"prompt_ids": [1, 2, 3], "chosen_ids": [4, 5], "rejected_ids": [6]}, + {"prompt_ids": [7, 8], "chosen_ids": [9, 10], "rejected_ids": [11, 12, 13]}, + ] + result = collator(examples) + + expected_input_ids = torch.tensor( + [ + [1, 2, 3, 4, 5], # prompt + chosen (example 1) + [7, 8, 9, 10, 0], # prompt + chosen (example 2, padded) + [1, 2, 3, 6, 0], # prompt + rejected (example 1, padded) + [7, 8, 11, 12, 13], # prompt + rejected (example 2) + ] + ) + expected_attention_mask = torch.tensor( + [ + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 0], + [1, 1, 1, 1, 0], + [1, 1, 1, 1, 1], + ] + ) + expected_completion_mask = torch.tensor( + [ + [0, 0, 0, 1, 1], # chosen completion (example 1) + [0, 0, 1, 1, 0], # chosen completion (example 2, padded) + [0, 0, 0, 1, 0], # rejected completion (example 1, padded) + [0, 0, 1, 1, 1], # rejected completion (example 2) + ] + ) + + assert set(result.keys()) == {"input_ids", "attention_mask", "completion_mask"} + torch.testing.assert_close(result["input_ids"], expected_input_ids) + torch.testing.assert_close(result["attention_mask"], expected_attention_mask) + torch.testing.assert_close(result["completion_mask"], expected_completion_mask) + + def test_optional_reference_logps(self): + collator = DataCollatorForPreference(pad_token_id=0) + examples = [ + { + "prompt_ids": [1, 2], + "chosen_ids": [3], + "rejected_ids": [4], + "ref_chosen_logps": 0.1, + "ref_rejected_logps": 0.2, + }, + { + "prompt_ids": [5], + "chosen_ids": [6, 7], + "rejected_ids": [8, 9], + "ref_chosen_logps": 0.3, + "ref_rejected_logps": 0.4, + }, + ] + result = collator(examples) + + expected_ref_chosen_logps = torch.tensor([0.1, 0.3]) + expected_ref_rejected_logps = torch.tensor([0.2, 0.4]) + + assert set(result.keys()) == { + "input_ids", + "attention_mask", + "completion_mask", + "ref_chosen_logps", + "ref_rejected_logps", + } + torch.testing.assert_close(result["ref_chosen_logps"], expected_ref_chosen_logps) + torch.testing.assert_close(result["ref_rejected_logps"], expected_ref_rejected_logps) + + def test_with_pad_to_multiple_of(self): + collator = DataCollatorForPreference(pad_token_id=0, pad_to_multiple_of=5) + examples = [ + {"prompt_ids": [1], "chosen_ids": [2], "rejected_ids": [3]}, + {"prompt_ids": [4, 5], "chosen_ids": [6, 7], "rejected_ids": [8, 9]}, + ] + result = collator(examples) + + expected_input_ids = torch.tensor( + [ + [1, 2, 0, 0, 0], # prompt + chosen (example 1, padded to multiple of 5) + [4, 5, 6, 7, 0], # prompt + chosen (example 2) + [1, 3, 0, 0, 0], # prompt + rejected (example 1, padded to multiple of 5) + [4, 5, 8, 9, 0], # prompt + rejected (example 2) + ] + ) + + assert set(result.keys()) == {"input_ids", "attention_mask", "completion_mask"} + torch.testing.assert_close(result["input_ids"], expected_input_ids) + + +class TestDataCollatorForVisionPreference(TrlTestCase): + @pytest.mark.skipif( + Version(transformers.__version__) < Version("5.3.0"), + reason="mm_token_type_ids are returned by default since transformers-5.3.0 (see transformers#43972)", + ) + @require_vision + def test_mm_token_type_ids_shape(self): + # Regression test: when the processor returns mm_token_type_ids (e.g. Qwen2.5-VL after + # transformers#43972), the collator must concatenate it with zeros for the completion part + # so that its shape matches input_ids. Without the fix this raises an IndexError in the model. + from PIL import Image + from transformers import AutoProcessor + + processor = AutoProcessor.from_pretrained("trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration") + collator = DataCollatorForVisionPreference(processor) + image = Image.new("RGB", (16, 16)) + examples = [ + { + "images": [image], + "prompt": [{"role": "user", "content": "What is this?"}], + "chosen": [{"role": "assistant", "content": "A red square."}], + "rejected": [{"role": "assistant", "content": "A blue circle."}], + } + ] + output = collator(examples) + assert "mm_token_type_ids" in output + assert output["mm_token_type_ids"].shape == output["input_ids"].shape, ( + f"mm_token_type_ids shape {output['mm_token_type_ids'].shape} != " + f"input_ids shape {output['input_ids'].shape}" + ) + + +class TestDPOTrainer(TrlTestCase): + @pytest.mark.parametrize( + "model_id", + [ + "trl-internal-testing/tiny-Cohere2ForCausalLM", + pytest.param( + "trl-internal-testing/tiny-Glm4MoeForCausalLM", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.0.0"), + reason="GLM4 tokenizer requires transformers>=5.0.0", + ), + ), + "trl-internal-testing/tiny-GptOssForCausalLM", + "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + "trl-internal-testing/tiny-Qwen3MoeForCausalLM", + pytest.param( + "trl-internal-testing/tiny-NemotronHForCausalLM-nano", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.7.0"), + reason="Nemotron 3 gradient checkpointing requires transformers>=5.7.0 (see transformers#45625)", + ), + ), + pytest.param( + "trl-internal-testing/tiny-Olmo3ForCausalLM", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("4.57.0"), + reason="Olmo 3 requires transformers>=4.57.0", + ), + ), + ], + ) + def test_train(self, model_id): + dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") + + training_args = DPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + report_to="none", + ) + trainer = DPOTrainer(model=model_id, args=training_args, train_dataset=dataset) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.parametrize( + "config_name", + [ + "standard_preference", + "conversational_preference", + "standard_implicit_prompt_preference", + "conversational_implicit_prompt_preference", + ], + ) + def test_train_dataset_format(self, config_name): + dataset = load_dataset("trl-internal-testing/zen", config_name, split="train") + + training_args = DPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + report_to="none", + ) + trainer = DPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + # Special case for harmony + def test_train_gpt_oss(self): + dataset = load_dataset("trl-internal-testing/harmony", "preference", split="train") + + training_args = DPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + report_to="none", + ) + trainer = DPOTrainer( + model="trl-internal-testing/tiny-GptOssForCausalLM", args=training_args, train_dataset=dataset + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_model(self): + model = AutoModelForCausalLM.from_pretrained( + "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + dtype="float32", + ) + + dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") + + training_args = DPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + report_to="none", + ) + trainer = DPOTrainer(model=model, args=training_args, train_dataset=dataset) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.parametrize( + "loss_type", + [ + "sigmoid", + "hinge", + "ipo", + "exo_pair", + "nca_pair", + "robust", + "bco_pair", + "sppo_hard", + "aot", + "aot_unpaired", + "apo_zero", + "apo_down", + "discopop", + "sft", + "sigmoid_norm", + ], + ) + def test_train_loss_types(self, loss_type): + dataset = load_dataset("trl-internal-testing/zen", "standard_preference") + + training_args = DPOConfig( + output_dir=self.tmp_dir, + loss_type=loss_type, + label_smoothing=1e-3 if loss_type == "exo_pair" else 0.0, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + report_to="none", + eval_strategy="steps", + eval_steps=3, + ) + trainer = DPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset["train"], + eval_dataset=dataset["test"], + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_multi_loss_types(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") + + training_args = DPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + loss_type=["sigmoid", "bco_pair", "sft"], # this specific combination is used in MPO + report_to="none", + ) + trainer = DPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_wpo(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") + + training_args = DPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + report_to="none", + use_weighting=True, + ) + trainer = DPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_ld(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") + + training_args = DPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + report_to="none", + ld_alpha=0.5, + ) + trainer = DPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.parametrize( + "f_divergence_type", + ["reverse_kl", "forward_kl", "js_divergence", "alpha_divergence"], + ) + def test_train_with_f_divergence(self, f_divergence_type): + dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") + + training_args = DPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + report_to="none", + f_divergence_type=f_divergence_type, + ) + trainer = DPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_explicit_ref_model(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") + + training_args = DPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + report_to="none", + ) + # When specifying a ref model, it's usually because we want it to be a different checkpoint, but for testing + # purposes we will just just use the same checkpoint + ref_model = AutoModelForCausalLM.from_pretrained( + "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", dtype="float32" + ) + trainer = DPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + ref_model=ref_model, + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + new_ref_param = trainer.ref_model.get_parameter(n) + torch.testing.assert_close(param, new_ref_param, msg=f"Reference model parameter {n} has changed.") + + def test_train_with_sync_ref_model(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") + + training_args = DPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + sync_ref_model=True, + ref_model_sync_steps=2, # reduce sync steps to ensure a sync happens + report_to="none", + ) + trainer = DPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + assert trainer.ref_model is not None + previous_ref_params = {n: param.clone() for n, param in trainer.ref_model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + new_ref_param = trainer.ref_model.get_parameter(n) + assert not torch.equal(previous_ref_params[n], new_ref_param), f"Ref Parameter {n} has not changed." + + def test_train_model_dtype(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") + + training_args = DPOConfig( + output_dir=self.tmp_dir, + model_init_kwargs={"dtype": torch.float16}, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + report_to="none", + ) + trainer = DPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + # For some reasonn model.layers.0.input_layernorm.weight doesn't change in GitHub Actions but does + # locally. We ignore this parameter for now + if "layernorm" in n: + continue + new_param = trainer.model.get_parameter(n) + # Check the torch dtype + assert new_param.dtype == torch.float16 + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @require_peft + def test_train_dense_with_peft_config_lora(self): + model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" + model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32") + base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()] + + dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") + + training_args = DPOConfig( + output_dir=self.tmp_dir, + learning_rate=1.0, # use higher lr because gradients are tiny and default lr can stall updates + report_to="none", + ) + + trainer = DPOTrainer( + model=model_id, + args=training_args, + train_dataset=dataset, + peft_config=LoraConfig(), + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the peft params have changed and the base model params have not changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + if n in base_param_names: # We expect the base model params to be the same + torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.") + elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @require_peft + def test_train_moe_with_peft_config(self): + model_id = "trl-internal-testing/tiny-GptOssForCausalLM" + model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32") + base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()] + + dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") + + training_args = DPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + report_to="none", + ) + + trainer = DPOTrainer( + model=model_id, + args=training_args, + train_dataset=dataset, + peft_config=LoraConfig(target_parameters=["mlp.experts.down_proj", "mlp.experts.gate_up_proj"]), + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the peft params have changed and the base model params have not changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + if n in base_param_names: # We expect the base model params to be the same + torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.") + elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @require_peft + def test_train_peft_model(self): + model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" + model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32") + + base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()] + + lora_config = LoraConfig() + model = get_peft_model(model, lora_config) + + dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") + + training_args = DPOConfig( + output_dir=self.tmp_dir, + learning_rate=1.0, # use higher lr because gradients are tiny and default lr can stall updates + report_to="none", + ) + trainer = DPOTrainer(model=model, args=training_args, train_dataset=dataset) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the peft params have changed and the base model params have not changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + if n in base_param_names: # We expect the base model params to be the same + torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.") + elif "base_layer" not in n and "ref" not in n: # and the peft params to be different (except base and ref) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + # In practice, this test is the same as `test_train_dense_with_peft_config_lora`, since gradient checkpointing is + # enabled by default in `DPOTrainer`. We keep it as a regression guard: if the default ever changes, we still + # explicitly test PEFT + gradient checkpointing, which has caused issues in the past. + @require_peft + def test_train_with_peft_config_and_gradient_checkpointing(self): + model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" + model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32") + base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()] + + dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") + + training_args = DPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + gradient_checkpointing=True, + report_to="none", + ) + + trainer = DPOTrainer( + model=model_id, + args=training_args, + train_dataset=dataset, + peft_config=LoraConfig(), + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the peft params have changed and the base model params have not changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + if n in base_param_names: # We expect the base model params to be the same + torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.") + elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @require_liger_kernel + def test_train_with_liger(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") + + training_args = DPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + use_liger_kernel=True, + report_to="none", + ) + trainer = DPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @require_liger_kernel + @require_peft + def test_init_fails_with_peft_and_liger(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") + + training_args = DPOConfig( + output_dir=self.tmp_dir, + use_liger_kernel=True, + report_to="none", + ) + + with pytest.raises(NotImplementedError, match="Liger DPO loss is not implemented for PEFT models."): + DPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset, + peft_config=LoraConfig(), + ) + + def test_train_with_iterable_dataset(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train", streaming=True) + + training_args = DPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + max_steps=3, + report_to="none", + ) + trainer = DPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @require_kernels + @pytest.mark.skipif( + not is_ampere_or_newer() and torch_device != "xpu", + reason="Flash Attention 2 requires Ampere or newer GPU, or XPU", + ) + def test_train_padding_free(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") + + training_args = DPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + padding_free=True, + model_init_kwargs={"attn_implementation": "kernels-community/flash-attn2"}, + bf16=True, # flash_attention_2 only supports bf16 and fp16 + report_to="none", + ) + trainer = DPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_chat_template_kwargs(self): + dataset = load_dataset("trl-internal-testing/zen", "conversational_preference", split="train") + + training_args = DPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + report_to="none", + ) + + tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5") + # The following template is a simplified version of the Qwen chat template, where an additional argument + # `role_capital` is used to control the capitalization of roles. + tokenizer.chat_template = '{%- if messages[0]["role"] == "system" -%} {{ "<|im_start|>" + ("SYSTEM" if role_capital else "system") + "\\n" + messages[0]["content"] + "<|im_end|>\\n" }}{%- else -%} {{ "<|im_start|>" + ("SYSTEM" if role_capital else "system") + "\\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\\n" }}{%- endif -%}{%- for message in messages -%} {%- if (message.role == "user") or (message.role == "system" and not loop.first) or (message.role == "assistant" and not message.tool_calls) -%} {{ "<|im_start|>" + (message.role.upper() if role_capital else message.role) + "\\n" + message.content + "<|im_end|>\\n" }} {%- elif message.role == "assistant" -%} {{ "<|im_start|>" + ("ASSISTANT" if role_capital else "assistant") }} {%- if message.content -%} {{ "\\n" + message.content }} {%- endif -%} {{ "<|im_end|>\\n" }} {%- elif message.role == "tool" -%} {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != "tool") -%} {{ "<|im_start|>" + ("USER" if role_capital else "user") }} {%- endif -%} {{ "\\n\\n" + message.content + "\\n" }} {%- if loop.last or (messages[loop.index0 + 1].role != "tool") -%} {{ "<|im_end|>\\n" }} {%- endif -%} {%- endif -%}{%- endfor -%}{%- if add_generation_prompt -%} {{ "<|im_start|>" + ("ASSISTANT" if role_capital else "assistant") + "\\n" }}{%- endif -%}' + + dataset = dataset.add_column( + "chat_template_kwargs", [{"role_capital": bool(i % 2)} for i in range(len(dataset))] + ) + assert "chat_template_kwargs" in dataset.features + + trainer = DPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset, + processing_class=tokenizer, + ) + + assert trainer.processing_class.chat_template == tokenizer.chat_template + + for i in range(2): + role = "SYSTEM" if i else "system" + system_prompt = ( + f"<|im_start|>{role}\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>" + ) + system_prompt_ids = trainer.processing_class(system_prompt)["input_ids"] + assert trainer.train_dataset[i]["prompt_ids"][: len(system_prompt_ids)] == system_prompt_ids + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_toolcall_data(self): + dataset = load_dataset("trl-internal-testing/toolcall", "preference", split="train") + + training_args = DPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=2, # toolcall sequences are longer than standard data, reduce batch size to avoid OOM + max_length=512, # toolcall sequences are longer than standard data, limit length to avoid OOM + report_to="none", + ) + trainer = DPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_eval(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_preference") + + training_args = DPOConfig(output_dir=self.tmp_dir, eval_strategy="steps", eval_steps=3, report_to="none") + trainer = DPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset["train"], + eval_dataset=dataset["test"], + ) + + trainer.train() + + assert trainer.state.log_history[0]["eval_loss"] is not None + + def test_train_with_multiple_eval_dataset(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_preference") + + training_args = DPOConfig(output_dir=self.tmp_dir, eval_strategy="steps", eval_steps=3, report_to="none") + trainer = DPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset["train"], + eval_dataset={"data1": dataset["test"], "data2": dataset["test"]}, + ) + trainer.train() + + assert trainer.state.log_history[-3]["eval_data1_loss"] is not None + assert trainer.state.log_history[-2]["eval_data2_loss"] is not None + + def test_train_with_compute_metrics(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_preference") + + def dummy_compute_metrics(eval_pred): + return {"my_metric": 0.123} + + training_args = DPOConfig( + output_dir=self.tmp_dir, + eval_strategy="steps", + eval_steps=3, + report_to="none", + ) + trainer = DPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset["train"], + eval_dataset=dataset["test"], + compute_metrics=dummy_compute_metrics, + ) + + trainer.train() + + assert trainer.state.log_history[-2]["eval_my_metric"] == 0.123 + + # In practice, this test is the same as `test_train`, since gradient checkpointing is enabled by default in + # `DPOTrainer`. We keep it as a regression guard: if the default ever changes, we still explicitly test gradient + # checkpointing, which has caused issues in the past. + def test_train_with_gradient_checkpointing(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") + + training_args = DPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + gradient_checkpointing=True, + report_to="none", + ) + trainer = DPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_tag_added(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") + + trainer = DPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + train_dataset=dataset, + ) + + for tag in ["dpo", "trl"]: + assert tag in trainer.model.model_tags + + @require_peft + def test_tag_added_peft(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") + + trainer = DPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + train_dataset=dataset, + peft_config=LoraConfig(), + ) + + for tag in ["dpo", "trl"]: + assert tag in trainer.model.model_tags + + @require_peft + @require_bitsandbytes + def test_peft_with_quantization(self): + model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" + + quantization_config = BitsAndBytesConfig( + load_in_4bit=True, + bnb_4bit_use_double_quant=True, + bnb_4bit_quant_type="nf4", + bnb_4bit_compute_dtype=torch.float16, + ) + model = AutoModelForCausalLM.from_pretrained( + model_id, + dtype="float32", + quantization_config=quantization_config, + ) + + dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") + + # Initialize the trainer with the already configured PeftModel + training_args = DPOConfig(output_dir=self.tmp_dir, learning_rate=0.1, report_to="none") + trainer = DPOTrainer(model=model, args=training_args, train_dataset=dataset, peft_config=LoraConfig()) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + assert trainer.state.log_history[-1]["mean_token_accuracy"] is not None + + # Check that the peft params have changed and the base model params have not changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + # In bitsandbytes, bias parameters are automatically cast to the input dtype during the forward pass if + # their dtype doesn’t match. This causes the module to change unexpectedly during the first forward pass of + # the training. To handle this, we cast these specific bias parameters to float32 before comparison. + # https://github.com/bitsandbytes-foundation/bitsandbytes/blob/45553f7392e524eacf400b132cfe01261f6477be/bitsandbytes/nn/modules.py#L518 + # We still need to investigate why the compute dtype ends up being different than for these parameters. + if n in [ + "base_model.model.model.layers.1.self_attn.k_proj.bias", + "base_model.model.model.layers.1.self_attn.q_proj.base_layer.bias", + "base_model.model.model.layers.1.self_attn.v_proj.base_layer.bias", + ]: + param = param.float() + + if "lora" not in n: # We expect the base model params to be the same + torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.") + elif "lora" in n: # We expect the peft params to be different + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + else: + raise ValueError(f"Unexpected parameter {n} in model: {trainer.model}") + + +@require_vision +class TestDPOTrainerVLM(TrlTestCase): + @pytest.mark.parametrize( + "model_id", + [ + "trl-internal-testing/tiny-Gemma3ForConditionalGeneration", + pytest.param( + "trl-internal-testing/tiny-Gemma4ForConditionalGeneration", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.5.0"), + reason="Gemma4 models were introduced in transformers-5.5.0", + ), + ), + # "trl-internal-testing/tiny-Idefics2ForConditionalGeneration", high memory peak, skipped for now + # "trl-internal-testing/tiny-Idefics3ForConditionalGeneration", high memory peak, skipped for now + "trl-internal-testing/tiny-LlavaForConditionalGeneration", + "trl-internal-testing/tiny-LlavaNextForConditionalGeneration", + "trl-internal-testing/tiny-Qwen2VLForConditionalGeneration", + "trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration", + # "trl-internal-testing/tiny-SmolVLMForConditionalGeneration", seems not to support bf16 properly + pytest.param( + "trl-internal-testing/tiny-Qwen3VLForConditionalGeneration", + marks=[ + pytest.mark.skipif( + Version(transformers.__version__) < Version("4.57.0"), + reason="Qwen3-VL series were introduced in transformers-4.57.0", + ), + ], + ), + pytest.param( + "trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-NoThink", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.2.0"), + reason="Qwen3.5 models were introduced in transformers-5.2.0", + ), + ), + pytest.param( + "trl-internal-testing/tiny-Qwen3_5MoeForConditionalGeneration-3.6", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.2.0"), + reason="Qwen3.5 models were introduced in transformers-5.2.0", + ), + ), + ], + ) + def test_train_vlm(self, model_id): + dataset = load_dataset("trl-internal-testing/zen-image", "conversational_preference", split="train") + + training_args = DPOConfig( + output_dir=self.tmp_dir, + max_length=None, # for VLMs, truncating can remove image tokens, leading to errors + per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM + report_to="none", + ) + trainer = DPOTrainer(model=model_id, args=training_args, train_dataset=dataset) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + # LLaVA & LLaVA-Next: vision_feature_layer=-2 leaves the last encoder layer (layers.1) and + # post_layernorm (pooler-only path) without gradient by design. Assert they stay frozen — if they + # ever start training, the feature-selection plumbing has likely regressed. + if model_id in ( + "trl-internal-testing/tiny-LlavaForConditionalGeneration", + "trl-internal-testing/tiny-LlavaNextForConditionalGeneration", + ) and ("encoder.layers.1" in n or "post_layernorm" in n): + assert torch.equal(param, new_param), f"Param {n} expected frozen by LLaVA design, but changed" + else: + assert not torch.equal(param, new_param), f"Param {n} is not updated" + + @pytest.mark.parametrize( + "model_id", + [ + "trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration", + ], + ) + @pytest.mark.xfail( + parse_version(transformers.__version__) < parse_version("4.57.0"), + reason="Mixing text-only and image+text examples is only supported in transformers >= 4.57.0", + strict=False, + ) + def test_train_vlm_multi_image(self, model_id): + dataset = load_dataset("trl-internal-testing/zen-multi-image", "conversational_preference", split="train") + + training_args = DPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + max_length=None, # for VLMs, truncating can remove image tokens, leading to errors + per_device_train_batch_size=1, # VLM training is memory intensive, reduce batch size to avoid OOM + report_to="none", + ) + trainer = DPOTrainer( + model=model_id, + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Param {n} is not updated" + + @pytest.mark.parametrize( + "model_id", + [ + "trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration", + ], + ) + @pytest.mark.parametrize( + "dataset_config", + ["conversational_preference", "standard_preference"], + ) + def test_train_vlm_text_only_data(self, model_id, dataset_config): + dataset = load_dataset("trl-internal-testing/zen", dataset_config, split="train") + + training_args = DPOConfig(output_dir=self.tmp_dir, report_to="none") + trainer = DPOTrainer( + model=model_id, + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + if n.startswith("model.visual"): + torch.testing.assert_close(param, new_param, rtol=1e-12, atol=1e-12, msg=f"Param {n} is updated") + else: + assert not torch.equal(param, new_param), f"Param {n} is not updated" + + def test_train_vlm_with_max_length(self): + # Regression test for #5283: mm_token_type_ids must be truncated alongside input_ids when max_length is set, + # otherwise a shape mismatch crashes the model forward pass. + # max_length=37 truncates 1 completion token (total_len=38) while keeping all image tokens (prompt_len=34) safe. + dataset = load_dataset("trl-internal-testing/zen-image", "conversational_preference", split="train") + training_args = DPOConfig( + output_dir=self.tmp_dir, + max_length=37, # total_len=38, prompt_len=34 — truncates completion, not image tokens + per_device_train_batch_size=2, + report_to="none", + ) + trainer = DPOTrainer( + model="trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration", + args=training_args, + train_dataset=dataset, + ) + trainer.train() + assert trainer.state.log_history[-1]["train_loss"] is not None + + def test_train_vlm_keep_end_raises(self): + # Regression test for #5285: keep_end with a VLM must raise at init time, not silently corrupt training. + # Image tokens live at the start of the sequence (in the prompt); keep_end would drop them. + dataset = load_dataset("trl-internal-testing/zen-image", "conversational_preference", split="train") + with pytest.warns(FutureWarning, match="keep_end.*deprecated"): + training_args = DPOConfig( + output_dir=self.tmp_dir, + max_length=32, + truncation_mode="keep_end", + report_to="none", + ) + with pytest.raises(ValueError, match="truncation_mode='keep_end' is not supported for vision-language models"): + DPOTrainer( + model="trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration", + args=training_args, + train_dataset=dataset, + ) + + def test_vision_dataset_with_text_model_raises(self): + dataset = load_dataset("trl-internal-testing/zen-image", "conversational_preference", split="train") + training_args = DPOConfig(output_dir=self.tmp_dir, report_to="none") + with pytest.raises(ValueError, match="vision-related.*vision-language model"): + DPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset, + ) + + def test_precompute_ref_log_probs_raises_for_vision(self): + dataset = load_dataset("trl-internal-testing/zen-image", "conversational_preference", split="train") + training_args = DPOConfig(output_dir=self.tmp_dir, report_to="none", precompute_ref_log_probs=True) + with pytest.raises(ValueError, match="precompute_ref_log_probs.*not supported for vision datasets"): + DPOTrainer( + model="trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration", + args=training_args, + train_dataset=dataset, + ) + + @require_liger_kernel + def test_train_vlm_liger(self): + dataset = load_dataset("trl-internal-testing/zen-image", "conversational_preference", split="train") + training_args = DPOConfig( + output_dir=self.tmp_dir, + max_length=None, # for VLMs, truncating can remove image tokens, leading to errors + per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM + use_liger_kernel=True, + report_to="none", + ) + trainer = DPOTrainer( + model="trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Param {n} is not updated" + + +@pytest.mark.slow +class TestDPOTrainerSlow(TrlTestCase): + # Gemma 3n uses a timm encoder, making it difficult to create a smaller variant for testing. + # To ensure coverage, we run tests on the full model but mark them as slow to exclude from default runs. + @pytest.mark.skip(reason="Model google/gemma-3n-E2B-it is gated and requires HF token") + @require_vision + def test_train_vlm_gemma_3n(self): + dataset = load_dataset("trl-internal-testing/zen-image", "conversational_preference", split="train") + + training_args = DPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + max_length=None, # for VLMs, truncating can remove image tokens, leading to errors + per_device_train_batch_size=1, # VLM training is memory intensive, reduce batch size to avoid OOM + model_init_kwargs={"dtype": "bfloat16"}, + report_to="none", + ) + trainer = DPOTrainer(model="google/gemma-3n-E2B-it", args=training_args, train_dataset=dataset) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + if "model.audio_tower" in n or "model.embed_audio" in n: + # The audio embedding parameters are not updated because this dataset contains no audio data + continue + assert not torch.equal(param, new_param), f"Param {n} is not updated" diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_grpo_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_grpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..5b74431bafb72399756306719e7eb25e02e21666 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_grpo_trainer.py @@ -0,0 +1,3380 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import gc +import os +import warnings +from collections.abc import Callable +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +import numpy as np +import pytest +import torch +import transformers +from accelerate.utils.memory import release_memory +from datasets import Dataset, Image, load_dataset +from packaging.version import Version +from transformers import ( + AutoModelForCausalLM, + AutoModelForImageTextToText, + AutoModelForSequenceClassification, + AutoProcessor, + AutoTokenizer, + BitsAndBytesConfig, +) +from transformers.testing_utils import backend_empty_cache, torch_device +from transformers.utils import is_peft_available + +from trl import GRPOConfig, GRPOTrainer +from trl.import_utils import is_liger_kernel_available +from trl.trainer.utils import get_kbit_device_map + +from .testing_utils import ( + TrlTestCase, + is_ampere_or_newer, + require_bitsandbytes, + require_jmespath, + require_kernels, + require_liger_kernel, + require_peft, + require_torch_accelerator, + require_vision, + require_vllm, +) + + +if is_peft_available(): + from peft import LoraConfig, PeftModel, get_peft_model + + +def multiply_tool(a: int, b: int) -> int: + """ + Multiplies two integers. + + Args: + a: The first integer. + b: The second integer. + + Returns: + The product of the two integers. + """ + return a * b + + +async def async_multiply_tool(a: int, b: int) -> int: + """ + Asynchronously multiplies two integers. + + Args: + a: The first integer. + b: The second integer. + + Returns: + The product of the two integers. + """ + return a * b + + +class TestGetHighEntropyMask(TrlTestCase): + def get_high_entropy_mask(self, entropies, mask, threshold): + """Helper method to test the get_high_entropy_mask functionality.""" + # Create a mock trainer with minimal setup + from unittest.mock import Mock + + # Create a mock accelerator + mock_accelerator = Mock() + mock_accelerator.num_processes = 1 # Single process for testing + + # Create a minimal trainer instance just to access the method + trainer = Mock(spec=GRPOTrainer) + trainer.accelerator = mock_accelerator + trainer.accelerator.gather = lambda x: x + trainer.accelerator.pad_across_processes = lambda x, dim, pad_index: x + + # Call the actual method from GRPOTrainer + return GRPOTrainer.get_high_entropy_mask(trainer, entropies, mask, threshold) + + def test_compute_entropy_mask_0(self): + # We have a total of 12 tokens out of which 10 are non-pad. + # for a top_entropy_quantile of 0.8, we expect the top 20% i.e 2 non-pad tokens corresponding to + # the highest entropy to be unmasked. + # In our example these will be the tokens corresponding to the entropies 0.9 and 1.0 since 1.1 and 1.2 are pad + # tokens they are excluded from the entropy threshold calculation. + entropies = torch.tensor([[0.1, 0.2, 0.3, 0.4, 0.5, 0.6], [0.7, 0.8, 0.9, 1.0, 1.1, 1.2]]) + mask = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0]]) + entropy_mask = self.get_high_entropy_mask(entropies, mask, threshold=0.8) + expected_mask = torch.tensor([[0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0]], dtype=torch.bool) + torch.testing.assert_close(entropy_mask, expected_mask) + + def test_compute_entropy_mask_1(self): + # Another example with a different set of entropies and a different mask. + entropies = torch.tensor([[0.1, 0.2, 0.3, 1.4, 0.5, 0.14], [0.5, 0.6, 0.7, 0.8, 0.9, 1.0]]) + mask = torch.tensor([[1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 0, 0]]) + entropy_mask = self.get_high_entropy_mask(entropies, mask, threshold=0.8) + expected_mask = torch.tensor([[0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 0, 0]], dtype=torch.bool) + torch.testing.assert_close(entropy_mask, expected_mask) + + def test_compute_entropy_mask_lower_threshold(self): + # For a threshold of 0.5 we expect the top half of the non-pad tokens to be unmasked. + entropies = torch.tensor([[0.1, 0.2, 0.3, 0.4, 0.5, 0.6], [0.7, 0.8, 0.9, 1.0, 1.1, 1.2]]) + mask = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0]]) + entropy_mask = self.get_high_entropy_mask(entropies, mask, threshold=0.5) + expected_mask = torch.tensor([[0, 0, 0, 0, 0, 1], [1, 1, 1, 1, 0, 0]], dtype=torch.bool) + torch.testing.assert_close(entropy_mask, expected_mask) + + def test_compute_entropy_threshold_0(self): + # If the threshold is 0.0 then we expect the mask to be all ones for non-pad tokens. + entropies = torch.tensor([[0.1, 0.2, 0.3, 0.4, 0.5, 0.6], [0.7, 0.8, 0.9, 1.0, 1.1, 1.2]]) + mask = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0]]) + entropy_mask = self.get_high_entropy_mask(entropies, mask, threshold=0.0) + expected_mask = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0]], dtype=torch.bool) + torch.testing.assert_close(entropy_mask, expected_mask) + + def test_compute_entropy_threshold_1(self): + # If the threshold is 1.0 then we expect the mask to be all zeros BUT ONE VALUE. + entropies = torch.tensor([[0.1, 0.2, 0.3, 0.4, 0.5, 0.6], [0.7, 0.8, 0.9, 1.0, 1.1, 1.2]]) + mask = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0]]) + entropy_mask = self.get_high_entropy_mask(entropies, mask, threshold=1.0) + expected_mask = torch.tensor([[0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0]], dtype=torch.bool) + torch.testing.assert_close(entropy_mask, expected_mask) + + def test_compute_entropy_all_masked(self): + # If there are no non-pad tokens we expect the mask to be all zeros. + entropies = torch.tensor([[0.1, 0.2, 0.3, 0.4, 0.5, 0.6], [0.7, 0.8, 0.9, 1.0, 1.1, 1.2]]) + mask = torch.tensor([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]) + entropy_mask = self.get_high_entropy_mask(entropies, mask, threshold=0.5) + expected_mask = torch.tensor([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]], dtype=torch.bool) + torch.testing.assert_close(entropy_mask, expected_mask) + + +class TestGRPORolloutDispatch: + def _make_trainer(self): + trainer = object.__new__(GRPOTrainer) + trainer.accelerator = SimpleNamespace( + device=torch.device("cpu"), + is_main_process=True, + gather=lambda t: t, + ) + trainer.args = SimpleNamespace(report_to=[]) + trainer.model = SimpleNamespace(training=True) + trainer.state = SimpleNamespace(global_step=2, num_input_tokens_seen=0) + trainer._last_loaded_step = 1 + trainer.use_vllm = False + trainer.use_transformers_paged = False + trainer.vllm_generation = SimpleNamespace(sync_weights=MagicMock()) + trainer.processing_class = SimpleNamespace( + batch_decode=MagicMock(return_value=["decoded"]), + ) + trainer._tokenizer = SimpleNamespace(eos_token_id=2, pad_token_id=0) + trainer.tools = None + trainer._metrics = { + "train": { + "num_tokens": [], + **{ + k: [] + for k in [ + "completions/mean_length", + "completions/min_length", + "completions/max_length", + "completions/clipped_ratio", + "completions/mean_terminated_length", + "completions/min_terminated_length", + "completions/max_terminated_length", + ] + }, + } + } + return trainer + + def test_generate_prefers_rollout_func(self): + trainer = self._make_trainer() + trainer.rollout_func = MagicMock( + return_value={ + "prompt_ids": [[1]], + "completion_ids": [[2]], + "logprobs": [[-0.1]], + "env_mask": [[1]], + } + ) + + result = trainer._generate(["prompt"]) + + assert result[0] == [[1]] # prompt_ids + assert result[1] == [[2]] # completion_ids + assert result[2] == [[1]] # tool_mask (from env_mask) + trainer.rollout_func.assert_called_once_with(["prompt"], trainer) + + def test_generate_rollout_func_syncs_vllm_weights_when_needed(self): + trainer = self._make_trainer() + trainer.use_vllm = True + trainer.rollout_func = MagicMock( + return_value={"prompt_ids": [[1]], "completion_ids": [[2]], "logprobs": [[0.0]]} + ) + + trainer._generate(["prompt"]) + + trainer.vllm_generation.sync_weights.assert_called_once() + assert trainer._last_loaded_step == trainer.state.global_step + trainer.rollout_func.assert_called_once_with(["prompt"], trainer) + + def test_generate_rollout_func_raises_when_required_keys_are_missing(self): + trainer = self._make_trainer() + trainer.rollout_func = MagicMock(return_value={"prompt_ids": [[1]], "completion_ids": [[2]]}) + + with pytest.raises(ValueError, match="rollout_func must return keys"): + trainer._generate(["prompt"]) + + +class TestGRPOTrainer(TrlTestCase): + def test_init_minimal(self): + # Test that GRPOTrainer can be instantiated with only model, reward_model and train_dataset + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + train_dataset=dataset, + ) + + @pytest.mark.parametrize( + "model_id", + [ + "trl-internal-testing/tiny-Cohere2ForCausalLM", + pytest.param( + "trl-internal-testing/tiny-Glm4MoeForCausalLM", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.0.0"), + reason="GLM4 tokenizer requires transformers>=5.0.0", + ), + ), + "trl-internal-testing/tiny-GptOssForCausalLM", + "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + "trl-internal-testing/tiny-Qwen3MoeForCausalLM", + pytest.param( + "trl-internal-testing/tiny-NemotronHForCausalLM-nano", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.7.0"), + reason="Nemotron 3 gradient checkpointing requires transformers>=5.7.0 (see transformers#45625)", + ), + ), + ], + ) + def test_train(self, model_id): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = GRPOTrainer( + model=model_id, + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.parametrize("config_name", ["standard_prompt_only", "conversational_prompt_only"]) + def test_train_dataset_format(self, config_name): + dataset = load_dataset("trl-internal-testing/zen", config_name, split="train") + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.parametrize("use_liger_kernel", [False, pytest.param(True, marks=require_liger_kernel)]) + @pytest.mark.parametrize("loss_type", ["bnpo", "dr_grpo", "dapo", "cispo", "sapo", "luspo", "vespo"]) + def test_train_loss_types(self, loss_type, use_liger_kernel): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + importance_sampling_level="sequence" if loss_type == "luspo" else "token", + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=32, # reduce the completion length to reduce memory usage + gradient_accumulation_steps=2, # set to 2 to test than DAPO can operate with accumulated batch + loss_type=loss_type, + use_liger_kernel=use_liger_kernel, + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_eval(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only") + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + per_device_eval_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + eval_strategy="steps", + eval_steps=2, + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset["train"], + eval_dataset=dataset["test"], + ) + + trainer.train() + + def test_train_with_num_generations_eval(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only") + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + per_device_eval_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + num_generations_eval=1, + eval_strategy="steps", + eval_steps=2, + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset["train"], + eval_dataset=dataset["test"], + ) + + trainer.train() + + # Regression test for eval_on_start with loss_type="grpo" (one of the loss types that depends on + # current_gradient_accumulation_steps): evaluation runs before the first training step, when that value is still + # unset. Previously this caused the initial eval to crash. + def test_train_eval_on_start(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only") + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + per_device_eval_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + loss_type="grpo", + eval_strategy="steps", + eval_steps=2, + eval_on_start=True, + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset["train"], + eval_dataset=dataset["test"], + ) + trainer.train() + + def test_train_multiple_iterations(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + num_iterations=2, + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @require_peft + def test_train_peft_config(self): + model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", dtype="float32") + base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()] + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = GRPOTrainer( + model=model, + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + peft_config=LoraConfig(), + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the peft params have changed and the base model params have not changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + if n in base_param_names: # We expect the base model params to be the same + torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.") + elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @require_peft + def test_train_peft_model(self): + model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", dtype="float32") + base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()] + lora_config = LoraConfig() + model = get_peft_model(model, lora_config) + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = GRPOTrainer( + model=model, + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the peft params have changed and the base model params have not changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + if n in base_param_names: # We expect the base model params to be the same + torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.") + elif "base_layer" not in n and "ref" not in n: # and the peft params to be different (except base and ref) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + # In practice, this test is the same as `test_train_peft_config`, since gradient checkpointing is enabled by + # default in `GRPOTrainer`. We keep it as a regression guard: if the default ever changes, we still explicitly test + # PEFT + gradient checkpointing, which has caused issues in the past. + @require_peft + def test_train_peft_with_gradient_checkpointing(self): + model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", dtype="float32") + base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()] + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + gradient_checkpointing=True, # enable gradient checkpointing + report_to="none", + ) + trainer = GRPOTrainer( + model=model, + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + peft_config=LoraConfig(), + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the peft params have changed and the base model params have not changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + if n in base_param_names: # We expect the base model params to be the same + torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.") + elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_different_reward_model(self): + # Use a reward model different from the model: different chat template, tokenization, etc. + dataset = load_dataset("trl-internal-testing/zen", "conversational_prompt_only", split="train") + reward_model_id = "trl-internal-testing/tiny-LlamaForSequenceClassification-3.2" + reward_model = AutoModelForSequenceClassification.from_pretrained(reward_model_id) + reward_tokenizer = AutoTokenizer.from_pretrained(reward_model_id) + # By default, the trainer uses the eos token as the padding token. However, for Llama models, the eos token + # appears in the chat template. Using it as a pad token disrupts the reward calculation, as the calculation + # considers the score of the last token before the first pad token. To ensure correct reward calculations, + # we use a separate pad token instead. + reward_tokenizer.pad_token = "<|finetune_right_pad_id|>" + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=reward_model, + args=training_args, + train_dataset=dataset, + reward_processing_classes=reward_tokenizer, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_reward_func_standard(self): + # Test if trainer can handle reward function with standard format + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + def reward_func(completions, **kwargs): + """Reward function that rewards longer completions.""" + return [float(len(completion)) for completion in completions] + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=reward_func, + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_reward_func_conversational(self): + # Test if trainer can handle reward function with conversational format + dataset = load_dataset("trl-internal-testing/zen", "conversational_prompt_only", split="train") + + def reward_func(completions, **kwargs): + """Reward function that gives higher scores to longer completion content.""" + completion_contents = [completion[0]["content"] for completion in completions] + return [float(len(content)) for content in completion_contents] + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=reward_func, + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_multiple_reward_funcs(self): + # Test that GRPOTrainer can be instantiated with multiple reward functions + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + def reward_func1(completions, **kwargs): + """Reward function that rewards longer completions.""" + return [float(len(completion)) for completion in completions] + + def reward_func2(completions, **kwargs): + """Reward function that rewards completions with more unique letters.""" + return [float(len(set(completion))) for completion in completions] + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=[reward_func1, reward_func2], + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_sync_and_async_reward_funcs(self): + # Test that GRPOTrainer can be instantiated with multiple reward functions one of which is async + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + def sync_reward_func1(completions, **kwargs): + """Reward function that rewards longer completions.""" + return [float(len(completion)) for completion in completions] + + def sync_reward_func2(completions, **kwargs): + return [1 for _ in completions] + + async def async_reward_func(completions, **kwargs): + """Async Reward function that rewards completions with more unique letters.""" + return [float(len(set(completion))) for completion in completions] + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=[sync_reward_func1, sync_reward_func2, async_reward_func], + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_multiple_reward_funcs_with_None_output(self): + """Test that a valid math reward function is processed correctly while the code reward function returns None.""" + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + def applicable_reward_func(completions, **kwargs): + """A reward function that rewards longer completions.""" + return [float(len(completion)) for completion in completions] + + def non_applicable_reward_func(completions, **kwargs): + """A reward function that returns None for all inputs, as it is not applicable to this sample.""" + return [None] * len(completions) + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=[ + applicable_reward_func, + non_applicable_reward_func, + ], # One applicable, one non applicable + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = { + n: param.clone() for n, param in trainer.model.named_parameters() if param.requires_grad + } + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_multiple_reward_funcs_with_weights(self): + """Test that GRPOTrainer can handle multiple reward functions with weights.""" + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + def reward_func1(completions, **kwargs): + """Reward function that rewards longer completions.""" + return [float(len(completion)) for completion in completions] + + def reward_func2(completions, **kwargs): + """Reward function that rewards completions with more unique letters.""" + return [float(len(set(completion))) for completion in completions] + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + reward_weights=[0.7, 0.3], # weight of reward_func1 and reward_func2 respectively + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=[reward_func1, reward_func2], + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + # Check that training logs contain both reward metrics + assert trainer.state.log_history[-1]["train_loss"] is not None + assert "rewards/reward_func1/mean" in trainer.state.log_history[-1] + assert "rewards/reward_func1/std" in trainer.state.log_history[-1] + assert "rewards/reward_func2/mean" in trainer.state.log_history[-1] + assert "rewards/reward_func2/std" in trainer.state.log_history[-1] + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.parametrize("multi_objective_aggregation", ["sum_then_normalize", "normalize_then_sum"]) + def test_reward_metric_reflects_reward_weights(self, multi_objective_aggregation): + """Test that the logged 'reward' metric uses reward_weights, not an unweighted sum.""" + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + def constant_reward_1(completions, **kwargs): + return [1.0] * len(completions) + + def constant_reward_0(completions, **kwargs): + return [0.0] * len(completions) + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + reward_weights=[0.7, 0.3], + multi_objective_aggregation=multi_objective_aggregation, + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=[constant_reward_1, constant_reward_0], + args=training_args, + train_dataset=dataset, + ) + + trainer.train() + + log = trainer.state.log_history[-1] + # With reward_weights=[0.7, 0.3] and rewards [1.0, 0.0]: + # weighted reward = 0.7*1.0 + 0.3*0.0 = 0.7 + # unweighted reward = 1.0 + 0.0 = 1.0 + assert abs(log["reward"] - 0.7) < 1e-5, ( + f"Expected logged reward to be ~0.7 (weighted), got {log['reward']}. " + "The reward metric should reflect reward_weights." + ) + + def test_train_multiple_mixed_reward_funcs(self): + # Test if the trainer can handle a mix of reward functions and reward models + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + def reward_func(completions, **kwargs): + """Reward function that rewards longer completions.""" + return [float(len(completion)) for completion in completions] + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=[reward_func, "trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5"], + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_reward_func_additional_column(self): + # Test if trainer can handle reward function that rely on additional columns in the dataset + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + # Add a column to the dataset (dummy example, the column could be anything) + some_values = list(range(len(dataset))) + dataset = dataset.add_column("some_values", some_values) + + def reward_func(completions, some_values, **kwargs): + """Reward function that rewards completions with lengths closer to the values in some_values.""" + return [ + float(abs(len(completion) - value)) for completion, value in zip(completions, some_values, strict=True) + ] + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=reward_func, + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_sync_ref_model(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + beta=0.1, # ensure ref model is created so sync can update it + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + sync_ref_model=True, + ref_model_sync_steps=2, # reduce sync steps to ensure a sync happens + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + assert trainer.ref_model is not None + previous_ref_params = {n: param.clone() for n, param in trainer.ref_model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + new_ref_param = trainer.ref_model.get_parameter(n) + assert not torch.equal(previous_ref_params[n], new_ref_param), f"Ref Parameter {n} has not changed." + + def test_train_beta_non_zero(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + training_args = GRPOConfig( + output_dir=self.tmp_dir, + beta=0.1, # set beta to non-zero value to test the case where the reference model is used + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_pad_to_multiple_of(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + pad_to_multiple_of=8, + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_get_off_policy_mask(self): + """ + Test the logic of off-policy masking: + - Keep if Advantage >= 0 + - Keep if KL <= threshold + - Drop if Advantage < 0 AND KL > threshold + """ + mask = torch.ones((3, 4)) # B=3 sequences, T=4 tokens + + advantages = torch.tensor([1.0, -1.0, -1.0]).unsqueeze(-1) + sampling_per_token_logps = torch.zeros((3, 4)) + per_token_logps = torch.zeros((3, 4)) + + per_token_logps[0, :] = -2.0 # Pos adv + High KL (0−(−2)=2) -> Keep + per_token_logps[1, :] = -0.5 # Neg adv + Low KL (0.5) -> Keep + per_token_logps[2, :] = -2.0 # Neg adv + High KL (2.0) -> Drop + + off_policy_threshold = 1.0 + + expected_mask = torch.tensor([[1.0], [1.0], [0.0]]) + + off_policy_mask = GRPOTrainer.get_off_policy_mask( + advantages, per_token_logps, sampling_per_token_logps, mask, off_policy_threshold + ) + + torch.testing.assert_close(off_policy_mask, expected_mask) + + def test_get_off_policy_mask_padding(self): + """Test that padding is correctly ignored in KL calculation.""" + mask = torch.tensor([[1.0, 1.0, 0.0, 0.0]]) # 2 valid tokens + advantages = torch.tensor([[-1.0]]) # Negative advantage + + sampling_per_token_logps = torch.zeros((1, 4)) + per_token_logps = torch.zeros((1, 4)) + + # Valid tokens have High KL (2.0) + per_token_logps[0, 0] = -2.0 + per_token_logps[0, 1] = -2.0 + + # Padding tokens have abnormal values (should be ignored) + per_token_logps[0, 2] = -10_000.0 + per_token_logps[0, 3] = 10_000.0 + + off_policy_threshold = 1.0 + + # Avg KL on valid tokens = (2+2)/2 = 2.0 > 1.0 -> Drop + expected_mask = torch.tensor([[0.0]]) + + off_policy_mask = GRPOTrainer.get_off_policy_mask( + advantages, per_token_logps, sampling_per_token_logps, mask, off_policy_threshold + ) + + torch.testing.assert_close(off_policy_mask, expected_mask) + + # Now test with Low KL on valid tokens + per_token_logps[0, 0] = -0.5 + per_token_logps[0, 1] = -0.5 + # Avg KL = 0.5 <= 1.0 -> Keep + expected_mask_keep = torch.tensor([[1.0]]) + + off_policy_mask_keep = GRPOTrainer.get_off_policy_mask( + advantages, per_token_logps, sampling_per_token_logps, mask, off_policy_threshold + ) + + torch.testing.assert_close(off_policy_mask_keep, expected_mask_keep) + + def test_train_with_off_policy_mask(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + off_policy_mask_threshold=0.5, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @require_liger_kernel + @pytest.mark.xfail(reason="Off-Policy Masking isn't compatible with Liger yet.") + def test_train_with_off_policy_mask_with_liger(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + off_policy_mask_threshold=0.5, + use_liger_kernel=True, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @require_liger_kernel + def test_compute_liger_loss_passes_vllm_is_ratio(self): + """Test that importance_sampling_ratio from inputs is passed to liger_grpo_loss as vllm_is_ratio.""" + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + use_liger_kernel=True, + report_to="none", + logging_strategy="no", + ) + + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + # Mock _generate_and_score_completions to inject importance_sampling_ratio + original_gen = trainer._generate_and_score_completions + + def gen_with_is_ratio(*args, **kwargs): + result = original_gen(*args, **kwargs) + B, T = result["completion_ids"].shape + result["importance_sampling_ratio"] = torch.full((B, T), 0.5, device=result["completion_ids"].device) + return result + + with ( + patch.object(trainer, "_generate_and_score_completions", side_effect=gen_with_is_ratio), + patch.object(trainer.liger_grpo_loss, "forward", wraps=trainer.liger_grpo_loss.forward) as mock_forward, + ): + trainer.train() + + # Verify vllm_is_ratio was passed in every call to liger_grpo_loss + assert mock_forward.call_count > 0, "liger_grpo_loss.forward was never called" + for call in mock_forward.call_args_list: + vllm_is_ratio = call.kwargs.get("vllm_is_ratio") + assert vllm_is_ratio is not None, ( + "vllm_is_ratio should not be None when importance_sampling_ratio is present" + ) + assert (vllm_is_ratio == 0.5).all(), ( + "vllm_is_ratio values should match the injected importance_sampling_ratio" + ) + + release_memory(trainer.model, trainer) + + @pytest.mark.parametrize("use_liger_kernel", [False, pytest.param(True, marks=require_liger_kernel)]) + def test_train_with_bias_correction_kl(self, use_liger_kernel): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + training_args = GRPOConfig( + output_dir=self.tmp_dir, + beta=0.1, # set beta to non-zero value to test the case where the reference model is used + use_bias_correction_kl=True, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + use_liger_kernel=use_liger_kernel, + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.parametrize( + "model_name", + ["trl-internal-testing/tiny-Qwen3ForCausalLM", "trl-internal-testing/tiny-Gemma2ForCausalLM"], + # Gemma2 has the input word embeddings and lm_head tied, Qwen3 does not + ) + def test_train_with_cast_lm_head_to_fp32(self, model_name): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + cast_lm_head_to_fp32=True, + ) + trainer = GRPOTrainer( + model=model_name, + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + assert trainer.model.lm_head.weight.dtype == torch.float32 + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_entropy_filter(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + top_entropy_quantile=0.2, + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @require_peft + @require_vllm + @pytest.mark.skip(reason="We should add a mock for the vLLM server.") + def test_train_vllm_and_peft(self): + """Test that training works with vLLM for generation.""" + model = AutoModelForCausalLM.from_pretrained( + "Qwen/Qwen2.5-0.5B-Instruct", dtype="float32" + ) # tiny model is too small for vLLM + base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()] + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + use_vllm=True, + ) + lora_config = LoraConfig( + target_modules="all-linear", + # test with non-default modules as it adds extra keys in state_dict that we need to handle + modules_to_save=["embed_tokens", "lm_head"], + ) + trainer = GRPOTrainer( + model=model, + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + peft_config=lora_config, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the peft params have changed and the base model params have not changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + if n in base_param_names: # We expect the base model params to be the same + torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.") + elif "base_layer" not in n and "original_module" not in n: + # We expect the peft params to be different (except for the base layer) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @require_vllm + @pytest.mark.skip(reason="We should add a mock for the vLLM server.") + def test_train_vllm_structured_outputs(self): + """Test that training works with vLLM for generation with structured outputs.""" + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + use_vllm=True, + vllm_structured_outputs_regex=r"\n.*\n\n\n.*\n", + ) + trainer = GRPOTrainer( + model="Qwen/Qwen2.5-0.5B-Instruct", # tiny model is too small for vLLM + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @require_vllm + @pytest.mark.skip(reason="We should add a mock for the vLLM server.") + @pytest.mark.parametrize( + "vllm_importance_sampling_clip_min, vllm_importance_sampling_clip_max", + [ + (None, 3.0), # only max (current default) + (0.5, None), # only min + (0.5, 5.0), # both (IcePop) + ], + ) + def test_train_vllm_importance_sampling_correction( + self, vllm_importance_sampling_clip_min, vllm_importance_sampling_clip_max + ): + """Test that training works with vLLM for generation with importance sampling correction.""" + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + use_vllm=True, + vllm_importance_sampling_correction=True, + vllm_importance_sampling_clip_min=vllm_importance_sampling_clip_min, + vllm_importance_sampling_clip_max=vllm_importance_sampling_clip_max, + ) + trainer = GRPOTrainer( + model="Qwen/Qwen2.5-0.5B-Instruct", # tiny model is too small for vLLM + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_additional_generation_kwargs(self): + """Test that training works with additional generation kwargs.""" + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + top_p=0.9, + top_k=10, + min_p=0.01, + repetition_penalty=1.1, + ) + + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @require_vllm + @pytest.mark.skip(reason="We should add a mock for the vLLM server.") + def test_train_vllm_with_additional_generation_kwargs(self): + """Test that training works with vLLM and additional generation kwargs.""" + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + use_vllm=True, + top_p=0.9, + top_k=10, + min_p=0.01, + repetition_penalty=1.1, + ) + + trainer = GRPOTrainer( + model="Qwen/Qwen2.5-0.5B-Instruct", # tiny model is too small for vLLM + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_normalize_then_sum_aggregation(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + def reward_func1(completions, **kwargs): + """Reward function that rewards longer completions.""" + return [float(len(completion)) for completion in completions] + + def reward_func2(completions, **kwargs): + """Reward function that rewards completions with more unique letters.""" + return [float(len(set(completion))) for completion in completions] + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + multi_objective_aggregation="normalize_then_sum", + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=[reward_func1, reward_func2], + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.parametrize("scale_rewards", [False, "group", "batch", True, "none"]) + def test_train_scale_rewards(self, scale_rewards): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + scale_rewards=scale_rewards, + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @patch("transformers.generation.utils.GenerationMixin.generate") + def test_train_with_mask_truncated_completions(self, mock_generate): + """Test that training works with mask_truncated_completions=True parameter.""" + + # We mock the generate method because the model's random weights make it extremely unlikely to produce a + # sequence containing the EOS token within the allowed max_completion_length. As a result, all tokens are + # masked in the loss, the model doesn't update, and the final check (which verifies the update) fails. + def fake_generate(input_ids, **kwargs): + # pad_token_id = 151643; eos_token_id = 151645 + completion_ids = torch.tensor( + [ + [1, 2, 3, 4, 5, 6, 7, 8], # this one is truncated + [9, 10, 11, 151645, 151643, 151643, 151643, 151643], # this one contains eos + [12, 13, 14, 15, 16, 17, 18, 151645], # particular case, eos is generated just within the limit + ], + device=input_ids.device, + ) + return torch.cat([input_ids, completion_ids], dim=1) + + mock_generate.side_effect = fake_generate + + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + mask_truncated_completions=True, # Enable masking of truncated completions + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_mask_truncated_completions_all_masked(self): + """ + Test that when all generated completions are truncated (i.e., none contain an EOS token), and + mask_truncated_completions=True, the model receives no effective learning signal and therefore does not update + its parameters. + + Here, we don't mock the generate method, be we rely on the fact that the model the probability of generating + the EOS token is extremely low, so all generated completions are truncated. + """ + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + mask_truncated_completions=True, # Enable masking of truncated completions + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert torch.equal(param, new_param), f"Parameter {n} has changed." + + def test_warning_raised_all_rewards_none(self, caplog): + """Test that a proper warning is raised when all rewards are None.""" + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + def always_none_reward_func(completions, **kwargs): + """Reward function that always returns None.""" + return [None] * len(completions) + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=always_none_reward_func, + args=training_args, + train_dataset=dataset, + ) + + with caplog.at_level("WARNING", logger="trl.trainer.grpo_trainer"): + trainer.train() + + expected_warning = "All reward functions returned None for the following kwargs:" + assert expected_warning in caplog.text + + def test_train_num_generations_larger_than_batch_size(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + num_generations=6, # the number of generations is larger than the batch size, but + gradient_accumulation_steps=2, # gradient accumulation should allow that + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.parametrize("use_liger_kernel", [False, pytest.param(True, marks=require_liger_kernel)]) + def test_train_delta_clipping(self, use_liger_kernel): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + delta=2.0, # set delta to a non-None value + use_liger_kernel=use_liger_kernel, + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_multiple_dataloader_workers(self): + # Pytest/CI often starts background threads before tests run. With Python 3.12, using the default "fork" start + # method in a multi-threaded process emits a DeprecationWarning and may deadlock. + # + # We force "spawn" here to make multiprocessing safe under pytest when DataLoader workers are enabled. This is + # test-environment–specific and not required by the training logic itself. + # + # This means the test does not cover "fork". However, "spawn" is stricter (requires full picklability and clean + # state) and avoids fork-after-threads issues that pytest cannot reliably test anyway. Fork-specific behavior, + # if needed, should be tested in a clean process outside pytest. + torch.multiprocessing.set_start_method("spawn", force=True) + + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + dataloader_num_workers=2, # use multiple dataloader workers + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_generation_kwargs(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + # Pass gen kwargs + generation_kwargs={"do_sample": True, "top_k": 50, "num_beams": 2, "length_penalty": -0.1}, + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_reward_func_accessing_trainer_state(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + def reward_func(completions, **kwargs): + trainer_state = kwargs.get("trainer_state") + assert trainer_state is not None + # transformers.TrainerState instance should have a `global_step` property. + assert hasattr(trainer_state, "global_step") + return [float(len(set(completion))) for completion in completions] + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=reward_func, + args=training_args, + train_dataset=dataset, + ) + trainer.train() + + def test_train_reward_func_with_log_extra(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + def reward_func(completions, **kwargs): + log_extra = kwargs.get("log_extra") + assert log_extra is not None + log_extra("test_column", [completion[:5] for completion in completions]) + return [float(len(completion)) for completion in completions] + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + log_completions=True, + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=reward_func, + args=training_args, + train_dataset=dataset, + ) + trainer.train() + assert "test_column" in trainer._logs["extra"] + + def test_train_reward_func_with_log_metric(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + def reward_func(completions, **kwargs): + log_metric = kwargs.get("log_metric") + assert log_metric is not None + log_metric("custom_accuracy", 0.75) + return [float(len(completion)) for completion in completions] + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=reward_func, + args=training_args, + train_dataset=dataset, + ) + trainer.train() + # log_metric appends to _metrics, which gets averaged and merged into log_history + logged_keys = {k for entry in trainer.state.log_history for k in entry} + assert "custom_accuracy" in logged_keys + + def test_prepare_input_called_with_correct_data(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + max_completion_length=8, # reduce the completion length to reduce memory usage + gradient_accumulation_steps=3, # can be anything in this test + # steps_per_generation*per_device_train_batch_size=24 is divisible by num_generations=4 + steps_per_generation=4, + num_generations=4, + per_device_train_batch_size=6, # reduce the batch size to reduce memory usage + num_iterations=2, + shuffle_dataset=False, + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + # steps_per_generation=4, per_device_train_batch_size=6 and num_generations=4, so we expect a + # generation batch of 24 samples (steps_per_generation * per_device_train_batch_size), containing 6 + # different prompts (steps_per_generation * per_device_train_batch_size // num_generations), each repeated + # 4 times (num_generations). + expected_first_generation_batch = ( + [{"prompt": "Beautiful is better than"}] * 4 + + [{"prompt": "Explicit is"}] * 4 + + [{"prompt": "Simple is better"}] * 4 + + [{"prompt": "Complex"}] * 4 + + [{"prompt": "Flat is better than"}] * 4 + + [{"prompt": "Sparse is better"}] * 4 + ) + expected_second_generation_batch = ( + [{"prompt": "Readability"}] * 4 + + [{"prompt": "Special cases aren't special"}] * 4 + + [{"prompt": "Although practicality beats"}] * 4 + + [{"prompt": "Errors should never"}] * 4 + + [{"prompt": "Unless explicitly"}] * 4 + + [{"prompt": "In the face of ambiguity, refuse"}] * 4 + ) + + with patch.object(GRPOTrainer, "training_step", wraps=trainer.training_step) as mock_prepare: + trainer.train() + # 3 epochs * 2 iterations * 2 generation batches to cover the dataset * 4 steps_per_generation + assert mock_prepare.call_count == 48 + for i in range(0, 8): # Generation batch repeated 8 times (steps_per_generation*num_iterations) + assert mock_prepare.call_args_list[i].args[1] == expected_first_generation_batch + for i in range(8, 16): + assert mock_prepare.call_args_list[i].args[1] == expected_second_generation_batch + + def test_train_sequence_importance_sampling(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + num_iterations=2, # the importance sampling weights won't be 0 in this case + importance_sampling_level="sequence", + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_chat_template_kwargs(self): + dataset = load_dataset("trl-internal-testing/zen", "conversational_prompt_only", split="train") + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + chat_template_kwargs={"enable_thinking": False}, + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen3ForCausalLM", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.xfail( + condition=Version(transformers.__version__) < Version("5.0.0"), + reason="Tool parsing is not supported in transformers versions below 5.0.0", + strict=True, + ) + @require_jmespath + @pytest.mark.parametrize("tools", [[multiply_tool], [async_multiply_tool]]) + def test_train_with_tools(self, tools: list[Callable]): + # In this test, we define a simple tool that multiplies two integers. Regardless of the input prompt, + # the model will generate 3 completions, 2 of which will be valid tool calls. Among the 2 tool calls, one will + # succeed and the other will fail (because of a wrong argument name). + + dataset = load_dataset("trl-internal-testing/zen", "conversational_prompt_only", split="train") + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=128, + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen3MoeForCausalLM", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + tools=tools, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + tool_name = tools[0].__name__ + + def fake_generate(input_ids, **kwargs): + if input_ids.shape[0] == 3: # first call + # fmt: off + if tool_name == "multiply_tool": + completion_ids = torch.tensor( + [ + # '\n{"name": "multiply_tool", "arguments": {"a": 3, "b": 4}}\n<|im_end|>' + [151657, 198, 4913, 606, 788, 330, 64648, 22785, 497, 330, 16370, 788, 5212, 64, 788, 220, 18, 11, 330, 65, 788, 220, 19, 11248, 151658, 151645], + # an invalid tool call with wrong argument name + # '\n{"name": "multiply_tool", "arguments": {"a": 3, "c": 4}}\n<|im_end|>' + [151657, 198, 4913, 606, 788, 330, 64648, 22785, 497, 330, 16370, 788, 5212, 64, 788, 220, 18, 11, 330, 66, 788, 220, 19, 11248, 151658, 151645], + # "I don't know any tool<|im_end|>" + [40, 1513, 944, 1414, 894, 5392, 151645, 151643, 151643, 151643, 151643, 151643, 151643, 151643, 151643, 151643, 151643, 151643, 151643, 151643, 151643, 151643, 151643, 151643, 151643, 151643], + ], + device=input_ids.device, + ) + elif tool_name == "async_multiply_tool": + completion_ids = torch.tensor( + [ + # '\n{"name": "async_multiply_tool", "arguments": {"a": 3, "b": 4}}\n<|im_end|>' + [151657, 198, 4913, 606, 788, 330, 7692, 93054, 22785, 497, 330, 16370, 788, 5212, 64, 788, 220, 18, 11, 330, 65, 788, 220, 19, 11248, 151658, 151645], + # an invalid tool call with wrong argument name + # '\n{"name": "async_multiply_tool", "arguments": {"a": 3, "c": 4}}\n<|im_end|>' + [151657, 198, 4913, 606, 788, 330, 7692, 93054, 22785, 497, 330, 16370, 788, 5212, 64, 788, 220, 18, 11, 330, 66, 788, 220, 19, 11248, 151658, 151645], + # "I don't know any tool<|im_end|>" + [40, 1513, 944, 1414, 894, 5392, 151645, 151643, 151643, 151643, 151643, 151643, 151643, 151643, 151643, 151643, 151643, 151643, 151643, 151643, 151643, 151643, 151643, 151643, 151643, 151643, 151643], + ], + device=input_ids.device, + ) + # fmt: on + else: # second call will only have two inputs in the batch, because two examples have a tool call. + completion_ids = torch.tensor( + [ + # 'Done!<|im_end|>' + [17453, 0, 151645], + # 'Done!<|im_end|>' + [17453, 0, 151645], + ], + device=input_ids.device, + ) + return torch.cat([input_ids, completion_ids], dim=-1) + + with patch.object(trainer.model, "generate", side_effect=fake_generate): + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + assert trainer.state.log_history[-1]["tools/call_frequency"] is not None + assert trainer.state.log_history[-1]["tools/call_frequency"] == pytest.approx(2 / 3) + assert trainer.state.log_history[-1]["tools/failure_frequency"] is not None + assert trainer.state.log_history[-1]["tools/failure_frequency"] == pytest.approx(1 / 2) + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.xfail( + condition=Version(transformers.__version__) < Version("5.2.0"), + reason="Environment factory support is not available in transformers versions below 5.2.0", + strict=True, + ) + @require_jmespath + @patch.dict(os.environ, {"TRL_EXPERIMENTAL_SILENCE": "1"}) + def test_train_with_environment_factory(self): + # In this test, we define a simple tool that increments an internal counter. Regardless of the input prompt, + # the model will generate 3 completions, 2 of which will be valid tool calls. Among the 2 tool calls, one will + # succeed and the other will fail (because of a wrong tool name). + + dataset = load_dataset("trl-internal-testing/zen", "conversational_prompt_only", split="train") + + class DummyEnvironment: + def reset(self, **kwargs): + self._counter = 0 + + def increment(self, step: int) -> int: + """ + Increment the internal counter. + + Args: + step: Value to add to the counter. + + Returns: + The updated counter value. + """ + self._counter += step + return self._counter + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + report_to="none", + ) + + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen3MoeForCausalLM", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + environment_factory=DummyEnvironment, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + def fake_generate(input_ids, **kwargs): + if input_ids.shape[0] == 3: # first call + # fmt: off + completion_ids = torch.tensor( + [ + # '\n{"name": "increment", "arguments": {"step": 1}}\n<|im_end|>' + [151657, 198, 4913, 606, 788, 330, 35744, 497, 330, 16370, 788, 5212, 9520, 788, 220, 16, 11248, 151658, 151645, 151643], + # an invalid tool call with wrong tool name + # '\n{"name": "decrement", "arguments": {"step": 2}}\n<|im_end|>' + [151657, 198, 4913, 606, 788, 330, 450, 13477, 497, 330, 16370, 788, 5212, 9520, 788, 220, 17, 11248, 151658, 151645], + # "I won't increment<|im_end|>" + [40, 2765, 944, 16252, 151645, 151643, 151643, 151643, 151643, 151643, 151643, 151643, 151643, 151643, 151643, 151643, 151643, 151643, 151643, 151643], + ], + device=input_ids.device, + ) + # fmt: on + else: # second call will only have two inputs in the batch, because two examples have a tool call. + completion_ids = torch.tensor( + [ + # 'Done!<|im_end|>' + [17453, 0, 151645], + # 'Done!<|im_end|>' + [17453, 0, 151645], + ], + device=input_ids.device, + ) + return torch.cat([input_ids, completion_ids], dim=-1) + + with patch.object(trainer.model, "generate", side_effect=fake_generate): + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + assert trainer.state.log_history[-1]["tools/call_frequency"] is not None + assert trainer.state.log_history[-1]["tools/call_frequency"] == pytest.approx(2 / 3) + assert trainer.state.log_history[-1]["tools/failure_frequency"] is not None + assert trainer.state.log_history[-1]["tools/failure_frequency"] == pytest.approx(1 / 2) + + # Check the states of the environment + assert trainer.environments[0]._counter == 1 # should have been incremented once + assert trainer.environments[1]._counter == 0 # shouldn't have been incremented because the tool call failed + assert trainer.environments[2]._counter == 0 # shouldn't have been incremented because no tool call was made + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.xfail( + condition=Version(transformers.__version__) < Version("5.0.0"), + reason="Tool parsing is not supported in transformers versions below 5.0.0", + strict=True, + ) + @require_jmespath + def test_train_with_malformed_tool_calls(self): + dataset = load_dataset("trl-internal-testing/zen", "conversational_prompt_only", split="train") + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=128, + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen3MoeForCausalLM", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + tools=[multiply_tool], + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + def fake_generate(input_ids, **kwargs): + # If input_ids.shape[0] < 3, it means that it's a second call, which should not happen here + assert input_ids.shape[0] == 3 + # fmt: off + completion_ids = torch.tensor( + [ + # '\n{"arguments": {"a": 3, "b": 4}}\n<|im_end|>' + [151657, 198, 4913, 16370, 788, 5212, 64, 788, 220, 18, 11, 330, 65, 788, 220, 19, 11248, 151658, 151645, 151643, 151643, 151643, 151643, 151643], + # '\n{"arguments": {"a": 3, "b": 4}}\n<|im_end|>' + [27, 14172, 6659, 397, 4913, 16370, 788, 5212, 64, 788, 220, 18, 11, 330, 65, 788, 220, 19, 11248, 522, 14172, 6659, 29, 151645], + # '\n{"arguments": {a: 3, b: 4}}\n<|im_end|>' + [151657, 198, 4913, 16370, 788, 314, 64, 25, 220, 18, 11, 293, 25, 220, 19, 11248, 151658, 151645, 151643, 151643, 151643, 151643, 151643, 151643], + ], + device=input_ids.device, + ) + # fmt: on + return torch.cat([input_ids, completion_ids], dim=-1) + + with patch.object(trainer.model, "generate", side_effect=fake_generate): + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_mismatched_reward_processing_classes_length(self): + """Test that mismatched length between reward_funcs and reward_processing_classes raises error.""" + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + # Use two reward models + reward_models = [ + "trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + "trl-internal-testing/tiny-Qwen3ForSequenceClassification", + ] + + # Create a single processing class (tokenizer) + single_processing_class = AutoTokenizer.from_pretrained( + "trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5" + ) + + training_args = GRPOConfig(output_dir=self.tmp_dir, report_to="none") + + with pytest.raises(ValueError, match="must match"): + GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=reward_models, + reward_processing_classes=single_processing_class, # only one, but need two + args=training_args, + train_dataset=dataset, + ) + + def test_correct_reward_processing_classes_list(self): + """Test that correct list of reward_processing_classes works properly.""" + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + # Use two reward models + reward_models = [ + "trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + "trl-internal-testing/tiny-Qwen3ForSequenceClassification", + ] + + # Create processing classes + processing_class1 = AutoTokenizer.from_pretrained( + "trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5" + ) + processing_class2 = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen3ForSequenceClassification") + + training_args = GRPOConfig(output_dir=self.tmp_dir, report_to="none") + + # Correct list length should work + correct_processing_classes = [processing_class1, processing_class2] + + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=reward_models, + reward_processing_classes=correct_processing_classes, + args=training_args, + train_dataset=dataset, + ) + + assert len(trainer.reward_processing_classes) == len(reward_models) + + def test_single_reward_model_with_single_processing_class(self): + """Test that single reward model with single processing class works.""" + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + # Use single reward model + reward_model = "trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5" + + # Create a single processing class (tokenizer) + single_processing_class = AutoTokenizer.from_pretrained( + "trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5" + ) + + training_args = GRPOConfig(output_dir=self.tmp_dir, report_to="none") + + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=reward_model, + reward_processing_classes=single_processing_class, # single object for single reward model + args=training_args, + train_dataset=dataset, + ) + + assert len(trainer.reward_processing_classes) == 1 + assert trainer.reward_processing_classes[0] == single_processing_class + + +@require_vision +class TestGRPOTrainerVLM(TrlTestCase): + @pytest.mark.parametrize( + "model_id", + [ + "trl-internal-testing/tiny-Gemma3ForConditionalGeneration", + pytest.param( + "trl-internal-testing/tiny-Gemma4ForConditionalGeneration", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.5.0"), + reason="Gemma4 models were introduced in transformers-5.5.0", + ), + ), + "trl-internal-testing/tiny-LlavaNextForConditionalGeneration", + "trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration", + "trl-internal-testing/tiny-Qwen2VLForConditionalGeneration", + pytest.param( + "trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-NoThink", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.2.0"), + reason="Qwen3.5 models were introduced in transformers-5.2.0", + ), + ), + pytest.param( + "trl-internal-testing/tiny-Qwen3_5MoeForConditionalGeneration-3.6", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.2.0"), + reason="Qwen3.5 models were introduced in transformers-5.2.0", + ), + ), + # "trl-internal-testing/tiny-SmolVLMForConditionalGeneration", seems not to support bf16 properly + ], + ) + def test_train_vlm(self, model_id): + dataset = load_dataset("trl-internal-testing/zen-image", "conversational_prompt_only", split="train") + + def reward_func(completions, **kwargs): + """Reward function that rewards longer completions.""" + return [float(len(completion[0]["content"])) for completion in completions] + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM + num_generations=2, # VLM training is memory intensive, reduce num_generations to avoid OOM + # note: num_generations=2 is only suitable for CI testing; production training should use more generations + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = GRPOTrainer( + model=model_id, + reward_funcs=reward_func, + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + # LLaVA & LLaVA-Next: vision_feature_layer=-2 leaves the last encoder layer (layers.1) and + # post_layernorm (pooler-only path) without gradient by design. Assert they stay frozen — if they + # ever start training, the feature-selection plumbing has likely regressed. + if model_id in ( + "trl-internal-testing/tiny-LlavaForConditionalGeneration", + "trl-internal-testing/tiny-LlavaNextForConditionalGeneration", + ) and ("encoder.layers.1" in n or "post_layernorm" in n): + assert torch.equal(param, new_param), f"Param {n} expected frozen by LLaVA design, but changed" + else: + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_vlm_with_pad_to_multiple_of(self): + # Models like Gemma3 use other forward keyword arguments like token_type_ids that also need to be padded when + # using pad_to_multiple_of, so we test that the trainer correctly pads all the necessary inputs in this case. + dataset = load_dataset("trl-internal-testing/zen-image", "conversational_prompt_only", split="train") + + def reward_func(completions, **kwargs): + """Reward function that rewards longer completions.""" + return [float(len(completion[0]["content"])) for completion in completions] + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM + num_generations=2, # VLM training is memory intensive, reduce num_generations to avoid OOM + # note: num_generations=2 is only suitable for CI testing; production training should use more generations + max_completion_length=8, # reduce the completion length to reduce memory usage + pad_to_multiple_of=7, + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Gemma3ForConditionalGeneration", + reward_funcs=reward_func, + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.parametrize( + "model_id", + [ + "trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration", + ], + ) + def test_train_vlm_beta_non_zero(self, model_id): + dataset = load_dataset("trl-internal-testing/zen-image", "conversational_prompt_only", split="train") + + def reward_func(completions, **kwargs): + """Reward function that rewards longer completions.""" + return [float(len(completion[0]["content"])) for completion in completions] + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + beta=0.1, # set beta to non-zero value to test the case where the reference model is used + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM + num_generations=2, # VLM training is memory intensive, reduce num_generations to avoid OOM + # note: num_generations=2 is only suitable for CI testing; production training should use more generations + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = GRPOTrainer( + model=model_id, + reward_funcs=reward_func, + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.parametrize( + "model_id", + [ + "trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration", + ], + ) + @require_peft + def test_train_vlm_peft(self, model_id): + model = AutoModelForImageTextToText.from_pretrained(model_id, dtype="float32") + base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()] + dataset = load_dataset("trl-internal-testing/zen-image", "conversational_prompt_only", split="train") + + def reward_func(completions, **kwargs): + """Reward function that rewards longer completions.""" + return [float(len(completion[0]["content"])) for completion in completions] + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM + num_generations=2, # VLM training is memory intensive, reduce num_generations to avoid OOM + # note: num_generations=2 is only suitable for CI testing; production training should use more generations + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = GRPOTrainer( + model=model, + reward_funcs=reward_func, + args=training_args, + train_dataset=dataset, + peft_config=LoraConfig(target_modules=["q_proj", "v_proj"]), + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the peft params have changed and the base model params have not changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + if n in base_param_names: # We expect the base model params to be the same + torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.") + elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.parametrize( + "model_id", + [ + "trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration", + ], + ) + def test_train_vlm_and_importance_sampling(self, model_id): + dataset = load_dataset("trl-internal-testing/zen-image", "conversational_prompt_only", split="train") + + def reward_func(completions, **kwargs): + """Reward function that rewards longer completions.""" + return [float(len(completion[0]["content"])) for completion in completions] + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM + num_generations=2, # VLM training is memory intensive, reduce num_generations to avoid OOM + # note: num_generations=2 is only suitable for CI testing; production training should use more generations + max_completion_length=8, # reduce the completion length to reduce memory usage + steps_per_generation=2, # increase the steps per generation to trigger IS + report_to="none", + ) + trainer = GRPOTrainer( + model=model_id, + reward_funcs=reward_func, + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.parametrize( + "model_id", + [ + pytest.param( + "trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration", + marks=pytest.mark.xfail( + (Version("5.2.0") < Version(transformers.__version__)) + and not is_liger_kernel_available(min_version="0.8.0"), + reason="Upstream issue tracked at https://github.com/linkedin/Liger-Kernel/issues/1117", + ), + ), + ], + ) + @require_liger_kernel + def test_train_vlm_and_liger(self, model_id): + dataset = load_dataset("trl-internal-testing/zen-image", "conversational_prompt_only", split="train") + + def reward_func(completions, **kwargs): + """Reward function that rewards longer completions.""" + return [float(len(completion[0]["content"])) for completion in completions] + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM + num_generations=2, # VLM training is memory intensive, reduce num_generations to avoid OOM + # note: num_generations=2 is only suitable for CI testing; production training should use more generations + max_completion_length=8, # reduce the completion length to reduce memory usage + use_liger_kernel=True, # enable Liger kernel + report_to="none", + ) + trainer = GRPOTrainer( + model=model_id, + reward_funcs=reward_func, + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.parametrize( + "model_id", + [ + "trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration", + "trl-internal-testing/tiny-Gemma3ForConditionalGeneration", + pytest.param( + "trl-internal-testing/tiny-Gemma4ForConditionalGeneration", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.5.0"), + reason="Gemma4 models were introduced in transformers-5.5.0", + ), + ), + ], + ) + @require_vllm + @pytest.mark.skip(reason="We should add a mock for the vLLM server.") + def test_train_vlm_and_vllm(self, model_id) -> None: + dataset = load_dataset("trl-internal-testing/zen-image", "conversational_prompt_only", split="train") + + def reward_func(completions, **kwargs): + """Reward function that rewards longer completions.""" + return [float(len(completion[0]["content"])) for completion in completions] + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM + num_generations=2, # VLM training is memory intensive, reduce num_generations to avoid OOM + # note: num_generations=2 is only suitable for CI testing; production training should use more generations + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + use_vllm=True, + vllm_mode="server", + ) + trainer = GRPOTrainer( + model=model_id, + reward_funcs=reward_func, + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.parametrize( + "model_id", + [ + "trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration", + ], + ) + def test_train_vlm_multi_image(self, model_id): + dataset = load_dataset("trl-internal-testing/zen-multi-image", "conversational_prompt_only", split="train") + + def reward_func(completions, **kwargs): + """Reward function that rewards longer completions.""" + return [float(len(completion[0]["content"])) for completion in completions] + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM + num_generations=2, # VLM training is memory intensive, reduce num_generations to avoid OOM + # note: num_generations=2 is only suitable for CI testing; production training should use more generations + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = GRPOTrainer( + model=model_id, + reward_funcs=reward_func, + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.xfail( + condition=Version(transformers.__version__) < Version("5.2.0"), + reason="Qwen3.5 models were introduced in transformers-5.2.0", + strict=True, + ) + @require_jmespath + def test_train_with_tools_multimodal_response(self): + # Test that tools returning images (multimodal responses) work correctly with a VLM. + # The tool returns a list of content blocks including an image. + from PIL import Image as PILImage + + def screenshot_tool() -> list: + """ + Takes a screenshot and returns it. + + Returns: + A list of content blocks with the screenshot image. + """ + img = PILImage.new("RGB", (64, 64), color="red") + return [{"type": "image", "image": img}, {"type": "text", "text": "Here is the screenshot"}] + + dataset = load_dataset("trl-internal-testing/zen", "conversational_prompt_only", split="train") + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM + num_generations=2, # VLM training is memory intensive, reduce num_generations to avoid OOM + # note: num_generations=2 is only suitable for CI testing; production training should use more generations + max_completion_length=512, + report_to="none", + ) + trainer = GRPOTrainer( + model="trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-NoThink", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + tools=[screenshot_tool], + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + def fake_generate(input_ids, **kwargs): + if input_ids.shape[0] == 2: # first call: num_generations=2 completions for 1 prompt + # fmt: off + completion_ids = torch.tensor( + [ + # '\n\n\n<|im_end|>' + [248058, 198, 27, 1628, 13744, 30091, 22076, 29, 198, 510, 1628, 29, 198, 248059, 248046], + # "I don't know any tool<|im_end|>" + padding + [40, 1459, 914, 1366, 866, 5224, 248046, 248044, 248044, 248044, 248044, 248044, 248044, 248044, 248044], + ], + device=input_ids.device, + ) + # fmt: on + else: # second call: 1 tool call succeeded + completion_ids = torch.tensor( + [ + # 'Done!<|im_end|>' + [16936, 0, 248046], + ], + device=input_ids.device, + ) + return torch.cat([input_ids, completion_ids], dim=-1) + + with patch.object(trainer.model, "generate", side_effect=fake_generate): + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + # With num_generations=2: 1 out of 2 completions is a tool call (1/2), and it succeeds (0 failures). + assert trainer.state.log_history[-1]["tools/call_frequency"] == pytest.approx(1 / 2) + assert trainer.state.log_history[-1]["tools/failure_frequency"] == pytest.approx(0.0) + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + +@pytest.mark.slow +@require_torch_accelerator +class TestGRPOTrainerSlow(TrlTestCase): + def setup_method(self): + self.train_dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + self.eval_dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="test") + self.max_length = 128 + + def teardown_method(self): + gc.collect() + backend_empty_cache(torch_device) + gc.collect() + + @pytest.mark.parametrize( + "model_name", + [ + "trl-internal-testing/tiny-LlamaForCausalLM-3.2", + "trl-internal-testing/tiny-MistralForCausalLM-0.2", + ], + ) + @require_liger_kernel + def test_train_with_liger_grpo_kernel(self, model_name): + training_args = GRPOConfig( + output_dir=self.tmp_dir, + per_device_train_batch_size=3, + num_generations=3, + use_liger_kernel=True, + max_completion_length=self.max_length, + report_to="none", + logging_strategy="no", + ) + + model = AutoModelForCausalLM.from_pretrained(model_name, dtype="float32") + tokenizer = AutoTokenizer.from_pretrained(model_name) + tokenizer.pad_token = tokenizer.eos_token if tokenizer.pad_token is None else tokenizer.pad_token + + trainer = GRPOTrainer( + model=model, + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=self.train_dataset, + eval_dataset=self.eval_dataset, + processing_class=tokenizer, + ) + from liger_kernel.chunked_loss import LigerFusedLinearGRPOLoss + + assert isinstance(trainer.liger_grpo_loss, LigerFusedLinearGRPOLoss) + + previous_trainable_params = {n: param.clone() for n, param in model.named_parameters()} + + trainer.train() + + for n, param in previous_trainable_params.items(): + new_param = model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + release_memory(model, trainer) + + @pytest.mark.parametrize( + "model_name", + [ + "trl-internal-testing/tiny-LlamaForCausalLM-3.2", + "trl-internal-testing/tiny-MistralForCausalLM-0.2", + ], + ) + @require_liger_kernel + @require_peft + def test_train_with_liger_grpo_kernel_and_peft(self, model_name): + from peft import LoraConfig, TaskType + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + per_device_train_batch_size=3, + num_generations=3, + use_liger_kernel=True, + max_completion_length=self.max_length, + report_to="none", + logging_strategy="no", + ) + + model = AutoModelForCausalLM.from_pretrained(model_name, dtype="float32") + tokenizer = AutoTokenizer.from_pretrained(model_name) + tokenizer.pad_token = tokenizer.eos_token if tokenizer.pad_token is None else tokenizer.pad_token + + # Configure PEFT with LoRA + peft_config = LoraConfig( + task_type=TaskType.CAUSAL_LM, + inference_mode=False, + r=8, + lora_alpha=32, + lora_dropout=0.1, + target_modules=["q_proj", "v_proj"], + ) + + trainer = GRPOTrainer( + model=model, + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=self.train_dataset, + eval_dataset=self.eval_dataset, + processing_class=tokenizer, + peft_config=peft_config, + ) + from liger_kernel.chunked_loss import LigerFusedLinearGRPOLoss + + assert isinstance(trainer.liger_grpo_loss, LigerFusedLinearGRPOLoss) + + # Verify PEFT adapter is properly initialized + from peft import PeftModel + + assert isinstance(trainer.model, PeftModel), "Model should be wrapped with PEFT" + + # Store adapter weights before training + previous_trainable_params = { + n: param.clone() for n, param in trainer.model.named_parameters() if param.requires_grad + } + assert len(previous_trainable_params) > 0, "No trainable parameters found in PEFT model" + + trainer.train() + + # Verify adapter weights have changed after training + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + release_memory(model, trainer) + + @require_liger_kernel + def test_liger_grpo_kernel_importance_sampling(self): + model_name = "trl-internal-testing/tiny-LlamaForCausalLM-3.2" + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + per_device_train_batch_size=3, + num_generations=3, + use_liger_kernel=True, + max_completion_length=self.max_length, + importance_sampling_level="sequence", + report_to="none", + logging_strategy="no", + ) + + model = AutoModelForCausalLM.from_pretrained(model_name, dtype="float32") + tokenizer = AutoTokenizer.from_pretrained(model_name) + tokenizer.pad_token = tokenizer.eos_token if tokenizer.pad_token is None else tokenizer.pad_token + + trainer = GRPOTrainer( + model=model, + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=self.train_dataset, + eval_dataset=self.eval_dataset, + processing_class=tokenizer, + ) + from liger_kernel.chunked_loss import LigerFusedLinearGRPOLoss + + assert isinstance(trainer.liger_grpo_loss, LigerFusedLinearGRPOLoss) + + previous_trainable_params = {n: param.clone() for n, param in model.named_parameters()} + + trainer.train() + + for n, param in previous_trainable_params.items(): + new_param = model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + release_memory(model, trainer) + + @pytest.mark.parametrize( + "model_name", + [ + "trl-internal-testing/tiny-LlamaForCausalLM-3.2", + "trl-internal-testing/tiny-MistralForCausalLM-0.2", + ], + ) + def test_train_with_transformers_paged(self, model_name): + """Test that training works with transformers paged implementation (requires GPU).""" + if Version(transformers.__version__) < Version("4.57.0"): + pytest.xfail("Bug in transformers solved in GH#40692, released in 4.57.0.") + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + use_transformers_paged=True, # Enable transformers paged implementation + report_to="none", + logging_strategy="no", + ) + + model = AutoModelForCausalLM.from_pretrained(model_name, dtype="float32") + + trainer = GRPOTrainer( + model=model, + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=self.train_dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + release_memory(model, trainer) + + @pytest.mark.parametrize( + "model_name", + [ + "HuggingFaceTB/SmolVLM-Instruct", # Only test the smaller model to avoid OOM + ], + ) + @pytest.mark.skipif( + not is_ampere_or_newer() and torch_device != "xpu", + reason="Flash Attention 2 requires Ampere or newer GPU, or XPU", + ) + @require_kernels + @require_bitsandbytes + @require_peft + def test_vlm_training(self, model_name): + """ + Test VLM training with aggressive memory optimization. + + This test uses multiple memory reduction techniques: + - 4-bit quantization with double quantization + - LoRA with very low rank (r=4) + - Minimal batch size (1) with gradient accumulation + - Small images (64x64 instead of 224x224) + - Short sequences (max_completion_length=8) + - Only 4 training samples + - Only 1 training step + - Gradient checkpointing and bfloat16 + """ + + # Create processor once outside the data generator + processor = AutoProcessor.from_pretrained(model_name, use_fast=True, padding_side="left") + prompt = [{"role": "user", "content": "What is in the image?"}] + + dataset = Dataset.from_list( + [ + { + "prompt": prompt, + "image": np.random.uniform(low=0.0, high=255.0, size=(64, 64, 3)).astype(np.uint8), + } + for _ in range(4) + ], + ).cast_column("image", Image()) + # reduce memory requirements as much as possible + quantization_config = BitsAndBytesConfig( + load_in_4bit=True, + bnb_4bit_compute_dtype="bfloat16", + bnb_4bit_quant_type="nf4", + bnb_4bit_use_double_quant=True, + bnb_4bit_quant_storage="bfloat16", + ) + model = AutoModelForImageTextToText.from_pretrained( + model_name, + attn_implementation="kernels-community/flash-attn2", + dtype="bfloat16", + device_map=get_kbit_device_map(), + quantization_config=quantization_config, + ) + + def reward_func(prompts, completions, **kwargs): + # Use hash-based reward to ensure different completions get different rewards, + # avoiding zero-std advantages which would result in zero loss and no parameter updates. + return [float(hash(c[0]["content"]) % 100) for c in completions] + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=1, # Minimal batch size + gradient_accumulation_steps=2, # Maintain effective batch size + num_generations=2, + max_completion_length=8, # Much shorter completions + bf16=True, # Use bfloat16 precision + max_steps=1, # Only do 1 training step to save time and memory + report_to="none", + logging_strategy="no", + ) + lora_config = LoraConfig( + task_type="CAUSAL_LM", + r=4, # Much lower rank for minimal memory + lora_alpha=8, # Reduced alpha proportionally + lora_dropout=0.1, + target_modules=["q_proj", "v_proj"], # Minimal target modules + # For VLM models, we typically want to freeze the vision encoder + # and only adapt the language model parameters + modules_to_save=None, + ) + + try: + trainer = GRPOTrainer( + model=model, + processing_class=processor, + reward_funcs=[reward_func], + args=training_args, + train_dataset=dataset, + peft_config=lora_config, + ) + + assert isinstance(trainer.model, PeftModel) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that LoRA parameters have changed + # For VLM models, we're more permissive about which parameters can change + lora_params_changed = False + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + if "lora" in n.lower(): # LoRA parameters should change + if not torch.equal(param, new_param): + lora_params_changed = True + + # At least some LoRA parameters should have changed during training + assert lora_params_changed, "No LoRA parameters were updated during training." + + except torch.OutOfMemoryError as e: + pytest.skip(f"Skipping VLM training test due to insufficient GPU memory: {e}") + except Exception as e: + # Check for other memory-related errors + if any(keyword in str(e).lower() for keyword in ["memory", "cuda", "out of memory", "insufficient"]): + pytest.skip(f"Skipping VLM training test due to hardware constraints: {e}") + else: + raise + + release_memory(model, trainer) + + @require_vllm + @require_bitsandbytes + @require_peft + def test_vlm_processor_vllm_colocate_mode(self): + """ + Test that VLM processors work with vLLM in colocate mode. + + This test uses multiple memory optimization techniques to ensure it runs on limited hardware: + - LoRA (Low-Rank Adaptation) with minimal rank (r=4) + - 4-bit quantization with BitsAndBytesConfig + - Gradient checkpointing + - bfloat16 precision + - Minimal batch sizes and sequence lengths + - Very low GPU memory utilization (5%) + """ + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + config = GRPOConfig( + output_dir=self.tmp_dir, + per_device_train_batch_size=1, # Minimal batch size + gradient_accumulation_steps=2, # Make effective batch size 2, divisible by num_generations + num_generations=2, + max_completion_length=4, # Very short completions to reduce memory + use_vllm=True, # Enable vLLM + vllm_mode="colocate", # Use colocate mode to avoid server dependency + vllm_gpu_memory_utilization=0.05, # Use minimal GPU memory (5%) + bf16=True, # Use bfloat16 to reduce memory + report_to="none", + logging_strategy="no", + ) + + # Create a VLM processor + processor = AutoProcessor.from_pretrained("HuggingFaceTB/SmolVLM-Instruct", use_fast=True, padding_side="left") + + # Verify processor has both required attributes for VLM detection + assert hasattr(processor, "tokenizer") + assert hasattr(processor, "image_processor") + + def dummy_reward_func(completions, **kwargs): + return [1.0] * len(completions) + + # Use LoRA configuration for memory efficiency + lora_config = LoraConfig( + r=4, # Very low rank for minimal memory + lora_alpha=8, + target_modules=["q_proj", "v_proj"], # Minimal target modules + lora_dropout=0.1, + bias="none", + task_type="CAUSAL_LM", + ) + + # Use 4-bit quantization for further memory reduction + quantization_config = BitsAndBytesConfig( + load_in_4bit=True, + bnb_4bit_compute_dtype=torch.bfloat16, + bnb_4bit_quant_type="nf4", + bnb_4bit_use_double_quant=True, + ) + + original_env = {} + required_env_vars = { + "RANK": "0", + "LOCAL_RANK": "0", + "WORLD_SIZE": "1", + "LOCAL_WORLD_SIZE": "1", + "MASTER_ADDR": "localhost", + "MASTER_PORT": "12355", + } + + for key, value in required_env_vars.items(): + original_env[key] = os.environ.get(key) + os.environ[key] = value + + try: + # Test VLM processor with vLLM colocate mode + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + try: + # Load model with quantization for memory efficiency + model = AutoModelForCausalLM.from_pretrained( + "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + quantization_config=quantization_config, + dtype=torch.bfloat16, + ) + + trainer = GRPOTrainer( + model=model, + reward_funcs=dummy_reward_func, + args=config, + train_dataset=dataset, + processing_class=processor, # VLM processor + peft_config=lora_config, # Use LoRA for memory efficiency + ) + + # Should detect VLM processor correctly and allow vLLM + assert trainer.use_vllm, "vLLM should be enabled for VLM processors in colocate mode" + assert trainer.vllm_mode == "colocate", "Should use colocate mode" + + # Check if signature columns were set properly + if trainer._signature_columns is not None: + # Should include 'image' in signature columns for VLM processors + assert "image" in trainer._signature_columns, ( + "Should include 'image' in signature columns for VLM" + ) + + # Should not emit any warnings about VLM incompatibility + incompatibility_warnings = [ + str(w_item.message) + for w_item in w + if "does not support VLMs" in str(w_item.message) + or "not compatible" in str(w_item.message).lower() + ] + assert len(incompatibility_warnings) == 0, ( + f"Should not emit VLM incompatibility warnings, but got: {incompatibility_warnings}" + ) + + # Test passes if we get this far without exceptions + + except Exception as e: + # If vLLM fails to initialize due to hardware constraints or other issues, that's expected + if any( + keyword in str(e).lower() + for keyword in [ + "outofmemoryerror", + "cuda", + "memory", + "insufficient", + "no such device", + "free memory", + "gpu memory utilization", + "decrease gpu memory", + ] + ): + pytest.skip(f"Skipping vLLM colocate test due to hardware constraints: {e}") + elif "KeyError" in str(e) and "RANK" in str(e): + pytest.skip(f"Skipping vLLM colocate test due to environment setup issues: {e}") + elif "ValueError" in str(e) and "memory" in str(e).lower(): + pytest.skip(f"Skipping vLLM colocate test due to memory constraints: {e}") + else: + raise + finally: + # Restore original environment variables + for key, original_value in original_env.items(): + if original_value is None: + os.environ.pop(key, None) + else: + os.environ[key] = original_value + + release_memory(model, trainer) + + @require_vllm + def test_train_vllm(self): + """Test that training works with vLLM for generation.""" + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = GRPOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + logging_strategy="no", + use_vllm=True, + ) + + try: + trainer = GRPOTrainer( + model="Qwen/Qwen2.5-0.5B-Instruct", # tiny models are too small for vLLM + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + except Exception as e: + # If vLLM fails to initialize due to hardware constraints or other issues, that's expected + if any( + keyword in str(e).lower() + for keyword in [ + "outofmemoryerror", + "cuda", + "memory", + "insufficient", + "no such device", + "free memory", + "gpu memory utilization", + "decrease gpu memory", + ] + ): + pytest.skip(f"Skipping vLLM training test due to hardware constraints: {e}") + elif "KeyError" in str(e) and "RANK" in str(e): + pytest.skip(f"Skipping vLLM training test due to environment setup issues: {e}") + elif "ValueError" in str(e) and "memory" in str(e).lower(): + pytest.skip(f"Skipping vLLM training test due to memory constraints: {e}") + else: + raise + + release_memory(trainer.model, trainer) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_model_utils.py b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_model_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7e3fde991ddcf4469b3efccb78bb412e1da1e8a6 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_model_utils.py @@ -0,0 +1,34 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from transformers import AutoModelForCausalLM + +from trl.models.utils import disable_gradient_checkpointing + + +class TestDisableGradientCheckpointing: + def test_when_disabled(self): + model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5") + assert model.is_gradient_checkpointing is False + with disable_gradient_checkpointing(model): + assert model.is_gradient_checkpointing is False + assert model.is_gradient_checkpointing is False + + def test_when_enabled(self): + model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5") + model.gradient_checkpointing_enable() + assert model.is_gradient_checkpointing is True + with disable_gradient_checkpointing(model): + assert model.is_gradient_checkpointing is False + assert model.is_gradient_checkpointing is True diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_reward_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_reward_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..7fc62b33f0f6914e06bcd681a621c189199e1b2a --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_reward_trainer.py @@ -0,0 +1,837 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +import pathlib + +import pytest +import torch +from datasets import load_dataset +from transformers import AutoModelForSequenceClassification, AutoTokenizer +from transformers.utils import is_peft_available + +from trl import RewardConfig, RewardTrainer +from trl.trainer.reward_trainer import DataCollatorForPreference + +from .testing_utils import TrlTestCase, require_peft + + +if is_peft_available(): + from peft import LoraConfig, get_peft_model + + +class TestDataCollatorForPreference(TrlTestCase): + def test_basic_padding(self): + """Test basic padding functionality without completion masks.""" + collator = DataCollatorForPreference(pad_token_id=0) + examples = [ + {"chosen_ids": [1, 2, 3], "rejected_ids": [4, 5]}, + {"chosen_ids": [6, 7], "rejected_ids": [8]}, + ] + + result = collator(examples) + + torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3], [6, 7, 0], [4, 5, 0], [8, 0, 0]])) + torch.testing.assert_close( + result["attention_mask"], torch.tensor([[1, 1, 1], [1, 1, 0], [1, 1, 0], [1, 0, 0]]) + ) + + def test_pad_to_multiple_of(self): + """Test padding to multiple of specified value.""" + collator = DataCollatorForPreference(pad_token_id=0, pad_to_multiple_of=4) + examples = [ + {"chosen_ids": [1, 2, 3], "rejected_ids": [4, 5]}, + {"chosen_ids": [6, 7], "rejected_ids": [8]}, + ] + + result = collator(examples) + + torch.testing.assert_close( + result["input_ids"], torch.tensor([[1, 2, 3, 0], [6, 7, 0, 0], [4, 5, 0, 0], [8, 0, 0, 0]]) + ) + torch.testing.assert_close( + result["attention_mask"], torch.tensor([[1, 1, 1, 0], [1, 1, 0, 0], [1, 1, 0, 0], [1, 0, 0, 0]]) + ) + + def test_single_example(self): + """Test collator with a single example.""" + collator = DataCollatorForPreference(pad_token_id=0) + examples = [{"chosen_ids": [1, 2, 3], "rejected_ids": [4, 5]}] + + result = collator(examples) + + torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3], [4, 5, 0]])) + torch.testing.assert_close(result["attention_mask"], torch.tensor([[1, 1, 1], [1, 1, 0]])) + + def test_different_pad_token_id(self): + """Test with different pad token ID.""" + collator = DataCollatorForPreference(pad_token_id=999) + examples = [ + {"chosen_ids": [1, 2, 3], "rejected_ids": [4, 5]}, + {"chosen_ids": [6, 7], "rejected_ids": [8]}, + ] + + result = collator(examples) + + torch.testing.assert_close( + result["input_ids"], torch.tensor([[1, 2, 3], [6, 7, 999], [4, 5, 999], [8, 999, 999]]) + ) + torch.testing.assert_close( + result["attention_mask"], torch.tensor([[1, 1, 1], [1, 1, 0], [1, 1, 0], [1, 0, 0]]) + ) + + def test_collate_with_margin(self): + collator = DataCollatorForPreference(pad_token_id=0) + examples = [ + {"chosen_ids": [1, 2, 3], "rejected_ids": [4, 5], "margin": 0.1}, + {"chosen_ids": [6, 7], "rejected_ids": [8], "margin": 0.2}, + ] + + result = collator(examples) + + torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3], [6, 7, 0], [4, 5, 0], [8, 0, 0]])) + torch.testing.assert_close( + result["attention_mask"], torch.tensor([[1, 1, 1], [1, 1, 0], [1, 1, 0], [1, 0, 0]]) + ) + torch.testing.assert_close(result["margin"], torch.tensor([0.1, 0.2])) + + +class TestRewardTrainer(TrlTestCase): + def test_raises_error_when_model_num_labels_not_one(self): + """Test that RewardTrainer raises ValueError when model doesn't have num_labels=1.""" + model = AutoModelForSequenceClassification.from_pretrained( + "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + dtype="float32", + # num_labels=2, # Defaults to 2 num_labels for causal models + ) + + dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train") + + training_args = RewardConfig(output_dir=self.tmp_dir, report_to="none") + with pytest.raises(ValueError, match=r"reward models require `num_labels=1`"): + RewardTrainer(model=model, args=training_args, train_dataset=dataset) + + @pytest.mark.parametrize( + "model_id", + [ + "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + "trl-internal-testing/tiny-Qwen3MoeForCausalLM", + "trl-internal-testing/tiny-LlamaForCausalLM-3.2", + ], + ) + def test_train(self, model_id): + dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train") + + training_args = RewardConfig(output_dir=self.tmp_dir, report_to="none") + trainer = RewardTrainer(model=model_id, args=training_args, train_dataset=dataset) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.parametrize( + "config_name", + [ + "standard_preference", + "conversational_preference", + "standard_implicit_prompt_preference", + "conversational_implicit_prompt_preference", + ], + ) + def test_train_dataset_types(self, config_name): + dataset = load_dataset("trl-internal-testing/zen", config_name, split="train") + + training_args = RewardConfig(output_dir=self.tmp_dir, report_to="none") + trainer = RewardTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_model(self): + model = AutoModelForSequenceClassification.from_pretrained( + "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + num_labels=1, # required for reward models + dtype="float32", + ) + + dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train") + + training_args = RewardConfig(output_dir=self.tmp_dir, report_to="none") + trainer = RewardTrainer(model=model, args=training_args, train_dataset=dataset) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_from_sequence_classification_model(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train") + + training_args = RewardConfig(output_dir=self.tmp_dir, report_to="none") + trainer = RewardTrainer( + model="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_model_dtype(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train") + + training_args = RewardConfig( + output_dir=self.tmp_dir, + model_init_kwargs={"dtype": torch.float16}, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + report_to="none", + ) + trainer = RewardTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + # For some reasonn model.layers.0.input_layernorm.weight doesn't change in GitHub Actions but does + # locally. We ignore this parameter for now + if "layernorm" in n: + continue + new_param = trainer.model.get_parameter(n) + # Check the torch dtype + assert new_param.dtype == torch.float16 + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @require_peft + def test_train_dense_with_peft_config(self): + model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" + model = AutoModelForSequenceClassification.from_pretrained(model_id, dtype="float32") + base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()] + + dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train") + + training_args = RewardConfig(output_dir=self.tmp_dir, report_to="none") + + trainer = RewardTrainer( + model=model_id, + args=training_args, + train_dataset=dataset, + peft_config=LoraConfig(), + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the peft params have changed and the base model params have not changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + if n in base_param_names: # We expect the base model params to be the same + torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.") + elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @require_peft + def test_train_moe_with_peft_config(self): + model_id = "trl-internal-testing/tiny-Qwen3MoeForCausalLM" + model = AutoModelForSequenceClassification.from_pretrained(model_id, dtype="float32") + base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()] + + dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train") + + training_args = RewardConfig(output_dir=self.tmp_dir, report_to="none") + + trainer = RewardTrainer( + model=model_id, + args=training_args, + train_dataset=dataset, + peft_config=LoraConfig(target_modules=["gate_proj", "up_proj", "down_proj", "score"]), + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the peft params have changed and the base model params have not changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + if n in base_param_names: # We expect the base model params to be the same + torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.") + elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @require_peft + def test_train_peft_model(self): + model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" + model = AutoModelForSequenceClassification.from_pretrained( + model_id, + num_labels=1, # required for reward models + dtype="float32", + ) + + base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()] + + lora_config = LoraConfig() + model = get_peft_model(model, lora_config) + + dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train") + + training_args = RewardConfig(output_dir=self.tmp_dir, report_to="none") + trainer = RewardTrainer(model=model, args=training_args, train_dataset=dataset) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the peft params have changed and the base model params have not changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + if n in base_param_names: # We expect the base model params to be the same + torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.") + elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + # In practice, this test is the same as `test_train_dense_with_peft_config`, since gradient checkpointing is + # enabled by default in `RewardTrainer`. We keep it as a regression guard: if the default ever changes, we still + # explicitly test PEFT + gradient checkpointing, which has caused issues in the past. + @require_peft + def test_train_with_peft_config_and_gradient_checkpointing(self): + model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" + model = AutoModelForSequenceClassification.from_pretrained(model_id, dtype="float32") + base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()] + + dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train") + + training_args = RewardConfig(output_dir=self.tmp_dir, gradient_checkpointing=True, report_to="none") + + trainer = RewardTrainer( + model=model_id, + args=training_args, + train_dataset=dataset, + peft_config=LoraConfig(), + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the peft params have changed and the base model params have not changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + if n in base_param_names: # We expect the base model params to be the same + torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.") + elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.parametrize("use_reentrant", [True, False]) + @require_peft + def test_train_with_peft_config_and_gradient_checkpointing_reentrant(self, use_reentrant): + model_id = "trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5" + model = AutoModelForSequenceClassification.from_pretrained(model_id, dtype="float32") + base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()] + + dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train") + + training_args = RewardConfig( + output_dir=self.tmp_dir, + gradient_checkpointing=True, + gradient_checkpointing_kwargs={"use_reentrant": use_reentrant}, + report_to="none", + ) + + trainer = RewardTrainer( + model=model_id, + args=training_args, + train_dataset=dataset, + peft_config=LoraConfig(), + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the peft params have changed and the base model params have not changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + if n in base_param_names: # We expect the base model params to be the same + torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.") + elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.parametrize( + "chosen_column,rejected_column,expect_deprecation_warning", + [ + ("chosen_ids", "rejected_ids", False), + ("chosen_input_ids", "rejected_input_ids", True), + ], + ) + def test_train_with_pretokenized_data(self, chosen_column, rejected_column, expect_deprecation_warning): + model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" + tokenizer = AutoTokenizer.from_pretrained(model_id) + dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train") + + def tokenize_example(example): + return { + chosen_column: tokenizer(example["chosen"]).input_ids, + rejected_column: tokenizer(example["rejected"]).input_ids, + } + + # Apply tokenization + tokenized_dataset = dataset.map(tokenize_example, remove_columns=["chosen", "rejected"]) + + training_args = RewardConfig(output_dir=self.tmp_dir, report_to="none") + if expect_deprecation_warning: + with pytest.warns(FutureWarning, match=r"will not be supported in v1"): + trainer = RewardTrainer(model=model_id, args=training_args, train_dataset=tokenized_dataset) + else: + trainer = RewardTrainer(model=model_id, args=training_args, train_dataset=tokenized_dataset) + + assert "chosen_ids" in trainer.train_dataset.column_names + assert "rejected_ids" in trainer.train_dataset.column_names + assert "chosen_input_ids" not in trainer.train_dataset.column_names + assert "rejected_input_ids" not in trainer.train_dataset.column_names + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_iterable_dataset(self): + dataset = load_dataset( + "trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train", streaming=True + ) + + training_args = RewardConfig(output_dir=self.tmp_dir, max_steps=3, report_to="none") + trainer = RewardTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_chat_template_kwargs(self): + dataset = load_dataset("trl-internal-testing/zen", "conversational_implicit_prompt_preference", split="train") + + training_args = RewardConfig(output_dir=self.tmp_dir, report_to="none") + + tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5") + # The following template is a simplified version of the Qwen chat template, where an additional argument + # `role_capital` is used to control the capitalization of roles. + tokenizer.chat_template = '{%- if messages[0]["role"] == "system" -%} {{ "<|im_start|>" + ("SYSTEM" if role_capital else "system") + "\\n" + messages[0]["content"] + "<|im_end|>\\n" }}{%- else -%} {{ "<|im_start|>" + ("SYSTEM" if role_capital else "system") + "\\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\\n" }}{%- endif -%}{%- for message in messages -%} {%- if (message.role == "user") or (message.role == "system" and not loop.first) or (message.role == "assistant" and not message.tool_calls) -%} {{ "<|im_start|>" + (message.role.upper() if role_capital else message.role) + "\\n" + message.content + "<|im_end|>\\n" }} {%- elif message.role == "assistant" -%} {{ "<|im_start|>" + ("ASSISTANT" if role_capital else "assistant") }} {%- if message.content -%} {{ "\\n" + message.content }} {%- endif -%} {{ "<|im_end|>\\n" }} {%- elif message.role == "tool" -%} {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != "tool") -%} {{ "<|im_start|>" + ("USER" if role_capital else "user") }} {%- endif -%} {{ "\\n\\n" + message.content + "\\n" }} {%- if loop.last or (messages[loop.index0 + 1].role != "tool") -%} {{ "<|im_end|>\\n" }} {%- endif -%} {%- endif -%}{%- endfor -%}{%- if add_generation_prompt -%} {{ "<|im_start|>" + ("ASSISTANT" if role_capital else "assistant") + "\\n" }}{%- endif -%}' + + dataset = dataset.add_column( + "chat_template_kwargs", [{"role_capital": bool(i % 2)} for i in range(len(dataset))] + ) + assert "chat_template_kwargs" in dataset.features + + trainer = RewardTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset, + processing_class=tokenizer, + ) + + assert trainer.processing_class.chat_template == tokenizer.chat_template + + for i in range(2): + role = "SYSTEM" if i else "system" + system_prompt = ( + f"<|im_start|>{role}\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>" + ) + system_prompt_ids = trainer.processing_class(system_prompt)["input_ids"] + assert trainer.train_dataset[i]["chosen_ids"][: len(system_prompt_ids)] == system_prompt_ids + assert trainer.train_dataset[i]["rejected_ids"][: len(system_prompt_ids)] == system_prompt_ids + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_set_chat_template_from_model(self): + dataset = load_dataset("trl-internal-testing/zen", "conversational_preference", split="train") + + training_args = RewardConfig(output_dir=self.tmp_dir, chat_template_path="Qwen/Qwen3-4B", report_to="none") + # trl-internal-testing/tiny-GPTNeoXForCausalLM doesn't have a chat template set by default + trainer = RewardTrainer( + model="trl-internal-testing/tiny-GPTNeoXForCausalLM", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + # RewardTrainer uses a mean-free loss that cancels uniform shifts in output scores. Since GPT-NeoX models + # include a final LayerNorm, its bias consistently receives zero gradient and remains unchanged, so we skip + # this parameter. + if n == "gpt_neox.final_layer_norm.bias": + continue + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_set_chat_template_from_path(self, lazy_shared_datadir): + dataset = load_dataset("trl-internal-testing/zen", "conversational_preference", split="train") + + training_args = RewardConfig( + output_dir=self.tmp_dir, + chat_template_path=str(lazy_shared_datadir / "template.jinja"), + report_to="none", + ) + # trl-internal-testing/tiny-GPTNeoXForCausalLM doesn't have a chat template set by default + trainer = RewardTrainer( + model="trl-internal-testing/tiny-GPTNeoXForCausalLM", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + # RewardTrainer uses a mean-free loss that cancels uniform shifts in output scores. Since GPT-NeoX models + # include a final LayerNorm, its bias consistently receives zero gradient and remains unchanged, so we skip + # this parameter. + if n == "gpt_neox.final_layer_norm.bias": + continue + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + # Check that the template saved in the output directory is the same as the one used for training + template_path = pathlib.Path(self.tmp_dir) / "checkpoint-9" / "chat_template.jinja" + assert template_path.exists(), f"Chat template not found at {template_path}" + + with open(template_path) as f: + template_content = f.read() + with open(training_args.chat_template_path) as f: + original_template_content = f.read() + assert template_content == original_template_content, "Chat template content does not match the original" + + def test_train_toolcall_data(self): + dataset = load_dataset("trl-internal-testing/toolcall", "preference", split="train") + + training_args = RewardConfig( + output_dir=self.tmp_dir, + per_device_train_batch_size=2, # toolcall sequences are longer than standard data, reduce batch size to avoid OOM + max_length=512, # toolcall sequences are longer than standard data, limit length to avoid OOM + report_to="none", + ) + trainer = RewardTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_toolcall_data_as_json(self): + # Tabular backends (Arrow/Parquet) can insert `None` for missing keys in nested structures. + # If `tools` is stored as a list of dicts and examples use different dict schemas, nulls may + # be introduced and break tool processing. This test ensures we also support `tools` provided + # as a list of dicts. + dataset = load_dataset("trl-internal-testing/toolcall", "preference", split="train") + + def convert_to_json(example): + return {"tools": json.loads(example["tools"])} + + dataset = dataset.map(convert_to_json) + + training_args = RewardConfig( + output_dir=self.tmp_dir, + per_device_train_batch_size=2, # toolcall sequences are longer than standard data, reduce batch size to avoid OOM + max_length=512, # toolcall sequences are longer than standard data, limit length to avoid OOM + report_to="none", + ) + trainer = RewardTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_eval(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference") + + training_args = RewardConfig(output_dir=self.tmp_dir, eval_strategy="steps", eval_steps=3, report_to="none") + trainer = RewardTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset["train"], + eval_dataset=dataset["test"], + ) + + trainer.train() + + assert trainer.state.log_history[0]["eval_loss"] is not None + + def test_train_with_multiple_eval_dataset(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference") + + training_args = RewardConfig(output_dir=self.tmp_dir, eval_strategy="steps", eval_steps=3, report_to="none") + trainer = RewardTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset["train"], + eval_dataset={"data1": dataset["test"], "data2": dataset["test"]}, + ) + trainer.train() + + assert trainer.state.log_history[-3]["eval_data1_loss"] is not None + assert trainer.state.log_history[-2]["eval_data2_loss"] is not None + + def test_train_with_compute_metrics(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference") + + def dummy_compute_metrics(eval_pred): + return {"my_metric": 0.123} + + training_args = RewardConfig( + output_dir=self.tmp_dir, + eval_strategy="steps", + eval_steps=3, + report_to="none", + ) + trainer = RewardTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset["train"], + eval_dataset=dataset["test"], + compute_metrics=dummy_compute_metrics, + ) + + trainer.train() + + assert trainer.state.log_history[-2]["eval_my_metric"] == 0.123 + + # In practice, this test is the same as `test_train`, since gradient checkpointing is enabled by default in + # `RewardTrainer`. We keep it as a regression guard: if the default ever changes, we still explicitly test gradient + # checkpointing, which has caused issues in the past. + def test_train_with_gradient_checkpointing(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train") + + training_args = RewardConfig(output_dir=self.tmp_dir, gradient_checkpointing=True, report_to="none") + trainer = RewardTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.parametrize("use_reentrant", [True, False]) + def test_train_with_gradient_checkpointing_reentrant(self, use_reentrant): + dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train") + + training_args = RewardConfig( + output_dir=self.tmp_dir, + gradient_checkpointing=True, + gradient_checkpointing_kwargs={"use_reentrant": use_reentrant}, + report_to="none", + ) + trainer = RewardTrainer( + model="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_tag_added(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train") + + trainer = RewardTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + train_dataset=dataset, + ) + + for tag in ["reward-trainer", "trl"]: + assert tag in trainer.model.model_tags + + @require_peft + def test_tag_added_peft(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train") + + trainer = RewardTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + train_dataset=dataset, + peft_config=LoraConfig(), + ) + + for tag in ["reward-trainer", "trl"]: + assert tag in trainer.model.model_tags + + def test_train_with_margin(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train") + + def add_margin(example): + # dummy margin based on the length of the chosen summary + return {"margin": len(example["chosen"])} + + dataset = dataset.map(add_margin) + + training_args = RewardConfig(output_dir=self.tmp_dir, report_to="none") + trainer = RewardTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_center_rewards_coefficient(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train") + + training_args = RewardConfig(output_dir=self.tmp_dir, center_rewards_coefficient=0.01, report_to="none") + trainer = RewardTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_rewards.py b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_rewards.py new file mode 100644 index 0000000000000000000000000000000000000000..890ee95fdef823428ed86e08a328faa101f3f3de --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_rewards.py @@ -0,0 +1,215 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import threading + +from trl.rewards import accuracy_reward, get_soft_overlong_punishment, reasoning_accuracy_reward, think_format_reward + +from .testing_utils import TrlTestCase, require_math_latex + + +class TestThinkFormatReward(TrlTestCase): + def test_valid_format(self): + completions = [ + "This is my reasoning.This is my answer.", # Simple, one-line reasoning + "\nThis is my reasoning.\n\nThis is my answer.", # Multiline reasoning + "\nThis is\nmy reasoning.\n\nThis is my answer.", # Multiline reasoning + "\nThis is my reasoning.\nThis is my answer.", # Reasoning including other tags + "\nThis is my answer.", # Empty reasoning + ] + completions = [[{"content": completion}] for completion in completions] + expected_rewards = [1.0, 1.0, 1.0, 1.0, 1.0] # All should be valid + rewards = think_format_reward(completions) + assert rewards == expected_rewards + + def test_invalid_format(self): + completions = [ + "\nThis is my reasoning.\nThis is my answer.", # No closing + "This is my reasoning.\nThis is my answer.", # No closing + "This is my reasoning. This is my answer.", # No tags + "This is my reasoning.\nThis is my answer.", # No tags + "This is my reasoning.\nThis is my answer.", # No opening + "This is my reasoning.This is my answer.", # No opening + "Thisis my reasoning.\nThis is my answer.", # tag in the middle + "This ismy reasoning.This is my answer.", # Nested tags + "This is\nmy\nreasoning.\nThis is my answer.", # Multiline + ] + completions = [[{"content": completion}] for completion in completions] + expected_rewards = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] # All should be invalid + rewards = think_format_reward(completions) + assert rewards == expected_rewards + + def test_mixed_format(self): + completions = [ + "This is my reasoning.This is my answer.", # Valid + "\nThis is my reasoning.\n\nThis is my answer.", # Valid + "This is my reasoning.\nThis is my answer.", # Invalid + "This is my reasoning. This is my answer.", # Invalid + ] + completions = [[{"content": completion}] for completion in completions] + expected_rewards = [1.0, 1.0, 0.0, 0.0] + rewards = think_format_reward(completions) + assert rewards == expected_rewards + + +class TestSoftOverlongPunishmentReward: + def test_soft_overlong_punishment_short_completion(self): + """Test soft overlong punishment reward function with a short completion.""" + # length 50, with max=100 and soft cache=20, reward should be 0. + reward_fn = get_soft_overlong_punishment(max_completion_len=100, soft_punish_cache=20) + completion_ids = [[1] * 50] # 50 <= 80 + rewards = reward_fn(completion_ids=completion_ids) + assert rewards == [0] + + def test_soft_overlong_punishment_long_completion(self): + """Test soft overlong punishment reward function with a longer than max completion.""" + # 110 > 100, reward should be -1. + reward_fn = get_soft_overlong_punishment(max_completion_len=100, soft_punish_cache=20) + completion_ids = [[1] * 110] + rewards = reward_fn(completion_ids) + assert rewards == [-1] + + def test_soft_overlong_punishment_intermediate_completion(self): + """Test soft overlong punishment reward function for intermediate length completion.""" + reward_fn = get_soft_overlong_punishment(max_completion_len=100, soft_punish_cache=20) + completion_ids = [[1] * 90] # 90 is between 80 and 100 + rewards = reward_fn(completion_ids) + assert round(abs(rewards[0] - -0.5), 4) == 0 + + +class TestAccuracyReward: + @require_math_latex + def test_accuracy_reward_correct_answer(self): + """Test accuracy_reward with a correct answer.""" + completion = [[{"content": r"\boxed{\frac{63}{400}}"}], [{"content": r"\boxed{\frac{63}{400}}"}]] + solution = [r"\frac{63}{400}", "63/400"] + rewards = accuracy_reward(completion, solution) + assert rewards[0] == 1.0 + assert rewards[1] == 1.0 + + @require_math_latex + def test_accuracy_reward_wrong_answer(self): + """Test accuracy_reward with an incorrect answer.""" + completion = [[{"content": r"\boxed{\frac{64}{400}}"}]] + solution = [r"\frac{63}{400}"] + rewards = accuracy_reward(completion, solution) + assert rewards[0] == 0.0 + + @require_math_latex + def test_accuracy_reward_wrong_answer_no_latex(self): + """Test accuracy_reward with an incorrect answer and gold solution with no latex.""" + completion = [[{"content": r"\boxed{3}"}]] + solution = ["6"] + rewards = accuracy_reward(completion, solution) + assert rewards[0] == 0.0 + + @require_math_latex + def test_accuracy_reward_unparsable_gold(self): + """Test accuracy_reward with an unparsable gold solution.""" + completion = [ + [{"content": "Answer is forty two."}], + [{"content": r"Some other content. \boxed{43}."}], + ] + solution = [ + "Answer is forty two.", + "Answer is forty three.", + ] + rewards = accuracy_reward(completion, solution) + assert rewards[0] is None + assert rewards[1] is None + + @require_math_latex + def test_accuracy_reward_in_worker_thread(self): + """Test that accuracy_reward works when called from a non-main thread.""" + completions = [[{"content": r"\boxed{\frac{1}{3}}"}]] + solutions = [r"\frac{1}{3}"] + results = [] + exceptions = [] + + def target(): + try: + results.extend(accuracy_reward(completions, solutions)) + except Exception as e: + exceptions.append(e) + + t = threading.Thread(target=target) + t.start() + t.join() + + assert not exceptions, f"accuracy_reward raised in worker thread: {exceptions[0]}" + assert results == [1.0] + + +class TestReasoningAccuracyReward: + @require_math_latex + def test_correct_answer_yields_unit_reward(self): + completions = [ + [{"content": r" Reasoning content \boxed{\frac{63}{400}}"}], + [{"content": r"Reasoning content \boxed{\frac{63}{400}}"}], + ] + solutions = [r"\frac{63}{400}", r"\frac{63}{400}"] + rewards = reasoning_accuracy_reward(completions, solutions) + assert rewards[0] == 1.0 + assert rewards[1] == 1.0 + + @require_math_latex + def test_correct_answer_with_custom_tags_yields_unit_reward(self): + completions = [ + [{"content": r" Reasoning content \boxed{\frac{63}{400}}"}], + ] + solutions = [ + r"\frac{63}{400}", + ] + rewards = reasoning_accuracy_reward(completions, solutions, reasoning_delimiters=[""]) + assert rewards[0] == 1.0 + + @require_math_latex + def test_incorrect_answer_yields_zero_reward(self): + completion = [[{"content": r" Reasoning content \boxed{\frac{64}{400}}"}]] + solution = [r"\frac{63}{400}"] + rewards = reasoning_accuracy_reward(completion, solution) + assert rewards[0] == 0.0 + + @require_math_latex + def test_correct_answer_in_reasoning_yields_zero_reward(self): + completions = [ + [{"content": r" My answer is \boxed{42} Some other text."}], + [{"content": r" The answer is \boxed{42} Here's a wrong answer: \boxed{43}."}], + ] + solutions = [r"\boxed{42}", r"\boxed{42}"] + rewards = reasoning_accuracy_reward(completions, solutions) + assert rewards[0] == 0.0 + assert rewards[1] == 0.0 + + @require_math_latex + def test_incomplete_reasoning_yields_zero_reward(self): + completions = [ + [{"content": r" Incomplete reasoning without closing tag"}], + [{"content": r"Correct answer \frac{63}{400} but completely missing reasoning content"}], + ] + solutions = [r"\frac{63}{400}", r"\frac{63}{400}"] + rewards = reasoning_accuracy_reward(completions, solutions) + assert rewards[0] == 0.0 + assert rewards[1] == 0.0 + + @require_math_latex + def test_unparsable_gold_solution_yields_none_reward(self): + completions = [ + [{"content": r" Reasoning content \boxed{42}"}], + ] + solutions = [ + "forty two", + ] + rewards = reasoning_accuracy_reward(completions, solutions) + assert rewards[0] is None diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_rich_progress_callback.py b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_rich_progress_callback.py new file mode 100644 index 0000000000000000000000000000000000000000..9c6a256b8a9805730b96a3d69d11a82a851e3266 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_rich_progress_callback.py @@ -0,0 +1,64 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch +import torch.nn as nn +from datasets import Dataset +from transformers import Trainer, TrainingArguments + +from trl.trainer.callbacks import RichProgressCallback + +from .testing_utils import TrlTestCase, require_rich + + +class DummyModel(nn.Module): + def __init__(self): + super().__init__() + self.a = nn.Parameter(torch.tensor(1.0)) + + def forward(self, x): + return self.a * x + + +@require_rich +class TestRichProgressCallback(TrlTestCase): + def setup_method(self): + self.dummy_model = DummyModel() + self.dummy_train_dataset = Dataset.from_list([{"x": 1.0, "y": 2.0}] * 5) + self.dummy_val_dataset = Dataset.from_list([{"x": 1.0, "y": 2.0}] * 101) + + def test_rich_progress_callback_logging(self): + training_args = TrainingArguments( + output_dir=self.tmp_dir, + per_device_eval_batch_size=2, + per_device_train_batch_size=2, + num_train_epochs=4, + eval_strategy="steps", + eval_steps=1, + logging_strategy="steps", + logging_steps=1, + save_strategy="no", + report_to="none", + disable_tqdm=True, + ) + callbacks = [RichProgressCallback()] + trainer = Trainer( + model=self.dummy_model, + train_dataset=self.dummy_train_dataset, + eval_dataset=self.dummy_val_dataset, + args=training_args, + callbacks=callbacks, + ) + + trainer.train() diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_rloo_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_rloo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..5f884a9a156ed3270203f0dfee8be812452f231f --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_rloo_trainer.py @@ -0,0 +1,1767 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from unittest.mock import patch + +import pytest +import torch +import transformers +from datasets import load_dataset +from packaging.version import Version +from transformers import ( + AutoModelForCausalLM, + AutoModelForImageTextToText, + AutoModelForSequenceClassification, + AutoTokenizer, +) +from transformers.utils import is_peft_available + +from trl import RLOOConfig, RLOOTrainer + +from .testing_utils import TrlTestCase, require_peft, require_vision, require_vllm + + +if is_peft_available(): + from peft import LoraConfig, get_peft_model + + +class TestRLOOTrainer(TrlTestCase): + def test_init_minimal(self): + # Test that RLOOTrainer can be instantiated with only model, reward_model and train_dataset + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + train_dataset=dataset, + ) + + @pytest.mark.parametrize( + "model_id", + [ + "trl-internal-testing/tiny-Cohere2ForCausalLM", + pytest.param( + "trl-internal-testing/tiny-Glm4MoeForCausalLM", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.0.0"), + reason="GLM4 tokenizer requires transformers>=5.0.0", + ), + ), + "trl-internal-testing/tiny-GptOssForCausalLM", + "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + "trl-internal-testing/tiny-Qwen3MoeForCausalLM", + pytest.param( + "trl-internal-testing/tiny-NemotronHForCausalLM-nano", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.7.0"), + reason="Nemotron 3 gradient checkpointing requires transformers>=5.7.0 (see transformers#45625)", + ), + ), + ], + ) + def test_train(self, model_id): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = RLOOTrainer( + model=model_id, + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.parametrize("config_name", ["standard_prompt_only", "conversational_prompt_only"]) + def test_train_dataset_format(self, config_name): + dataset = load_dataset("trl-internal-testing/zen", config_name, split="train") + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_eval(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only") + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + per_device_eval_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + eval_strategy="steps", + eval_steps=2, + report_to="none", + ) + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset["train"], + eval_dataset=dataset["test"], + ) + + trainer.train() + + def test_train_with_num_generations_eval(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only") + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + per_device_eval_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + num_generations_eval=1, + eval_strategy="steps", + eval_steps=2, + report_to="none", + ) + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset["train"], + eval_dataset=dataset["test"], + ) + + trainer.train() + + def test_train_multiple_iterations(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + num_iterations=2, + report_to="none", + ) + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @require_peft + def test_train_peft_config(self): + model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", dtype="float32") + base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()] + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = RLOOTrainer( + model=model, + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + peft_config=LoraConfig(), + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the peft params have changed and the base model params have not changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + if n in base_param_names: # We expect the base model params to be the same + torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.") + elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @require_peft + def test_train_peft_model(self): + model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", dtype="float32") + base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()] + lora_config = LoraConfig() + model = get_peft_model(model, lora_config) + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = RLOOTrainer( + model=model, + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the peft params have changed and the base model params have not changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + if n in base_param_names: # We expect the base model params to be the same + torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.") + elif "base_layer" not in n and "ref" not in n: # and the peft params to be different (except base and ref) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + # In practice, this test is the same as `test_train_peft_config`, since gradient checkpointing is enabled by + # default in `RLOOTrainer`. We keep it as a regression guard: if the default ever changes, we still explicitly test + # PEFT + gradient checkpointing, which has caused issues in the past. + @require_peft + def test_train_peft_with_gradient_checkpointing(self): + model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", dtype="float32") + base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()] + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + gradient_checkpointing=True, # enable gradient checkpointing + report_to="none", + ) + trainer = RLOOTrainer( + model=model, + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + peft_config=LoraConfig(), + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the peft params have changed and the base model params have not changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + if n in base_param_names: # We expect the base model params to be the same + torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.") + elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_different_reward_model(self): + # Use a reward model different from the model: different chat template, tokenization, etc. + dataset = load_dataset("trl-internal-testing/zen", "conversational_prompt_only", split="train") + reward_model_id = "trl-internal-testing/tiny-LlamaForSequenceClassification-3.2" + reward_model = AutoModelForSequenceClassification.from_pretrained(reward_model_id) + reward_tokenizer = AutoTokenizer.from_pretrained(reward_model_id) + # By default, the trainer uses the eos token as the padding token. However, for Llama models, the eos token + # appears in the chat template. Using it as a pad token disrupts the reward calculation, as the calculation + # considers the score of the last token before the first pad token. To ensure correct reward calculations, + # we use a separate pad token instead. + reward_tokenizer.pad_token = "<|finetune_right_pad_id|>" + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=reward_model, + args=training_args, + train_dataset=dataset, + reward_processing_classes=reward_tokenizer, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_reward_func_standard(self): + # Test if trainer can handle reward function with standard format + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + def reward_func(completions, **kwargs): + """Reward function that rewards longer completions.""" + return [float(len(completion)) for completion in completions] + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=reward_func, + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_reward_func_conversational(self): + # Test if trainer can handle reward function with conversational format + dataset = load_dataset("trl-internal-testing/zen", "conversational_prompt_only", split="train") + + def reward_func(completions, **kwargs): + """Reward function that gives higher scores to longer completion content.""" + completion_contents = [completion[0]["content"] for completion in completions] + return [float(len(content)) for content in completion_contents] + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=reward_func, + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_multiple_reward_funcs(self): + # Test that RLOOTrainer can be instantiated with multiple reward functions + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + def reward_func1(completions, **kwargs): + """Reward function that rewards longer completions.""" + return [float(len(completion)) for completion in completions] + + def reward_func2(completions, **kwargs): + """Reward function that rewards completions with more unique letters.""" + return [float(len(set(completion))) for completion in completions] + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=[reward_func1, reward_func2], + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_sync_and_async_reward_funcs(self): + # Test that RLOOTrainer can be instantiated with multiple reward functions one of which is async + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + def sync_reward_func1(completions, **kwargs): + """Reward function that rewards longer completions.""" + return [float(len(completion)) for completion in completions] + + def sync_reward_func2(completions, **kwargs): + return [1 for _ in completions] + + async def async_reward_func(completions, **kwargs): + """Async Reward function that rewards completions with more unique letters.""" + return [float(len(set(completion))) for completion in completions] + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=[sync_reward_func1, sync_reward_func2, async_reward_func], + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_multiple_reward_funcs_with_None_output(self): + """Test that a valid math reward function is processed correctly while the code reward function returns None.""" + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + def applicable_reward_func(completions, **kwargs): + """A reward function that rewards longer completions.""" + return [float(len(completion)) for completion in completions] + + def non_applicable_reward_func(completions, **kwargs): + """A reward function that returns None for all inputs, as it is not applicable to this sample.""" + return [None] * len(completions) + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=[ + applicable_reward_func, + non_applicable_reward_func, + ], # One applicable, one non applicable + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = { + n: param.clone() for n, param in trainer.model.named_parameters() if param.requires_grad + } + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_multiple_reward_funcs_with_weights(self): + """Test that RLOOTrainer can handle multiple reward functions with weights.""" + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + def reward_func1(completions, **kwargs): + """Reward function that rewards longer completions.""" + return [float(len(completion)) for completion in completions] + + def reward_func2(completions, **kwargs): + """Reward function that rewards completions with more unique letters.""" + return [float(len(set(completion))) for completion in completions] + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + reward_weights=[0.7, 0.3], # weight of reward_func1 and reward_func2 respectively + ) + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=[reward_func1, reward_func2], + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + # Check that training logs contain both reward metrics + assert trainer.state.log_history[-1]["train_loss"] is not None + assert "rewards/reward_func1/mean" in trainer.state.log_history[-1] + assert "rewards/reward_func1/std" in trainer.state.log_history[-1] + assert "rewards/reward_func2/mean" in trainer.state.log_history[-1] + assert "rewards/reward_func2/std" in trainer.state.log_history[-1] + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_reward_metric_reflects_reward_weights(self): + """Test that the logged 'reward' metric uses reward_weights, not an unweighted sum.""" + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + def constant_reward_1(completions, **kwargs): + return [1.0] * len(completions) + + def constant_reward_0(completions, **kwargs): + return [0.0] * len(completions) + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + reward_weights=[0.7, 0.3], + ) + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=[constant_reward_1, constant_reward_0], + args=training_args, + train_dataset=dataset, + ) + + trainer.train() + + log = trainer.state.log_history[-1] + # With reward_weights=[0.7, 0.3] and rewards [1.0, 0.0]: + # weighted reward = 0.7*1.0 + 0.3*0.0 = 0.7 + # unweighted reward = 1.0 + 0.0 = 1.0 + assert abs(log["reward"] - 0.7) < 1e-5, ( + f"Expected logged reward to be ~0.7 (weighted), got {log['reward']}. " + "The reward metric should reflect reward_weights." + ) + + def test_train_multiple_mixed_reward_funcs(self): + # Test if the trainer can handle a mix of reward functions and reward models + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + def reward_func(completions, **kwargs): + """Reward function that rewards longer completions.""" + return [float(len(completion)) for completion in completions] + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=[reward_func, "trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5"], + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_reward_func_additional_column(self): + # Test if trainer can handle reward function that rely on additional columns in the dataset + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + # Add a column to the dataset (dummy example, the column could be anything) + some_values = list(range(len(dataset))) + dataset = dataset.add_column("some_values", some_values) + + def reward_func(completions, some_values, **kwargs): + """Reward function that rewards completions with lengths closer to the values in some_values.""" + return [ + float(abs(len(completion) - value)) for completion, value in zip(completions, some_values, strict=True) + ] + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=reward_func, + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_sync_ref_model(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + beta=0.1, # ensure ref model is created so sync can update it + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + sync_ref_model=True, + ref_model_sync_steps=2, # reduce sync steps to ensure a sync happens + report_to="none", + ) + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + assert trainer.ref_model is not None + previous_ref_params = {n: param.clone() for n, param in trainer.ref_model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + new_ref_param = trainer.ref_model.get_parameter(n) + assert not torch.equal(previous_ref_params[n], new_ref_param), f"Ref Parameter {n} has not changed." + + def test_train_beta_zero(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + training_args = RLOOConfig( + output_dir=self.tmp_dir, + beta=0.0, # set beta to zero value to test the case where the reference model is not used + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_pad_to_multiple_of(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + pad_to_multiple_of=8, + report_to="none", + ) + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @require_peft + @require_vllm + @pytest.mark.skip(reason="We should add a mock for the vLLM server.") + def test_train_vllm_and_peft(self): + """Test that training works with vLLM for generation.""" + model = AutoModelForCausalLM.from_pretrained( + "Qwen/Qwen2.5-0.5B-Instruct", dtype="float32" + ) # tiny model is too small for vLLM + base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()] + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + use_vllm=True, + ) + lora_config = LoraConfig( + target_modules="all-linear", + # test with non-default modules as it adds extra keys in state_dict that we need to handle + modules_to_save=["embed_tokens", "lm_head"], + ) + trainer = RLOOTrainer( + model=model, + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + peft_config=lora_config, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the peft params have changed and the base model params have not changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + if n in base_param_names: # We expect the base model params to be the same + torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.") + elif "base_layer" not in n and "original_module" not in n: + # We expect the peft params to be different (except for the base layer) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @require_vllm + @pytest.mark.skip(reason="We should add a mock for the vLLM server.") + def test_train_vllm_structured_outputs(self): + """Test that training works with vLLM for generation with structured outputs.""" + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + use_vllm=True, + vllm_structured_outputs_regex=r"\n.*\n\n\n.*\n", + ) + trainer = RLOOTrainer( + model="Qwen/Qwen2.5-0.5B-Instruct", # tiny model is too small for vLLM + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_additional_generation_kwargs(self): + """Test that training works with additional generation kwargs.""" + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + top_p=0.9, + top_k=10, + min_p=0.01, + repetition_penalty=1.1, + ) + + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @require_vllm + @pytest.mark.skip(reason="We should add a mock for the vLLM server.") + def test_train_vllm_with_additional_generation_kwargs(self): + """Test that training works with vLLM and additional generation kwargs.""" + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + use_vllm=True, + top_p=0.9, + top_k=10, + min_p=0.01, + repetition_penalty=1.1, + ) + + trainer = RLOOTrainer( + model="Qwen/Qwen2.5-0.5B-Instruct", # tiny model is too small for vLLM + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_normalized_advantages(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + normalize_advantages=True, + report_to="none", + ) + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_clipped_rewards(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + reward_clip_range=(-1, 1), + report_to="none", + ) + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @patch("transformers.generation.utils.GenerationMixin.generate") + def test_train_with_mask_truncated_completions(self, mock_generate): + """Test that training works with mask_truncated_completions=True parameter.""" + + # We mock the generate method because the model's random weights make it extremely unlikely to produce a + # sequence containing the EOS token within the allowed max_completion_length. As a result, all tokens are + # masked in the loss, the model doesn't update, and the final check (which verifies the update) fails. + def fake_generate(input_ids, **kwargs): + # pad_token_id = 151643; eos_token_id = 151645 + completion_ids = torch.tensor( + [ + [1, 2, 3, 4, 5, 6, 7, 8], # this one is truncated + [9, 10, 11, 151645, 151643, 151643, 151643, 151643], # this one contains eos + [12, 13, 14, 15, 16, 17, 18, 151645], # particular case, eos is generated just within the limit + ], + device=input_ids.device, + ) + return torch.cat([input_ids, completion_ids], dim=1) + + mock_generate.side_effect = fake_generate + + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + mask_truncated_completions=True, # Enable masking of truncated completions + report_to="none", + ) + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_mask_truncated_completions_all_masked(self): + """ + Test that when all generated completions are truncated (i.e., none contain an EOS token), and + mask_truncated_completions=True, the model receives no effective learning signal and therefore does not update + its parameters. + + Here, we don't mock the generate method, be we rely on the fact that the model the probability of generating + the EOS token is extremely low, so all generated completions are truncated. + """ + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + mask_truncated_completions=True, # Enable masking of truncated completions + report_to="none", + ) + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert torch.equal(param, new_param), f"Parameter {n} has changed." + + def test_warning_raised_all_rewards_none(self, caplog): + """Test that a proper warning is raised when all rewards are None.""" + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + def always_none_reward_func(completions, **kwargs): + """Reward function that always returns None.""" + return [None] * len(completions) + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=always_none_reward_func, + args=training_args, + train_dataset=dataset, + ) + + with caplog.at_level("WARNING", logger="trl.trainer.rloo_trainer"): + trainer.train() + + expected_warning = "All reward functions returned None for the following kwargs:" + assert expected_warning in caplog.text + + def test_train_num_generations_larger_than_batch_size(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + num_generations=6, # the number of generations is larger than the batch size, but + gradient_accumulation_steps=2, # gradient accumulation should allow that + report_to="none", + ) + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_multiple_dataloader_workers(self): + # Pytest/CI often starts background threads before tests run. With Python 3.12, using the default "fork" start + # method in a multi-threaded process emits a DeprecationWarning and may deadlock. + # + # We force "spawn" here to make multiprocessing safe under pytest when DataLoader workers are enabled. This is + # test-environment–specific and not required by the training logic itself. + # + # This means the test does not cover "fork". However, "spawn" is stricter (requires full picklability and clean + # state) and avoids fork-after-threads issues that pytest cannot reliably test anyway. Fork-specific behavior, + # if needed, should be tested in a clean process outside pytest. + torch.multiprocessing.set_start_method("spawn", force=True) + + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + dataloader_num_workers=2, # use multiple dataloader workers + report_to="none", + ) + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_generation_kwargs(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + # Pass gen kwargs + generation_kwargs={"do_sample": True, "top_k": 50, "num_beams": 2, "length_penalty": -0.1}, + report_to="none", + ) + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_reward_func_accessing_trainer_state(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + def reward_func(completions, **kwargs): + trainer_state = kwargs.get("trainer_state") + assert trainer_state is not None + # transformers.TrainerState instance should have a `global_step` property. + assert hasattr(trainer_state, "global_step") + return [float(len(set(completion))) for completion in completions] + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=reward_func, + args=training_args, + train_dataset=dataset, + ) + trainer.train() + + def test_train_reward_func_with_log_extra(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + def reward_func(completions, **kwargs): + log_extra = kwargs.get("log_extra") + assert log_extra is not None + log_extra("test_column", [completion[:5] for completion in completions]) + return [float(len(completion)) for completion in completions] + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + log_completions=True, + ) + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=reward_func, + args=training_args, + train_dataset=dataset, + ) + trainer.train() + assert "test_column" in trainer._logs["extra"] + + def test_train_reward_func_with_log_metric(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + def reward_func(completions, **kwargs): + log_metric = kwargs.get("log_metric") + assert log_metric is not None + log_metric("custom_accuracy", 0.75) + return [float(len(completion)) for completion in completions] + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=reward_func, + args=training_args, + train_dataset=dataset, + ) + trainer.train() + # log_metric appends to _metrics, which gets averaged and merged into log_history + logged_keys = {k for entry in trainer.state.log_history for k in entry} + assert "custom_accuracy" in logged_keys + + def test_prepare_input_called_with_correct_data(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + max_completion_length=8, # reduce the completion length to reduce memory usage + gradient_accumulation_steps=3, # can be anything in this test + # steps_per_generation*per_device_train_batch_size=24 is divisible by num_generations=4 + steps_per_generation=4, + num_generations=4, + per_device_train_batch_size=6, # reduce the batch size to reduce memory usage + num_iterations=2, + shuffle_dataset=False, + report_to="none", + ) + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + # steps_per_generation=4, per_device_train_batch_size=6 and num_generations=4, so we expect a + # generation batch of 24 samples (steps_per_generation * per_device_train_batch_size), containing 6 + # different prompts (steps_per_generation * per_device_train_batch_size // num_generations), each repeated + # 4 times (num_generations). + expected_first_generation_batch = ( + [{"prompt": "Beautiful is better than"}] * 4 + + [{"prompt": "Explicit is"}] * 4 + + [{"prompt": "Simple is better"}] * 4 + + [{"prompt": "Complex"}] * 4 + + [{"prompt": "Flat is better than"}] * 4 + + [{"prompt": "Sparse is better"}] * 4 + ) + expected_second_generation_batch = ( + [{"prompt": "Readability"}] * 4 + + [{"prompt": "Special cases aren't special"}] * 4 + + [{"prompt": "Although practicality beats"}] * 4 + + [{"prompt": "Errors should never"}] * 4 + + [{"prompt": "Unless explicitly"}] * 4 + + [{"prompt": "In the face of ambiguity, refuse"}] * 4 + ) + + with patch.object(RLOOTrainer, "training_step", wraps=trainer.training_step) as mock_prepare: + trainer.train() + # 3 epochs * 2 iterations * 2 generation batches to cover the dataset * 4 steps_per_generation + assert mock_prepare.call_count == 48 + for i in range(0, 8): # Generation batch repeated 8 times (steps_per_generation*num_iterations) + assert mock_prepare.call_args_list[i].args[1] == expected_first_generation_batch + for i in range(8, 16): + assert mock_prepare.call_args_list[i].args[1] == expected_second_generation_batch + + def test_train_with_chat_template_kwargs(self): + dataset = load_dataset("trl-internal-testing/zen", "conversational_prompt_only", split="train") + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=3, # reduce the batch size to reduce memory usage + num_generations=3, # reduce the number of generations to reduce memory usage + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + chat_template_kwargs={"enable_thinking": False}, + ) + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Qwen3ForCausalLM", + reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_mismatched_reward_processing_classes_length(self): + """Test that mismatched length between reward_funcs and reward_processing_classes raises error.""" + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + # Use two reward models + reward_models = [ + "trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + "trl-internal-testing/tiny-Qwen3ForSequenceClassification", + ] + + # Create a single processing class (tokenizer) + single_processing_class = AutoTokenizer.from_pretrained( + "trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5" + ) + + training_args = RLOOConfig(output_dir=self.tmp_dir, report_to="none") + + with pytest.raises(ValueError, match="must match"): + RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=reward_models, + reward_processing_classes=single_processing_class, # only one, but need two + args=training_args, + train_dataset=dataset, + ) + + def test_correct_reward_processing_classes_list(self): + """Test that correct list of reward_processing_classes works properly.""" + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + # Use two reward models + reward_models = [ + "trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", + "trl-internal-testing/tiny-Qwen3ForSequenceClassification", + ] + + # Create processing classes + processing_class1 = AutoTokenizer.from_pretrained( + "trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5" + ) + processing_class2 = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen3ForSequenceClassification") + + training_args = RLOOConfig(output_dir=self.tmp_dir, report_to="none") + + # Correct list length should work + correct_processing_classes = [processing_class1, processing_class2] + + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=reward_models, + reward_processing_classes=correct_processing_classes, + args=training_args, + train_dataset=dataset, + ) + + assert len(trainer.reward_processing_classes) == len(reward_models) + + def test_single_reward_model_with_single_processing_class(self): + """Test that single reward model with single processing class works.""" + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + + # Use single reward model + reward_model = "trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5" + + # Create a single processing class (tokenizer) + single_processing_class = AutoTokenizer.from_pretrained( + "trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5" + ) + + training_args = RLOOConfig(output_dir=self.tmp_dir, report_to="none") + + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + reward_funcs=reward_model, + reward_processing_classes=single_processing_class, # single object for single reward model + args=training_args, + train_dataset=dataset, + ) + + assert len(trainer.reward_processing_classes) == 1 + assert trainer.reward_processing_classes[0] == single_processing_class + + +@require_vision +class TestRLOOTrainerVLM(TrlTestCase): + @pytest.mark.parametrize( + "model_id", + [ + "trl-internal-testing/tiny-Gemma3ForConditionalGeneration", + pytest.param( + "trl-internal-testing/tiny-Gemma4ForConditionalGeneration", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.5.0"), + reason="Gemma4 models were introduced in transformers-5.5.0", + ), + ), + "trl-internal-testing/tiny-LlavaNextForConditionalGeneration", + "trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration", + "trl-internal-testing/tiny-Qwen2VLForConditionalGeneration", + pytest.param( + "trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-NoThink", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.2.0"), + reason="Qwen3.5 models were introduced in transformers-5.2.0", + ), + ), + pytest.param( + "trl-internal-testing/tiny-Qwen3_5MoeForConditionalGeneration-3.6", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.2.0"), + reason="Qwen3.5 models were introduced in transformers-5.2.0", + ), + ), + # "trl-internal-testing/tiny-SmolVLMForConditionalGeneration", seems not to support bf16 properly + ], + ) + def test_train_vlm(self, model_id): + dataset = load_dataset("trl-internal-testing/zen-image", "conversational_prompt_only", split="train") + + def reward_func(completions, **kwargs): + """Reward function that rewards longer completions.""" + return [float(len(completion[0]["content"])) for completion in completions] + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM + num_generations=2, # VLM training is memory intensive, reduce num_generations to avoid OOM + # note: num_generations=2 is only suitable for CI testing; production training should use more generations + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = RLOOTrainer( + model=model_id, + reward_funcs=reward_func, + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + # LLaVA & LLaVA-Next: vision_feature_layer=-2 leaves the last encoder layer (layers.1) and + # post_layernorm (pooler-only path) without gradient by design. Assert they stay frozen — if they + # ever start training, the feature-selection plumbing has likely regressed. + if model_id in ( + "trl-internal-testing/tiny-LlavaForConditionalGeneration", + "trl-internal-testing/tiny-LlavaNextForConditionalGeneration", + ) and ("encoder.layers.1" in n or "post_layernorm" in n): + assert torch.equal(param, new_param), f"Param {n} expected frozen by LLaVA design, but changed" + else: + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_vlm_with_pad_to_multiple_of(self): + # Models like Gemma3 use other forward keyword arguments like token_type_ids that also need to be padded when + # using pad_to_multiple_of, so we test that the trainer correctly pads all the necessary inputs in this case. + dataset = load_dataset("trl-internal-testing/zen-image", "conversational_prompt_only", split="train") + + def reward_func(completions, **kwargs): + """Reward function that rewards longer completions.""" + return [float(len(completion[0]["content"])) for completion in completions] + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM + num_generations=2, # VLM training is memory intensive, reduce num_generations to avoid OOM + # note: num_generations=2 is only suitable for CI testing; production training should use more generations + max_completion_length=8, # reduce the completion length to reduce memory usage + pad_to_multiple_of=7, + report_to="none", + ) + trainer = RLOOTrainer( + model="trl-internal-testing/tiny-Gemma3ForConditionalGeneration", + reward_funcs=reward_func, + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.parametrize( + "model_id", + [ + "trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration", + ], + ) + def test_train_vlm_beta_non_zero(self, model_id): + dataset = load_dataset("trl-internal-testing/zen-image", "conversational_prompt_only", split="train") + + def reward_func(completions, **kwargs): + """Reward function that rewards longer completions.""" + return [float(len(completion[0]["content"])) for completion in completions] + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + beta=0.1, # set beta to non-zero value to test the case where the reference model is used + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM + num_generations=2, # VLM training is memory intensive, reduce num_generations to avoid OOM + # note: num_generations=2 is only suitable for CI testing; production training should use more generations + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = RLOOTrainer( + model=model_id, + reward_funcs=reward_func, + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.parametrize( + "model_id", + [ + "trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration", + ], + ) + @require_peft + def test_train_vlm_peft(self, model_id): + model = AutoModelForImageTextToText.from_pretrained(model_id, dtype="float32") + base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()] + dataset = load_dataset("trl-internal-testing/zen-image", "conversational_prompt_only", split="train") + + def reward_func(completions, **kwargs): + """Reward function that rewards longer completions.""" + return [float(len(completion[0]["content"])) for completion in completions] + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM + num_generations=2, # VLM training is memory intensive, reduce num_generations to avoid OOM + # note: num_generations=2 is only suitable for CI testing; production training should use more generations + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = RLOOTrainer( + model=model, + reward_funcs=reward_func, + args=training_args, + train_dataset=dataset, + peft_config=LoraConfig(target_modules=["q_proj", "v_proj"]), + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the peft params have changed and the base model params have not changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + if n in base_param_names: # We expect the base model params to be the same + torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.") + elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.parametrize( + "model_id", + [ + "trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration", + "trl-internal-testing/tiny-Gemma3ForConditionalGeneration", + pytest.param( + "trl-internal-testing/tiny-Gemma4ForConditionalGeneration", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.5.0"), + reason="Gemma4 models were introduced in transformers-5.5.0", + ), + ), + ], + ) + @require_vllm + @pytest.mark.skip(reason="We should add a mock for the vLLM server.") + def test_train_vlm_and_vllm(self, model_id) -> None: + dataset = load_dataset("trl-internal-testing/zen-image", "conversational_prompt_only", split="train") + + def reward_func(completions, **kwargs): + """Reward function that rewards longer completions.""" + return [float(len(completion[0]["content"])) for completion in completions] + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM + num_generations=2, # VLM training is memory intensive, reduce num_generations to avoid OOM + # note: num_generations=2 is only suitable for CI testing; production training should use more generations + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + use_vllm=True, + vllm_mode="server", + ) + trainer = RLOOTrainer( + model=model_id, + reward_funcs=reward_func, + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.parametrize( + "model_id", + [ + "trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration", + ], + ) + def test_train_vlm_multi_image(self, model_id): + dataset = load_dataset("trl-internal-testing/zen-multi-image", "conversational_prompt_only", split="train") + + def reward_func(completions, **kwargs): + """Reward function that rewards longer completions.""" + return [float(len(completion[0]["content"])) for completion in completions] + + training_args = RLOOConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM + num_generations=2, # VLM training is memory intensive, reduce num_generations to avoid OOM + # note: num_generations=2 is only suitable for CI testing; production training should use more generations + max_completion_length=8, # reduce the completion length to reduce memory usage + report_to="none", + ) + trainer = RLOOTrainer( + model=model_id, + reward_funcs=reward_func, + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_sft_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_sft_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..e3ba32d0d1ae6678fd3d60ab71f5fe400c066bba --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_sft_trainer.py @@ -0,0 +1,2837 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import copy +import gc +import json +import pathlib +from unittest.mock import MagicMock, patch + +import pytest +import torch +import torch.nn.functional as F +import transformers +from accelerate.utils.memory import release_memory +from datasets import Dataset, load_dataset +from packaging.version import Version +from packaging.version import parse as parse_version +from transformers import ( + AutoModelForCausalLM, + AutoModelForImageTextToText, + AutoTokenizer, + BitsAndBytesConfig, + TrainingArguments, +) +from transformers.testing_utils import backend_empty_cache, torch_device +from transformers.utils import is_peft_available + +from trl import SFTConfig, SFTTrainer +from trl.trainer.sft_trainer import ( + DataCollatorForLanguageModeling, + _chunked_cross_entropy_loss, + _patch_chunked_ce_lm_head, + dft_loss, +) + +from .testing_utils import ( + TrlTestCase, + ignore_warnings, + is_ampere_or_newer, + require_bitsandbytes, + require_kernels, + require_liger_kernel, + require_peft, + require_torch_accelerator, + require_torch_multi_accelerator, + require_vision, +) + + +if is_peft_available(): + import peft + from peft import ( + LoraConfig, + PeftModel, + PrefixTuningConfig, + PromptEncoderConfig, + PromptTuningConfig, + TaskType, + get_peft_model, + ) + + +class TestDFTLoss(TrlTestCase): + def test_dft_loss(self): + batch_size = 2 + seq_len = 3 + vocab_size = 2 + # All tokens have the same probability + logits = torch.fill(torch.empty(batch_size, seq_len, vocab_size), torch.rand(1).item()) + outputs = MagicMock() + outputs.logits = logits + labels = torch.tensor([[1, 0, 0], [0, 1, -100]]) + ce_loss = torch.nn.functional.cross_entropy( + logits.view(-1, vocab_size), labels.view(-1), ignore_index=-100, reduction="mean" + ) + # We need to account for the logits shift operation so we don't consider the first tokens + # in each row of the batch + num_items_in_batch = 3 + # Dft loss + predicted_dft_loss = dft_loss(outputs, labels, num_items_in_batch) + # If we have just two tokens in our vocab and all logits are the same, + # dft scales the ce_loss per token by 0.5. So the dft_loss should be ce_loss/2 + torch.testing.assert_close(ce_loss / 2.0, predicted_dft_loss, atol=1e-4, rtol=1e-4) + + +class TestDataCollatorForLanguageModeling(TrlTestCase): + def test_basic_padding(self): + """Test basic padding functionality without completion masks.""" + collator = DataCollatorForLanguageModeling(pad_token_id=0) + examples = [{"input_ids": [1, 2, 3]}, {"input_ids": [4, 5]}] + + result = collator(examples) + + assert set(result.keys()) == {"input_ids", "attention_mask", "labels"} + torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3], [4, 5, 0]])) + torch.testing.assert_close(result["attention_mask"], torch.tensor([[1, 1, 1], [1, 1, 0]])) + torch.testing.assert_close(result["labels"], torch.tensor([[1, 2, 3], [4, 5, -100]])) + + def test_completion_mask(self): + """Test completion mask functionality.""" + collator = DataCollatorForLanguageModeling(pad_token_id=0) + examples = [ + {"input_ids": [1, 2, 3], "completion_mask": [0, 1, 1]}, + {"input_ids": [4, 5], "completion_mask": [0, 1]}, + ] + + result = collator(examples) + + assert set(result.keys()) == {"input_ids", "attention_mask", "labels"} + torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3], [4, 5, 0]])) + torch.testing.assert_close(result["attention_mask"], torch.tensor([[1, 1, 1], [1, 1, 0]])) + torch.testing.assert_close(result["labels"], torch.tensor([[-100, 2, 3], [-100, 5, -100]])) + + def test_completion_only_loss_disabled(self): + """Test behavior when completion_only_loss is disabled.""" + collator = DataCollatorForLanguageModeling(pad_token_id=0, completion_only_loss=False) + examples = [ + {"input_ids": [1, 2, 3], "completion_mask": [0, 1, 1]}, + {"input_ids": [4, 5], "completion_mask": [0, 1]}, + ] + + result = collator(examples) + + # Labels should not be masked when completion_only_loss=False + assert set(result.keys()) == {"input_ids", "attention_mask", "labels"} + torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3], [4, 5, 0]])) + torch.testing.assert_close(result["attention_mask"], torch.tensor([[1, 1, 1], [1, 1, 0]])) + torch.testing.assert_close(result["labels"], torch.tensor([[1, 2, 3], [4, 5, -100]])) + + def test_padding_free_mode(self): + """Test padding-free mode where sequences are concatenated.""" + collator = DataCollatorForLanguageModeling(pad_token_id=0, padding_free=True) + examples = [{"input_ids": [1, 2, 3]}, {"input_ids": [4, 5]}] + + result = collator(examples) + + assert set(result.keys()) == {"input_ids", "position_ids", "labels"} + torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3, 4, 5]])) + torch.testing.assert_close(result["position_ids"], torch.tensor([[0, 1, 2, 0, 1]])) + torch.testing.assert_close(result["labels"], torch.tensor([[-100, 2, 3, -100, 5]])) + + def test_padding_free_with_completion_mask(self): + """Test padding-free mode with completion masks.""" + collator = DataCollatorForLanguageModeling(pad_token_id=0, padding_free=True) + examples = [ + {"input_ids": [1, 2, 3], "completion_mask": [0, 0, 1]}, + {"input_ids": [4, 5], "completion_mask": [1, 1]}, + ] + + result = collator(examples) + + assert set(result.keys()) == {"input_ids", "position_ids", "labels"} + torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3, 4, 5]])) + torch.testing.assert_close(result["position_ids"], torch.tensor([[0, 1, 2, 0, 1]])) + torch.testing.assert_close(result["labels"], torch.tensor([[-100, -100, 3, -100, 5]])) + + def test_packing(self): + """Test that when using packing with position_ids, attention_mask is dropped with fa2.""" + collator = DataCollatorForLanguageModeling(pad_token_id=0, padding_free=True) + + # Simulate packed sequences with position_ids that restart (typical of BFD packing) + examples = [ + {"input_ids": [1, 2, 3, 4, 5, 6], "seq_lengths": [3, 3]}, + {"input_ids": [7, 8, 9, 10, 11], "seq_lengths": [4, 1]}, + ] + + result = collator(examples) + + assert set(result.keys()) == {"input_ids", "position_ids", "labels"} + torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]])) + torch.testing.assert_close(result["position_ids"], torch.tensor([[0, 1, 2, 0, 1, 2, 0, 1, 2, 3, 0]])) + torch.testing.assert_close(result["labels"], torch.tensor([[-100, 2, 3, -100, 5, 6, -100, 8, 9, 10, -100]])) + + def test_pad_to_multiple_of(self): + """Test padding to multiple of specified value.""" + collator = DataCollatorForLanguageModeling(pad_token_id=0, pad_to_multiple_of=4) + examples = [{"input_ids": [1, 2, 3]}, {"input_ids": [4, 5]}] + + result = collator(examples) + + assert set(result.keys()) == {"input_ids", "attention_mask", "labels"} + torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3, 0], [4, 5, 0, 0]])) + torch.testing.assert_close(result["attention_mask"], torch.tensor([[1, 1, 1, 0], [1, 1, 0, 0]])) + torch.testing.assert_close(result["labels"], torch.tensor([[1, 2, 3, -100], [4, 5, -100, -100]])) + + def test_pad_to_multiple_of_and_padding_free(self): + """Test padding to multiple of specified value.""" + collator = DataCollatorForLanguageModeling(pad_token_id=0, padding_free=True, pad_to_multiple_of=4) + examples = [{"input_ids": [1, 2, 3]}, {"input_ids": [4, 5]}] + + result = collator(examples) + + assert set(result.keys()) == {"input_ids", "position_ids", "labels"} + torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3, 4, 5, 0, 0, 0]])) + torch.testing.assert_close(result["position_ids"], torch.tensor([[0, 1, 2, 0, 1, 0, 0, 0]])) + torch.testing.assert_close(result["labels"], torch.tensor([[-100, 2, 3, -100, 5, -100, -100, -100]])) + + def test_custom_position_ids_but_no_padding_free(self): + """Test that custom position_ids are ignored if padding_free is False.""" + collator = DataCollatorForLanguageModeling(pad_token_id=0) + examples = [{"input_ids": [1, 2, 3], "seq_lengths": [1, 2]}, {"input_ids": [4, 5], "seq_lengths": [2]}] + + result = collator(examples) + + assert set(result.keys()) == {"input_ids", "attention_mask", "labels"} + torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3], [4, 5, 0]])) + torch.testing.assert_close(result["attention_mask"], torch.tensor([[1, 1, 1], [1, 1, 0]])) + torch.testing.assert_close(result["labels"], torch.tensor([[1, 2, 3], [4, 5, -100]])) + + def test_single_example(self): + """Test collator with a single example.""" + collator = DataCollatorForLanguageModeling(pad_token_id=0) + examples = [{"input_ids": [1, 2, 3, 4]}] + + result = collator(examples) + + assert set(result.keys()) == {"input_ids", "attention_mask", "labels"} + torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3, 4]])) + torch.testing.assert_close(result["attention_mask"], torch.tensor([[1, 1, 1, 1]])) + torch.testing.assert_close(result["labels"], torch.tensor([[1, 2, 3, 4]])) + + def test_different_pad_token_id(self): + """Test with different pad token ID.""" + collator = DataCollatorForLanguageModeling(pad_token_id=999) + examples = [{"input_ids": [1, 2, 3]}, {"input_ids": [4, 5]}] + + result = collator(examples) + + assert set(result.keys()) == {"input_ids", "attention_mask", "labels"} + torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3], [4, 5, 999]])) + torch.testing.assert_close(result["attention_mask"], torch.tensor([[1, 1, 1], [1, 1, 0]])) + torch.testing.assert_close(result["labels"], torch.tensor([[1, 2, 3], [4, 5, -100]])) + + def test_assistant_masks(self): + """Test handling of assistant masks in examples.""" + collator = DataCollatorForLanguageModeling(pad_token_id=0) + examples = [ + {"input_ids": [1, 2, 3], "assistant_masks": [0, 1, 1]}, + {"input_ids": [4, 5], "assistant_masks": [0, 1]}, + ] + + result = collator(examples) + + torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3], [4, 5, 0]])) + torch.testing.assert_close(result["attention_mask"], torch.tensor([[1, 1, 1], [1, 1, 0]])) + torch.testing.assert_close(result["labels"], torch.tensor([[-100, 2, 3], [-100, 5, -100]])) + + def test_max_length_keep_start(self): + """Test that sequences longer than max_length are truncated from the start.""" + collator = DataCollatorForLanguageModeling(pad_token_id=0, max_length=3) + examples = [{"input_ids": [1, 2, 3, 4, 5]}, {"input_ids": [6, 7, 8]}] + + result = collator(examples) + + assert set(result.keys()) == {"input_ids", "attention_mask", "labels"} + torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3], [6, 7, 8]])) + torch.testing.assert_close(result["attention_mask"], torch.tensor([[1, 1, 1], [1, 1, 1]])) + torch.testing.assert_close(result["labels"], torch.tensor([[1, 2, 3], [6, 7, 8]])) + + def test_max_length_keep_end(self): + """Test that sequences longer than max_length are truncated from the end (keeping last tokens).""" + collator = DataCollatorForLanguageModeling(pad_token_id=0, max_length=3, truncation_mode="keep_end") + examples = [{"input_ids": [1, 2, 3, 4, 5]}, {"input_ids": [6, 7, 8]}] + + result = collator(examples) + + assert set(result.keys()) == {"input_ids", "attention_mask", "labels"} + torch.testing.assert_close(result["input_ids"], torch.tensor([[3, 4, 5], [6, 7, 8]])) + torch.testing.assert_close(result["attention_mask"], torch.tensor([[1, 1, 1], [1, 1, 1]])) + torch.testing.assert_close(result["labels"], torch.tensor([[3, 4, 5], [6, 7, 8]])) + + def test_max_length_no_truncation_needed(self): + """Test that max_length larger than sequences does not alter the output.""" + collator = DataCollatorForLanguageModeling(pad_token_id=0, max_length=10) + examples = [{"input_ids": [1, 2, 3]}, {"input_ids": [4, 5]}] + + result = collator(examples) + + assert set(result.keys()) == {"input_ids", "attention_mask", "labels"} + torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3], [4, 5, 0]])) + torch.testing.assert_close(result["attention_mask"], torch.tensor([[1, 1, 1], [1, 1, 0]])) + torch.testing.assert_close(result["labels"], torch.tensor([[1, 2, 3], [4, 5, -100]])) + + def test_max_length_with_completion_mask(self): + """Test that truncation is applied correctly when completion masks are present.""" + collator = DataCollatorForLanguageModeling(pad_token_id=0, max_length=3) + examples = [ + {"input_ids": [1, 2, 3, 4, 5], "completion_mask": [0, 0, 1, 1, 1]}, + {"input_ids": [6, 7, 8], "completion_mask": [0, 1, 1]}, + ] + + result = collator(examples) + + assert set(result.keys()) == {"input_ids", "attention_mask", "labels"} + torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3], [6, 7, 8]])) + torch.testing.assert_close(result["attention_mask"], torch.tensor([[1, 1, 1], [1, 1, 1]])) + torch.testing.assert_close(result["labels"], torch.tensor([[-100, -100, 3], [-100, 7, 8]])) + + def test_max_length_keep_end_with_completion_mask(self): + """Test keep_end truncation with completion masks preserves the final tokens.""" + collator = DataCollatorForLanguageModeling(pad_token_id=0, max_length=3, truncation_mode="keep_end") + examples = [ + {"input_ids": [1, 2, 3, 4, 5], "completion_mask": [0, 0, 1, 1, 1]}, + {"input_ids": [6, 7, 8], "completion_mask": [0, 1, 1]}, + ] + + result = collator(examples) + + assert set(result.keys()) == {"input_ids", "attention_mask", "labels"} + torch.testing.assert_close(result["input_ids"], torch.tensor([[3, 4, 5], [6, 7, 8]])) + torch.testing.assert_close(result["attention_mask"], torch.tensor([[1, 1, 1], [1, 1, 1]])) + torch.testing.assert_close(result["labels"], torch.tensor([[3, 4, 5], [-100, 7, 8]])) + + def test_max_length_invalid_truncation_mode(self): + """Test that an invalid truncation_mode raises ValueError.""" + collator = DataCollatorForLanguageModeling(pad_token_id=0, max_length=3, truncation_mode="invalid") + examples = [{"input_ids": [1, 2, 3, 4, 5]}] + + with pytest.raises(ValueError, match="Unsupported truncation mode"): + collator(examples) + + def test_single_example_single_doc(self): + batch_seq_lengths = [[5]] + result = DataCollatorForLanguageModeling.get_position_ids_from_packed_seq_lengths(batch_seq_lengths) + assert len(result) == 1 + assert torch.equal(result[0], torch.arange(5)) + + def test_single_example_multiple_docs(self): + batch_seq_lengths = [[3, 2]] + result = DataCollatorForLanguageModeling.get_position_ids_from_packed_seq_lengths(batch_seq_lengths) + assert len(result) == 1 + # First sequence: 0, 1, 2; second sequence: 0, 1 + assert torch.equal(result[0], torch.tensor([0, 1, 2, 0, 1])) + + def test_multiple_examples(self): + batch_seq_lengths = [[2, 2], [3]] + result = DataCollatorForLanguageModeling.get_position_ids_from_packed_seq_lengths(batch_seq_lengths) + assert len(result) == 2 + assert torch.equal(result[0], torch.tensor([0, 1, 0, 1])) + assert torch.equal(result[1], torch.arange(3)) + + +class TestSFTTrainer(TrlTestCase): + def test_init_with_training_arguments(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train") + args = TrainingArguments(output_dir=self.tmp_dir, report_to="none") + SFTTrainer(model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=args, train_dataset=dataset) + + @pytest.mark.parametrize( + "model_id", + [ + "trl-internal-testing/tiny-Cohere2ForCausalLM", + pytest.param( + "trl-internal-testing/tiny-Glm4MoeForCausalLM", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.0.0"), + reason="GLM4 tokenizer requires transformers>=5.0.0", + ), + ), + "trl-internal-testing/tiny-GptOssForCausalLM", + "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + "trl-internal-testing/tiny-Qwen3MoeForCausalLM", + pytest.param( + "trl-internal-testing/tiny-NemotronHForCausalLM-nano", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.7.0"), + reason="Nemotron 3 gradient checkpointing requires transformers>=5.7.0 (see transformers#45625)", + ), + ), + pytest.param( + "trl-internal-testing/tiny-Olmo3ForCausalLM", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("4.57.0"), + reason="Olmo 3 requires transformers>=4.57.0", + ), + ), + ], + ) + def test_train(self, model_id): + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train") + + training_args = SFTConfig(output_dir=self.tmp_dir, report_to="none") + trainer = SFTTrainer(model=model_id, args=training_args, train_dataset=dataset) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.parametrize( + "config_name", + [ + "standard_language_modeling", + "conversational_language_modeling", + "standard_prompt_completion", + "conversational_prompt_completion", + ], + ) + def test_train_dataset_format(self, config_name): + dataset = load_dataset("trl-internal-testing/zen", config_name, split="train") + + training_args = SFTConfig(output_dir=self.tmp_dir, report_to="none") + trainer = SFTTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + # Special case for harmony + def test_train_gpt_oss(self): + dataset = load_dataset("trl-internal-testing/harmony", "language_modeling", split="train") + + training_args = SFTConfig(output_dir=self.tmp_dir, report_to="none") + trainer = SFTTrainer( + model="trl-internal-testing/tiny-GptOssForCausalLM", args=training_args, train_dataset=dataset + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_model(self): + model = AutoModelForCausalLM.from_pretrained( + "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + dtype="float32", + ) + + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train") + + training_args = SFTConfig(output_dir=self.tmp_dir, report_to="none") + trainer = SFTTrainer(model=model, args=training_args, train_dataset=dataset) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_dft_loss(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling") + + training_args = SFTConfig( + output_dir=self.tmp_dir, + loss_type="dft", + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + report_to="none", + eval_strategy="steps", + eval_steps=3, + ) + trainer = SFTTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset["train"], + eval_dataset=dataset["test"], + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_nll_loss(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train") + + training_args = SFTConfig(output_dir=self.tmp_dir, loss_type="nll", report_to="none") + trainer = SFTTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @require_peft + def test_train_nll_loss_peft(self): + model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" + model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32") + base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()] + + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train") + + training_args = SFTConfig(output_dir=self.tmp_dir, loss_type="nll", report_to="none") + trainer = SFTTrainer( + model=model_id, + args=training_args, + train_dataset=dataset, + peft_config=LoraConfig(), + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the peft params have changed and the base model params have not changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + if n in base_param_names: # We expect the base model params to be the same + torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.") + elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.parametrize( + "model_id", + [ + "trl-internal-testing/tiny-Gemma3ForConditionalGeneration", + pytest.param( + "trl-internal-testing/tiny-Gemma4ForConditionalGeneration", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.5.0"), + reason="Gemma4 models were introduced in transformers-5.5.0", + ), + ), + "trl-internal-testing/tiny-LlavaForConditionalGeneration", + "trl-internal-testing/tiny-LlavaNextForConditionalGeneration", + "trl-internal-testing/tiny-Qwen2VLForConditionalGeneration", + "trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration", + pytest.param( + "trl-internal-testing/tiny-Qwen3VLForConditionalGeneration", + marks=[ + pytest.mark.skipif( + Version(transformers.__version__) < Version("4.57.0"), + reason="Qwen3-VL series were introduced in transformers-4.57.0", + ), + ], + ), + pytest.param( + "trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-NoThink", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.2.0"), + reason="Qwen3.5 models were introduced in transformers-5.2.0", + ), + ), + pytest.param( + "trl-internal-testing/tiny-Qwen3_5MoeForConditionalGeneration-3.6", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.2.0"), + reason="Qwen3.5 models were introduced in transformers-5.2.0", + ), + ), + ], + ) + @require_vision + def test_train_nll_loss_vlm(self, model_id): + dataset = load_dataset("trl-internal-testing/zen-image", "conversational_language_modeling", split="train") + + training_args = SFTConfig( + output_dir=self.tmp_dir, + loss_type="nll", + max_length=None, # for VLMs, truncating can remove image tokens, leading to errors + report_to="none", + ) + trainer = SFTTrainer(model=model_id, args=training_args, train_dataset=dataset) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + # LLaVA & LLaVA-Next: vision_feature_layer=-2 leaves the last encoder layer (layers.1) and + # post_layernorm (pooler-only path) without gradient by design. Assert they stay frozen — if they + # ever start training, the feature-selection plumbing has likely regressed. + if model_id in ( + "trl-internal-testing/tiny-LlavaForConditionalGeneration", + "trl-internal-testing/tiny-LlavaNextForConditionalGeneration", + ) and ("encoder.layers.1" in n or "post_layernorm" in n): + assert torch.equal(param, new_param), f"Param {n} expected frozen by LLaVA design, but changed" + else: + assert not torch.equal(param, new_param), f"Param {n} is not updated" + + def test_train_moe_model_with_aux_loss(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train") + + training_args = SFTConfig( + output_dir=self.tmp_dir, + report_to="none", + model_init_kwargs={"output_router_logits": True}, + ) + trainer = SFTTrainer( + model="trl-internal-testing/tiny-Qwen3MoeForCausalLM", args=training_args, train_dataset=dataset + ) + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + # Check that the training loss and aux loss are not None + assert trainer.state.log_history[-1]["train_loss"] is not None + assert trainer.state.log_history[-1]["aux_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_formatting_func(self): + # Dummy formatting function + def formatting_prompts_func(example): + chosen, rejected = example["chosen"], example["rejected"] + return f"### Chosen: {chosen}\n### Rejected: {rejected}" + + dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train") + + training_args = SFTConfig(output_dir=self.tmp_dir, report_to="none") + trainer = SFTTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset, + formatting_func=formatting_prompts_func, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_model_dtype(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train") + + training_args = SFTConfig( + output_dir=self.tmp_dir, + model_init_kwargs={"dtype": torch.float16}, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + report_to="none", + ) + trainer = SFTTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + # For some reasonn model.layers.0.input_layernorm.weight doesn't change in GitHub Actions but does + # locally. We ignore this parameter for now + if "layernorm" in n: + continue + new_param = trainer.model.get_parameter(n) + # Check the torch dtype + assert new_param.dtype == torch.float16 + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @require_peft + def test_train_dense_with_peft_config_lora(self): + model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" + model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32") + base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()] + + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train") + + training_args = SFTConfig(output_dir=self.tmp_dir, report_to="none") + + trainer = SFTTrainer( + model=model_id, + args=training_args, + train_dataset=dataset, + peft_config=LoraConfig(), + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the peft params have changed and the base model params have not changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + if n in base_param_names: # We expect the base model params to be the same + torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.") + elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.parametrize( + "peft_type", + [ + "prompt_tuning", + "prefix_tuning", + "prompt_encoder", + ], + ) + @require_peft + def test_train_with_peft_config_prompt_tuning(self, peft_type): + model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" + model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32") + base_param_names = [f"base_model.{n}" for n, _ in model.named_parameters()] + + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train") + + # Initialize the trainer, p-tuning doesn't support gradient checkpointing + training_args = SFTConfig(bf16=False, output_dir=self.tmp_dir, report_to="none", gradient_checkpointing=False) + if peft_type == "prompt_tuning": + peft_config = PromptTuningConfig( + task_type=TaskType.CAUSAL_LM, + num_virtual_tokens=4, + tokenizer_name_or_path="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + ) + elif peft_type == "prefix_tuning": + if parse_version(peft.__version__) <= Version("0.17.1"): + pytest.xfail( + "Prefix tuning with device_map='auto' is broken in peft 0.17.1 and below. See " + "https://github.com/huggingface/peft/issues/2821" + ) + peft_config = PrefixTuningConfig( + task_type=TaskType.CAUSAL_LM, + num_virtual_tokens=4, + ) + elif peft_type == "prompt_encoder": + peft_config = PromptEncoderConfig( + task_type=TaskType.CAUSAL_LM, + num_virtual_tokens=4, + encoder_hidden_size=model.config.hidden_size, # This will be overwritten below + ) + trainer = SFTTrainer( + model=model_id, + args=training_args, + train_dataset=dataset, + peft_config=peft_config, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the peft params have changed and the base model params have not changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + if n in base_param_names: # We expect the base model params to be the same + torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.") + else: # We expect the peft params to be different + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @require_peft + def test_train_moe_with_peft_config(self): + model_id = "trl-internal-testing/tiny-GptOssForCausalLM" + model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32") + base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()] + + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train") + + training_args = SFTConfig(output_dir=self.tmp_dir, report_to="none") + + trainer = SFTTrainer( + model=model_id, + args=training_args, + train_dataset=dataset, + peft_config=LoraConfig(target_parameters=["mlp.experts.down_proj", "mlp.experts.gate_up_proj"]), + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the peft params have changed and the base model params have not changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + if n in base_param_names: # We expect the base model params to be the same + torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.") + elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @require_peft + def test_train_peft_model(self): + model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" + model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32") + + base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()] + + lora_config = LoraConfig() + model = get_peft_model(model, lora_config) + + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train") + + training_args = SFTConfig(output_dir=self.tmp_dir, report_to="none") + trainer = SFTTrainer(model=model, args=training_args, train_dataset=dataset) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the peft params have changed and the base model params have not changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + if n in base_param_names: # We expect the base model params to be the same + torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.") + elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + # In practice, this test is the same as `test_train_dense_with_peft_config_lora`, since gradient checkpointing is + # enabled by default in `SFTTrainer`. We keep it as a regression guard: if the default ever changes, we still + # explicitly test PEFT + gradient checkpointing, which has caused issues in the past. + @require_peft + def test_train_with_peft_config_and_gradient_checkpointing(self): + model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" + model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32") + base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()] + + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train") + + training_args = SFTConfig(output_dir=self.tmp_dir, gradient_checkpointing=True, report_to="none") + + trainer = SFTTrainer( + model=model_id, + args=training_args, + train_dataset=dataset, + peft_config=LoraConfig(), + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the peft params have changed and the base model params have not changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + if n in base_param_names: # We expect the base model params to be the same + torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.") + elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.parametrize("use_reentrant", [True, False]) + @require_peft + def test_train_with_peft_config_and_gradient_checkpointing_reentrant(self, use_reentrant): + model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" + model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32") + base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()] + + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train") + + training_args = SFTConfig( + output_dir=self.tmp_dir, + gradient_checkpointing=True, + gradient_checkpointing_kwargs={"use_reentrant": use_reentrant}, + report_to="none", + ) + + trainer = SFTTrainer( + model=model_id, + args=training_args, + train_dataset=dataset, + peft_config=LoraConfig(), + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the peft params have changed and the base model params have not changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + if n in base_param_names: # We expect the base model params to be the same + torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.") + elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @require_liger_kernel + def test_train_with_liger(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train") + + training_args = SFTConfig(output_dir=self.tmp_dir, use_liger_kernel=True, report_to="none") + trainer = SFTTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @require_torch_accelerator + @require_liger_kernel + def test_compute_loss_skip_logits_on_eval_without_metrics_with_liger(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train[:1]") + + # Init with `use_liger_kernel=False` to skip Liger model wrapping, then flip the flag after to exercise the + # Liger branch of `compute_loss`. `loss_type="nll"` so the chunked path isn't patched in (incompatible with + # Liger), keeping `model.forward` unmodified. + training_args = SFTConfig( + output_dir=self.tmp_dir, + use_liger_kernel=False, + loss_type="nll", + report_to="none", + max_length=8, + bf16=False, + ) + trainer = SFTTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset, + compute_metrics=None, + ) + trainer.args.use_liger_kernel = True + trainer.model.eval() + + captured = {} + + def mock_super_compute_loss(model, inputs, return_outputs=False, num_items_in_batch=None): + captured["skip_logits"] = inputs.get("skip_logits") + dummy_loss = torch.tensor(1.0, requires_grad=True) + dummy_outputs = MagicMock() + dummy_outputs.token_accuracy = None + dummy_outputs.logits = torch.randn(1, 5, trainer.model.config.vocab_size) + return (dummy_loss, dummy_outputs) + + inputs = { + "input_ids": torch.tensor([[1, 2, 3, 4, 5]]), + "labels": torch.tensor([[1, 2, 3, 4, 5]]), + "attention_mask": torch.tensor([[1, 1, 1, 1, 1]]), + } + + with patch("transformers.Trainer.compute_loss", side_effect=mock_super_compute_loss): + trainer.compute_loss(trainer.model, inputs) + + assert captured["skip_logits"] is True + + @require_torch_accelerator + @require_liger_kernel + def test_predict_does_not_skip_logits_with_liger(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train[:1]") + + # Same pattern as `test_compute_loss_skip_logits_on_eval_without_metrics_with_liger`: init without Liger then + # flip the flag, and force `loss_type="nll"` to keep `model.forward` unpatched. + training_args = SFTConfig( + output_dir=self.tmp_dir, + use_liger_kernel=False, + loss_type="nll", + report_to="none", + max_length=8, + bf16=False, + ) + trainer = SFTTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset, + compute_metrics=None, + ) + trainer.args.use_liger_kernel = True + trainer.model.eval() + + captured = {} + + def mock_super_compute_loss(model, inputs, return_outputs=False, num_items_in_batch=None): + captured["skip_logits"] = inputs.get("skip_logits") + dummy_loss = torch.tensor(1.0, requires_grad=True) + dummy_outputs = (dummy_loss, torch.randn(1, 5, trainer.model.config.vocab_size)) + return (dummy_loss, dummy_outputs) + + with patch("transformers.Trainer.compute_loss", side_effect=mock_super_compute_loss): + trainer.predict(trainer.train_dataset) + + assert captured["skip_logits"] is False + + def test_train_with_non_chatml_conversational_data(self): + dataset = load_dataset("trl-internal-testing/zen", "conversational_language_modeling", split="train") + + # Rename role/content to from/value to ensure SFT works with non-chatML conversational data + def rename_fields(example: list[dict]): + return {"conversations": [{"from": m["role"], "value": m["content"]} for m in example["messages"]]} + + dataset = dataset.map(rename_fields, remove_columns="messages") + + training_args = SFTConfig(output_dir=self.tmp_dir, report_to="none") + trainer = SFTTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_pretokenized_data(self): + model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" + tokenizer = AutoTokenizer.from_pretrained(model_id) + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train") + + def tokenize_example(example): + return tokenizer(example["text"]) + + # Apply tokenization + tokenized_dataset = dataset.map(tokenize_example, remove_columns=["text"]) + + training_args = SFTConfig(output_dir=self.tmp_dir, report_to="none") + trainer = SFTTrainer(model=model_id, args=training_args, train_dataset=tokenized_dataset) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_skip_prepare_dataset_passes_truncation_to_text_collator(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train[:2]") + with pytest.warns(FutureWarning, match="keep_end.*deprecated"): + training_args = SFTConfig( + output_dir=self.tmp_dir, + max_length=16, + truncation_mode="keep_end", + dataset_kwargs={"skip_prepare_dataset": True}, + report_to="none", + ) + + trainer = SFTTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset + ) + + assert isinstance(trainer.data_collator, DataCollatorForLanguageModeling) + assert trainer.data_collator.max_length == 16 + assert trainer.data_collator.truncation_mode == "keep_end" + + def test_dataset_with_transform_requires_skip_prepare_dataset(self): + dataset = Dataset.from_dict({"text": ["hello world"]}) + + def add_suffix(batch): + batch["text"] = [text + " " for text in batch["text"]] + return batch + + dataset = dataset.with_transform(add_suffix) + training_args = SFTConfig(output_dir=self.tmp_dir, report_to="none") + + with pytest.raises( + ValueError, + match=r"Dataset\.with_transform\(\).*skip_prepare_dataset.*trainer-ready", + ): + SFTTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset + ) + + def test_padding_free_without_packing_and_max_length_raises(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train[:2]") + training_args = SFTConfig( + output_dir=self.tmp_dir, + max_length=16, + padding_free=True, + report_to="none", + ) + + with pytest.raises(ValueError, match="`max_length` is not enforced"): + SFTTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset + ) + + def test_train_with_iterable_dataset(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train", streaming=True) + + training_args = SFTConfig(output_dir=self.tmp_dir, max_steps=3, report_to="none") + trainer = SFTTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @require_kernels + @pytest.mark.skipif( + not is_ampere_or_newer() and torch_device != "xpu", + reason="Flash Attention 2 requires Ampere or newer GPU, or XPU", + ) + def test_train_padding_free(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train") + + training_args = SFTConfig( + output_dir=self.tmp_dir, + padding_free=True, + max_length=None, # padding-free without packing doesn't enforce max_length + model_init_kwargs={"attn_implementation": "kernels-community/flash-attn2"}, + bf16=True, # flash_attention_2 only supports bf16 and fp16 + report_to="none", + ) + trainer = SFTTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.parametrize("packing_strategy", ["bfd", "wrapped"]) + @ignore_warnings(message="You are using packing, but the attention implementation is not.*", category=UserWarning) + @ignore_warnings(message="Padding-free training is enabled, but the attention.*", category=UserWarning) + def test_train_packing(self, packing_strategy): + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train") + + training_args = SFTConfig( + output_dir=self.tmp_dir, packing=True, packing_strategy=packing_strategy, max_length=10, report_to="none" + ) + trainer = SFTTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @ignore_warnings(message="You are using packing, but the attention implementation is not.*", category=UserWarning) + @ignore_warnings(message="Padding-free training is enabled, but the attention.*", category=UserWarning) + def test_eval_packing(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling") + + training_args = SFTConfig( + output_dir=self.tmp_dir, + packing=True, + max_length=64, + report_to="none", + ) + trainer = SFTTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset["train"], + eval_dataset=dataset["test"], + ) + + # Check the number of sequences in train and eval datasets + num_train_seqs = sum(len(x) for x in trainer.train_dataset["seq_lengths"]) + num_eval_seqs = sum(len(x) for x in trainer.eval_dataset["seq_lengths"]) + assert num_train_seqs == 17 # we should still have 17 seqs + assert num_eval_seqs == 2 # we should still have 2 seqs + + # Check that all sequences are shorter than the max length + assert all(sum(x) <= 64 for x in trainer.train_dataset["seq_lengths"]) + assert all(sum(x) <= 64 for x in trainer.eval_dataset["seq_lengths"]) + + # Check the number of sequences in train and eval datasets + assert len(trainer.train_dataset["input_ids"]) == 3 # w/ this dataset, we end up with 46 seqs + assert len(trainer.eval_dataset["input_ids"]) == 1 # w/ this dataset, we end up with 6 seqs + + @ignore_warnings(message="You are using packing, but the attention implementation is not.*", category=UserWarning) + @ignore_warnings(message="Padding-free training is enabled, but the attention.*", category=UserWarning) + def test_only_train_packing(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling") + + training_args = SFTConfig( + output_dir=self.tmp_dir, + packing=True, + eval_packing=False, + max_length=64, + report_to="none", + ) + trainer = SFTTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset["train"], + eval_dataset=dataset["test"], + ) + + # Check the number of sequences in train dataset + num_train_seqs = sum(len(x) for x in trainer.train_dataset["seq_lengths"]) + assert num_train_seqs == 17 # we should still have 17 seqs + + # We expect eval dataset not having "seq_lengths" as eval_packing is False + assert "seq_lengths" not in trainer.eval_dataset + + # Check that all sequences are shorter than the max length + assert all(sum(x) <= 64 for x in trainer.train_dataset["seq_lengths"]) + + # Check the number of sequences in train and eval datasets + assert len(trainer.train_dataset["input_ids"]) == 3 # w/ this dataset, we end up with 46 seqs + assert len(trainer.eval_dataset["input_ids"]) == 2 # w/ this dataset, we end up with 6 seqs + + def test_train_with_chat_template_kwargs(self): + dataset = load_dataset("trl-internal-testing/zen", "conversational_language_modeling", split="train") + + training_args = SFTConfig(output_dir=self.tmp_dir, report_to="none") + + tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5") + # The following template is a simplified version of the Qwen chat template, where an additional argument + # `role_capital` is used to control the capitalization of roles. + tokenizer.chat_template = '{%- if messages[0]["role"] == "system" -%} {{ "<|im_start|>" + ("SYSTEM" if role_capital else "system") + "\\n" + messages[0]["content"] + "<|im_end|>\\n" }}{%- else -%} {{ "<|im_start|>" + ("SYSTEM" if role_capital else "system") + "\\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\\n" }}{%- endif -%}{%- for message in messages -%} {%- if (message.role == "user") or (message.role == "system" and not loop.first) or (message.role == "assistant" and not message.tool_calls) -%} {{ "<|im_start|>" + (message.role.upper() if role_capital else message.role) + "\\n" + message.content + "<|im_end|>\\n" }} {%- elif message.role == "assistant" -%} {{ "<|im_start|>" + ("ASSISTANT" if role_capital else "assistant") }} {%- if message.content -%} {{ "\\n" + message.content }} {%- endif -%} {{ "<|im_end|>\\n" }} {%- elif message.role == "tool" -%} {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != "tool") -%} {{ "<|im_start|>" + ("USER" if role_capital else "user") }} {%- endif -%} {{ "\\n\\n" + message.content + "\\n" }} {%- if loop.last or (messages[loop.index0 + 1].role != "tool") -%} {{ "<|im_end|>\\n" }} {%- endif -%} {%- endif -%}{%- endfor -%}{%- if add_generation_prompt -%} {{ "<|im_start|>" + ("ASSISTANT" if role_capital else "assistant") + "\\n" }}{%- endif -%}' + + dataset = dataset.add_column( + "chat_template_kwargs", [{"role_capital": bool(i % 2)} for i in range(len(dataset))] + ) + assert "chat_template_kwargs" in dataset.features + + trainer = SFTTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset, + processing_class=tokenizer, + ) + + assert trainer.processing_class.chat_template == tokenizer.chat_template + + for i in range(2): + role = "SYSTEM" if i else "system" + system_prompt = ( + f"<|im_start|>{role}\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>" + ) + system_prompt_ids = trainer.processing_class(system_prompt)["input_ids"] + assert trainer.train_dataset[i]["input_ids"][: len(system_prompt_ids)] == system_prompt_ids + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_assistant_only(self): + dataset = load_dataset("trl-internal-testing/zen", "conversational_language_modeling", split="train") + + training_args = SFTConfig(output_dir=self.tmp_dir, assistant_only_loss=True, report_to="none") + trainer = SFTTrainer( + model="trl-internal-testing/tiny-Qwen3ForCausalLM", args=training_args, train_dataset=dataset + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_completion_only(self): + dataset = load_dataset("trl-internal-testing/zen", "conversational_prompt_completion", split="train") + + training_args = SFTConfig(output_dir=self.tmp_dir, completion_only_loss=True, report_to="none") + trainer = SFTTrainer( + model="trl-internal-testing/tiny-Qwen3ForCausalLM", args=training_args, train_dataset=dataset + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_completion_only_harmony(self): + dataset = load_dataset("trl-internal-testing/harmony", "prompt_completion", split="train") + + training_args = SFTConfig(output_dir=self.tmp_dir, completion_only_loss=True, report_to="none") + trainer = SFTTrainer( + model="trl-internal-testing/tiny-GptOssForCausalLM", args=training_args, train_dataset=dataset + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_assistant_only_and_completion_only(self): + dataset = load_dataset("trl-internal-testing/zen", "conversational_prompt_completion", split="train") + + # To test this case, we need to add user messages in the completion (they'll be masked in the loss) + def add_to_completion(example): + example["completion"].append(example["prompt"][0]) + example["completion"].append(example["completion"][0]) + return example + + dataset = dataset.map(add_to_completion) + + training_args = SFTConfig( + output_dir=self.tmp_dir, assistant_only_loss=True, completion_only_loss=True, report_to="none" + ) + trainer = SFTTrainer( + model="trl-internal-testing/tiny-Qwen3ForCausalLM", args=training_args, train_dataset=dataset + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_assistant_only_iterable_dataset(self): + dataset = load_dataset( + "trl-internal-testing/zen", "conversational_language_modeling", split="train", streaming=True + ) + + training_args = SFTConfig(output_dir=self.tmp_dir, assistant_only_loss=True, max_steps=3, report_to="none") + trainer = SFTTrainer( + model="trl-internal-testing/tiny-Qwen3ForCausalLM", args=training_args, train_dataset=dataset + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_set_chat_template_from_model(self): + dataset = load_dataset("trl-internal-testing/zen", "conversational_language_modeling", split="train") + + training_args = SFTConfig(output_dir=self.tmp_dir, chat_template_path="Qwen/Qwen3-4B", report_to="none") + # trl-internal-testing/tiny-GPTNeoXForCausalLM doesn't have a chat template set by default + trainer = SFTTrainer( + model="trl-internal-testing/tiny-GPTNeoXForCausalLM", args=training_args, train_dataset=dataset + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_set_chat_template_from_path(self, lazy_shared_datadir): + dataset = load_dataset("trl-internal-testing/zen", "conversational_language_modeling", split="train") + + training_args = SFTConfig( + output_dir=self.tmp_dir, + chat_template_path=str(lazy_shared_datadir / "template.jinja"), + report_to="none", + ) + # trl-internal-testing/tiny-GPTNeoXForCausalLM doesn't have a chat template set by default + trainer = SFTTrainer( + model="trl-internal-testing/tiny-GPTNeoXForCausalLM", args=training_args, train_dataset=dataset + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + # Check that the template saved in the output directory is the same as the one used for training + template_path = pathlib.Path(self.tmp_dir) / "checkpoint-9" / "chat_template.jinja" + assert template_path.exists(), f"Chat template not found at {template_path}" + + with open(template_path) as f: + template_content = f.read() + with open(training_args.chat_template_path) as f: + original_template_content = f.read() + assert template_content == original_template_content, "Chat template content does not match the original" + + def test_train_toolcall_data(self): + dataset = load_dataset("trl-internal-testing/toolcall", "language_modeling", split="train") + + training_args = SFTConfig( + output_dir=self.tmp_dir, + per_device_train_batch_size=2, # toolcall sequences are longer than standard data, reduce batch size to avoid OOM + max_length=512, # toolcall sequences are longer than standard data, limit length to avoid OOM + report_to="none", + ) + trainer = SFTTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_toolcall_data_as_json(self): + # Tabular backends (Arrow/Parquet) can insert `None` for missing keys in nested structures. + # If `tools` is stored as a list of dicts and examples use different dict schemas, nulls may + # be introduced and break tool processing. This test ensures we also support `tools` provided + # as a list of dicts. + dataset = load_dataset("trl-internal-testing/toolcall", "language_modeling", split="train") + + def convert_to_json(example): + return {"tools": json.loads(example["tools"])} + + dataset = dataset.map(convert_to_json) + + training_args = SFTConfig( + output_dir=self.tmp_dir, + per_device_train_batch_size=2, # toolcall sequences are longer than standard data, reduce batch size to avoid OOM + max_length=512, # toolcall sequences are longer than standard data, limit length to avoid OOM + report_to="none", + ) + trainer = SFTTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_train_with_eval(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling") + + training_args = SFTConfig(output_dir=self.tmp_dir, eval_strategy="steps", eval_steps=3, report_to="none") + trainer = SFTTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset["train"], + eval_dataset=dataset["test"], + ) + + trainer.train() + + assert trainer.state.log_history[0]["eval_loss"] is not None + + def test_train_with_metric_for_best_model(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling") + + training_args = SFTConfig( + output_dir=self.tmp_dir, + eval_strategy="steps", + eval_steps=3, + # It's important to use a key that SFTTrainer adds itself (not one from the base Trainer), since the bug is + # that trainer-specific metrics don't reach the dict returned by `evaluate()`. + metric_for_best_model="eval_mean_token_accuracy", + report_to="none", + ) + trainer = SFTTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset["train"], + eval_dataset=dataset["test"], + ) + + trainer.train() + + def test_train_with_multiple_eval_dataset(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling") + + training_args = SFTConfig(output_dir=self.tmp_dir, eval_strategy="steps", eval_steps=3, report_to="none") + trainer = SFTTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset["train"], + eval_dataset={"data1": dataset["test"], "data2": dataset["test"]}, + ) + trainer.train() + + assert trainer.state.log_history[-3]["eval_data1_loss"] is not None + assert trainer.state.log_history[-2]["eval_data2_loss"] is not None + + def test_train_with_compute_metrics(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling") + + def dummy_compute_metrics(eval_pred): + return {"my_metric": 0.123} + + training_args = SFTConfig( + output_dir=self.tmp_dir, + eval_strategy="steps", + eval_steps=3, + report_to="none", + ) + trainer = SFTTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset["train"], + eval_dataset=dataset["test"], + compute_metrics=dummy_compute_metrics, + ) + + trainer.train() + + assert trainer.state.log_history[-2]["eval_my_metric"] == 0.123 + + # In practice, this test is the same as `test_train`, since gradient checkpointing is enabled by default in + # `SFTTrainer`. We keep it as a regression guard: if the default ever changes, we still explicitly test gradient + # checkpointing, which has caused issues in the past. + def test_train_with_gradient_checkpointing(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train") + + training_args = SFTConfig(output_dir=self.tmp_dir, gradient_checkpointing=True, report_to="none") + trainer = SFTTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + @pytest.mark.parametrize("use_reentrant", [True, False]) + def test_train_with_gradient_checkpointing_reentrant(self, use_reentrant): + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train") + + training_args = SFTConfig( + output_dir=self.tmp_dir, + gradient_checkpointing=True, + gradient_checkpointing_kwargs={"use_reentrant": use_reentrant}, + report_to="none", + ) + trainer = SFTTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + def test_tag_added(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train") + + trainer = SFTTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + train_dataset=dataset, + ) + + for tag in ["sft", "trl"]: + assert tag in trainer.model.model_tags + + @require_peft + def test_tag_added_peft(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train") + + trainer = SFTTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + train_dataset=dataset, + peft_config=LoraConfig(), + ) + + for tag in ["sft", "trl"]: + assert tag in trainer.model.model_tags + + @pytest.mark.parametrize( + "model_id", + [ + "trl-internal-testing/tiny-Gemma3ForConditionalGeneration", + pytest.param( + "trl-internal-testing/tiny-Gemma4ForConditionalGeneration", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.5.0"), + reason="Gemma4 models were introduced in transformers-5.5.0", + ), + ), + # "trl-internal-testing/tiny-Idefics2ForConditionalGeneration", high memory peak, skipped for now + # "trl-internal-testing/tiny-Idefics3ForConditionalGeneration", high memory peak, skipped for now + "trl-internal-testing/tiny-LlavaForConditionalGeneration", + "trl-internal-testing/tiny-LlavaNextForConditionalGeneration", + "trl-internal-testing/tiny-Qwen2VLForConditionalGeneration", + "trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration", + # "trl-internal-testing/tiny-SmolVLMForConditionalGeneration", seems not to support bf16 properly + pytest.param( + "trl-internal-testing/tiny-Qwen3VLForConditionalGeneration", + marks=[ + pytest.mark.skipif( + Version(transformers.__version__) < Version("4.57.0"), + reason="Qwen3-VL series were introduced in transformers-4.57.0", + ), + ], + ), + pytest.param( + "trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-NoThink", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.2.0"), + reason="Qwen3.5 models were introduced in transformers-5.2.0", + ), + ), + pytest.param( + "trl-internal-testing/tiny-Qwen3_5MoeForConditionalGeneration-3.6", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.2.0"), + reason="Qwen3.5 models were introduced in transformers-5.2.0", + ), + ), + ], + ) + @require_vision + def test_train_vlm(self, model_id): + dataset = load_dataset("trl-internal-testing/zen-image", "conversational_language_modeling", split="train") + + training_args = SFTConfig( + output_dir=self.tmp_dir, + per_device_train_batch_size=1, # VLM training is memory intensive, reduce batch size to avoid OOM + max_length=None, # for VLMs, truncating can remove image tokens, leading to errors + report_to="none", + ) + trainer = SFTTrainer(model=model_id, args=training_args, train_dataset=dataset) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + # LLaVA & LLaVA-Next: vision_feature_layer=-2 leaves the last encoder layer (layers.1) and + # post_layernorm (pooler-only path) without gradient by design. Assert they stay frozen — if they + # ever start training, the feature-selection plumbing has likely regressed. + if model_id in ( + "trl-internal-testing/tiny-LlavaForConditionalGeneration", + "trl-internal-testing/tiny-LlavaNextForConditionalGeneration", + ) and ("encoder.layers.1" in n or "post_layernorm" in n): + assert torch.equal(param, new_param), f"Param {n} expected frozen by LLaVA design, but changed" + else: + assert not torch.equal(param, new_param), f"Param {n} is not updated" + + @pytest.mark.parametrize( + "model_id", + [ + "trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration", + ], + ) + @pytest.mark.xfail( + parse_version(transformers.__version__) < parse_version("4.57.0"), + reason="Mixing text-only and image+text examples is only supported in transformers >= 4.57.0", + strict=False, + ) + @require_vision + def test_train_vlm_multi_image(self, model_id): + dataset = load_dataset( + "trl-internal-testing/zen-multi-image", "conversational_prompt_completion", split="train" + ) + + training_args = SFTConfig( + output_dir=self.tmp_dir, + per_device_train_batch_size=1, # VLM training is memory intensive, reduce batch size to avoid OOM + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + max_length=None, # for VLMs, truncating can remove image tokens, leading to errors + report_to="none", + ) + trainer = SFTTrainer( + model=model_id, + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Param {n} is not updated" + + @pytest.mark.parametrize( + "model_id", + [ + "trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration", + # Special case for Gemma, as it uses token_type_ids, and we need to ensure they are properly in the collator: + "trl-internal-testing/tiny-Gemma3ForConditionalGeneration", + pytest.param( + "trl-internal-testing/tiny-Gemma4ForConditionalGeneration", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.5.0"), + reason="Gemma4 models were introduced in transformers-5.5.0", + ), + ), + ], + ) + @require_vision + def test_train_vlm_prompt_completion(self, model_id): + dataset = load_dataset("trl-internal-testing/zen-image", "conversational_prompt_completion", split="train") + + training_args = SFTConfig( + output_dir=self.tmp_dir, + per_device_train_batch_size=1, # VLM training is memory intensive, reduce batch size to avoid OOM + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + max_length=None, # for VLMs, truncating can remove image tokens, leading to errors + report_to="none", + ) + trainer = SFTTrainer( + model=model_id, + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Param {n} is not updated" + + # Gemma 3n uses a timm encoder, making it difficult to create a smaller variant for testing. + # To ensure coverage, we run tests on the full model but mark them as slow to exclude from default runs. + @pytest.mark.slow + @require_vision + @pytest.mark.skip(reason="Model google/gemma-3n-E2B-it is gated and requires HF token") + def test_train_vlm_gemma_3n(self): + dataset = load_dataset("trl-internal-testing/zen-image", "conversational_language_modeling", split="train") + + training_args = SFTConfig( + output_dir=self.tmp_dir, + learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates + max_length=None, # for VLMs, truncating can remove image tokens, leading to errors + per_device_train_batch_size=1, # VLM training is memory intensive, reduce batch size to avoid OOM + model_init_kwargs={"dtype": "bfloat16"}, + report_to="none", + ) + trainer = SFTTrainer(model="google/gemma-3n-E2B-it", args=training_args, train_dataset=dataset) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + if "model.audio_tower" in n or "model.embed_audio" in n: + # The audio embedding parameters are not updated because this dataset contains no audio data + continue + assert not torch.equal(param, new_param), f"Param {n} is not updated" + + @pytest.mark.parametrize( + "model_id", + [ + "trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration", + ], + ) + @pytest.mark.parametrize( + "dataset_config", + [ + "conversational_language_modeling", + "conversational_prompt_completion", + "standard_language_modeling", # Regression test for #5334 + "standard_prompt_completion", + ], + ) + @require_vision + def test_train_vlm_text_only_data(self, model_id, dataset_config): + dataset = load_dataset("trl-internal-testing/zen", dataset_config, split="train") + + training_args = SFTConfig(output_dir=self.tmp_dir, report_to="none") + trainer = SFTTrainer( + model=model_id, + args=training_args, + train_dataset=dataset, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + if n.startswith("model.visual"): + torch.testing.assert_close(param, new_param, rtol=1e-12, atol=1e-12, msg=f"Param {n} is updated") + else: + assert not torch.equal(param, new_param), f"Param {n} is not updated" + + @require_vision + def test_vision_dataset_with_text_model_raises(self): + dataset = load_dataset("trl-internal-testing/zen-image", "conversational_language_modeling", split="train") + training_args = SFTConfig(output_dir=self.tmp_dir, report_to="none") + with pytest.raises(ValueError, match="vision-related.*vision-language model"): + SFTTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset, + ) + + @require_peft + def test_prompt_tuning(self): + """Test that SFT works with Prompt Tuning.""" + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train") + + training_args = SFTConfig(output_dir=self.tmp_dir, report_to="none") + trainer = SFTTrainer( + model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + args=training_args, + train_dataset=dataset, + peft_config=PromptEncoderConfig(task_type=TaskType.CAUSAL_LM, num_virtual_tokens=8), + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + assert trainer.state.log_history[-1]["mean_token_accuracy"] is not None + + # Check that the peft params have changed and the base model params have not changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + if "base_model" in n: # We expect the base model params to be the same + torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.") + elif "prompt_encoder" in n: # We expect the peft params to be different + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + else: + raise ValueError(f"Unexpected parameter {n} in model: {trainer.model}") + + @require_peft + @require_bitsandbytes + def test_peft_with_quantization(self): + model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" + + quantization_config = BitsAndBytesConfig( + load_in_4bit=True, + bnb_4bit_use_double_quant=True, + bnb_4bit_quant_type="nf4", + bnb_4bit_compute_dtype=torch.float16, + ) + model = AutoModelForCausalLM.from_pretrained( + model_id, + dtype="float32", + quantization_config=quantization_config, + ) + + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train") + + # Initialize the trainer with the already configured PeftModel + training_args = SFTConfig(output_dir=self.tmp_dir, learning_rate=0.1, report_to="none") + trainer = SFTTrainer(model=model, args=training_args, train_dataset=dataset, peft_config=LoraConfig()) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + assert trainer.state.log_history[-1]["mean_token_accuracy"] is not None + + # Check that the peft params have changed and the base model params have not changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + # In bitsandbytes, bias parameters are automatically cast to the input dtype during the forward pass if + # their dtype doesn’t match. This causes the module to change unexpectedly during the first forward pass of + # the training. To handle this, we cast these specific bias parameters to float32 before comparison. + # https://github.com/bitsandbytes-foundation/bitsandbytes/blob/45553f7392e524eacf400b132cfe01261f6477be/bitsandbytes/nn/modules.py#L518 + # We still need to investigate why the compute dtype ends up being different than for these parameters. + if n in [ + "base_model.model.model.layers.1.self_attn.k_proj.bias", + "base_model.model.model.layers.1.self_attn.q_proj.base_layer.bias", + "base_model.model.model.layers.1.self_attn.v_proj.base_layer.bias", + ]: + param = param.float() + + if "lora" not in n: # We expect the base model params to be the same + torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.") + elif "lora" in n: # We expect the peft params to be different + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + else: + raise ValueError(f"Unexpected parameter {n} in model: {trainer.model}") + + @require_peft + def test_prompt_tuning_peft_model(self): + """Test that SFT works with Prompt Tuning and a pre-converted PeftModel""" + model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", dtype="float32") + model = get_peft_model(model, PromptEncoderConfig(task_type=TaskType.CAUSAL_LM, num_virtual_tokens=8)) + + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train") + + training_args = SFTConfig(output_dir=self.tmp_dir, report_to="none") + trainer = SFTTrainer(model=model, args=training_args, train_dataset=dataset) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + assert trainer.state.log_history[-1]["mean_token_accuracy"] is not None + + # Check that the peft params have changed and the base model params have not changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + if "base_model" in n: # We expect the base model params to be the same + torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.") + elif "prompt_encoder" in n: # We expect the peft params to be different + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + else: + raise ValueError(f"Unexpected parameter {n} in model: {trainer.model}") + + +@pytest.mark.slow +@require_torch_accelerator +@require_peft +class TestSFTTrainerSlow(TrlTestCase): + def setup_method(self): + self.train_dataset = load_dataset("stanfordnlp/imdb", split="train[:10%]") + self.eval_dataset = load_dataset("stanfordnlp/imdb", split="test[:10%]") + self.max_length = 128 + self.peft_config = LoraConfig( + lora_alpha=16, + lora_dropout=0.1, + r=8, + bias="none", + task_type="CAUSAL_LM", + ) + + def teardown_method(self): + gc.collect() + backend_empty_cache(torch_device) + gc.collect() + + @pytest.mark.parametrize("packing", [True, False]) + @pytest.mark.parametrize( + "model_name", + [ + "trl-internal-testing/tiny-LlamaForCausalLM-3.2", + "trl-internal-testing/tiny-MistralForCausalLM-0.2", + ], + ) + def test_sft_trainer_transformers_mp(self, model_name, packing): + """ + Simply tests if passing a transformers model to `SFTTrainer` loads and runs the trainer as expected in mixed + precision. + """ + training_args = SFTConfig( + output_dir=self.tmp_dir, + logging_strategy="no", + report_to="none", + per_device_train_batch_size=2, + max_steps=10, + fp16=True, # this is sufficient to enable amp + packing=packing, + max_length=self.max_length, + ) + + model = AutoModelForCausalLM.from_pretrained(model_name, dtype="float32") + tokenizer = AutoTokenizer.from_pretrained(model_name) + + trainer = SFTTrainer( + model, + args=training_args, + processing_class=tokenizer, + train_dataset=self.train_dataset, + eval_dataset=self.eval_dataset, + ) + + trainer.train() + + release_memory(model, trainer) + + @pytest.mark.parametrize("device_map", [{"": 0}, "auto"]) + @pytest.mark.parametrize( + "gradient_checkpointing_kwargs", [None, {"use_reentrant": False}, {"use_reentrant": True}] + ) + @pytest.mark.parametrize("packing", [True, False]) + @pytest.mark.parametrize( + "model_name", + [ + "trl-internal-testing/tiny-LlamaForCausalLM-3.2", + "trl-internal-testing/tiny-MistralForCausalLM-0.2", + ], + ) + @require_torch_multi_accelerator + def test_sft_trainer_transformers_mp_gc_device_map( + self, model_name, packing, gradient_checkpointing_kwargs, device_map + ): + """ + Simply tests if passing a transformers model to `SFTTrainer` loads and runs the trainer as expected in mixed + precision + different scenarios of gradient_checkpointing (single, multi-gpu, etc). + """ + training_args = SFTConfig( + output_dir=self.tmp_dir, + logging_strategy="no", + report_to="none", + per_device_train_batch_size=2, + max_steps=10, + packing=packing, + max_length=self.max_length, + fp16=True, # this is sufficient to enable amp + gradient_checkpointing=True, # default, here for clarity + gradient_checkpointing_kwargs=gradient_checkpointing_kwargs, + ) + + model = AutoModelForCausalLM.from_pretrained(model_name, dtype="float32", device_map=device_map) + tokenizer = AutoTokenizer.from_pretrained(model_name) + + trainer = SFTTrainer( + model, + args=training_args, + processing_class=tokenizer, + train_dataset=self.train_dataset, + eval_dataset=self.eval_dataset, + ) + + trainer.train() + + release_memory(model, trainer) + + @pytest.mark.parametrize( + "gradient_checkpointing_kwargs", [None, {"use_reentrant": False}, {"use_reentrant": True}] + ) + @pytest.mark.parametrize("packing", [True, False]) + @pytest.mark.parametrize( + "model_name", + [ + "trl-internal-testing/tiny-LlamaForCausalLM-3.2", + "trl-internal-testing/tiny-MistralForCausalLM-0.2", + ], + ) + @require_peft + @require_bitsandbytes + def test_sft_trainer_transformers_mp_gc_peft_qlora(self, model_name, packing, gradient_checkpointing_kwargs): + """ + Simply tests if passing a transformers model + PEFT + bnb to `SFTTrainer` loads and runs the trainer as + expected in mixed precision + different scenarios of gradient_checkpointing. + """ + training_args = SFTConfig( + output_dir=self.tmp_dir, + logging_strategy="no", + report_to="none", + per_device_train_batch_size=2, + max_steps=10, + packing=packing, + max_length=self.max_length, + gradient_checkpointing=True, # default, here for clarity + gradient_checkpointing_kwargs=gradient_checkpointing_kwargs, + ) + + quantization_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.float16) + + model = AutoModelForCausalLM.from_pretrained( + model_name, dtype="float32", quantization_config=quantization_config + ) + tokenizer = AutoTokenizer.from_pretrained(model_name) + + trainer = SFTTrainer( + model, + args=training_args, + processing_class=tokenizer, + train_dataset=self.train_dataset, + eval_dataset=self.eval_dataset, + peft_config=self.peft_config, + ) + + assert isinstance(trainer.model, PeftModel) + + trainer.train() + + release_memory(model, trainer) + + @pytest.mark.parametrize("packing", [True, False]) + @pytest.mark.parametrize( + "model_name", + [ + "trl-internal-testing/tiny-LlamaForCausalLM-3.2", + "trl-internal-testing/tiny-MistralForCausalLM-0.2", + ], + ) + @require_peft + @require_bitsandbytes + def test_sft_trainer_with_chat_format_qlora(self, model_name, packing): + """ + Simply tests if using setup_chat_format with a transformers model + peft + bnb config to `SFTTrainer` loads and + runs the trainer as expected. + """ + train_dataset = load_dataset("trl-internal-testing/dolly-chatml-sft", split="train") + + training_args = SFTConfig( + packing=packing, + max_length=self.max_length, + output_dir=self.tmp_dir, + logging_strategy="no", + report_to="none", + per_device_train_batch_size=2, + max_steps=10, + ) + + quantization_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.float16) + + model = AutoModelForCausalLM.from_pretrained( + model_name, dtype="float32", quantization_config=quantization_config + ) + tokenizer = AutoTokenizer.from_pretrained(model_name) + + trainer = SFTTrainer( + model, + args=training_args, + processing_class=tokenizer, + train_dataset=train_dataset, + peft_config=self.peft_config, + ) + + assert isinstance(trainer.model, PeftModel) + + trainer.train() + + release_memory(model, trainer) + + @pytest.mark.parametrize("packing", [True, False]) + @pytest.mark.parametrize( + "model_name", + [ + "trl-internal-testing/tiny-LlamaForCausalLM-3.2", + "trl-internal-testing/tiny-MistralForCausalLM-0.2", + ], + ) + @require_liger_kernel + def test_sft_trainer_with_liger(self, model_name, packing): + """ + Tests if passing use_liger=True to SFTConfig loads and runs the trainer with AutoLigerKernelForCausalLM as + expected. + """ + import importlib + + def cleanup_liger_patches(trainer): + """Clean up liger_kernel patches by reloading the model's specific module""" + try: + # Get the specific module that was used by the trainer's model + module_path = trainer.model.__module__ + reload_module = importlib.import_module(module_path) + importlib.reload(reload_module) + except Exception: + pass # Continue if reload fails + + training_args = SFTConfig( + output_dir=self.tmp_dir, + logging_strategy="no", + report_to="none", + per_device_train_batch_size=2, + max_steps=2, + packing=packing, + max_length=self.max_length, + use_liger_kernel=True, + ) + + trainer = SFTTrainer( + model_name, + args=training_args, + train_dataset=self.train_dataset, + eval_dataset=self.eval_dataset, + ) + + # Ensure cleanup of liger patches after the test + try: + trainer.train() + release_memory(trainer.model, trainer) + finally: + cleanup_liger_patches(trainer) + + @pytest.mark.parametrize("packing", [True, False]) + @pytest.mark.parametrize( + "model_name", + [ + "trl-internal-testing/tiny-LlamaForCausalLM-3.2", + "trl-internal-testing/tiny-MistralForCausalLM-0.2", + ], + ) + @require_torch_accelerator + def test_train_offloading(self, model_name, packing): + """Test that activation offloading works with SFTTrainer.""" + training_args = SFTConfig( + output_dir=self.tmp_dir, + activation_offloading=True, + report_to="none", + per_device_train_batch_size=2, + max_steps=2, + packing=packing, + max_length=self.max_length, + ) + trainer = SFTTrainer( + model=model_name, args=training_args, train_dataset=self.train_dataset, eval_dataset=self.eval_dataset + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + assert trainer.state.log_history[-1]["train_loss"] is not None + + # Check that the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + assert not torch.equal(param, new_param), f"Parameter {n} has not changed." + + release_memory(trainer.model, trainer) + + +_CHUNKED_CE_MODEL_IDS = [ + "trl-internal-testing/tiny-CohereForCausalLM", + pytest.param( + "trl-internal-testing/tiny-DeepseekV3ForCausalLM", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.0.0"), + reason="DeepseekV3 SDPA attention is broken in transformers < 5.0.0", + ), + ), + pytest.param( + "trl-internal-testing/tiny-DeepseekV3ForCausalLM-0528", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.0.0"), + reason="DeepseekV3 SDPA attention is broken in transformers < 5.0.0", + ), + ), + "trl-internal-testing/tiny-Gemma2ForCausalLM", + "trl-internal-testing/tiny-GemmaForCausalLM", + "trl-internal-testing/tiny-Glm4MoeForCausalLM", + "trl-internal-testing/tiny-GptOssForCausalLM", + "trl-internal-testing/tiny-LlamaForCausalLM-3.1", + "trl-internal-testing/tiny-LlamaForCausalLM-3.2", + "trl-internal-testing/tiny-LlamaForCausalLM-3", + "trl-internal-testing/tiny-MistralForCausalLM-0.1", + "trl-internal-testing/tiny-MistralForCausalLM-0.2", + pytest.param( + "trl-internal-testing/tiny-NemotronHForCausalLM-nano", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.3.0"), + reason="Nemotron 3 was introduced in transformers>=5.3.0", + ), + ), + "trl-internal-testing/tiny-Phi3ForCausalLM", + "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + "trl-internal-testing/tiny-Qwen3ForCausalLM", + "trl-internal-testing/tiny-Qwen3MoeForCausalLM", +] + + +_CHUNKED_CE_VLM_MODEL_IDS = [ + "trl-internal-testing/tiny-Gemma3ForConditionalGeneration", + pytest.param( + "trl-internal-testing/tiny-Gemma4ForConditionalGeneration", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.5.0"), + reason="Gemma4 models were introduced in transformers-5.5.0", + ), + ), + "trl-internal-testing/tiny-LlavaForConditionalGeneration", + "trl-internal-testing/tiny-LlavaNextForConditionalGeneration", + "trl-internal-testing/tiny-Qwen2VLForConditionalGeneration", + "trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration", + pytest.param( + "trl-internal-testing/tiny-Qwen3VLForConditionalGeneration", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("4.57.0"), + reason="Qwen3-VL series were introduced in transformers-4.57.0", + ), + ), + pytest.param( + "trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-NoThink", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.2.0"), + reason="Qwen3.5 models were introduced in transformers-5.2.0", + ), + ), + pytest.param( + "trl-internal-testing/tiny-Qwen3_5MoeForConditionalGeneration-3.6", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.2.0"), + reason="Qwen3.5 models were introduced in transformers-5.2.0", + ), + ), +] + + +class TestChunkedCrossEntropyLoss: + B, S, H, V = 2, 8, 4, 16 + CHUNK_SIZE = 3 # deliberately small to force multiple chunks and a partial final chunk + + def _inputs(self, seed=0, ignore_positions=None, requires_grad=False): + torch.manual_seed(seed) + hidden = torch.randn(self.B, self.S, self.H, dtype=torch.float32, requires_grad=requires_grad) + weight = torch.randn(self.V, self.H, dtype=torch.float32, requires_grad=requires_grad) + labels = torch.randint(0, self.V, (self.B, self.S)) + if ignore_positions is not None: + labels[:, ignore_positions] = -100 + return hidden, weight, labels + + @staticmethod + def _reference(hidden, weight, labels, num_items_in_batch=None): + shift_h = hidden[..., :-1, :].reshape(-1, hidden.size(-1)) + shift_l = labels[..., 1:].reshape(-1) + logits = shift_h.float() @ weight.float().t() + if num_items_in_batch is None: + loss = F.cross_entropy(logits, shift_l, ignore_index=-100, reduction="mean") + else: + loss = F.cross_entropy(logits, shift_l, ignore_index=-100, reduction="sum") + loss = loss / num_items_in_batch + valid = shift_l != -100 + if valid.any(): + log_p = F.log_softmax(logits, dim=-1) + preds = logits.argmax(dim=-1) + accuracy = (preds[valid] == shift_l[valid]).float().mean() + entropy = -(log_p.exp() * log_p).sum(dim=-1)[valid].mean() + else: + accuracy = torch.zeros((), dtype=torch.float32) + entropy = torch.zeros((), dtype=torch.float32) + return loss, accuracy, entropy + + def test_forward_matches_cross_entropy(self): + """With no ignored tokens, chunked loss equals standard mean cross-entropy.""" + hidden, weight, labels = self._inputs() + expected_n_valid = (labels[..., 1:] != -100).sum() + loss_c, correct_c, ent_sum_c, n_valid_c = _chunked_cross_entropy_loss(hidden, weight, self.CHUNK_SIZE, labels) + loss_r, acc_r, ent_r = self._reference(hidden, weight, labels) + torch.testing.assert_close(loss_c, loss_r, atol=1e-5, rtol=1e-5) + torch.testing.assert_close(correct_c / n_valid_c, acc_r, atol=1e-5, rtol=1e-5) + torch.testing.assert_close(ent_sum_c / n_valid_c, ent_r, atol=1e-5, rtol=1e-5) + assert n_valid_c.item() == expected_n_valid.item() + + def test_forward_ignore_index(self): + """Ignored labels are excluded from loss, accuracy and entropy (matches F.cross_entropy).""" + hidden, weight, labels = self._inputs(ignore_positions=slice(0, 3)) + expected_n_valid = (labels[..., 1:] != -100).sum() + loss_c, correct_c, ent_sum_c, n_valid_c = _chunked_cross_entropy_loss(hidden, weight, self.CHUNK_SIZE, labels) + loss_r, acc_r, ent_r = self._reference(hidden, weight, labels) + torch.testing.assert_close(loss_c, loss_r, atol=1e-5, rtol=1e-5) + torch.testing.assert_close(correct_c / n_valid_c, acc_r, atol=1e-5, rtol=1e-5) + torch.testing.assert_close(ent_sum_c / n_valid_c, ent_r, atol=1e-5, rtol=1e-5) + assert n_valid_c.item() == expected_n_valid.item() + + def test_num_items_in_batch_reduction(self): + """When num_items_in_batch is provided, loss is sum / num_items_in_batch.""" + hidden, weight, labels = self._inputs(ignore_positions=slice(0, 3)) + num_items = 5 # arbitrary global denominator, != local valid count + loss_c, *_ = _chunked_cross_entropy_loss(hidden, weight, self.CHUNK_SIZE, labels, num_items_in_batch=num_items) + loss_r, *_ = self._reference(hidden, weight, labels, num_items_in_batch=num_items) + torch.testing.assert_close(loss_c, loss_r, atol=1e-5, rtol=1e-5) + + def test_num_items_in_batch_tensor(self): + """A tensor `num_items_in_batch` is accepted and produces the same result as the int form.""" + hidden, weight, labels = self._inputs() + num_items_tensor = torch.tensor(7, dtype=torch.float32) + loss_t, *_ = _chunked_cross_entropy_loss( + hidden, weight, self.CHUNK_SIZE, labels, num_items_in_batch=num_items_tensor + ) + loss_i, *_ = _chunked_cross_entropy_loss(hidden, weight, self.CHUNK_SIZE, labels, num_items_in_batch=7) + torch.testing.assert_close(loss_t, loss_i, atol=1e-6, rtol=1e-6) + + def test_backward_matches_reference(self): + """Gradients on hidden_states and lm_head weight match the standard CE path.""" + hidden_c, weight_c, labels = self._inputs(ignore_positions=slice(0, 3), requires_grad=True) + hidden_r = hidden_c.detach().clone().requires_grad_(True) + weight_r = weight_c.detach().clone().requires_grad_(True) + + loss_c, *_ = _chunked_cross_entropy_loss(hidden_c, weight_c, self.CHUNK_SIZE, labels) + loss_c.backward() + + loss_r, *_ = self._reference(hidden_r, weight_r, labels) + loss_r.backward() + + torch.testing.assert_close(hidden_c.grad, hidden_r.grad, atol=1e-5, rtol=1e-5) + torch.testing.assert_close(weight_c.grad, weight_r.grad, atol=1e-5, rtol=1e-5) + + def test_all_ignored_returns_zero(self): + """If every label is ignored, loss/correct/entropy_sum are all zero and backward still works. + + Every trainable parameter of the chunked path (hidden_states, lm_head_weight, and lm_head_bias when present) + must receive a gradient — otherwise DDP / FSDP synchronization hangs or errors at the all-reduce step. + """ + hidden, weight, labels = self._inputs(requires_grad=True) + bias = torch.zeros(self.V, dtype=torch.float32, requires_grad=True) + labels[:] = -100 + loss, correct, ent_sum, n_valid = _chunked_cross_entropy_loss( + hidden, weight, self.CHUNK_SIZE, labels, lm_head_bias=bias + ) + assert loss.item() == 0.0 + assert correct.item() == 0.0 + assert ent_sum.item() == 0.0 + assert n_valid.item() == 0 + assert not torch.isnan(loss) + # Backward must succeed even when n_valid == 0 (can happen with completion-only loss + # + truncation where a whole micro-batch is masked). + loss.backward() + assert hidden.grad is not None and hidden.grad.abs().sum().item() == 0.0 + assert weight.grad is not None and weight.grad.abs().sum().item() == 0.0 + assert bias.grad is not None and bias.grad.abs().sum().item() == 0.0 + + def test_shift_labels_matches_labels(self): + """`shift_labels` path (CP/SP) must match the default `labels` path after external shifting.""" + hidden, weight, labels = self._inputs(ignore_positions=slice(0, 3)) + loss_l, correct_l, ent_l, n_valid_l = _chunked_cross_entropy_loss(hidden, weight, self.CHUNK_SIZE, labels) + # Mimic what transformers does under CP/SP: pad labels with -100, then shift. + shift_labels = F.pad(labels, (0, 1), value=-100)[..., 1:].contiguous() + loss_s, correct_s, ent_s, n_valid_s = _chunked_cross_entropy_loss( + hidden, weight, self.CHUNK_SIZE, shift_labels=shift_labels + ) + torch.testing.assert_close(loss_s, loss_l, atol=1e-6, rtol=1e-6) + torch.testing.assert_close(correct_s, correct_l, atol=1e-6, rtol=1e-6) + torch.testing.assert_close(ent_s, ent_l, atol=1e-6, rtol=1e-6) + assert n_valid_s.item() == n_valid_l.item() + + def test_requires_labels_or_shift_labels(self): + """Must provide at least one of `labels` or `shift_labels`.""" + hidden, weight, _ = self._inputs() + with pytest.raises(ValueError, match="At least one"): + _chunked_cross_entropy_loss(hidden, weight, self.CHUNK_SIZE) + + def test_shift_labels_wins_when_both_provided(self): + """When both `labels` and `shift_labels` are provided (Ulysses / CP / SP path), `shift_labels` wins.""" + hidden, weight, labels = self._inputs(ignore_positions=slice(0, 3)) + shift_labels = F.pad(labels, (0, 1), value=-100)[..., 1:].contiguous() + # Chunked result with both passed in must match the shift_labels-only path. + loss_both, *_ = _chunked_cross_entropy_loss( + hidden, weight, self.CHUNK_SIZE, labels=labels, shift_labels=shift_labels + ) + loss_shift, *_ = _chunked_cross_entropy_loss(hidden, weight, self.CHUNK_SIZE, shift_labels=shift_labels) + torch.testing.assert_close(loss_both, loss_shift, atol=1e-6, rtol=1e-6) + + def test_lm_head_bias(self): + """When `lm_head_bias` is provided, chunked loss matches `F.linear(h, w, b)` followed by CE.""" + hidden, weight, labels = self._inputs(ignore_positions=slice(0, 3)) + torch.manual_seed(1) + bias = torch.randn(self.V, dtype=torch.float32) + + loss_c, *_ = _chunked_cross_entropy_loss(hidden, weight, self.CHUNK_SIZE, labels, lm_head_bias=bias) + + # Reference: full F.linear with bias, then CE over non-ignored shifted positions. + logits_ref = F.linear(hidden[..., :-1, :], weight, bias).reshape(-1, self.V) + labels_ref = labels[..., 1:].reshape(-1) + valid = labels_ref != -100 + loss_r = F.cross_entropy(logits_ref[valid], labels_ref[valid], reduction="mean") + torch.testing.assert_close(loss_c, loss_r, atol=1e-5, rtol=1e-5) + + +@require_torch_accelerator +class TestPatchChunkedCELMHead: + """Patched `forward` must be numerically equivalent to the standard HF causal-LM loss path.""" + + CHUNK_SIZE = 5 # small, to exercise the chunk loop + + def _setup(self, model_id): + ref_model = AutoModelForCausalLM.from_pretrained(model_id, dtype=torch.float32, device_map=torch_device) + chunked_model = copy.deepcopy(ref_model) + _patch_chunked_ce_lm_head(chunked_model, chunk_size=self.CHUNK_SIZE) + + B, S = 2, 16 + input_ids = torch.randint(0, ref_model.config.vocab_size, (B, S), device=torch_device) + labels = input_ids.clone() + labels[:, :4] = -100 # prompt-like mask + num_items = int((labels[..., 1:] != -100).sum()) + return ref_model, chunked_model, input_ids, labels, num_items + + def _setup_vlm(self, model_id): + ref_model = AutoModelForImageTextToText.from_pretrained(model_id, dtype=torch.float32, device_map=torch_device) + chunked_model = copy.deepcopy(ref_model) + _patch_chunked_ce_lm_head(chunked_model, chunk_size=self.CHUNK_SIZE, is_vlm=True) + + B, S = 2, 16 + vocab_size = ref_model.config.text_config.vocab_size + input_ids = torch.randint(0, vocab_size, (B, S), device=torch_device) + labels = input_ids.clone() + labels[:, :4] = -100 + num_items = int((labels[..., 1:] != -100).sum()) + return ref_model, chunked_model, input_ids, labels, num_items + + @pytest.mark.parametrize("model_id", _CHUNKED_CE_MODEL_IDS) + def test_forward_matches_reference(self, model_id): + ref_model, chunked_model, input_ids, labels, num_items = self._setup(model_id) + + with torch.no_grad(): + ref_out = ref_model(input_ids=input_ids, labels=labels, num_items_in_batch=num_items) + out = chunked_model(input_ids=input_ids, labels=labels, num_items_in_batch=num_items) + + torch.testing.assert_close(out.loss, ref_out.loss, atol=1e-5, rtol=1e-5) + assert out.logits is None + assert out.num_correct_tokens is not None and out.num_correct_tokens.item() >= 0 + assert out.entropy_sum is not None and out.entropy_sum.item() >= 0.0 + + @pytest.mark.parametrize( + "model_id", + [ + "trl-internal-testing/tiny-Qwen3MoeForCausalLM", + "trl-internal-testing/tiny-GptOssForCausalLM", + ], + ) + def test_forward_matches_reference_with_aux_loss(self, model_id): + """MoE models with `output_router_logits=True` add `router_aux_loss_coef * load_balancing_loss` + to the main loss. The chunked path must match the reference loss and expose `aux_loss`.""" + ref_model = AutoModelForCausalLM.from_pretrained( + model_id, dtype=torch.float32, output_router_logits=True, device_map=torch_device + ) + chunked_model = copy.deepcopy(ref_model) + _patch_chunked_ce_lm_head(chunked_model, chunk_size=self.CHUNK_SIZE) + + B, S = 2, 16 + input_ids = torch.randint(0, ref_model.config.vocab_size, (B, S), device=torch_device) + labels = input_ids.clone() + labels[:, :4] = -100 + num_items = int((labels[..., 1:] != -100).sum()) + + with torch.no_grad(): + ref_out = ref_model(input_ids=input_ids, labels=labels, num_items_in_batch=num_items) + out = chunked_model(input_ids=input_ids, labels=labels, num_items_in_batch=num_items) + + torch.testing.assert_close(out.loss, ref_out.loss, atol=1e-5, rtol=1e-5) + torch.testing.assert_close(out.aux_loss, ref_out.aux_loss, atol=1e-5, rtol=1e-5) + + @pytest.mark.parametrize("model_id", _CHUNKED_CE_MODEL_IDS) + def test_backward_matches_reference(self, model_id): + ref_model, chunked_model, input_ids, labels, num_items = self._setup(model_id) + + ref_out = ref_model(input_ids=input_ids, labels=labels, num_items_in_batch=num_items) + ref_out.loss.backward() + + out = chunked_model(input_ids=input_ids, labels=labels, num_items_in_batch=num_items) + out.loss.backward() + + # lm_head gradient + torch.testing.assert_close( + chunked_model.lm_head.weight.grad, ref_model.lm_head.weight.grad, atol=1e-5, rtol=1e-5 + ) + # Base decoder gradients + for name, ref_param in ref_model.model.named_parameters(): + chunked_grad = chunked_model.model.get_parameter(name).grad + ref_grad = ref_param.grad + assert (chunked_grad is None) == (ref_grad is None), f"grad presence mismatch on model.{name}" + if ref_grad is not None: + torch.testing.assert_close( + chunked_grad, ref_grad, atol=1e-5, rtol=1e-5, msg=f"gradient mismatch on model.{name}" + ) + + @pytest.mark.parametrize("model_id", _CHUNKED_CE_VLM_MODEL_IDS) + def test_forward_matches_reference_vlm(self, model_id): + ref_model, chunked_model, input_ids, labels, num_items = self._setup_vlm(model_id) + + with torch.no_grad(): + ref_out = ref_model(input_ids=input_ids, labels=labels, num_items_in_batch=num_items) + out = chunked_model(input_ids=input_ids, labels=labels, num_items_in_batch=num_items) + + torch.testing.assert_close(out.loss, ref_out.loss, atol=1e-5, rtol=1e-5) + assert out.logits is None + assert out.num_correct_tokens is not None and out.num_correct_tokens.item() >= 0 + assert out.entropy_sum is not None and out.entropy_sum.item() >= 0.0 + + @pytest.mark.parametrize( + "model_id", + [ + pytest.param( + "trl-internal-testing/tiny-Qwen3_5MoeForConditionalGeneration-3.6", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.2.0"), + reason="Qwen3.5 models were introduced in transformers-5.2.0", + ), + ), + ], + ) + def test_forward_matches_reference_vlm_with_aux_loss(self, model_id): + ref_model = AutoModelForImageTextToText.from_pretrained(model_id, dtype=torch.float32, device_map=torch_device) + chunked_model = copy.deepcopy(ref_model) + _patch_chunked_ce_lm_head(chunked_model, chunk_size=self.CHUNK_SIZE, is_vlm=True) + + # VLM MoE wrappers only read `output_router_logits` from forward kwargs (their `text_config` explicitly + # removes the attribute), so we have to pass it at call time on both paths. + B, S = 2, 16 + input_ids = torch.randint(0, ref_model.config.text_config.vocab_size, (B, S), device=torch_device) + labels = input_ids.clone() + labels[:, :4] = -100 + num_items = int((labels[..., 1:] != -100).sum()) + + with torch.no_grad(): + ref_out = ref_model( + input_ids=input_ids, labels=labels, num_items_in_batch=num_items, output_router_logits=True + ) + out = chunked_model( + input_ids=input_ids, labels=labels, num_items_in_batch=num_items, output_router_logits=True + ) + + torch.testing.assert_close(out.loss, ref_out.loss, atol=1e-5, rtol=1e-5) + torch.testing.assert_close(out.aux_loss, ref_out.aux_loss, atol=1e-5, rtol=1e-5) + + @pytest.mark.parametrize("model_id", _CHUNKED_CE_VLM_MODEL_IDS) + def test_backward_matches_reference_vlm(self, model_id): + ref_model, chunked_model, input_ids, labels, num_items = self._setup_vlm(model_id) + + ref_out = ref_model(input_ids=input_ids, labels=labels, num_items_in_batch=num_items) + ref_out.loss.backward() + + out = chunked_model(input_ids=input_ids, labels=labels, num_items_in_batch=num_items) + out.loss.backward() + + # lm_head gradient + torch.testing.assert_close( + chunked_model.lm_head.weight.grad, ref_model.lm_head.weight.grad, atol=1e-5, rtol=1e-5 + ) + # Multimodal-wrapper gradients (covers both vision tower and inner text decoder). + for name, ref_param in ref_model.model.named_parameters(): + chunked_grad = chunked_model.model.get_parameter(name).grad + ref_grad = ref_param.grad + assert (chunked_grad is None) == (ref_grad is None), f"grad presence mismatch on model.{name}" + if ref_grad is not None: + torch.testing.assert_close( + chunked_grad, ref_grad, atol=1e-5, rtol=1e-5, msg=f"gradient mismatch on model.{name}" + ) + + def test_forward_without_labels_uses_original_path(self): + """With labels=None the patched forward returns real logits (for generation / eval).""" + _, chunked_model, input_ids, _, _ = self._setup("trl-internal-testing/tiny-LlamaForCausalLM-3.2") + with torch.no_grad(): + out = chunked_model(input_ids=input_ids) + assert out.logits is not None + assert out.logits.shape[-1] == chunked_model.config.vocab_size + + def test_forward_without_labels_matches_reference(self): + """labels=None logits must match the unpatched model, including per-model post-processing + (`final_logit_softcapping`, `logit_scale`, ...). This is what makes `.generate()` safe to call on a patched + model.""" + ref_model, chunked_model, input_ids, *_ = self._setup("trl-internal-testing/tiny-CohereForCausalLM") + with torch.no_grad(): + ref_out = ref_model(input_ids=input_ids) + out = chunked_model(input_ids=input_ids) + torch.testing.assert_close(out.logits, ref_out.logits, atol=1e-5, rtol=1e-5) + + @require_peft + @pytest.mark.filterwarnings("ignore:Model has `tie_word_embeddings=True`") + @pytest.mark.parametrize( + "peft_config_factory", + [ + pytest.param(lambda: LoraConfig(r=4, target_modules=["q_proj", "v_proj"]), id="lora"), + pytest.param( + lambda: LoraConfig(r=4, target_modules=["q_proj", "v_proj"], modules_to_save=["lm_head"]), + id="lora+modules_to_save", + ), + pytest.param( + lambda: PromptTuningConfig(task_type=TaskType.CAUSAL_LM, num_virtual_tokens=4), id="prompt_tuning" + ), + pytest.param( + lambda: PromptEncoderConfig(task_type=TaskType.CAUSAL_LM, num_virtual_tokens=4), id="prompt_encoder" + ), + pytest.param( + lambda: PrefixTuningConfig(task_type=TaskType.CAUSAL_LM, num_virtual_tokens=4), id="prefix_tuning" + ), + ], + ) + def test_forward_matches_reference_with_peft(self, peft_config_factory): + """Patching the inner causal LM (`peft_model.get_base_model()`) must produce a forward whose loss matches + the unpatched PEFT reference for both LoRA-style (adapters live in the module tree) and prompt-learning + (`PeftModel.forward` injects virtual tokens, then delegates into the patched inner forward).""" + base = AutoModelForCausalLM.from_pretrained( + "trl-internal-testing/tiny-Qwen3ForCausalLM", dtype=torch.float32, device_map=torch_device + ) + ref_model = get_peft_model(copy.deepcopy(base), peft_config_factory()) + chunked_model = copy.deepcopy(ref_model) + _patch_chunked_ce_lm_head(chunked_model.get_base_model(), chunk_size=self.CHUNK_SIZE) + + B, S = 2, 16 + input_ids = torch.randint(0, base.config.vocab_size, (B, S), device=torch_device) + labels = input_ids.clone() + labels[:, :4] = -100 + num_items = int((labels[..., 1:] != -100).sum()) + + ref_out = ref_model(input_ids=input_ids, labels=labels, num_items_in_batch=num_items) + out = chunked_model(input_ids=input_ids, labels=labels, num_items_in_batch=num_items) + torch.testing.assert_close(out.loss, ref_out.loss, atol=1e-5, rtol=1e-5) + + ref_out.loss.backward() + out.loss.backward() + chunked_params = dict(chunked_model.named_parameters()) + for name, ref_param in ref_model.named_parameters(): + if not ref_param.requires_grad or ref_param.grad is None: + continue + torch.testing.assert_close( + chunked_params[name].grad, + ref_param.grad, + atol=1e-5, + rtol=1e-5, + msg=f"gradient mismatch on {name}", + ) + + @require_peft + @pytest.mark.filterwarnings("ignore:Model has `tie_word_embeddings=True`") + def test_num_valid_tokens_with_prompt_learning_peft(self): + """For prompt-learning PEFT (PromptTuning, P-Tuning), `PeftModel.forward` prepends `-100`-padded virtual + tokens before delegating into the patched inner forward. The patched output's `num_valid_tokens` must reflect + the padded labels — when original `label[0] != -100`, it counts as a valid target paired with the last virtual + token's hidden state, so it must be included in the metric denominator to keep accuracy ≤ 1.""" + base = AutoModelForCausalLM.from_pretrained( + "trl-internal-testing/tiny-Qwen3ForCausalLM", dtype=torch.float32, device_map=torch_device + ) + peft_config = PromptTuningConfig(task_type=TaskType.CAUSAL_LM, num_virtual_tokens=4) + chunked_model = get_peft_model(base, peft_config) + _patch_chunked_ce_lm_head(chunked_model.get_base_model(), chunk_size=self.CHUNK_SIZE) + + B, S = 2, 16 + input_ids = torch.randint(0, base.config.vocab_size, (B, S), device=torch_device) + labels = input_ids.clone() # all positions valid, including label[0] + + out = chunked_model(input_ids=input_ids, labels=labels) + + # `labels[..., 1:]` (un-padded, what compute_loss used to compute) excludes original `label[0]`, + # but the patched forward sees padded labels and counts `label[0]` as a valid target. + unpadded = int((labels[..., 1:] != -100).sum()) + # One extra valid target per sequence (original `label[0]`). + assert out.num_valid_tokens.item() == unpadded + B + # Accuracy denominator from the patched output keeps numerator/denominator aligned, so accuracy ≤ 1. + assert out.num_correct_tokens.item() <= out.num_valid_tokens.item() diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_skills.py b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_skills.py new file mode 100644 index 0000000000000000000000000000000000000000..bcbec3971a25ef1ca44e9999c54b68125525ff12 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_skills.py @@ -0,0 +1,578 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from pathlib import Path + +import pytest + +from trl.skills import install_skill, list_agent_names, list_skills, resolve_target_path, uninstall_skill +from trl.skills.skills import _get_trl_skills_dir + + +class TestGetTrlSkillsDir: + """Tests for _get_trl_skills_dir function.""" + + def test_returns_path_object(self): + """Test that returns a Path object.""" + skills_dir = _get_trl_skills_dir() + assert isinstance(skills_dir, Path) + + def test_directory_exists(self): + """Test that the returned directory exists.""" + skills_dir = _get_trl_skills_dir() + assert skills_dir.exists(), f"Skills directory does not exist: {skills_dir}" + + def test_is_directory(self): + """Test that the returned path is a directory.""" + skills_dir = _get_trl_skills_dir() + assert skills_dir.is_dir(), f"Skills path is not a directory: {skills_dir}" + + def test_contains_skills_module(self): + """Test that the path ends with 'skills' (the module name).""" + skills_dir = _get_trl_skills_dir() + assert skills_dir.name == "skills" + + +class TestListSkills: + """Tests for list_skills function.""" + + def test_returns_list(self): + """Test that list_skills returns a list.""" + skills = list_skills() + assert isinstance(skills, list) + + def test_contains_trl_training(self): + """Test that list_skills includes the trl-training skill.""" + skills = list_skills() + assert "trl-training" in skills + + def test_skills_are_sorted(self): + """Test that skills are returned in sorted order.""" + skills = list_skills() + assert skills == sorted(skills) + + def test_with_custom_directory(self, tmp_path): + """Test list_skills with a custom directory.""" + # Create fake skills + (tmp_path / "skill1").mkdir() + (tmp_path / "skill1" / "SKILL.md").write_text("# Skill 1") + (tmp_path / "skill2").mkdir() + (tmp_path / "skill2" / "SKILL.md").write_text("# Skill 2") + (tmp_path / "not-a-skill").mkdir() # No SKILL.md + + skills = list_skills(tmp_path) + assert skills == ["skill1", "skill2"] + + def test_empty_directory(self, tmp_path): + """Test list_skills with an empty directory.""" + skills = list_skills(tmp_path) + assert skills == [] + + def test_nonexistent_directory(self, tmp_path): + """Test list_skills with a non-existent directory.""" + nonexistent = tmp_path / "nonexistent" + skills = list_skills(nonexistent) + assert skills == [] + + def test_ignores_files(self, tmp_path): + """Test that list_skills ignores files, only returns directories.""" + (tmp_path / "skill1").mkdir() + (tmp_path / "skill1" / "SKILL.md").write_text("# Skill 1") + (tmp_path / "not-a-skill.txt").write_text("Not a skill") + + skills = list_skills(tmp_path) + assert skills == ["skill1"] + + def test_requires_skill_md(self, tmp_path): + """Test that directories without SKILL.md are ignored.""" + (tmp_path / "has-skill-md").mkdir() + (tmp_path / "has-skill-md" / "SKILL.md").write_text("# Valid") + (tmp_path / "no-skill-md").mkdir() + (tmp_path / "no-skill-md" / "readme.md").write_text("# Invalid") + + skills = list_skills(tmp_path) + assert skills == ["has-skill-md"] + + +class TestInstallSkill: + """Tests for install_skill function.""" + + def test_basic_installation(self, tmp_path): + """Test basic skill installation.""" + target_dir = tmp_path / "target" + + result = install_skill("trl-training", target_dir) + + assert result is True + assert (target_dir / "trl-training").exists() + assert (target_dir / "trl-training" / "SKILL.md").exists() + + def test_creates_target_directory(self, tmp_path): + """Test that install_skill creates the target directory if it doesn't exist.""" + target_dir = tmp_path / "nested" / "target" + + install_skill("trl-training", target_dir) + + assert target_dir.exists() + assert (target_dir / "trl-training").exists() + + def test_skill_not_found(self, tmp_path): + """Test that install_skill raises FileNotFoundError for non-existent skill.""" + target_dir = tmp_path / "target" + + with pytest.raises(FileNotFoundError, match="Skill 'nonexistent' not found"): + install_skill("nonexistent", target_dir) + + def test_skill_already_exists_without_force(self, tmp_path): + """Test that install_skill raises FileExistsError if skill exists and force=False.""" + target_dir = tmp_path / "target" + + # Install once + install_skill("trl-training", target_dir) + + # Try to install again without force + with pytest.raises(FileExistsError, match="already installed"): + install_skill("trl-training", target_dir, force=False) + + def test_force_overwrites_existing(self, tmp_path): + """Test that install_skill with force=True overwrites existing skill.""" + target_dir = tmp_path / "target" + + # Install once + install_skill("trl-training", target_dir) + + # Modify the installed skill + marker_file = target_dir / "trl-training" / "marker.txt" + marker_file.write_text("This should be removed") + + # Install again with force + result = install_skill("trl-training", target_dir, force=True) + + assert result is True + assert (target_dir / "trl-training").exists() + assert not marker_file.exists() # Marker should be gone + + def test_force_overwrites_symlink(self, tmp_path): + """Test that install_skill with force=True can overwrite a symlink.""" + target_dir = tmp_path / "target" + target_dir.mkdir() + + # Create a symlink + symlink = target_dir / "trl-training" + symlink.symlink_to(_get_trl_skills_dir() / "trl-training") + + # Install with force should replace symlink with copy + result = install_skill("trl-training", target_dir, force=True) + + assert result is True + assert (target_dir / "trl-training").exists() + assert not (target_dir / "trl-training").is_symlink() + + def test_skill_not_directory(self, tmp_path): + """Test that install_skill raises ValueError if skill is not a directory.""" + source_dir = tmp_path / "source" + source_dir.mkdir() + target_dir = tmp_path / "target" + + # Create a file instead of directory + (source_dir / "fake-skill").write_text("not a directory") + + with pytest.raises(ValueError, match="is not a directory"): + install_skill("fake-skill", target_dir, source=source_dir) + + def test_preserves_directory_structure(self, tmp_path): + """Test that install_skill preserves the skill's directory structure.""" + source_dir = tmp_path / "source" + target_dir = tmp_path / "target" + + # Create a skill with subdirectories + skill_dir = source_dir / "test-skill" + skill_dir.mkdir(parents=True) + (skill_dir / "SKILL.md").write_text("# Test") + (skill_dir / "subdir").mkdir() + (skill_dir / "subdir" / "file.txt").write_text("content") + + install_skill("test-skill", target_dir, source=source_dir) + + assert (target_dir / "test-skill" / "SKILL.md").exists() + assert (target_dir / "test-skill" / "subdir" / "file.txt").exists() + assert (target_dir / "test-skill" / "subdir" / "file.txt").read_text() == "content" + + def test_install_to_same_directory_fails(self, tmp_path): + """Test that installing to the same directory as source is handled correctly.""" + source_dir = tmp_path / "skills" + source_dir.mkdir() + + # Create a skill + skill_dir = source_dir / "test-skill" + skill_dir.mkdir() + (skill_dir / "SKILL.md").write_text("# Test") + + # Try to install to same directory (should fail with exists error) + with pytest.raises(FileExistsError): + install_skill("test-skill", source_dir, source=source_dir, force=False) + + +class TestUninstallSkill: + """Tests for uninstall_skill function.""" + + def test_basic_uninstallation(self, tmp_path): + """Test basic skill uninstallation.""" + target_dir = tmp_path / "target" + + # Install first + install_skill("trl-training", target_dir) + assert (target_dir / "trl-training").exists() + + # Uninstall + result = uninstall_skill("trl-training", target_dir) + + assert result is True + assert not (target_dir / "trl-training").exists() + + def test_skill_not_installed(self, tmp_path): + """Test that uninstall_skill raises FileNotFoundError for non-existent skill.""" + target_dir = tmp_path / "target" + target_dir.mkdir() + + with pytest.raises(FileNotFoundError, match="not installed"): + uninstall_skill("nonexistent", target_dir) + + def test_uninstall_from_nonexistent_directory(self, tmp_path): + """Test uninstall_skill when target directory doesn't exist.""" + target_dir = tmp_path / "nonexistent" + + with pytest.raises(FileNotFoundError, match="not installed"): + uninstall_skill("trl-training", target_dir) + + def test_uninstall_removes_all_contents(self, tmp_path): + """Test that uninstall removes the entire skill directory.""" + source_dir = tmp_path / "source" + target_dir = tmp_path / "target" + + # Create a skill with multiple files + skill_dir = source_dir / "test-skill" + skill_dir.mkdir(parents=True) + (skill_dir / "SKILL.md").write_text("# Test") + (skill_dir / "file1.txt").write_text("content1") + (skill_dir / "subdir").mkdir() + (skill_dir / "subdir" / "file2.txt").write_text("content2") + + # Install and uninstall + install_skill("test-skill", target_dir, source=source_dir) + uninstall_skill("test-skill", target_dir) + + assert not (target_dir / "test-skill").exists() + # Target directory itself should still exist + assert target_dir.exists() + + def test_uninstall_doesnt_affect_other_skills(self, tmp_path): + """Test that uninstalling one skill doesn't affect others.""" + source_dir = tmp_path / "source" + target_dir = tmp_path / "target" + + # Create two skills + for skill_name in ["skill1", "skill2"]: + skill_dir = source_dir / skill_name + skill_dir.mkdir(parents=True) + (skill_dir / "SKILL.md").write_text(f"# {skill_name}") + + # Install both + install_skill("skill1", target_dir, source=source_dir) + install_skill("skill2", target_dir, source=source_dir) + + # Uninstall one + uninstall_skill("skill1", target_dir) + + # Check that only skill1 is removed + assert not (target_dir / "skill1").exists() + assert (target_dir / "skill2").exists() + + +class TestIntegration: + """Integration tests for skills functions.""" + + def test_full_workflow(self, tmp_path): + """Test complete install -> list -> uninstall workflow.""" + source_dir = tmp_path / "source" + target_dir = tmp_path / "target" + + # Create skills + for i in range(3): + skill_dir = source_dir / f"skill{i}" + skill_dir.mkdir(parents=True) + (skill_dir / "SKILL.md").write_text(f"# Skill {i}") + + # List available skills + available = list_skills(target=source_dir) + assert available == ["skill0", "skill1", "skill2"] + + # Install skills + for skill in available: + install_skill(skill, target_dir, source=source_dir) + + # List installed skills + installed_dirs = [d.name for d in target_dir.iterdir() if d.is_dir()] + assert sorted(installed_dirs) == ["skill0", "skill1", "skill2"] + + # Uninstall one skill + uninstall_skill("skill1", target_dir) + + # Verify + installed_dirs = [d.name for d in target_dir.iterdir() if d.is_dir()] + assert sorted(installed_dirs) == ["skill0", "skill2"] + + def test_install_uninstall_cycle(self, tmp_path): + """Test that we can install and uninstall the same skill multiple times.""" + source_dir = tmp_path / "source" + target_dir = tmp_path / "target" + + # Create skill + skill_dir = source_dir / "test-skill" + skill_dir.mkdir(parents=True) + (skill_dir / "SKILL.md").write_text("# Test") + + # Install -> Uninstall -> Install -> Uninstall + for _ in range(2): + install_skill("test-skill", target_dir, source=source_dir) + assert (target_dir / "test-skill").exists() + + uninstall_skill("test-skill", target_dir) + assert not (target_dir / "test-skill").exists() + + def test_force_reinstall_workflow(self, tmp_path): + """Test the workflow of using force to update an installed skill.""" + source_dir = tmp_path / "source" + target_dir = tmp_path / "target" + + # Create initial skill version + skill_dir = source_dir / "test-skill" + skill_dir.mkdir(parents=True) + (skill_dir / "SKILL.md").write_text("# Version 1") + + # Install + install_skill("test-skill", target_dir, source=source_dir) + assert (target_dir / "test-skill" / "SKILL.md").read_text() == "# Version 1" + + # Update source skill + (skill_dir / "SKILL.md").write_text("# Version 2") + + # Force reinstall + install_skill("test-skill", target_dir, source=source_dir, force=True) + assert (target_dir / "test-skill" / "SKILL.md").read_text() == "# Version 2" + + +class TestEdgeCases: + """Tests for edge cases and special scenarios.""" + + def test_skill_with_special_characters_in_name(self, tmp_path): + """Test handling skills with special characters in names.""" + source_dir = tmp_path / "source" + target_dir = tmp_path / "target" + + # Create skill with hyphens and underscores (common in skill names) + skill_name = "test-skill_v2" + skill_dir = source_dir / skill_name + skill_dir.mkdir(parents=True) + (skill_dir / "SKILL.md").write_text("# Test") + + # Should work fine + install_skill(skill_name, target_dir, source=source_dir) + assert (target_dir / skill_name).exists() + + uninstall_skill(skill_name, target_dir) + assert not (target_dir / skill_name).exists() + + def test_empty_skill_directory(self, tmp_path): + """Test installing a skill with only SKILL.md (no other files).""" + source_dir = tmp_path / "source" + target_dir = tmp_path / "target" + + skill_dir = source_dir / "minimal-skill" + skill_dir.mkdir(parents=True) + (skill_dir / "SKILL.md").write_text("# Minimal") + + install_skill("minimal-skill", target_dir, source=source_dir) + + assert (target_dir / "minimal-skill" / "SKILL.md").exists() + # Should only contain SKILL.md + files = list((target_dir / "minimal-skill").iterdir()) + assert len(files) == 1 + assert files[0].name == "SKILL.md" + + def test_skill_with_hidden_files(self, tmp_path): + """Test that hidden files are preserved during installation.""" + source_dir = tmp_path / "source" + target_dir = tmp_path / "target" + + skill_dir = source_dir / "test-skill" + skill_dir.mkdir(parents=True) + (skill_dir / "SKILL.md").write_text("# Test") + (skill_dir / ".hidden").write_text("hidden content") + + install_skill("test-skill", target_dir, source=source_dir) + + assert (target_dir / "test-skill" / ".hidden").exists() + assert (target_dir / "test-skill" / ".hidden").read_text() == "hidden content" + + def test_list_skills_with_symlinks(self, tmp_path): + """Test that list_skills handles symlinked skill directories.""" + source_dir = tmp_path / "source" + skills_dir = tmp_path / "skills" + skills_dir.mkdir() + + # Create a real skill + skill_dir = source_dir / "real-skill" + skill_dir.mkdir(parents=True) + (skill_dir / "SKILL.md").write_text("# Real") + + # Create symlink to it + (skills_dir / "linked-skill").symlink_to(skill_dir) + + # list_skills should include symlinked skills if they have SKILL.md + skills = list_skills(target=skills_dir) + assert "linked-skill" in skills + + +class TestListAgentNames: + """Tests for list_agent_names function.""" + + def test_returns_list(self): + """Test that list_agent_names returns a list.""" + agents = list_agent_names() + assert isinstance(agents, list) + + def test_contains_expected_agents(self): + """Test that list includes expected agent names.""" + agents = list_agent_names() + assert "agents" in agents + assert "claude" in agents + + +class TestResolveTargetPath: + """Tests for resolve_target_path function.""" + + def test_resolve_agent_name_project_scope(self): + """Test resolving agent name with project scope.""" + path = resolve_target_path("claude", "project") + assert path == Path("./.claude/skills").expanduser().resolve() + + def test_resolve_agent_name_global_scope(self): + """Test resolving agent name with global scope.""" + path = resolve_target_path("claude", "global") + assert path == Path("~/.claude/skills").expanduser().resolve() + + def test_resolve_custom_path_string(self): + """Test resolving custom path as string.""" + path = resolve_target_path("/custom/path", "project") + assert path == Path("/custom/path").resolve() + + def test_resolve_custom_path_object(self): + """Test resolving Path object.""" + custom = Path("/custom/path") + path = resolve_target_path(custom, "project") + assert path == Path("/custom/path").resolve() + + def test_resolve_path_with_tilde(self): + """Test that tilde expansion works.""" + path = resolve_target_path("~/my/skills", "project") + assert path == Path("~/my/skills").expanduser().resolve() + assert "~" not in str(path) + + def test_all_predefined_agents(self): + """Test that all predefined agents can be resolved.""" + for agent in list_agent_names(): + for scope in ["project", "global"]: + path = resolve_target_path(agent, scope) + assert isinstance(path, Path) + assert path.is_absolute() + + def test_invalid_scope_for_predefined_agent(self): + """Test invalid scope raises ValueError for predefined agents.""" + with pytest.raises(ValueError, match="Invalid scope"): + resolve_target_path("claude", "invalid") + + +class TestHighLevelAPI: + """Tests for the new high-level API (target/scope instead of Path).""" + + def test_list_skills_with_target_string(self, tmp_path): + """Test list_skills with target as string (custom path).""" + # Create skills in target + (tmp_path / "skill1").mkdir() + (tmp_path / "skill1" / "SKILL.md").write_text("# Skill 1") + + skills = list_skills(target=str(tmp_path), scope="project") + assert skills == ["skill1"] + + def test_list_skills_with_target_path(self, tmp_path): + """Test list_skills with target as Path object.""" + (tmp_path / "skill1").mkdir() + (tmp_path / "skill1" / "SKILL.md").write_text("# Skill 1") + + skills = list_skills(target=tmp_path, scope="project") + assert skills == ["skill1"] + + def test_list_skills_without_target(self): + """Test list_skills without target lists TRL's built-in skills.""" + skills = list_skills() + assert isinstance(skills, list) + assert "trl-training" in skills + + def test_install_skill_with_target_string(self, tmp_path): + """Test install_skill with target as string.""" + result = install_skill("trl-training", target=str(tmp_path), scope="project") + assert result is True + assert (tmp_path / "trl-training").exists() + + def test_install_skill_with_target_path(self, tmp_path): + """Test install_skill with target as Path object.""" + result = install_skill("trl-training", target=tmp_path, scope="project") + assert result is True + assert (tmp_path / "trl-training").exists() + + def test_install_skill_with_force(self, tmp_path): + """Test install_skill with force parameter.""" + install_skill("trl-training", target=tmp_path) + # Install again with force + result = install_skill("trl-training", target=tmp_path, force=True) + assert result is True + + def test_uninstall_skill_with_target_string(self, tmp_path): + """Test uninstall_skill with target as string.""" + install_skill("trl-training", target=tmp_path) + result = uninstall_skill("trl-training", target=str(tmp_path), scope="project") + assert result is True + assert not (tmp_path / "trl-training").exists() + + def test_uninstall_skill_with_target_path(self, tmp_path): + """Test uninstall_skill with target as Path object.""" + install_skill("trl-training", target=tmp_path) + result = uninstall_skill("trl-training", target=tmp_path, scope="project") + assert result is True + assert not (tmp_path / "trl-training").exists() + + def test_install_with_custom_source(self, tmp_path): + """Test install_skill with custom source parameter.""" + source_dir = tmp_path / "source" + target_dir = tmp_path / "target" + + # Create custom skill + skill_dir = source_dir / "custom-skill" + skill_dir.mkdir(parents=True) + (skill_dir / "SKILL.md").write_text("# Custom") + + result = install_skill("custom-skill", target=target_dir, source=source_dir) + assert result is True + assert (target_dir / "custom-skill").exists() diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_skills_cli.py b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_skills_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..e2afff3fe900ad62cb09b8b3da997a5662022110 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_skills_cli.py @@ -0,0 +1,288 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse + +import pytest + +from trl.skills import install_skill +from trl.skills.cli import add_skills_subcommands, cmd_install, cmd_list, cmd_uninstall + + +class TestCLICommands: + """Tests for CLI command handlers.""" + + def test_cmd_list_without_target(self, capsys): + """Test cmd_list without target (lists TRL skills).""" + args = argparse.Namespace(target=None, scope="project") + + result = cmd_list(args) + + captured = capsys.readouterr() + assert result == 0 + assert "TRL (available for installation)" in captured.out + assert "trl-training" in captured.out + assert "Use 'trl skills install" in captured.out + + def test_cmd_list_with_target(self, tmp_path, capsys): + """Test cmd_list with target (lists installed skills).""" + # Install a skill + install_skill("trl-training", target=tmp_path) + + args = argparse.Namespace(target=str(tmp_path), scope="project") + result = cmd_list(args) + + captured = capsys.readouterr() + assert result == 0 + assert "trl-training" in captured.out + assert str(tmp_path) in captured.out + + def test_cmd_list_empty_target(self, tmp_path, capsys): + """Test cmd_list with empty target directory.""" + args = argparse.Namespace(target=str(tmp_path), scope="project") + + result = cmd_list(args) + + captured = capsys.readouterr() + assert result == 0 + assert "No skills installed" in captured.out + + def test_cmd_install_single_skill(self, tmp_path, capsys): + """Test cmd_install with single skill.""" + args = argparse.Namespace(skill="trl-training", all=False, target=str(tmp_path), scope="project", force=False) + + result = cmd_install(args) + + captured = capsys.readouterr() + assert result == 0 + assert "✓" in captured.out + assert "1/1 skills installed" in captured.out + assert (tmp_path / "trl-training").exists() + + def test_cmd_install_all_skills(self, tmp_path, capsys): + """Test cmd_install with --all flag.""" + args = argparse.Namespace(skill=None, all=True, target=str(tmp_path), scope="project", force=False) + + result = cmd_install(args) + + captured = capsys.readouterr() + assert result == 0 + assert "✓" in captured.out + assert "installed successfully" in captured.out + assert (tmp_path / "trl-training").exists() + + def test_cmd_install_no_skill_or_all(self, capsys): + """Test cmd_install without skill name or --all flag.""" + args = argparse.Namespace(skill=None, all=False, target="/tmp/test", scope="project", force=False) + + result = cmd_install(args) + + captured = capsys.readouterr() + assert result == 1 + assert "Error: Either provide a skill name or use --all" in captured.out + + def test_cmd_install_both_skill_and_all(self, capsys): + """Test cmd_install with both skill name and --all (error).""" + args = argparse.Namespace(skill="trl-training", all=True, target="/tmp/test", scope="project", force=False) + + result = cmd_install(args) + + captured = capsys.readouterr() + assert result == 1 + assert "Cannot specify both" in captured.out + + def test_cmd_install_nonexistent_skill(self, tmp_path, capsys): + """Test cmd_install with non-existent skill.""" + args = argparse.Namespace(skill="nonexistent", all=False, target=str(tmp_path), scope="project", force=False) + + result = cmd_install(args) + + captured = capsys.readouterr() + assert result == 1 + assert "✗" in captured.out + assert "0/1 skills installed" in captured.out + + def test_cmd_install_already_exists(self, tmp_path, capsys): + """Test cmd_install when skill already exists without force.""" + # Install once + install_skill("trl-training", target=tmp_path) + + args = argparse.Namespace(skill="trl-training", all=False, target=str(tmp_path), scope="project", force=False) + + result = cmd_install(args) + + captured = capsys.readouterr() + assert result == 1 + assert "✗" in captured.out + assert "Use --force to overwrite" in captured.out + + def test_cmd_install_with_force(self, tmp_path, capsys): + """Test cmd_install with --force to overwrite.""" + # Install once + install_skill("trl-training", target=tmp_path) + + args = argparse.Namespace(skill="trl-training", all=False, target=str(tmp_path), scope="project", force=True) + + result = cmd_install(args) + + captured = capsys.readouterr() + assert result == 0 + assert "✓" in captured.out + assert "1/1 skills installed" in captured.out + + def test_cmd_uninstall_success(self, tmp_path, capsys): + """Test cmd_uninstall with installed skill.""" + # Install first + install_skill("trl-training", target=tmp_path) + + args = argparse.Namespace(skill="trl-training", target=str(tmp_path), scope="project") + + result = cmd_uninstall(args) + + captured = capsys.readouterr() + assert result == 0 + assert "✓" in captured.out + assert "has been removed" in captured.out + assert not (tmp_path / "trl-training").exists() + + def test_cmd_uninstall_not_installed(self, tmp_path, capsys): + """Test cmd_uninstall when skill is not installed.""" + args = argparse.Namespace(skill="nonexistent", target=str(tmp_path), scope="project") + + result = cmd_uninstall(args) + + captured = capsys.readouterr() + assert result == 1 + assert "✗" in captured.out + assert "Error:" in captured.out + + def test_cmd_install_creates_target_directory(self, tmp_path, capsys): + """Test cmd_install creates target directory if it doesn't exist.""" + # Custom path that doesn't exist yet + target_path = tmp_path / "new_directory" + assert not target_path.exists() + + args = argparse.Namespace( + skill="trl-training", all=False, target=str(target_path), scope="project", force=False + ) + + result = cmd_install(args) + + captured = capsys.readouterr() + assert result == 0 + assert "✓" in captured.out + assert target_path.exists() + + def test_cmd_uninstall_invalid_target(self, capsys): + """Test cmd_uninstall with non-existent path.""" + args = argparse.Namespace(skill="trl-training", target="/nonexistent/invalid/path", scope="project") + + result = cmd_uninstall(args) + + captured = capsys.readouterr() + assert result == 1 + assert "✗" in captured.out + + +class TestCLIArgumentParsing: + """Tests for CLI argument parsing setup.""" + + def test_add_skills_subcommands_creates_parsers(self): + """Test that add_skills_subcommands creates the expected subparsers.""" + parser = argparse.ArgumentParser() + subparsers = parser.add_subparsers(dest="command") + + add_skills_subcommands(subparsers) + + # Test that we can parse expected commands + args = parser.parse_args(["list"]) + assert args.command == "list" + assert hasattr(args, "func") + + args = parser.parse_args(["install", "trl-training", "--target", "claude"]) + assert args.command == "install" + assert args.skill == "trl-training" + assert args.target == "claude" + + args = parser.parse_args(["uninstall", "trl-training", "--target", "claude"]) + assert args.command == "uninstall" + assert args.skill == "trl-training" + + def test_list_command_optional_target(self): + """Test that list command has optional target.""" + parser = argparse.ArgumentParser() + subparsers = parser.add_subparsers(dest="command") + add_skills_subcommands(subparsers) + + # Should work without target + args = parser.parse_args(["list"]) + assert args.target is None + + # Should work with target + args = parser.parse_args(["list", "--target", "claude"]) + assert args.target == "claude" + + def test_default_target_is_agents(self): + """Test that default target is 'agents'.""" + parser = argparse.ArgumentParser() + subparsers = parser.add_subparsers(dest="command") + add_skills_subcommands(subparsers) + + args = parser.parse_args(["install", "trl-training"]) + assert args.target == "agents" + + def test_scope_choices(self): + """Test that scope parameter accepts valid choices.""" + parser = argparse.ArgumentParser() + subparsers = parser.add_subparsers(dest="command") + add_skills_subcommands(subparsers) + + # Valid scopes + args = parser.parse_args(["install", "trl-training", "--target", "claude", "--scope", "project"]) + assert args.scope == "project" + + args = parser.parse_args(["install", "trl-training", "--target", "claude", "--scope", "global"]) + assert args.scope == "global" + + # Invalid scope should fail + with pytest.raises(SystemExit): + parser.parse_args(["install", "trl-training", "--target", "claude", "--scope", "invalid"]) + + def test_install_all_flag(self): + """Test install --all flag.""" + parser = argparse.ArgumentParser() + subparsers = parser.add_subparsers(dest="command") + add_skills_subcommands(subparsers) + + args = parser.parse_args(["install", "--all", "--target", "claude"]) + assert args.all is True + assert args.skill is None + + def test_install_force_flag(self): + """Test install --force flag.""" + parser = argparse.ArgumentParser() + subparsers = parser.add_subparsers(dest="command") + add_skills_subcommands(subparsers) + + args = parser.parse_args(["install", "trl-training", "--target", "claude", "--force"]) + assert args.force is True + + def test_default_scope_is_project(self): + """Test that default scope is 'project'.""" + parser = argparse.ArgumentParser() + subparsers = parser.add_subparsers(dest="command") + add_skills_subcommands(subparsers) + + args = parser.parse_args(["install", "trl-training", "--target", "claude"]) + assert args.scope == "project" diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_utils.py b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b4a48523611b32b696e6d234ff35da8c0650d5a1 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_utils.py @@ -0,0 +1,1380 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import copy +import textwrap +from io import StringIO +from unittest.mock import patch + +import pytest +import torch +import torch.nn as nn +import torch.nn.functional as F +import transformers +from packaging.version import Version +from transformers import AutoConfig, AutoModelForCausalLM +from transformers.testing_utils import torch_device +from transformers.utils import is_peft_available + +from trl import ModelConfig +from trl.trainer.utils import ( + RepeatSampler, + _ChunkedLogProbFunction, + adjusted_mfu, + compute_flops_per_token, + compute_mfu, + entropy_from_logits, + flush_left, + generate_model_card, + get_peft_config, + hash_module, + nanstd, + pad, + patch_chunked_lm_head, + print_prompt_completions_sample, + selective_log_softmax, + shuffle_sequence_dict, + split_pixel_values_by_grid, + split_tensor_dict, + unsplit_pixel_values_by_grid, + use_adapter, +) + +from .testing_utils import TrlTestCase, require_peft, require_rich, require_torch_accelerator + + +if is_peft_available(): + from peft import AutoPeftModelForCausalLM, LoraConfig + + +@require_peft +class TestUseAdapter(TrlTestCase): + def test_disables_on_none(self): + model = AutoPeftModelForCausalLM.from_pretrained( + "trl-internal-testing/tiny-PeftModel", adapter_name="my_adapter" + ) + input_ids = torch.tensor([[1, 2, 3], [4, 5, 6]]) + with model.disable_adapter(): + expected = model(input_ids).logits + + with use_adapter(model, None): + output = model(input_ids).logits + + assert torch.equal(output, expected) + + def test_restores_previous_adapter(self): + model = AutoPeftModelForCausalLM.from_pretrained( + "trl-internal-testing/tiny-PeftModel", adapter_name="my_adapter" + ) + input_ids = torch.tensor([[1, 2, 3], [4, 5, 6]]) + expected = model(input_ids).logits + with use_adapter(model, "my_adapter"): + pass + output = model(input_ids).logits + assert torch.equal(output, expected) + + with use_adapter(model, None): + pass + output = model(input_ids).logits + assert torch.equal(output, expected) + + def test_with_multiple_adapters(self): + model = AutoPeftModelForCausalLM.from_pretrained( + "trl-internal-testing/tiny-PeftModel", adapter_name="my_adapter_1" + ) + model.load_adapter("trl-internal-testing/tiny-PeftModel-2", "my_adapter_2") + input_ids = torch.tensor([[1, 2, 3], [4, 5, 6]]) + + model.set_adapter("my_adapter_1") # should be a no-op, but let's keep it for clarity + expected_1 = model(input_ids).logits + model.set_adapter("my_adapter_2") + expected_2 = model(input_ids).logits + + with use_adapter(model, "my_adapter_1"): + output_1 = model(input_ids).logits + + with use_adapter(model, "my_adapter_2"): + output_2 = model(input_ids).logits + + assert torch.equal(output_1, expected_1) + assert torch.equal(output_2, expected_2) + + +class TestPad(TrlTestCase): + def test_pad_1_dim_left(self): + x = torch.tensor([1, 2, 3]) + y = torch.tensor([4, 5]) + output = pad((x, y), padding_value=0, padding_side="left") + expected = torch.tensor([[1, 2, 3], [0, 4, 5]]) + assert torch.equal(output, expected) + + def test_pad_1_dim_right(self): + x = torch.tensor([1, 2, 3]) + y = torch.tensor([4, 5]) + output = pad((x, y), padding_value=0, padding_side="right") + expected = torch.tensor([[1, 2, 3], [4, 5, 0]]) + assert torch.equal(output, expected) + + def test_pad_2_dim_left(self): + x = torch.tensor([[1, 2], [3, 4]]) + y = torch.tensor([[5, 6]]) + output = pad((x, y), padding_value=0, padding_side="left") + expected = torch.tensor( + [ + [[1, 2], [3, 4]], + [[0, 0], [5, 6]], + ] + ) + assert torch.equal(output, expected) + + def test_pad_2_dim_right(self): + x = torch.tensor([[1, 2], [3, 4]]) + y = torch.tensor([[5, 6]]) + output = pad((x, y), padding_value=0, padding_side="right") + expected = torch.tensor( + [ + [[1, 2], [3, 4]], + [[5, 6], [0, 0]], + ] + ) + assert torch.equal(output, expected) + + def test_pad_2_dim_right_multidim(self): + x = torch.tensor([[1, 2], [3, 4]]) + y = torch.tensor([[5]]) + output = pad((x, y), padding_value=0, padding_side="right") + expected = torch.tensor( + [ + [[1, 2], [3, 4]], + [[5, 0], [0, 0]], + ] + ) + assert torch.equal(output, expected) + + def test_pad_to_multiple_of_1(self): + x = torch.tensor([1, 2, 3]) + y = torch.tensor([4, 5]) + # Max length is 3, pad to multiple of 4 + output = pad((x, y), padding_value=0, padding_side="right", pad_to_multiple_of=4) + expected = torch.tensor([[1, 2, 3, 0], [4, 5, 0, 0]]) + assert torch.equal(output, expected) + + def test_pad_to_multiple_of_2(self): + x = torch.tensor([1, 2, 3, 4, 5]) + y = torch.tensor([6, 7, 8]) + # Max length is 3, pad to multiple of 4 + output = pad((x, y), padding_value=0, padding_side="right", pad_to_multiple_of=4) + expected = torch.tensor([[1, 2, 3, 4, 5, 0, 0, 0], [6, 7, 8, 0, 0, 0, 0, 0]]) + assert torch.equal(output, expected) + + def test_pad_to_multiple_of_side_left(self): + x = torch.tensor([1, 2, 3, 4, 5]) + y = torch.tensor([6, 7, 8]) + # Max length is 3, pad to multiple of 4 + output = pad((x, y), padding_value=0, padding_side="left", pad_to_multiple_of=4) + expected = torch.tensor([[0, 0, 0, 1, 2, 3, 4, 5], [0, 0, 0, 0, 0, 6, 7, 8]]) + assert torch.equal(output, expected) + + def test_pad_to_multiple_of_no_extra_padding(self): + x = torch.tensor([1, 2, 3, 4]) + y = torch.tensor([5, 6, 7, 8]) + # Already multiple of 4 + output = pad((x, y), padding_value=0, padding_side="left", pad_to_multiple_of=4) + expected = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]]) + assert torch.equal(output, expected) + + +class TestHashModule(TrlTestCase): + def test_hash_module_deterministic_across_order(self): + class ModAB(torch.nn.Module): + def __init__(self, a: torch.Tensor, b: torch.Tensor): + super().__init__() + self.a = torch.nn.Parameter(a) + self.b = torch.nn.Parameter(b) + + class ModBA(torch.nn.Module): + def __init__(self, a: torch.Tensor, b: torch.Tensor): + super().__init__() + self.b = torch.nn.Parameter(b) + self.a = torch.nn.Parameter(a) + + a = torch.tensor([[1.0, 2.0]]) + b = torch.tensor([3.0]) + assert hash_module(ModAB(a, b)) == hash_module(ModBA(a, b)) + + def test_hash_module_changes_with_value(self): + class Mod(torch.nn.Module): + def __init__(self, value: float): + super().__init__() + self.weight = torch.nn.Parameter(torch.tensor([value, 2.0])) + + assert hash_module(Mod(1.0)) != hash_module(Mod(1.5)) + + def test_hash_module_includes_dtype(self): + class Mod(torch.nn.Module): + def __init__(self, dtype: torch.dtype): + super().__init__() + self.weight = torch.nn.Parameter(torch.tensor([1.0, 2.0], dtype=dtype)) + + assert hash_module(Mod(torch.float32)) != hash_module(Mod(torch.float16)) + + def test_hash_module_tiny_model_twice(self): + model_id = "trl-internal-testing/tiny-GptOssForCausalLM" + model_a = AutoModelForCausalLM.from_pretrained(model_id) + model_b = AutoModelForCausalLM.from_pretrained(model_id) + assert hash_module(model_a) == hash_module(model_b) + + def test_hash_module_tiny_model_change_layer(self): + model_id = "trl-internal-testing/tiny-GptOssForCausalLM" + model = AutoModelForCausalLM.from_pretrained(model_id) + h1 = hash_module(model) + with torch.no_grad(): + model.lm_head.weight.add_(0.01) + h2 = hash_module(model) + assert h1 != h2 + + +@require_peft +class TestGetPEFTConfig(TrlTestCase): + def test_create_peft_config_use_peft_false(self): + """Test that when use_peft is False, the function returns None.""" + model_args = ModelConfig(use_peft=False) + peft_config = get_peft_config(model_args) + assert peft_config is None + + def test_create_peft_config_use_peft_true(self): + """Test that when use_peft is True, the function returns a LoraConfig object.""" + # Provide non-default values to the model config for testing + peft_kwargs = { + "lora_r": 8, + "lora_alpha": 16, + "lora_dropout": 0.1, + "lora_task_type": "SEQ_CLS", + "use_rslora": True, + "lora_target_modules": ["up_proj", "down_proj"], + "lora_modules_to_save": ["up_proj"], + } + model_args = ModelConfig(use_peft=True, **peft_kwargs) + peft_config = get_peft_config(model_args) + assert isinstance(peft_config, LoraConfig) + for arg, value in peft_kwargs.items(): + # Test that lists of modules are converted to sets + if arg == "lora_target_modules": + value = set(value) + # Rename the argument to match the LoraConfig attribute name + if arg in ["lora_r", "lora_task_type", "lora_target_modules", "lora_modules_to_save"]: + arg = arg[len("lora_") :] if arg.startswith("lora_") else arg + + assert getattr(peft_config, arg) == value + + +class TestNanStd(TrlTestCase): + def test_nanstd_ignores_nans(self): + x = torch.tensor([1.0, 2.0, 3.0, float("nan")]) + result = nanstd(x) + torch.testing.assert_close(result, torch.tensor(1.0)) + + def test_nanstd_dim_and_keepdim(self): + x = torch.tensor([[1.0, float("nan")], [3.0, 5.0]]) + result = nanstd(x, dim=1, keepdim=True) + assert torch.isnan(result[0, 0]) + torch.testing.assert_close(result[1, 0], torch.tensor(1.4142135), rtol=1e-5, atol=1e-6) + + def test_nanstd_all_nan(self): + x = torch.tensor([float("nan"), float("nan")]) + result = nanstd(x) + assert torch.isnan(result) + + +class TestGenerateModelCard(TrlTestCase): + def test_full(self): + model_card = generate_model_card( + base_model="username/my_base_model", + model_name="my_model", + hub_model_id="username/my_hub_model", + dataset_name="username/my_dataset", + tags=["trl", "trainer-tag"], + wandb_url="https://wandb.ai/username/project_id/runs/abcd1234", + trackio_url="https://huggingface.co/spaces/username/space_id", + comet_url="https://www.comet.com/username/project_id/experiment_id", + trainer_name="My Trainer", + trainer_citation="@article{my_trainer, ...}", + paper_title="My Paper", + paper_id="1234.56789", + ) + card_text = str(model_card) + assert "[username/my_base_model](https://huggingface.co/username/my_base_model)" in card_text + assert "my_model" in card_text + assert 'pipeline("text-generation", model="username/my_hub_model", device="cuda")' in card_text + assert "datasets: username/my_dataset" in card_text + assert "](https://wandb.ai/username/project_id/runs/abcd1234)" in card_text + assert "](https://huggingface.co/spaces/username/space_id)" in card_text + assert "](https://www.comet.com/username/project_id/experiment_id" in card_text + assert "My Trainer" in card_text + assert "```bibtex\n@article{my_trainer, ...}\n```" in card_text + assert "[My Paper](https://huggingface.co/papers/1234.56789)" in card_text + + def test_val_none(self): + model_card = generate_model_card( + base_model=None, + model_name="my_model", + hub_model_id="username/my_hub_model", + dataset_name=None, + tags=[], + wandb_url=None, + trackio_url=None, + comet_url=None, + trainer_name="My Trainer", + trainer_citation=None, + paper_title=None, + paper_id=None, + ) + card_text = str(model_card) + assert "my_model" in card_text + assert 'pipeline("text-generation", model="username/my_hub_model", device="cuda")' in card_text + assert "My Trainer" in card_text + + +class TestFlushLeft(TrlTestCase): + def test_basic_case(self): + mask = torch.tensor([[0, 0, 1, 1, 1], [0, 1, 1, 0, 0]]) + tensor1 = torch.tensor([[0, 0, 2, 3, 4], [0, 5, 6, 0, 0]]) + tensor2 = torch.tensor([[0, 0, 7, 8, 9], [0, 10, 11, 0, 0]]) + new_mask, new_tensor1, new_tensor2 = flush_left(mask, tensor1, tensor2) + + expected_mask = torch.tensor([[1, 1, 1], [1, 1, 0]]) + expected_tensor1 = torch.tensor([[2, 3, 4], [5, 6, 0]]) + expected_tensor2 = torch.tensor([[7, 8, 9], [10, 11, 0]]) + + assert torch.equal(new_mask, expected_mask) + assert torch.equal(new_tensor1, expected_tensor1) + assert torch.equal(new_tensor2, expected_tensor2) + + def test_single_row(self): + mask = torch.tensor([[0, 0, 1, 1]]) + tensor1 = torch.tensor([[0, 0, 2, 3]]) + new_mask, new_tensor1 = flush_left(mask, tensor1) + + expected_mask = torch.tensor([[1, 1]]) + expected_tensor1 = torch.tensor([[2, 3]]) + + assert torch.equal(new_mask, expected_mask) + assert torch.equal(new_tensor1, expected_tensor1) + + def test_no_shift_needed(self): + mask = torch.tensor([[1, 1, 0, 0], [1, 0, 0, 0]]) + tensor1 = torch.tensor([[5, 6, 0, 0], [7, 0, 0, 0]]) + new_mask, new_tensor1 = flush_left(mask, tensor1) + + expected_mask = torch.tensor([[1, 1], [1, 0]]) + expected_tensor1 = torch.tensor([[5, 6], [7, 0]]) + + assert torch.equal(new_mask, expected_mask) + assert torch.equal(new_tensor1, expected_tensor1) + + def test_no_tensors(self): + mask = torch.tensor([[0, 0, 1, 1, 1], [0, 1, 1, 0, 0]]) + new_mask = flush_left(mask) + expected_mask = torch.tensor([[1, 1, 1], [1, 1, 0]]) + assert torch.equal(new_mask, expected_mask) + + +class TestRepeatRandomSampler(TrlTestCase): + def test_sampler(self): + dataset = ["a", "b", "c", "d", "e", "f", "g"] + sampler = RepeatSampler(dataset, mini_repeat_count=2) + # Should output something like [4, 4, 3, 3, 0, 0, 1, 1, 2, 2, 6, 6, 5, 5] + sampled = list(sampler) + # Check that the length is doubled + assert len(sampled) == 2 * len(dataset) + # Check that all indexes are present + assert set(sampled) == set(range(len(dataset))) + # Check that each element is repeated twice + assert all(sampled[i] == sampled[i + 1] for i in range(0, len(sampled), 2)) + + def test_sampler_no_shuffle(self): + dataset = ["a", "b", "c", "d", "e", "f", "g"] + sampler = RepeatSampler(dataset, mini_repeat_count=2, shuffle=False) + sampled = list(sampler) + expected = [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6] + assert sampled == expected + + def test_sampler_no_repeat(self): + dataset = ["a", "b", "c", "d", "e", "f", "g"] + sampler = RepeatSampler(dataset, mini_repeat_count=1) + # Should output something like [4, 3, 0, 1, 2, 6, 5] + sampled = list(sampler) + # Check that the length is the same + assert len(sampled) == len(dataset) + # Check that all indexes are present + assert set(sampled) == set(range(len(dataset))) + + def test_sampler_with_batch_size(self): + dataset = ["a", "b", "c", "d", "e", "f", "g", "h"] + sampler = RepeatSampler(dataset, mini_repeat_count=1, batch_size=2, repeat_count=2) + # Should output something like [4, 3, 4, 3, 0, 1, 0, 1, 2, 6, 2, 6, 5, 7, 5, 7] + sampled = list(sampler) + # Check that the length is doubled + assert len(sampled) == 2 * len(dataset) + # Check that all indexes are present + assert set(sampled) == set(range(len(dataset))) + # Check that each element is repeated as expected + assert all(sampled[i : i + 1] == sampled[i + 2 : i + 3] for i in range(0, len(sampled), 4)) + + def test_sampler_with_batch_size_and_drop(self): + dataset = ["a", "b", "c", "d", "e", "f", "g"] + sampler = RepeatSampler(dataset, mini_repeat_count=1, batch_size=2, repeat_count=2) + # Should output something like [4, 3, 4, 3, 0, 1, 0, 1, 2, 6, 2, 6] + sampled = list(sampler) + # Check that the length is doubled + assert len(sampled) == 2 * ( + len(dataset) - 1 + ) # one element is dropped, because it's not enough to form a batch + assert len(sampler) == len(sampled) # the length should be the same as the sampled length + # Check that the sampled indexes are a subset of the dataset indexes + assert set(sampled).issubset(set(range(len(dataset)))) + # Check that each element is repeated as expected + assert all(sampled[i : i + 1] == sampled[i + 2 : i + 3] for i in range(0, len(sampled), 4)) + + def test_sampler_with_mini_repeat_count_and_batch_size_1(self): + dataset = ["a", "b", "c", "d", "e", "f", "g"] + sampler = RepeatSampler(dataset, mini_repeat_count=2, batch_size=3, repeat_count=2) + # Should output something like [4, 4, 3, 3, 0, 0, 4, 4, 3, 3, 0, 0, + # 1, 1, 2, 2, 6, 6, 1, 1, 2, 2, 6, 6] + sampled = list(sampler) + # Check that the length is quadrupled + assert len(sampled) == 4 * (len(dataset) - 1) # 1 element is dropped, because it's not enough to form a batch + assert len(sampler) == len(sampled) # the length should be the same as the sampled length + # Check that the sampled indexes are a subset of the dataset indexes + assert set(sampled).issubset(set(range(len(dataset)))) + # Check that each element is repeated as expected + assert all(sampled[i] == sampled[i + 1] for i in range(0, len(sampled), 2)) + # Check that the batch is repeated as expected + assert sampled[0:6] == sampled[6:12] + assert sampled[12:18] == sampled[18:24] + + def test_sampler_with_mini_repeat_count_and_batch_size_2(self): + dataset = ["a", "b", "c", "d", "e", "f", "g"] + sampler = RepeatSampler(dataset, mini_repeat_count=3, batch_size=2, repeat_count=2) + # Should output something like [4, 4, 4, 3, 3, 3, 4, 4, 4, 3, 3, 3, + # 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, + # 2, 2, 2, 6, 6, 6, 2, 2, 2, 6, 6, 6] + sampled = list(sampler) + # Check that the length is sextupled + assert len(sampled) == 6 * (len(dataset) - 1) # 1 element is dropped, because it's not enough to form a batch + assert len(sampler) == len(sampled) # the length should be the same as the sampled length + # Check that the sampled indexes are a subset of the dataset indexes + assert set(sampled).issubset(set(range(len(dataset)))) + # Check that each element is repeated as expected + assert all(sampled[i] == sampled[i + 1] == sampled[i + 2] for i in range(0, len(sampled), 3)) + # Check that the batch is repeated as expected + assert sampled[0:6] == sampled[6:12] + assert sampled[12:18] == sampled[18:24] + assert sampled[24:30] == sampled[30:36] + + def test_sampler_with_mini_repeat_count_and_batch_size_3(self): + dataset = ["a", "b", "c", "d", "e", "f", "g"] + sampler = RepeatSampler(dataset, mini_repeat_count=2, batch_size=2, repeat_count=3) + # Should output something like [4, 4, 3, 3, 4, 4, 3, 3, 4, 4, 3, 3, + # 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, + # 2, 2, 6, 6, 2, 2, 6, 6, 2, 2, 6, 6] + sampled = list(sampler) + # Check that the length is sextupled + assert len(sampled) == 6 * (len(dataset) - 1) # 1 element is dropped, because it's not enough to form a batch + # Check that the sampled indexes are a subset of the dataset indexes + assert set(sampled).issubset(set(range(len(dataset)))) + # Check that each element is repeated as expected + assert all(sampled[i] == sampled[i + 1] for i in range(0, len(sampled), 2)) + # Check that the batch is repeated as expected + assert sampled[0:4] == sampled[4:8] == sampled[8:12] + assert sampled[12:16] == sampled[16:20] == sampled[20:24] + assert sampled[24:28] == sampled[28:32] == sampled[32:36] + + +class TestEntropyFromLogits(TrlTestCase): + @pytest.mark.parametrize("shape", [(768,), (32, 768), (8, 16, 768), (2, 4, 8, 768)]) + @pytest.mark.parametrize("chunk_size", [1, 16]) + @pytest.mark.parametrize("dtype", [torch.float64, torch.float32, torch.float16, torch.bfloat16]) + def test_entropy_from_logits_2_dims(self, dtype, chunk_size, shape): + logits = torch.randn(*shape, dtype=dtype) + if dtype in (torch.float64, torch.float32): + p = logits.softmax(-1) + entropy = -torch.sum(p * p.log(), dim=-1) + else: + logps = logits.log_softmax(dim=-1) + entropy = -(torch.exp(logps) * logps).sum(-1) + predicted_entropy = entropy_from_logits(logits, chunk_size=chunk_size) + torch.testing.assert_close(predicted_entropy, entropy, rtol=1e-5, atol=1e-5) + + +@require_rich +class TestPrintPromptCompletionsSample(TrlTestCase): + @patch("sys.stdout", new_callable=StringIO) + def test_print_output(self, mock_stdout): + prompts = ["The sky is", "The sun is"] + completions = [" blue.", " in the sky."] + rewards = {"Correctness": [0.123, 0.456], "Format": [0.789, 0.101]} + advantages = [0.987, 0.654] + step = 42 + + print_prompt_completions_sample(prompts, completions, rewards, advantages, step) + + output = mock_stdout.getvalue() + + # docstyle-ignore + expected_output = textwrap.dedent("""\ + ╭──────────────────────────── Step 42 ─────────────────────────────╮ + │ ┏━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━━┓ │ + │ ┃ Prompt ┃ Completion ┃ Correctness ┃ Format ┃ Advantage ┃ │ + │ ┡━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━━┩ │ + │ │ The sky is │ blue. │ 0.12 │ 0.79 │ 0.99 │ │ + │ ├────────────┼──────────────┼─────────────┼────────┼───────────┤ │ + │ │ The sun is │ in the sky. │ 0.46 │ 0.10 │ 0.65 │ │ + │ └────────────┴──────────────┴─────────────┴────────┴───────────┘ │ + ╰──────────────────────────────────────────────────────────────────╯ + """) + + assert output == expected_output + + @patch("sys.stdout", new_callable=StringIO) + def test_extra_columns(self, mock_stdout): + prompts = ["The sky is", "The sun is"] + completions = [" blue.", " in the sky."] + rewards = {"Correctness": [0.123, 0.456], "Format": [0.789, 0.101]} + advantages = [0.987, 0.654] + extra = {"source": ["dataset_A", "dataset_B"]} + step = 42 + + print_prompt_completions_sample(prompts, completions, rewards, advantages, step, extra=extra) + + output = mock_stdout.getvalue() + + # docstyle-ignore + expected_output = textwrap.dedent("""\ + ╭────────────────────────────────── Step 42 ───────────────────────────────────╮ + │ ┏━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━┓ │ + │ ┃ Prompt ┃ Completion ┃ Correctness ┃ Format ┃ Advantage ┃ source ┃ │ + │ ┡━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━┩ │ + │ │ The sky is │ blue. │ 0.12 │ 0.79 │ 0.99 │ dataset_A │ │ + │ ├────────────┼──────────────┼─────────────┼────────┼───────────┼───────────┤ │ + │ │ The sun is │ in the sky. │ 0.46 │ 0.10 │ 0.65 │ dataset_B │ │ + │ └────────────┴──────────────┴─────────────┴────────┴───────────┴───────────┘ │ + ╰──────────────────────────────────────────────────────────────────────────────╯ + """) + + assert output == expected_output + + @patch("sys.stdout", new_callable=StringIO) + def test_num_samples(self, mock_stdout): + prompts = ["A", "B"] + completions = ["1", "2"] + rewards = {"Score": [0.1, 0.2]} + advantages = [0.3, 0.4] + step = 10 + + print_prompt_completions_sample(prompts, completions, rewards, advantages, step, num_samples=1) + output = mock_stdout.getvalue() + + # docstyle-ignore + possible_outputs = [ + textwrap.dedent("""\ + ╭────────────────── Step 10 ──────────────────╮ + │ ┏━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━┓ │ + │ ┃ Prompt ┃ Completion ┃ Score ┃ Advantage ┃ │ + │ ┡━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━┩ │ + │ │ A │ 1 │ 0.10 │ 0.30 │ │ + │ └────────┴────────────┴───────┴───────────┘ │ + ╰─────────────────────────────────────────────╯ + """), + # docstyle-ignore + textwrap.dedent("""\ + ╭────────────────── Step 10 ──────────────────╮ + │ ┏━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━┓ │ + │ ┃ Prompt ┃ Completion ┃ Score ┃ Advantage ┃ │ + │ ┡━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━┩ │ + │ │ B │ 2 │ 0.20 │ 0.40 │ │ + │ └────────┴────────────┴───────┴───────────┘ │ + ╰─────────────────────────────────────────────╯ + """), + ] + assert output in possible_outputs + + @patch("sys.stdout", new_callable=StringIO) + def test_print_messages(self, mock_stdout): + prompts = [ + [ + {"role": "system", "content": "You are an helpful assistant."}, + {"role": "user", "content": "What color is the sky?"}, + ], + [ + {"role": "system", "content": "You are an helpful assistant."}, + {"role": "user", "content": "Where is the sun?"}, + ], + ] + completions = [ + [{"role": "assistant", "content": "It is blue."}], + [{"role": "assistant", "content": "In the sky."}], + ] + rewards = {"Correctness": [0.123, 0.456], "Format": [0.789, 0.101]} + advantages = [0.987, 0.654] + step = 42 + + print_prompt_completions_sample(prompts, completions, rewards, advantages, step) + + output = mock_stdout.getvalue() + + # docstyle-ignore + expected_output = textwrap.dedent("""\ + ╭────────────────────────────────── Step 42 ───────────────────────────────────╮ + │ ┏━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━━┓ │ + │ ┃ Prompt ┃ Completion ┃ Correctness ┃ Format ┃ Advantage ┃ │ + │ ┡━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━━┩ │ + │ │ SYSTEM │ ASSISTANT │ 0.12 │ 0.79 │ 0.99 │ │ + │ │ You are an helpful │ It is blue. │ │ │ │ │ + │ │ assistant. │ │ │ │ │ │ + │ │ │ │ │ │ │ │ + │ │ USER │ │ │ │ │ │ + │ │ What color is the sky? │ │ │ │ │ │ + │ ├─────────────────────────┼─────────────┼─────────────┼────────┼───────────┤ │ + │ │ SYSTEM │ ASSISTANT │ 0.46 │ 0.10 │ 0.65 │ │ + │ │ You are an helpful │ In the sky. │ │ │ │ │ + │ │ assistant. │ │ │ │ │ │ + │ │ │ │ │ │ │ │ + │ │ USER │ │ │ │ │ │ + │ │ Where is the sun? │ │ │ │ │ │ + │ └─────────────────────────┴─────────────┴─────────────┴────────┴───────────┘ │ + ╰──────────────────────────────────────────────────────────────────────────────╯ + """) + + assert output == expected_output + + @patch("sys.stdout", new_callable=StringIO) + def test_print_messages_with_tools(self, mock_stdout): + prompts = [ + [{"role": "user", "content": "What is the temperature in Paris?"}], + [{"role": "user", "content": "What is the weather in London?"}], + ] + completions = [ + [{"role": "tool", "name": "get_temperature", "args": {"location": "Paris"}}], + [{"role": "tool", "name": "get_weather", "args": {"location": "London"}}], + ] + rewards = {"Correctness": [0.123, 0.456], "Format": [0.789, 0.101]} + advantages = [0.987, 0.654] + step = 42 + + print_prompt_completions_sample(prompts, completions, rewards, advantages, step) + + output = mock_stdout.getvalue() + + # docstyle-ignore + expected_output = textwrap.dedent("""\ + ╭────────────────────────────────── Step 42 ───────────────────────────────────╮ + │ ┏━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━━┓ │ + │ ┃ Prompt ┃ Completion ┃ Correctness ┃ Format ┃ Advantage ┃ │ + │ ┡━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━━┩ │ + │ │ USER │ TOOL │ 0.12 │ 0.79 │ 0.99 │ │ + │ │ What is the │ get_temperature(… │ │ │ │ │ + │ │ temperature in │ 'Paris'}) │ │ │ │ │ + │ │ Paris? │ │ │ │ │ │ + │ ├───────────────────┼───────────────────┼─────────────┼────────┼───────────┤ │ + │ │ USER │ TOOL │ 0.46 │ 0.10 │ 0.65 │ │ + │ │ What is the │ get_weather({'lo… │ │ │ │ │ + │ │ weather in │ 'London'}) │ │ │ │ │ + │ │ London? │ │ │ │ │ │ + │ └───────────────────┴───────────────────┴─────────────┴────────┴───────────┘ │ + ╰──────────────────────────────────────────────────────────────────────────────╯ + """) + + assert output == expected_output + + @patch("sys.stdout", new_callable=StringIO) + def test_print_messages_with_reasoning_content(self, mock_stdout): + prompts = [[{"role": "user", "content": "What color is the sky?"}]] + completions = [[{"role": "assistant", "reasoning_content": "I think it is blue.", "content": "It is blue."}]] + rewards = {"Score": [0.5]} + advantages = [0.9] + step = 1 + + print_prompt_completions_sample(prompts, completions, rewards, advantages, step) + + output = mock_stdout.getvalue() + + # docstyle-ignore + expected_output = textwrap.dedent("""\ + ╭─────────────────────────────── Step 1 ───────────────────────────────╮ + │ ┏━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━┓ │ + │ ┃ Prompt ┃ Completion ┃ Score ┃ Advantage ┃ │ + │ ┡━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━┩ │ + │ │ USER │ ASSISTANT │ 0.50 │ 0.90 │ │ + │ │ What color is the sky? │ I think it is blue. │ │ │ │ + │ │ │ It is blue. │ │ │ │ + │ └────────────────────────┴─────────────────────┴───────┴───────────┘ │ + ╰──────────────────────────────────────────────────────────────────────╯ + """) + + assert output == expected_output + + @patch("sys.stdout", new_callable=StringIO) + def test_print_messages_with_thinking(self, mock_stdout): + prompts = [[{"role": "user", "content": "What color is the sky?"}]] + completions = [[{"role": "assistant", "thinking": "I think it is blue.", "content": "It is blue."}]] + rewards = {"Score": [0.5]} + advantages = [0.9] + step = 1 + + print_prompt_completions_sample(prompts, completions, rewards, advantages, step) + + output = mock_stdout.getvalue() + + # docstyle-ignore + expected_output = textwrap.dedent("""\ + ╭─────────────────────────────── Step 1 ───────────────────────────────╮ + │ ┏━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━┓ │ + │ ┃ Prompt ┃ Completion ┃ Score ┃ Advantage ┃ │ + │ ┡━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━┩ │ + │ │ USER │ ASSISTANT │ 0.50 │ 0.90 │ │ + │ │ What color is the sky? │ I think it is blue. │ │ │ │ + │ │ │ It is blue. │ │ │ │ + │ └────────────────────────┴─────────────────────┴───────┴───────────┘ │ + ╰──────────────────────────────────────────────────────────────────────╯ + """) + + assert output == expected_output + + +class TestSelectiveLogSoftmax(TrlTestCase): + @pytest.mark.parametrize("dtype", [torch.float64, torch.float32, torch.float16, torch.bfloat16]) + def test_selective_log_softmax(self, dtype): + """Test selective_log_softmax with logits of different dtypes""" + vocab_size = 1024 + batch_size = 4 + seq_len = 32 + + input_ids = torch.randint(low=0, high=vocab_size, size=(batch_size, seq_len)) + logits = torch.randn(batch_size, seq_len, vocab_size, dtype=dtype) + + expected_output = torch.gather(logits.log_softmax(-1), dim=-1, index=input_ids.unsqueeze(-1)).squeeze(-1) + actual_output = selective_log_softmax(logits, input_ids) + + if dtype in [torch.float16, torch.bfloat16]: + # half-precision dtypes fall back to an exact method + assert torch.equal(actual_output, expected_output) + else: + torch.testing.assert_close(actual_output, expected_output, rtol=1e-5, atol=1e-5) + + @pytest.mark.parametrize("dtype", [torch.float64, torch.float32, torch.float16, torch.bfloat16]) + @pytest.mark.parametrize("k", [1, 8]) + def test_selective_log_softmax_multi_index(self, dtype, k): + """Test selective_log_softmax with logits of different dtypes and index widths""" + vocab_size = 1024 + batch_size = 4 + seq_len = 32 + + index = torch.randint(low=0, high=vocab_size, size=(batch_size, seq_len, k)) + logits = torch.randn(batch_size, seq_len, vocab_size, dtype=dtype) + + expected_output = torch.gather(logits.log_softmax(-1), dim=-1, index=index) + actual_output = selective_log_softmax(logits, index) + + assert actual_output.shape == (batch_size, seq_len, k) + if dtype in [torch.float16, torch.bfloat16]: + # half-precision dtypes fall back to an exact method + assert torch.equal(actual_output, expected_output) + else: + torch.testing.assert_close(actual_output, expected_output, rtol=1e-5, atol=1e-5) + + +class TestShuffleSequenceDict(TrlTestCase): + def test_shuffle_preserves_shape(self): + x = torch.arange(6).reshape(3, 2) + y = torch.arange(3).reshape(3, 1) + tensor_dict = {"x": x.clone(), "y": y.clone()} + + shuffled = shuffle_sequence_dict(tensor_dict) + + assert shuffled["x"].shape == x.shape + assert shuffled["y"].shape == y.shape + + def test_shuffle_consistent_across_tensors(self): + # Use known patterns to check alignment + x = torch.tensor([[10, 11], [20, 21], [30, 31]]) + y = torch.tensor([[1], [2], [3]]) + tensor_dict = {"x": x.clone(), "y": y.clone()} + + shuffled = shuffle_sequence_dict(tensor_dict) + + # Build a reverse map from shuffled x rows to y values + for i in range(3): + x_row = shuffled["x"][i] + y_val = shuffled["y"][i].item() + + if torch.equal(x_row, torch.tensor([10, 11])): + assert y_val == 1 + elif torch.equal(x_row, torch.tensor([20, 21])): + assert y_val == 2 + elif torch.equal(x_row, torch.tensor([30, 31])): + assert y_val == 3 + else: + pytest.fail("Unexpected x row in shuffled output.") + + def test_none_tensor_remains_none(self): + x = torch.arange(6).reshape(3, 2) + tensor_dict = {"x": x.clone(), "y": None} + + shuffled = shuffle_sequence_dict(tensor_dict) + + assert shuffled["y"] is None + assert shuffled["x"].shape == x.shape + + def test_shuffle_with_list(self): + x = torch.tensor([[10, 11], [20, 21], [30, 31]]) + y = ["a", "b", "c"] + + sequence_dict = {"x": x.clone(), "y": y} + + shuffled = shuffle_sequence_dict(sequence_dict) + + # Check that the list y is shuffled in the same order as x + for i in range(3): + x_row = shuffled["x"][i] + y_val = shuffled["y"][i] + + if torch.equal(x_row, torch.tensor([10, 11])): + assert y_val == "a" + elif torch.equal(x_row, torch.tensor([20, 21])): + assert y_val == "b" + elif torch.equal(x_row, torch.tensor([30, 31])): + assert y_val == "c" + else: + pytest.fail("Unexpected x row in shuffled output.") + + +class TestSplitTensorDict(TrlTestCase): + def test_split_equal_chunks(self): + x = torch.arange(12).reshape(6, 2) + y = torch.arange(6).reshape(6, 1) + tensor_dict = {"x": x, "y": y} + + result = split_tensor_dict(tensor_dict, 3) + + expected_x_chunks = torch.chunk(x, 3, dim=0) + expected_y_chunks = torch.chunk(y, 3, dim=0) + assert len(result) == 3 + for i in range(3): + assert torch.equal(result[i]["x"], expected_x_chunks[i]) + assert torch.equal(result[i]["y"], expected_y_chunks[i]) + + def test_with_none_tensor(self): + x = torch.arange(12).reshape(6, 2) + tensor_dict = {"x": x, "y": None} + + result = split_tensor_dict(tensor_dict, 2) + + expected_x_chunks = torch.chunk(x, 2, dim=0) + assert len(result) == 2 + for i in range(2): + assert torch.equal(result[i]["x"], expected_x_chunks[i]) + assert result[i]["y"] is None + + def test_with_scalar(self): + x = torch.arange(12).reshape(6, 2) + tensor_dict = {"x": x, "y": torch.tensor(1)} + + result = split_tensor_dict(tensor_dict, 2) + + expected_x_chunks = torch.chunk(x, 2, dim=0) + assert len(result) == 2 + for i in range(2): + assert torch.equal(result[i]["x"], expected_x_chunks[i]) + assert torch.equal(result[i]["y"], torch.tensor(1)) + + +class TestSplitPixelValuesByGrid(TrlTestCase): + def test_split_correctly_0(self): + batch = { + "image_grid_thw": torch.tensor([[1, 2, 2], [1, 2, 2]]), + "num_images": [1, 1], + "pixel_values": torch.arange(8 * 3).reshape(8, 3), # Shape: [8, 3] + } + result = split_pixel_values_by_grid(batch) + assert isinstance(result["pixel_values"], list) + assert len(result["pixel_values"]) == 2 + assert torch.equal(result["pixel_values"][0], batch["pixel_values"][:4]) + assert torch.equal(result["pixel_values"][1], batch["pixel_values"][4:]) + assert isinstance(result["image_grid_thw"], list) + assert len(result["image_grid_thw"]) == 2 + assert torch.equal(result["image_grid_thw"][0], torch.tensor([[1, 2, 2]])) + assert torch.equal(result["image_grid_thw"][1], torch.tensor([[1, 2, 2]])) + + def test_split_correctly_1(self): + batch = { + "image_grid_thw": torch.tensor([[1, 2, 2], [1, 2, 4]]), + "num_images": [1, 1], + "pixel_values": torch.arange(12 * 3).reshape(12, 3), # Shape: [12, 3] + } + result = split_pixel_values_by_grid(batch) + assert isinstance(result["pixel_values"], list) + assert len(result["pixel_values"]) == 2 + assert torch.equal(result["pixel_values"][0], batch["pixel_values"][:4]) + assert torch.equal(result["pixel_values"][1], batch["pixel_values"][4:12]) + assert isinstance(result["image_grid_thw"], list) + assert len(result["image_grid_thw"]) == 2 + assert torch.equal(result["image_grid_thw"][0], torch.tensor([[1, 2, 2]])) + assert torch.equal(result["image_grid_thw"][1], torch.tensor([[1, 2, 4]])) + + def test_missing_keys(self): + batch = {"pixel_values": torch.tensor([1.0])} + result = split_pixel_values_by_grid(batch) + assert result == batch + + def test_mismatched_length(self): + batch = { + "image_grid_thw": torch.tensor([[1, 1, 2], [1, 2, 1]]), # Total = 8 + "num_images": [1, 1], + "pixel_values": torch.randn(3, 5), # Only 3 rows + } + with pytest.raises(ValueError): + split_pixel_values_by_grid(batch) + + def test_multi_images(self): + batch = { + "image_grid_thw": torch.tensor([[1, 1, 2], [1, 2, 2], [1, 2, 1]]), # Total = 8 + "num_images": [1, 2], + "pixel_values": torch.arange(8 * 3).reshape(8, 3), # Shape: [8, 3] + } + result = split_pixel_values_by_grid(batch) + assert isinstance(result["pixel_values"], list) + assert len(result["pixel_values"]) == 2 + assert torch.equal(result["pixel_values"][0], batch["pixel_values"][:2]) + assert torch.equal(result["pixel_values"][1], batch["pixel_values"][2:]) + assert isinstance(result["image_grid_thw"], list) + assert len(result["image_grid_thw"]) == 2 + assert torch.equal(result["image_grid_thw"][0], torch.tensor([[1, 1, 2]])) + assert torch.equal(result["image_grid_thw"][1], torch.tensor([[1, 2, 2], [1, 2, 1]])) + + def test_split_by_image_position_ids(self): + # Gemma-style: no image_grid_thw, split by num_images using image_position_ids + batch = { + "num_images": [1, 2], + "pixel_values": torch.arange(3 * 4).reshape(3, 4), + "image_position_ids": torch.tensor([[0, 1], [2, 3], [4, 5]]), + } + result = split_pixel_values_by_grid(batch) + assert isinstance(result["pixel_values"], list) + assert len(result["pixel_values"]) == 2 + assert torch.equal(result["pixel_values"][0], batch["pixel_values"][:1]) + assert torch.equal(result["pixel_values"][1], batch["pixel_values"][1:]) + assert isinstance(result["image_position_ids"], list) + assert len(result["image_position_ids"]) == 2 + assert torch.equal(result["image_position_ids"][0], batch["image_position_ids"][:1]) + assert torch.equal(result["image_position_ids"][1], batch["image_position_ids"][1:]) + + +class TestUnsplitPixelValuesByGrid(TrlTestCase): + def test_unsplit_correctly(self): + pixel_values = [torch.randn(4, 5), torch.randn(2, 5)] + pixel_values_merged = torch.cat(pixel_values, dim=0) + image_grid_thw = [torch.tensor([[1, 2, 2]]), torch.tensor([[1, 2, 1]])] + image_grid_thw_merged = torch.cat(image_grid_thw, dim=0) + batch = {"pixel_values": pixel_values, "image_grid_thw": image_grid_thw, "other_key": torch.tensor([1])} + result = unsplit_pixel_values_by_grid(batch) + assert isinstance(result["pixel_values"], torch.Tensor) + torch.testing.assert_close(result["pixel_values"], pixel_values_merged) + assert isinstance(result["image_grid_thw"], torch.Tensor) + assert torch.equal(result["image_grid_thw"], image_grid_thw_merged) + assert "other_key" in result + + def test_unsplit_image_position_ids(self): + image_position_ids = [torch.tensor([[0, 1]]), torch.tensor([[2, 3], [4, 5]])] + image_position_ids_merged = torch.cat(image_position_ids, dim=0) + pixel_values = [torch.randn(1, 4), torch.randn(2, 4)] + batch = {"pixel_values": pixel_values, "image_position_ids": image_position_ids} + result = unsplit_pixel_values_by_grid(batch) + assert isinstance(result["image_position_ids"], torch.Tensor) + assert torch.equal(result["image_position_ids"], image_position_ids_merged) + + def test_no_op_if_not_list(self): + original = torch.randn(5, 3) + batch = {"pixel_values": original} + result = unsplit_pixel_values_by_grid(batch) + assert torch.equal(result["pixel_values"], original) + + +class TestChunkedLogProbFunction: + N, H, V = 64, 32, 128 + CHUNK_SIZE = 32 + + def _reference_logprobs_and_entropy(self, hidden, weight, labels, temperature): + logits = (hidden @ weight.t()).to(torch.float32) / temperature # [N, V] + log_p = F.log_softmax(logits, dim=-1) + logprobs = log_p.gather(-1, labels.unsqueeze(-1)).squeeze(-1) + p = torch.softmax(logits, dim=-1) + entropy = -(p * log_p).sum(dim=-1) + return logprobs, entropy + + @pytest.mark.parametrize("temperature", [1.0, 0.7]) + def test_forward(self, temperature): + torch.manual_seed(42) + hidden = torch.randn(self.N, self.H) + weight = torch.randn(self.V, self.H) + labels = torch.randint(0, self.V, (self.N,)) + + logprobs_chunked, entropy_chunked = _ChunkedLogProbFunction.apply( + hidden, weight, labels, temperature, self.CHUNK_SIZE + ) + logprobs_ref, entropy_ref = self._reference_logprobs_and_entropy(hidden, weight, labels, temperature) + + torch.testing.assert_close(logprobs_chunked, logprobs_ref, atol=1e-5, rtol=1e-5) + torch.testing.assert_close(entropy_chunked, entropy_ref, atol=1e-5, rtol=1e-5) + + @pytest.mark.parametrize("temperature", [1.0, 0.7]) + def test_backward(self, temperature): + torch.manual_seed(42) + hidden = torch.randn(self.N, self.H, requires_grad=True) + weight = torch.randn(self.V, self.H, requires_grad=True) + labels = torch.randint(0, self.V, (self.N,)) + + # Chunked backward + logprobs_chunked, _ = _ChunkedLogProbFunction.apply(hidden, weight, labels, temperature, self.CHUNK_SIZE) + logprobs_chunked.sum().backward() + grad_hidden_chunked = hidden.grad.clone() + grad_weight_chunked = weight.grad.clone() + + hidden.grad = None + weight.grad = None + + # Reference backward + logprobs_ref, _ = self._reference_logprobs_and_entropy(hidden, weight, labels, temperature) + logprobs_ref.sum().backward() + + torch.testing.assert_close(grad_hidden_chunked, hidden.grad, atol=1e-5, rtol=1e-5) + torch.testing.assert_close(grad_weight_chunked, weight.grad, atol=1e-5, rtol=1e-5) + + @pytest.mark.parametrize("temperature", [1.0, 0.7]) + def test_backward_bfloat16(self, temperature): + torch.manual_seed(42) + hidden = torch.randn(self.N, self.H, dtype=torch.bfloat16, requires_grad=True) + weight = torch.randn(self.V, self.H, dtype=torch.bfloat16, requires_grad=True) + labels = torch.randint(0, self.V, (self.N,)) + + # Chunked backward + logprobs_chunked, _ = _ChunkedLogProbFunction.apply(hidden, weight, labels, temperature, self.CHUNK_SIZE) + logprobs_chunked.sum().backward() + grad_hidden_chunked = hidden.grad.clone() + grad_weight_chunked = weight.grad.clone() + + hidden.grad = None + weight.grad = None + + # Reference backward + logprobs_ref, _ = self._reference_logprobs_and_entropy(hidden, weight, labels, temperature) + logprobs_ref.sum().backward() + + torch.testing.assert_close(grad_hidden_chunked, hidden.grad, atol=1e-2, rtol=1e-2) + torch.testing.assert_close(grad_weight_chunked, weight.grad, atol=1e-2, rtol=1e-2) + + +class _FakeTransformerModel(nn.Module): + """Minimal stand-in for a transformer body: returns random hidden states of the right shape.""" + + def __init__(self, hidden_size): + super().__init__() + self.hidden_size = hidden_size + self._hidden = None + + def forward(self, input_ids, attention_mask=None, use_cache=False, **kwargs): + b, s = input_ids.shape + if self._hidden is None or self._hidden.shape[:2] != (b, s): + torch.manual_seed(123) + self._hidden = torch.randn(b, s, self.hidden_size, requires_grad=True) + return type("Out", (), {"last_hidden_state": self._hidden})() + + +class _FakeCausalLM(nn.Module): + """Minimal CausalLM with .model and .lm_head, enough for patch_chunked_lm_head.""" + + def __init__(self, hidden_size, vocab_size): + super().__init__() + self.config = type("Config", (), {})() + self.model = _FakeTransformerModel(hidden_size) + self.lm_head = nn.Linear(hidden_size, vocab_size, bias=False) + + def forward(self, input_ids, attention_mask=None, labels=None, **kwargs): + raise NotImplementedError("should be monkey-patched") + + +_CHUNKED_LM_HEAD_MODEL_IDS = [ + "trl-internal-testing/tiny-CohereForCausalLM", + "trl-internal-testing/tiny-Cohere2ForCausalLM", + pytest.param( + "trl-internal-testing/tiny-DeepseekV3ForCausalLM", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.0.0"), + reason="DeepseekV3 SDPA attention is broken in transformers < 5.0.0", + ), + ), + pytest.param( + "trl-internal-testing/tiny-DeepseekV3ForCausalLM-0528", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.0.0"), + reason="DeepseekV3 SDPA attention is broken in transformers < 5.0.0", + ), + ), + "trl-internal-testing/tiny-Gemma2ForCausalLM", + "trl-internal-testing/tiny-GemmaForCausalLM", + "trl-internal-testing/tiny-Glm4MoeForCausalLM", + "trl-internal-testing/tiny-GptOssForCausalLM", + "trl-internal-testing/tiny-LlamaForCausalLM-3.1", + "trl-internal-testing/tiny-LlamaForCausalLM-3.2", + "trl-internal-testing/tiny-LlamaForCausalLM-3", + "trl-internal-testing/tiny-MistralForCausalLM-0.1", + "trl-internal-testing/tiny-MistralForCausalLM-0.2", + pytest.param( + "trl-internal-testing/tiny-NemotronHForCausalLM-nano", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("5.3.0"), + reason="Nemotron 3 was introduced in transformers>=5.3.0", + ), + ), + pytest.param( + "trl-internal-testing/tiny-Olmo3ForCausalLM", + marks=pytest.mark.skipif( + Version(transformers.__version__) < Version("4.57.0"), + reason="Olmo 3 was introduced in transformers>=4.57.0", + ), + ), + "trl-internal-testing/tiny-Phi3ForCausalLM-3", + "trl-internal-testing/tiny-Phi3ForCausalLM-3.5", + "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", + "trl-internal-testing/tiny-Qwen3ForCausalLM", + "trl-internal-testing/tiny-Qwen3ForCausalLM-Instruct-2507", +] + + +@require_torch_accelerator +class TestPatchChunkedLMHead: + B, S = 4, 16 # batch size, sequence length (including prompt + completion) + H, V = 32, 128 + CHUNK_SIZE = 32 + + def _build_model_and_inputs(self, temperature=1.0): + torch.manual_seed(42) + model = _FakeCausalLM(self.H, self.V) + patch_chunked_lm_head(model, self.CHUNK_SIZE, temperature) + + input_ids = torch.randint(0, self.V, (self.B, self.S)) + attention_mask = torch.ones(self.B, self.S, dtype=torch.long) + # First half of each sequence is prompt (0), second half is completion (1) + completion_mask = torch.zeros(self.B, self.S, dtype=torch.float32) + completion_mask[:, self.S // 2 :] = 1.0 + return model, input_ids, attention_mask, completion_mask + + @pytest.mark.parametrize("temperature", [1.0, 0.7]) + def test_dummy_model_chunked_forward_with_completion_mask(self, temperature): + """Masked forward matches unmasked forward at completion positions and is zero at prompt positions.""" + model, input_ids, attention_mask, completion_mask = self._build_model_and_inputs(temperature) + + # Run WITHOUT completion_mask (baseline — computes all positions) + out_full = model(input_ids=input_ids, attention_mask=attention_mask, labels=input_ids) + + # Reset hidden state cache so both runs use the same hidden states + model.model._hidden = None + + # Run WITH completion_mask + out_masked = model( + input_ids=input_ids, attention_mask=attention_mask, labels=input_ids, completion_mask=completion_mask + ) + + # shifted completion_mask (matching the shift in _chunked_forward) + shifted_mask = completion_mask[:, 1:].bool() + + # At completion positions, values should match + torch.testing.assert_close( + out_masked["log_probs"][shifted_mask], + out_full["log_probs"][shifted_mask], + atol=1e-5, + rtol=1e-5, + ) + torch.testing.assert_close( + out_masked["entropy"][shifted_mask], + out_full["entropy"][shifted_mask], + atol=1e-5, + rtol=1e-5, + ) + + # At prompt positions, values should be zero + prompt_mask = ~shifted_mask + assert (out_masked["log_probs"][prompt_mask] == 0).all() + assert (out_masked["entropy"][prompt_mask] == 0).all() + + @pytest.mark.parametrize("temperature", [1.0, 0.7]) + def test_dummy_model_chunked_forward_completion_mask_backward(self, temperature): + model, input_ids, attention_mask, completion_mask = self._build_model_and_inputs(temperature) + + # Full forward + backward (mask applied after, as the trainer does) + out_full = model(input_ids=input_ids, attention_mask=attention_mask, labels=input_ids) + shifted_mask = completion_mask[:, 1:] + loss_full = (out_full["log_probs"] * shifted_mask).sum() + loss_full.backward() + grad_weight_full = model.lm_head.weight.grad.clone() + + model.lm_head.weight.grad = None + model.model._hidden = None + + # Masked forward + backward + out_masked = model( + input_ids=input_ids, attention_mask=attention_mask, labels=input_ids, completion_mask=completion_mask + ) + loss_masked = (out_masked["log_probs"] * shifted_mask).sum() + loss_masked.backward() + grad_weight_masked = model.lm_head.weight.grad.clone() + + torch.testing.assert_close(grad_weight_masked, grad_weight_full, atol=1e-5, rtol=1e-5) + + @pytest.mark.parametrize("model_id", _CHUNKED_LM_HEAD_MODEL_IDS) + @pytest.mark.parametrize("temperature", [1.0, 0.7]) + def test_forward(self, model_id, temperature): + model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.bfloat16).to(torch_device) + model.eval() + + B, S, chunk_size = 2, 8, 32 + torch.manual_seed(42) + input_ids = torch.randint(0, model.config.vocab_size, (B, S), device=torch_device) + labels = input_ids.clone() + + # Reference: standard forward → shifted logits → logprobs & entropy + with torch.no_grad(): + ref_logits = model(input_ids=input_ids).logits[:, :-1, :].float() / temperature + shifted_labels = labels[:, 1:] + ref_log_p = F.log_softmax(ref_logits, dim=-1) + ref_logprobs = ref_log_p.gather(-1, shifted_labels.unsqueeze(-1)).squeeze(-1) + ref_p = ref_logits.softmax(dim=-1) + ref_entropy = -(ref_p * ref_log_p).sum(dim=-1) + + # Chunked forward + patch_chunked_lm_head(model, chunk_size, temperature) + with torch.no_grad(): + out = model(input_ids=input_ids, labels=labels) + + torch.testing.assert_close(out["log_probs"], ref_logprobs, atol=5e-3, rtol=5e-3) + torch.testing.assert_close(out["entropy"], ref_entropy, atol=5e-3, rtol=5e-3) + + @pytest.mark.parametrize("model_id", _CHUNKED_LM_HEAD_MODEL_IDS) + @pytest.mark.parametrize("temperature", [1.0, 0.7]) + def test_backward(self, model_id, temperature): + model_ref = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.bfloat16).to(torch_device) + model_chunked = copy.deepcopy(model_ref) + + B, S, chunk_size = 2, 8, 32 + torch.manual_seed(42) + input_ids = torch.randint(0, model_ref.config.vocab_size, (B, S), device=torch_device) + labels = input_ids.clone() + shifted_labels = labels[:, 1:] + + # Reference backward: standard logits → logprobs → backward + ref_logits = model_ref(input_ids=input_ids).logits[:, :-1, :].float() / temperature + ref_log_p = F.log_softmax(ref_logits, dim=-1) + ref_logprobs = ref_log_p.gather(-1, shifted_labels.unsqueeze(-1)).squeeze(-1) + ref_logprobs.sum().backward() + ref_grad = model_ref.lm_head.weight.grad.clone() + + # Chunked backward + patch_chunked_lm_head(model_chunked, chunk_size, temperature) + out = model_chunked(input_ids=input_ids, labels=labels) + out["log_probs"].sum().backward() + chunked_grad = model_chunked.lm_head.weight.grad.clone() + + torch.testing.assert_close(chunked_grad, ref_grad, atol=5e-2, rtol=5e-2) + + +class TestComputeFlopsPerToken(TrlTestCase): + DENSE_MODEL_ID = "trl-internal-testing/tiny-Qwen3ForCausalLM" + MOE_MODEL_ID = "trl-internal-testing/tiny-Qwen3MoeForCausalLM" + + def test_seq_scaling_linear(self): + # Attention-score FLOPs per token scale linearly with seq_len; everything else + # is seq-len-independent. Doubling seq_len should double the seq-dependent delta, + # which differences cancel out from. `F(32k) - F(16k) == 2 * (F(16k) - F(8k))`. + cfg = AutoConfig.from_pretrained(self.DENSE_MODEL_ID) + f_8k = compute_flops_per_token(cfg, 8192) + f_16k = compute_flops_per_token(cfg, 16384) + f_32k = compute_flops_per_token(cfg, 32768) + assert f_32k - f_16k == 2 * (f_16k - f_8k) + + def test_tied_vs_untied_lm_head(self): + # Untied lm_head adds `2 * V * h` forward FLOPs, ×3 for fwd+bwd. + cfg = AutoConfig.from_pretrained(self.DENSE_MODEL_ID) + cfg.tie_word_embeddings = True + f_tied = compute_flops_per_token(cfg, 16384) + cfg.tie_word_embeddings = False + f_untied = compute_flops_per_token(cfg, 16384) + expected_delta = 3 * 2 * cfg.vocab_size * cfg.hidden_size + assert f_untied - f_tied == expected_delta + + def test_moe_active_vs_total_experts(self): + # Doubling `num_experts_per_tok` (active experts) changes FLOPs by exactly the + # routed-experts contribution: `num_experts_per_tok × 3 matmuls × 2 × h × moe_intermediate` + # per MoE layer, ×3 for fwd+bwd. Holding `num_local_experts` constant pins the + # router term so the delta is purely the active-expert math. + cfg = AutoConfig.from_pretrained(self.MOE_MODEL_ID) + cfg.num_experts_per_tok = 1 + f_lo = compute_flops_per_token(cfg, 16384) + cfg.num_experts_per_tok = 2 + f_hi = compute_flops_per_token(cfg, 16384) + moe_layers = sum(1 for i in range(cfg.num_hidden_layers) if i % cfg.decoder_sparse_step == 0) + per_expert_per_layer = 2 * 3 * cfg.hidden_size * cfg.moe_intermediate_size + expected_delta = 3 * moe_layers * (2 - 1) * per_expert_per_layer + assert f_hi - f_lo == expected_delta + + +class TestComputeMfu(TrlTestCase): + def test_perfect_utilization(self): + # If aggregate TPS is exactly `peak * world_size / flops_per_token`, MFU is 100%. + flops = 100e9 + peak = 989.5e12 + world_size = 8 + tps = peak * world_size / flops + assert compute_mfu(flops, tps, world_size, peak_flops_per_device=peak) == pytest.approx(100.0) + + +class TestAdjustedMfu(TrlTestCase): + MOE_MODEL_ID = "trl-internal-testing/tiny-Qwen3MoeForCausalLM" + + def test_consistent_with_formula(self): + # `adjusted_mfu(mfu, cfg, seq_len) == mfu * (full - half_attn) / full`, with + # `full = compute_flops_per_token(cfg, seq_len)` and + # `half_attn = L * 3 * 2 * n_heads * head_dim * seq_len`. Cross-check the two helpers. + cfg = AutoConfig.from_pretrained(self.MOE_MODEL_ID) + seq_len = 16384 + flops_full = compute_flops_per_token(cfg, seq_len) + half_attn = cfg.num_hidden_layers * 3 * 2 * cfg.num_attention_heads * cfg.head_dim * seq_len + expected = 100.0 * (flops_full - half_attn) / flops_full + assert adjusted_mfu(100.0, cfg, seq_len) == pytest.approx(expected) + + def test_proportional_to_input(self): + # The correction is purely multiplicative in `mfu`. `adjusted_mfu(2*x, ...)` should + # equal `2 * adjusted_mfu(x, ...)`. + cfg = AutoConfig.from_pretrained(self.MOE_MODEL_ID) + a = adjusted_mfu(50.0, cfg, 16384) + b = adjusted_mfu(100.0, cfg, 16384) + assert b == pytest.approx(2 * a) + + def test_decreases_with_seq_len(self): + # Longer sequences → attention takes a larger share of total compute → causal + # correction subtracts a larger absolute amount → factor strictly decreases. + cfg = AutoConfig.from_pretrained(self.MOE_MODEL_ID) + f_short = adjusted_mfu(100.0, cfg, 4096) + f_med = adjusted_mfu(100.0, cfg, 16384) + f_long = adjusted_mfu(100.0, cfg, 65536) + assert f_short > f_med > f_long diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_vllm_client_server.py b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_vllm_client_server.py new file mode 100644 index 0000000000000000000000000000000000000000..820483a9d7e003316e2204b0e2ed8565495041a2 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_vllm_client_server.py @@ -0,0 +1,1036 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import subprocess +from types import SimpleNamespace + +import pytest +from packaging.version import Version +from transformers import AutoModelForCausalLM, AutoProcessor, AutoTokenizer +from transformers.testing_utils import torch_device + +from trl.generation.vllm_client import VLLMClient +from trl.generation.vllm_generation import extract_logprobs +from trl.import_utils import is_vllm_available +from trl.scripts.vllm_serve import chunk_list + +from .testing_utils import ( + TrlTestCase, + kill_process, + require_3_accelerators, + require_torch_multi_accelerator, + require_vision, + require_vllm, +) + + +if is_vllm_available(): + import vllm + from vllm import LLM, SamplingParams + + _is_vllm_ge_014 = Version(vllm.__version__) >= Version("0.14.0") +else: + _is_vllm_ge_014 = False + + +class TestChunkList(TrlTestCase): + def test_even_split(self): + assert chunk_list([1, 2, 3, 4, 5, 6], 2) == [[1, 2, 3], [4, 5, 6]] + + def test_uneven_split(self): + assert chunk_list([1, 2, 3, 4, 5, 6], 4) == [[1, 2], [3, 4], [5], [6]] + + def test_more_chunks_than_elements(self): + assert chunk_list([1, 2, 3, 4, 5, 6], 8) == [[1], [2], [3], [4], [5], [6], [], []] + + def test_n_equals_len(self): + assert chunk_list([1, 2, 3], 3) == [[1], [2], [3]] + + def test_n_is_1(self): + assert chunk_list([1, 2, 3], 1) == [[1, 2, 3]] + + def test_single_element_list(self): + assert chunk_list([42], 2) == [[42], []] + + def test_any_dtype(self): + assert chunk_list([1, "two", 3.0, {"four": 4}, ["f", "i", "v", "e"]], 2) == [ + [1, "two", 3.0], + [{"four": 4}, ["f", "i", "v", "e"]], + ] + + +class TestExtractLogprobs(TrlTestCase): + def test_extract_logprobs_sorts_by_rank_and_replaces_nan(self): + all_outputs = [ + SimpleNamespace( + outputs=[ + SimpleNamespace( + logprobs=[ + { + 11: SimpleNamespace(rank=1, logprob=-0.2), + 99: SimpleNamespace(rank=0, logprob=-0.1), + 42: SimpleNamespace(rank=2, logprob=float("nan")), + }, + { + 5: SimpleNamespace(rank=0, logprob=-1.1), + }, + ] + ) + ] + ), + SimpleNamespace( + outputs=[ + SimpleNamespace( + logprobs=[ + { + 3: SimpleNamespace(rank=1, logprob=-0.5), + 7: SimpleNamespace(rank=0, logprob=-0.4), + } + ] + ) + ] + ), + ] + + all_logprobs, all_token_ids = extract_logprobs(all_outputs) + + assert all_token_ids == [ + [[99, 11, 42], [5]], + [[7, 3]], + ] + assert all_logprobs == [ + [[-0.1, -0.2, None], [-1.1]], + [[-0.4, -0.5]], + ] + + def test_extract_logprobs_returns_none_token_ids_when_logprobs_missing(self): + all_outputs = [SimpleNamespace(outputs=[SimpleNamespace(logprobs=None)])] + + all_logprobs, all_token_ids = extract_logprobs(all_outputs) + + assert all_logprobs is None + assert all_token_ids is None + + +@pytest.mark.slow +@require_torch_multi_accelerator +@require_vllm +class TestVLLMClientServer(TrlTestCase): + model_id = "Qwen/Qwen2.5-1.5B" + + @classmethod + def setup_class(cls): + # We want the server to run on accelerator 1, so we set VISIBLE_DEVICES to "1" + env = os.environ.copy() + VISIBLE_DEVICES = "ZE_AFFINITY_MASK" if torch_device == "xpu" else "CUDA_VISIBLE_DEVICES" + env[VISIBLE_DEVICES] = "1" # Restrict to accelerator 1 + + # Start the server process + cls.server_process = subprocess.Popen( + ["trl", "vllm-serve", "--model", cls.model_id], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env + ) + + # Initialize the client + cls.client = VLLMClient(connection_timeout=240, host="localhost") + cls.client.init_communicator() + + def test_generate(self): + prompts = ["Hello, AI!", "Tell me a joke"] + outputs = self.client.generate(prompts) + prompt_ids = outputs["prompt_ids"] + completion_ids = outputs["completion_ids"] + + # Check that the outputs are lists + assert isinstance(prompt_ids, list) + assert isinstance(completion_ids, list) + + # Check that the number of sequences are equal to the number of prompts + assert len(prompt_ids) == len(prompts) + assert len(completion_ids) == len(prompts) + + # Check that the sequences are lists of integers + for seq in prompt_ids: + assert all(isinstance(tok, int) for tok in seq) + for seq in completion_ids: + assert all(isinstance(tok, int) for tok in seq) + + def test_generate_with_logprobs_none(self): + outputs = self.client.generate(["Hello, AI!"], logprobs=None) + + assert isinstance(outputs["prompt_ids"], list) + assert isinstance(outputs["completion_ids"], list) + assert outputs["logprobs"] is None + assert outputs["logprob_token_ids"] is None + + def test_chat(self): + messages = [[{"role": "user", "content": "Hello, AI!"}], [{"role": "user", "content": "Tell me a joke"}]] + outputs = self.client.chat(messages) + prompt_ids = outputs["prompt_ids"] + completion_ids = outputs["completion_ids"] + + # Check that the outputs are lists + assert isinstance(prompt_ids, list) + assert isinstance(completion_ids, list) + + # Check that the number of sequences are equal to the number of messages + assert len(prompt_ids) == len(messages) + assert len(completion_ids) == len(messages) + + # Check that the sequences are lists of integers + for seq in prompt_ids: + assert all(isinstance(tok, int) for tok in seq) + for seq in completion_ids: + assert all(isinstance(tok, int) for tok in seq) + + def test_chat_with_logprobs_none(self): + outputs = self.client.chat([[{"role": "user", "content": "Hello, AI!"}]], logprobs=None) + + assert isinstance(outputs["prompt_ids"], list) + assert isinstance(outputs["completion_ids"], list) + assert outputs["logprobs"] is None + assert outputs["logprob_token_ids"] is None + + def test_chat_with_tools(self): + def multiply(a: int, b: int) -> int: + """ + Multiplies two integers. + + Args: + a: The first integer. + b: The second integer. + + Returns: + The product of the two integers. + """ + return a * b + + messages = [[{"role": "user", "content": "What is 3 multiplied by 4?"}]] + outputs = self.client.chat(messages, tools=[multiply]) + + # Decode prompt and check that "Multiplies two integers." is in the prompt. + tokenizer = AutoTokenizer.from_pretrained(self.model_id) + decoded_prompt = tokenizer.decode(outputs["prompt_ids"][0]) + assert "Multiplies two integers." in decoded_prompt + + def test_generate_with_token_ids(self): + tokenizer = AutoTokenizer.from_pretrained(self.model_id) + prompts = ["Hello, AI!", "Tell me a joke"] + prompt_token_ids = tokenizer(prompts)["input_ids"] + outputs = self.client.generate(prompt_token_ids) + prompt_ids = outputs["prompt_ids"] + completion_ids = outputs["completion_ids"] + + # Check that the outputs are lists + assert isinstance(prompt_ids, list) + assert isinstance(completion_ids, list) + + # Check that the number of sequences are equal to the number of prompts + assert len(prompt_ids) == len(prompts) + assert len(completion_ids) == len(prompts) + + # Check that prompt_ids match the input token IDs + assert prompt_ids == prompt_token_ids + + # Check that the sequences are lists of integers + for seq in prompt_ids: + assert all(isinstance(tok, int) for tok in seq) + for seq in completion_ids: + assert all(isinstance(tok, int) for tok in seq) + + def test_generate_with_params(self): + prompts = ["Hello, AI!", "Tell me a joke"] + completion_ids = self.client.generate(prompts, n=2, repetition_penalty=0.9, temperature=0.8, max_tokens=32)[ + "completion_ids" + ] + + # Check that the output is a list + assert isinstance(completion_ids, list) + + # Check that the number of generated sequences is 2 times the number of prompts + assert len(completion_ids) == 2 * len(prompts) + + # Check that the generated sequences are lists of integers + for seq in completion_ids: + assert all(isinstance(tok, int) for tok in seq) + + # Check that the length of the generated sequences is less than or equal to 32 + for seq in completion_ids: + assert len(seq) <= 32 + + def test_update_model_params(self): + model = AutoModelForCausalLM.from_pretrained(self.model_id, device_map=torch_device) + self.client.update_model_params(model) + + def test_reset_prefix_cache(self): + # Test resetting the prefix cache + self.client.reset_prefix_cache() + + @pytest.mark.xfail(reason="Importing `bitsandbytes` causes issues, see vllm-project/vllm#32793") + def test_logprobs_match_with_non_default_sampling(self): + prompts = ["Hello, AI!", "Tell me a joke"] + # Use non-default sampling parameters (especially temperature) to ensure vLLM applies logprob processing. With + # default sampling, raw and processed logprobs are identical, so mismatches would not be detected. + temperature = 0.7 + repetition_penalty = 1.05 + top_p = 0.9 + max_tokens = 8 + seed = 1234 + num_logprobs = 5 + + server_outputs = self.client.generate( + prompts, + temperature=temperature, + repetition_penalty=repetition_penalty, + top_p=top_p, + max_tokens=max_tokens, + logprobs=num_logprobs, + generation_kwargs={"seed": seed}, + ) + os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn" + llm = LLM( + model=self.model_id, + tensor_parallel_size=1, + gpu_memory_utilization=0.2, + max_model_len=128, + logprobs_mode="processed_logprobs", + ) + + sampling_params = SamplingParams( + temperature=temperature, + repetition_penalty=repetition_penalty, + top_p=top_p, + max_tokens=max_tokens, + logprobs=num_logprobs, + seed=seed, + ) + colocate_outputs = llm.generate(prompts, sampling_params=sampling_params, use_tqdm=False) + colocate_prompt_ids = [output.prompt_token_ids for output in colocate_outputs] + colocate_completion_ids = [ + list(output.token_ids) for outputs in colocate_outputs for output in outputs.outputs + ] + colocate_logprobs, colocate_logprob_token_ids = extract_logprobs(colocate_outputs) + + # Generation correctness: prompt and completion IDs match between server and colocate + assert server_outputs["prompt_ids"] == colocate_prompt_ids + assert server_outputs["completion_ids"] == colocate_completion_ids + + server_logprobs = server_outputs["logprobs"] + server_logprob_token_ids = server_outputs["logprob_token_ids"] + + # Shape: both should be (num_sequences, seq_len, num_logprobs) with multiple logprobs per token + assert len(server_logprobs) == len(prompts) + assert len(server_logprob_token_ids) == len(prompts) + for seq_lps in server_logprobs: + for token_lps in seq_lps: + assert len(token_lps) > 1, "Expected multiple logprobs per token when logprobs > 0" + + # Value correctness: server extraction matches colocate extraction via extract_logprobs + assert server_logprob_token_ids == colocate_logprob_token_ids + for server_seq, colocate_seq in zip(server_logprobs, colocate_logprobs, strict=True): + assert len(server_seq) == len(colocate_seq) + for server_token_lps, colocate_token_lps in zip(server_seq, colocate_seq, strict=True): + assert server_token_lps == pytest.approx(colocate_token_lps, rel=1e-6, abs=1e-6) + + # Ordering: logprobs at each position should be sorted descending + for seq_lps in server_logprobs: + for token_lps in seq_lps: + assert token_lps == sorted(token_lps, reverse=True), "Logprobs should be sorted descending" + + # Sampled token presence: the actual completion token should appear in the logprob token IDs + for seq_idx, (completion_seq, token_ids_seq) in enumerate( + zip(server_outputs["completion_ids"], server_logprob_token_ids, strict=True) + ): + for pos, (sampled_id, lp_ids) in enumerate(zip(completion_seq, token_ids_seq, strict=True)): + assert sampled_id in lp_ids, ( + f"Sampled token {sampled_id} not found in logprob token IDs {lp_ids} " + f"at sequence {seq_idx}, position {pos}" + ) + + @classmethod + def teardown_class(cls): + # Close the client + cls.client.close_communicator() + + # vLLM x pytest (or Popen) seems not to handle process termination well. To avoid zombie processes, we need to + # kill the server process and its children explicitly. + kill_process(cls.server_process) + + +# Same as above but using base_url to instantiate the client. +@pytest.mark.slow +@require_torch_multi_accelerator +@require_vllm +class TestVLLMClientServerBaseURL(TrlTestCase): + model_id = "Qwen/Qwen2.5-1.5B" + + @classmethod + def setup_class(cls): + # We want the server to run on accelerator 1, so we set VISIBLE_DEVICES to "1" + env = os.environ.copy() + VISIBLE_DEVICES = "ZE_AFFINITY_MASK" if torch_device == "xpu" else "CUDA_VISIBLE_DEVICES" + env[VISIBLE_DEVICES] = "1" # Restrict to accelerator 1 + + # Start the server process + cls.server_process = subprocess.Popen( + ["trl", "vllm-serve", "--model", cls.model_id], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env + ) + + # Initialize the client + cls.client = VLLMClient(base_url="http://localhost:8000", connection_timeout=240) + cls.client.init_communicator() + + def test_generate(self): + prompts = ["Hello, AI!", "Tell me a joke"] + outputs = self.client.generate(prompts) + prompt_ids = outputs["prompt_ids"] + completion_ids = outputs["completion_ids"] + + # Check that the outputs are lists + assert isinstance(prompt_ids, list) + assert isinstance(completion_ids, list) + + # Check that the number of sequences are equal to the number of prompts + assert len(prompt_ids) == len(prompts) + assert len(completion_ids) == len(prompts) + + # Check that the sequences are lists of integers + for seq in prompt_ids: + assert all(isinstance(tok, int) for tok in seq) + for seq in completion_ids: + assert all(isinstance(tok, int) for tok in seq) + + def test_generate_with_logprobs_none(self): + outputs = self.client.generate(["Hello, AI!"], logprobs=None) + + assert isinstance(outputs["prompt_ids"], list) + assert isinstance(outputs["completion_ids"], list) + assert outputs["logprobs"] is None + assert outputs["logprob_token_ids"] is None + + def test_chat(self): + messages = [[{"role": "user", "content": "Hello, AI!"}], [{"role": "user", "content": "Tell me a joke"}]] + outputs = self.client.chat(messages) + prompt_ids = outputs["prompt_ids"] + completion_ids = outputs["completion_ids"] + + # Check that the outputs are lists + assert isinstance(prompt_ids, list) + assert isinstance(completion_ids, list) + + # Check that the number of sequences are equal to the number of messages + assert len(prompt_ids) == len(messages) + assert len(completion_ids) == len(messages) + + # Check that the sequences are lists of integers + for seq in prompt_ids: + assert all(isinstance(tok, int) for tok in seq) + for seq in completion_ids: + assert all(isinstance(tok, int) for tok in seq) + + def test_chat_with_logprobs_none(self): + outputs = self.client.chat([[{"role": "user", "content": "Hello, AI!"}]], logprobs=None) + + assert isinstance(outputs["prompt_ids"], list) + assert isinstance(outputs["completion_ids"], list) + assert outputs["logprobs"] is None + assert outputs["logprob_token_ids"] is None + + def test_chat_with_tools(self): + def multiply(a: int, b: int) -> int: + """ + Multiplies two integers. + + Args: + a: The first integer. + b: The second integer. + + Returns: + The product of the two integers. + """ + return a * b + + messages = [[{"role": "user", "content": "What is 3 multiplied by 4?"}]] + outputs = self.client.chat(messages, tools=[multiply]) + + # Decode prompt and check that "Multiplies two integers." is in the prompt. + tokenizer = AutoTokenizer.from_pretrained(self.model_id) + decoded_prompt = tokenizer.decode(outputs["prompt_ids"][0]) + assert "Multiplies two integers." in decoded_prompt + + def test_generate_with_token_ids(self): + tokenizer = AutoTokenizer.from_pretrained(self.model_id) + prompts = ["Hello, AI!", "Tell me a joke"] + prompt_token_ids = tokenizer(prompts)["input_ids"] + outputs = self.client.generate(prompt_token_ids) + prompt_ids = outputs["prompt_ids"] + completion_ids = outputs["completion_ids"] + + # Check that the outputs are lists + assert isinstance(prompt_ids, list) + assert isinstance(completion_ids, list) + + # Check that the number of sequences are equal to the number of prompts + assert len(prompt_ids) == len(prompts) + assert len(completion_ids) == len(prompts) + + # Check that prompt_ids match the input token IDs + assert prompt_ids == prompt_token_ids + + # Check that the sequences are lists of integers + for seq in prompt_ids: + assert all(isinstance(tok, int) for tok in seq) + for seq in completion_ids: + assert all(isinstance(tok, int) for tok in seq) + + def test_generate_with_params(self): + prompts = ["Hello, AI!", "Tell me a joke"] + completion_ids = self.client.generate(prompts, n=2, repetition_penalty=0.9, temperature=0.8, max_tokens=32)[ + "completion_ids" + ] + + # Check that the output is a list + assert isinstance(completion_ids, list) + + # Check that the number of generated sequences is 2 times the number of prompts + assert len(completion_ids) == 2 * len(prompts) + + # Check that the generated sequences are lists of integers + for seq in completion_ids: + assert all(isinstance(tok, int) for tok in seq) + + # Check that the length of the generated sequences is less than or equal to 32 + for seq in completion_ids: + assert len(seq) <= 32 + + def test_update_model_params(self): + model = AutoModelForCausalLM.from_pretrained(self.model_id, device_map=torch_device) + self.client.update_model_params(model) + + def test_reset_prefix_cache(self): + # Test resetting the prefix cache + self.client.reset_prefix_cache() + + @classmethod + def teardown_class(cls): + # Close the client + cls.client.close_communicator() + + # vLLM x pytest (or Popen) seems not to handle process termination well. To avoid zombie processes, we need to + # kill the server process and its children explicitly. + kill_process(cls.server_process) + + +@pytest.mark.slow +@require_3_accelerators +@require_vllm +class TestVLLMClientServerTP(TrlTestCase): + model_id = "Qwen/Qwen2.5-1.5B" + + @classmethod + def setup_class(cls): + # We want the server to run on accelerator 1 and 2, so we set VISIBLE_DEVICES to "1,2" + env = os.environ.copy() + VISIBLE_DEVICES = "ZE_AFFINITY_MASK" if torch_device == "xpu" else "CUDA_VISIBLE_DEVICES" + env[VISIBLE_DEVICES] = "1,2" # Restrict to accelerator 1 and 2 + + # Start the server process + cls.server_process = subprocess.Popen( + ["trl", "vllm-serve", "--model", cls.model_id, "--tensor_parallel_size", "2"], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + env=env, + ) + + # Initialize the client + cls.client = VLLMClient(connection_timeout=240, host="localhost") + cls.client.init_communicator() + + def test_generate(self): + prompts = ["Hello, AI!", "Tell me a joke"] + outputs = self.client.generate(prompts) + prompt_ids = outputs["prompt_ids"] + completion_ids = outputs["completion_ids"] + + # Check that the outputs are lists + assert isinstance(prompt_ids, list) + assert isinstance(completion_ids, list) + + # Check that the number of sequences are equal to the number of prompts + assert len(prompt_ids) == len(prompts) + assert len(completion_ids) == len(prompts) + + # Check that the sequences are lists of integers + for seq in prompt_ids: + assert all(isinstance(tok, int) for tok in seq) + for seq in completion_ids: + assert all(isinstance(tok, int) for tok in seq) + + def test_generate_with_logprobs_none(self): + outputs = self.client.generate(["Hello, AI!"], logprobs=None) + + assert isinstance(outputs["prompt_ids"], list) + assert isinstance(outputs["completion_ids"], list) + assert outputs["logprobs"] is None + assert outputs["logprob_token_ids"] is None + + def test_chat(self): + messages = [[{"role": "user", "content": "Hello, AI!"}], [{"role": "user", "content": "Tell me a joke"}]] + outputs = self.client.chat(messages) + prompt_ids = outputs["prompt_ids"] + completion_ids = outputs["completion_ids"] + + # Check that the outputs are lists + assert isinstance(prompt_ids, list) + assert isinstance(completion_ids, list) + + # Check that the number of sequences are equal to the number of messages + assert len(prompt_ids) == len(messages) + assert len(completion_ids) == len(messages) + + # Check that the sequences are lists of integers + for seq in prompt_ids: + assert all(isinstance(tok, int) for tok in seq) + for seq in completion_ids: + assert all(isinstance(tok, int) for tok in seq) + + def test_chat_with_logprobs_none(self): + outputs = self.client.chat([[{"role": "user", "content": "Hello, AI!"}]], logprobs=None) + + assert isinstance(outputs["prompt_ids"], list) + assert isinstance(outputs["completion_ids"], list) + assert outputs["logprobs"] is None + assert outputs["logprob_token_ids"] is None + + def test_chat_with_tools(self): + def multiply(a: int, b: int) -> int: + """ + Multiplies two integers. + + Args: + a: The first integer. + b: The second integer. + + Returns: + The product of the two integers. + """ + return a * b + + messages = [[{"role": "user", "content": "What is 3 multiplied by 4?"}]] + outputs = self.client.chat(messages, tools=[multiply]) + + # Decode prompt and check that "Multiplies two integers." is in the prompt. + tokenizer = AutoTokenizer.from_pretrained(self.model_id) + decoded_prompt = tokenizer.decode(outputs["prompt_ids"][0]) + assert "Multiplies two integers." in decoded_prompt + + def test_generate_with_token_ids(self): + tokenizer = AutoTokenizer.from_pretrained(self.model_id) + prompts = ["Hello, AI!", "Tell me a joke"] + prompt_token_ids = tokenizer(prompts)["input_ids"] + outputs = self.client.generate(prompt_token_ids) + prompt_ids = outputs["prompt_ids"] + completion_ids = outputs["completion_ids"] + + # Check that the outputs are lists + assert isinstance(prompt_ids, list) + assert isinstance(completion_ids, list) + + # Check that the number of sequences are equal to the number of prompts + assert len(prompt_ids) == len(prompts) + assert len(completion_ids) == len(prompts) + + # Check that prompt_ids match the input token IDs + assert prompt_ids == prompt_token_ids + + # Check that the sequences are lists of integers + for seq in prompt_ids: + assert all(isinstance(tok, int) for tok in seq) + for seq in completion_ids: + assert all(isinstance(tok, int) for tok in seq) + + def test_generate_with_params(self): + prompts = ["Hello, AI!", "Tell me a joke"] + completion_ids = self.client.generate(prompts, n=2, repetition_penalty=0.9, temperature=0.8, max_tokens=32)[ + "completion_ids" + ] + + # Check that the output is a list + assert isinstance(completion_ids, list) + + # Check that the number of generated sequences is 2 times the number of prompts + assert len(completion_ids) == 2 * len(prompts) + + # Check that the generated sequences are lists of integers + for seq in completion_ids: + assert all(isinstance(tok, int) for tok in seq) + + # Check that the length of the generated sequences is less than or equal to 32 + for seq in completion_ids: + assert len(seq) <= 32 + + def test_update_model_params(self): + model = AutoModelForCausalLM.from_pretrained(self.model_id, device_map=torch_device) + self.client.update_model_params(model) + + def test_reset_prefix_cache(self): + # Test resetting the prefix cache + self.client.reset_prefix_cache() + + @classmethod + def teardown_class(cls): + # Close the client + cls.client.close_communicator() + + # vLLM x pytest (or Popen) seems not to handle process termination well. To avoid zombie processes, we need to + # kill the server process and its children explicitly. + kill_process(cls.server_process) + + +@pytest.mark.slow +@pytest.mark.skipif( + _is_vllm_ge_014, + reason="Skipping DP server test for vLLM>=0.14.0 (PR vllm#30739: DP for non-MoE/dense models no longer supported).", +) +@require_3_accelerators +@require_vllm +class TestVLLMClientServerDP(TrlTestCase): + model_id = "Qwen/Qwen2.5-1.5B" + + @classmethod + def setup_class(cls): + # We want the server to run on accelerator 1 and 2, so we set VISIBLE_DEVICES to "1,2" + env = os.environ.copy() + VISIBLE_DEVICES = "ZE_AFFINITY_MASK" if torch_device == "xpu" else "CUDA_VISIBLE_DEVICES" + env[VISIBLE_DEVICES] = "1,2" # Restrict to accelerator 1 and 2 + + # Start the server process + cls.server_process = subprocess.Popen( + ["trl", "vllm-serve", "--model", cls.model_id, "--data_parallel_size", "2"], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + env=env, + ) + + # Initialize the client + cls.client = VLLMClient(connection_timeout=240, host="localhost") + cls.client.init_communicator() + + def test_generate(self): + prompts = ["Hello, AI!", "Tell me a joke"] + outputs = self.client.generate(prompts) + prompt_ids = outputs["prompt_ids"] + completion_ids = outputs["completion_ids"] + + # Check that the outputs are lists + assert isinstance(prompt_ids, list) + assert isinstance(completion_ids, list) + + # Check that the number of sequences are equal to the number of prompts + assert len(prompt_ids) == len(prompts) + assert len(completion_ids) == len(prompts) + + # Check that the sequences are lists of integers + for seq in prompt_ids: + assert all(isinstance(tok, int) for tok in seq) + for seq in completion_ids: + assert all(isinstance(tok, int) for tok in seq) + + def test_generate_with_logprobs_none(self): + outputs = self.client.generate(["Hello, AI!"], logprobs=None) + + assert isinstance(outputs["prompt_ids"], list) + assert isinstance(outputs["completion_ids"], list) + assert outputs["logprobs"] is None + assert outputs["logprob_token_ids"] is None + + def test_chat(self): + messages = [[{"role": "user", "content": "Hello, AI!"}], [{"role": "user", "content": "Tell me a joke"}]] + outputs = self.client.chat(messages) + prompt_ids = outputs["prompt_ids"] + completion_ids = outputs["completion_ids"] + + # Check that the outputs are lists + assert isinstance(prompt_ids, list) + assert isinstance(completion_ids, list) + + # Check that the number of sequences are equal to the number of messages + assert len(prompt_ids) == len(messages) + assert len(completion_ids) == len(messages) + + # Check that the sequences are lists of integers + for seq in prompt_ids: + assert all(isinstance(tok, int) for tok in seq) + for seq in completion_ids: + assert all(isinstance(tok, int) for tok in seq) + + def test_chat_with_logprobs_none(self): + outputs = self.client.chat([[{"role": "user", "content": "Hello, AI!"}]], logprobs=None) + + assert isinstance(outputs["prompt_ids"], list) + assert isinstance(outputs["completion_ids"], list) + assert outputs["logprobs"] is None + assert outputs["logprob_token_ids"] is None + + def test_chat_with_tools(self): + def multiply(a: int, b: int) -> int: + """ + Multiplies two integers. + + Args: + a: The first integer. + b: The second integer. + + Returns: + The product of the two integers. + """ + return a * b + + messages = [[{"role": "user", "content": "What is 3 multiplied by 4?"}]] + outputs = self.client.chat(messages, tools=[multiply]) + + # Decode prompt and check that "Multiplies two integers." is in the prompt. + tokenizer = AutoTokenizer.from_pretrained(self.model_id) + decoded_prompt = tokenizer.decode(outputs["prompt_ids"][0]) + assert "Multiplies two integers." in decoded_prompt + + def test_generate_with_token_ids(self): + tokenizer = AutoTokenizer.from_pretrained(self.model_id) + prompts = ["Hello, AI!", "Tell me a joke"] + prompt_token_ids = tokenizer(prompts)["input_ids"] + outputs = self.client.generate(prompt_token_ids) + prompt_ids = outputs["prompt_ids"] + completion_ids = outputs["completion_ids"] + + # Check that the outputs are lists + assert isinstance(prompt_ids, list) + assert isinstance(completion_ids, list) + + # Check that the number of sequences are equal to the number of prompts + assert len(prompt_ids) == len(prompts) + assert len(completion_ids) == len(prompts) + + # Check that prompt_ids match the input token IDs + assert prompt_ids == prompt_token_ids + + # Check that the sequences are lists of integers + for seq in prompt_ids: + assert all(isinstance(tok, int) for tok in seq) + for seq in completion_ids: + assert all(isinstance(tok, int) for tok in seq) + + def test_generate_with_params(self): + prompts = ["Hello, AI!", "Tell me a joke"] + completion_ids = self.client.generate(prompts, n=2, repetition_penalty=0.9, temperature=0.8, max_tokens=32)[ + "completion_ids" + ] + + # Check that the output is a list + assert isinstance(completion_ids, list) + + # Check that the number of generated sequences is 2 times the number of prompts + assert len(completion_ids) == 2 * len(prompts) + + # Check that the generated sequences are lists of integers + for seq in completion_ids: + assert all(isinstance(tok, int) for tok in seq) + + # Check that the length of the generated sequences is less than or equal to 32 + for seq in completion_ids: + assert len(seq) <= 32 + + def test_update_model_params(self): + model = AutoModelForCausalLM.from_pretrained(self.model_id, device_map=torch_device) + self.client.update_model_params(model) + + def test_reset_prefix_cache(self): + # Test resetting the prefix cache + self.client.reset_prefix_cache() + + @classmethod + def teardown_class(cls): + # Close the client + cls.client.close_communicator() + + # vLLM x pytest (or Popen) seems not to handle process termination well. To avoid zombie processes, we need to + # kill the server process and its children explicitly. + kill_process(cls.server_process) + + +@pytest.mark.slow +@require_torch_multi_accelerator +@require_vllm +class TestVLLMClientServerDeviceParameter(TrlTestCase): + """Test the device parameter functionality in init_communicator.""" + + model_id = "Qwen/Qwen2.5-1.5B" + + @classmethod + def setup_class(cls): + # We want the server to run on accelerator 1, so we set VISIBLE_DEVICES to "1" + env = os.environ.copy() + VISIBLE_DEVICES = "ZE_AFFINITY_MASK" if torch_device == "xpu" else "CUDA_VISIBLE_DEVICES" + env[VISIBLE_DEVICES] = "1" # Restrict to accelerator 1 + + # Start the server process + cls.server_process = subprocess.Popen( + ["trl", "vllm-serve", "--model", cls.model_id], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env + ) + + def test_init_communicator_with_device_int(self): + """Test init_communicator with integer device parameter.""" + client = VLLMClient(connection_timeout=240, host="localhost") + client.init_communicator(device=0) # Explicitly specify device 0 + + # Test basic functionality + prompts = ["Hello, AI!"] + outputs = client.generate(prompts) + prompt_ids = outputs["prompt_ids"] + completion_ids = outputs["completion_ids"] + assert isinstance(prompt_ids, list) + assert len(prompt_ids) == len(prompts) + assert isinstance(completion_ids, list) + assert len(completion_ids) == len(prompts) + + client.close_communicator() + + def test_init_communicator_with_device_string(self): + """Test init_communicator with string device parameter.""" + client = VLLMClient(connection_timeout=240, host="localhost") + client.init_communicator(device=0) # Explicitly specify device as string + + # Test basic functionality + prompts = ["Hello, AI!"] + outputs = client.generate(prompts)["completion_ids"] + assert isinstance(outputs, list) + assert len(outputs) == len(prompts) + + client.close_communicator() + + def test_init_communicator_with_torch_device(self): + """Test init_communicator with torch.device object.""" + import torch + + client = VLLMClient(connection_timeout=240, host="localhost") + device = torch.device(0) + client.init_communicator(device=device) # Explicitly specify torch.device object + + # Test basic functionality + prompts = ["Hello, AI!"] + outputs = client.generate(prompts)["completion_ids"] + assert isinstance(outputs, list) + assert len(outputs) == len(prompts) + + client.close_communicator() + + @classmethod + def teardown_class(cls): + # vLLM x pytest (or Popen) seems not to handle process termination well. To avoid zombie processes, we need to + # kill the server process and its children explicitly. + kill_process(cls.server_process) + + +@pytest.mark.slow +@require_vllm +@require_vision +class TestVLLMClientServerVLM(TrlTestCase): + model_id = "Qwen/Qwen2.5-VL-3B-Instruct" + + @classmethod + def setup_class(cls): + # Start the server process + cls.server_process = subprocess.Popen( + ["trl", "vllm-serve", "--model", cls.model_id], stdout=subprocess.PIPE, stderr=subprocess.PIPE + ) + + # Initialize the client (no communicator needed for generation-only tests) + cls.client = VLLMClient(connection_timeout=240, host="localhost") + + def test_generate_with_token_ids_and_image(self): + from PIL import Image + + processor = AutoProcessor.from_pretrained(self.model_id) + image1 = Image.new("RGB", (64, 64), color="red") + image2 = Image.new("RGB", (64, 64), color="blue") + image3 = Image.new("RGB", (64, 64), color="green") + messages = [ + [ + { + "role": "user", + "content": [ + {"type": "image", "image": image1}, + {"type": "image", "image": image2}, + {"type": "text", "text": "What are the differences between these two images?"}, + ], + } + ], + [ + { + "role": "user", + "content": [ + {"type": "image", "image": image3}, + {"type": "text", "text": "What is the color of this image?"}, + ], + } + ], + ] + prompt_token_ids = processor.apply_chat_template( + conversation=messages, tokenize=True, add_generation_prompt=True + ) + outputs = self.client.generate(prompt_token_ids, images=[[image1, image2], [image3]], max_tokens=64) + prompt_ids = outputs["prompt_ids"] + completion_ids = outputs["completion_ids"] + + assert len(prompt_ids) == 2 + assert len(completion_ids) == 2 + assert all(isinstance(tok, int) for tok in prompt_ids[0]) + assert all(isinstance(tok, int) for tok in completion_ids[0]) + + def test_generate_with_token_ids_mixed_images(self): + """Test a batch where one prompt has an image and the other does not.""" + from PIL import Image + + processor = AutoProcessor.from_pretrained(self.model_id) + image = Image.new("RGB", (64, 64), color="red") + messages = [ + [ + { + "role": "user", + "content": [{"type": "image", "image": image}, {"type": "text", "text": "Describe this image."}], + } + ], + [ + { + "role": "user", + "content": [{"type": "text", "text": "What is 1+1?"}], + } + ], + ] + prompt_token_ids = processor.apply_chat_template( + conversation=messages, tokenize=True, add_generation_prompt=True + ) + outputs = self.client.generate(prompt_token_ids, images=[[image], None], max_tokens=64) + prompt_ids = outputs["prompt_ids"] + completion_ids = outputs["completion_ids"] + + assert len(prompt_ids) == 2 + assert len(completion_ids) == 2 + assert all(isinstance(tok, int) for tok in prompt_ids[0]) + assert all(isinstance(tok, int) for tok in prompt_ids[1]) + assert all(isinstance(tok, int) for tok in completion_ids[0]) + assert all(isinstance(tok, int) for tok in completion_ids[1]) + + @classmethod + def teardown_class(cls): + kill_process(cls.server_process) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/tests/testing_constants.py b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/testing_constants.py new file mode 100644 index 0000000000000000000000000000000000000000..7589117c85a06be131489b8a7b905f2162b3c14d --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/testing_constants.py @@ -0,0 +1,18 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +CI_HUB_USER = "__DUMMY_TRANSFORMERS_USER__" +CI_HUB_USER_FULL_NAME = "Dummy User" + +CI_HUB_ENDPOINT = "https://hub-ci.huggingface.co" diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/tests/testing_utils.py b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/testing_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..cbb91cfe0cdfc1b4cb21a563207bda9b0bb8b05d --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/tests/testing_utils.py @@ -0,0 +1,148 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import functools +import signal +import warnings +from collections.abc import Callable + +import psutil +import pytest +import torch +from transformers import is_bitsandbytes_available, is_comet_available, is_sklearn_available, is_wandb_available +from transformers.testing_utils import backend_device_count, torch_device +from transformers.utils import ( + is_kernels_available, + is_peft_available, + is_rich_available, + is_torch_available, + is_vision_available, +) + +from trl.import_utils import ( + is_jmespath_available, + is_joblib_available, + is_liger_kernel_available, + is_math_verify_available, + is_mergekit_available, + is_openreward_available, + is_vllm_available, +) + + +require_bitsandbytes = pytest.mark.skipif(not is_bitsandbytes_available(), reason="test requires bitsandbytes") +require_comet = pytest.mark.skipif(not is_comet_available(), reason="test requires comet_ml") +require_jmespath = pytest.mark.skipif(not is_jmespath_available(), reason="test requires jmespath") +require_kernels = pytest.mark.skipif(not is_kernels_available(), reason="test requires kernels") +require_liger_kernel = pytest.mark.skipif(not is_liger_kernel_available(), reason="test requires liger-kernel") +require_math_latex = pytest.mark.skipif(not is_math_verify_available(), reason="test requires math_verify") +require_mergekit = pytest.mark.skipif(not is_mergekit_available(), reason="test requires mergekit") +require_openreward = pytest.mark.skipif(not is_openreward_available(), reason="test requires openreward") +require_peft = pytest.mark.skipif(not is_peft_available(), reason="test requires peft") +require_rich = pytest.mark.skipif(not is_rich_available(), reason="test requires rich") +require_sklearn = pytest.mark.skipif( + not (is_sklearn_available() and is_joblib_available()), reason="test requires sklearn" +) +require_torch_accelerator = pytest.mark.skipif( + torch_device is None or torch_device == "cpu", reason="test requires accelerator" +) +require_torch_multi_accelerator = pytest.mark.skipif( + not is_torch_available() or backend_device_count(torch_device) <= 1, reason="test requires multiple accelerators" +) +require_vision = pytest.mark.skipif(not is_vision_available(), reason="test requires vision") +require_vllm = pytest.mark.skipif(not is_vllm_available(), reason="test requires vllm") +require_wandb = pytest.mark.skipif(not is_wandb_available(), reason="test requires wandb") +require_no_wandb = pytest.mark.skipif(is_wandb_available(), reason="test requires no wandb") +require_3_accelerators = pytest.mark.skipif( + not (getattr(torch, torch_device, torch.cuda).device_count() >= 3), + reason=f"test requires at least 3 {torch_device}s", +) + + +def is_bitsandbytes_multi_backend_available() -> bool: + if is_bitsandbytes_available(): + import bitsandbytes as bnb + + return "multi_backend" in getattr(bnb, "features", set()) + return False + + +# Function ported from transformers.testing_utils before transformers#41283 +require_torch_gpu_if_bnb_not_multi_backend_enabled = pytest.mark.skipif( + not is_bitsandbytes_multi_backend_available() and not torch_device == "cuda", + reason="test requires bitsandbytes multi-backend enabled or 'cuda' torch device", +) + + +def is_ampere_or_newer(device_index=0): + if not torch.cuda.is_available(): + return False + + # "Ampere" is an NVIDIA architecture; an AMD (ROCm) GPU is never Ampere. On ROCm, + # torch.cuda.get_device_capability returns the gfx version, which would spuriously compare >= (8, 0). + if torch.version.hip is not None: + return False + + major, minor = torch.cuda.get_device_capability(device_index) + # Ampere starts at compute capability 8.0 (e.g., A100 = 8.0, RTX 30xx = 8.6) + return (major, minor) >= (8, 0) + + +class TrlTestCase: + @pytest.fixture(autouse=True) + def set_tmp_dir(self, tmp_path): + self.tmp_dir = str(tmp_path) + + +def ignore_warnings(message: str = None, category: type[Warning] = Warning) -> Callable: + """ + Decorator to ignore warnings with a specific message and/or category. + + Args: + message (`str`, *optional*): + Regex pattern for the warning message to ignore. If `None`, all messages are ignored. + category (`type[Warning]`, *optional*, defaults to `Warning`): + Warning class to ignore. Defaults to `Warning`, which ignores all warnings. + """ + + def decorator(test_func): + @functools.wraps(test_func) + def wrapper(*args, **kwargs): + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", message=message, category=category) + return test_func(*args, **kwargs) + + return wrapper + + return decorator + + +def kill_process(process): + parent = psutil.Process(process.pid) + children = parent.children(recursive=True) + for child in children: + try: + child.send_signal(signal.SIGTERM) + child.wait(timeout=5) + except psutil.TimeoutExpired: + child.kill() + except psutil.NoSuchProcess: + pass + try: + process.terminate() + process.wait(timeout=5) + except psutil.TimeoutExpired: + process.kill() + except psutil.NoSuchProcess: + pass diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4947fc16c56e7abf1de978619b878bde579c9d15 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/__init__.py @@ -0,0 +1,132 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import sys +from importlib.metadata import PackageNotFoundError, version +from typing import TYPE_CHECKING + +from . import _compat +from ._lazy_module import _LazyModule + + +try: + __version__ = version("trl") +except PackageNotFoundError: + __version__ = "unknown" + +_import_structure = { + "chat_template_utils": [ + "add_response_schema", + "clone_chat_template", + "get_training_chat_template", + "supports_tool_calling", + ], + "data_utils": [ + "apply_chat_template", + "extract_prompt", + "is_conversational", + "is_conversational_from_value", + "maybe_apply_chat_template", + "maybe_convert_to_chatml", + "maybe_extract_prompt", + "maybe_unpair_preference_dataset", + "pack_dataset", + "prepare_multimodal_messages", + "prepare_multimodal_messages_vllm", + "unpair_preference_dataset", + ], + "models": ["create_reference_model"], + "scripts": ["DatasetMixtureConfig", "ScriptArguments", "TrlParser", "get_dataset", "init_zero_verbose"], + "trainer": [ + "BEMACallback", + "DPOConfig", + "DPOTrainer", + "GRPOConfig", + "GRPOTrainer", + "KTOConfig", + "KTOTrainer", + "LogCompletionsCallback", + "ModelConfig", + "RewardConfig", + "RewardTrainer", + "RichProgressCallback", + "RLOOConfig", + "RLOOTrainer", + "SFTConfig", + "SFTTrainer", + "SyncRefModelCallback", + "WeaveCallback", + "get_kbit_device_map", + "get_peft_config", + "get_quantization_config", + ], +} + +if TYPE_CHECKING: + from .chat_template_utils import ( + add_response_schema, + clone_chat_template, + get_training_chat_template, + supports_tool_calling, + ) + from .data_utils import ( + apply_chat_template, + extract_prompt, + is_conversational, + is_conversational_from_value, + maybe_apply_chat_template, + maybe_convert_to_chatml, + maybe_extract_prompt, + maybe_unpair_preference_dataset, + pack_dataset, + prepare_multimodal_messages, + prepare_multimodal_messages_vllm, + unpair_preference_dataset, + ) + from .models import create_reference_model + from .scripts import DatasetMixtureConfig, ScriptArguments, TrlParser, get_dataset, init_zero_verbose + from .trainer import ( + BEMACallback, + DPOConfig, + DPOTrainer, + GRPOConfig, + GRPOTrainer, + KTOConfig, + KTOTrainer, + LogCompletionsCallback, + ModelConfig, + RewardConfig, + RewardTrainer, + RichProgressCallback, + RLOOConfig, + RLOOTrainer, + SFTConfig, + SFTTrainer, + SyncRefModelCallback, + WeaveCallback, + get_kbit_device_map, + get_peft_config, + get_quantization_config, + ) + +else: + import sys + + sys.modules[__name__] = _LazyModule( + __name__, + globals()["__file__"], + _import_structure, + module_spec=__spec__, + extra_objects={"__version__": __version__}, + ) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/_compat.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..31086a2e912cc9926e3fab7d2a8045fa5421c49d --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/_compat.py @@ -0,0 +1,164 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Compatibility shims for third-party dependencies. + +This module contains temporary patches to handle version incompatibilities between TRL's dependencies. + +Each patch should be removed when minimum version requirements eliminate the need. +""" + +import warnings + +from packaging.version import Version + +from .import_utils import _is_package_available + + +def _is_package_version_below(package_name: str, version_threshold: str) -> bool: + """ + Check if installed package version is below the given threshold. + + Args: + package_name (str): Package name. + version_threshold (str): Maximum version threshold. + + Returns: + - True if package is installed and version < version_threshold. + - False if package is not installed or version >= version_threshold. + """ + try: + is_available, version = _is_package_available(package_name, return_version=True) + return is_available and Version(version) < Version(version_threshold) + except Exception as e: + warnings.warn( + f"Failed to check {package_name} version against {version_threshold}: {e}. " + f"Compatibility patch may not be applied.", + stacklevel=2, + ) + return False + + +def _is_package_version_at_least(package_name: str, version_threshold: str) -> bool: + """ + Check if installed package version is at least the given threshold. + + Args: + package_name (str): Package name. + version_threshold (str): Minimum version threshold. + + Returns: + - True if package is installed and version >= version_threshold. + - False if package is not installed or version < version_threshold. + """ + try: + is_available, version = _is_package_available(package_name, return_version=True) + return is_available and Version(version) >= Version(version_threshold) + except Exception as e: + warnings.warn( + f"Failed to check {package_name} version against {version_threshold}: {e}. " + f"Compatibility patch may not be applied.", + stacklevel=2, + ) + return False + + +def _patch_vllm_logging() -> None: + """Set vLLM logging level to ERROR by default to reduce noise.""" + if _is_package_available("vllm"): + import os + + os.environ["VLLM_LOGGING_LEVEL"] = os.getenv("VLLM_LOGGING_LEVEL", "ERROR") + + +def _patch_transformers_hybrid_cache() -> None: + """ + Fix HybridCache import for transformers v5 compatibility. + + - Issue: peft import HybridCache from transformers.cache_utils + - HybridCache removed in https://github.com/huggingface/transformers/pull/43168 (transformers>=5.0.0) + - Fixed in peft: https://github.com/huggingface/peft/pull/2735 (released in v0.18.0) + - This can be removed when TRL requires peft>=0.18.0 + """ + if _is_package_version_at_least("transformers", "5.0.0") and _is_package_version_below("peft", "0.18.0"): + try: + import transformers.cache_utils + from transformers.utils.import_utils import _LazyModule + + Cache = transformers.cache_utils.Cache + + # Patch for liger_kernel: Add HybridCache as an alias for Cache in the cache_utils module + transformers.cache_utils.HybridCache = Cache + + # Patch for peft: Patch _LazyModule.__init__ to add HybridCache to transformers' lazy loading structures + _original_lazy_module_init = _LazyModule.__init__ + + def _patched_lazy_module_init(self, name, *args, **kwargs): + _original_lazy_module_init(self, name, *args, **kwargs) + if name == "transformers": + # Update _LazyModule's internal structures + if hasattr(self, "_import_structure") and "cache_utils" in self._import_structure: + if "HybridCache" not in self._import_structure["cache_utils"]: + self._import_structure["cache_utils"].append("HybridCache") + + if hasattr(self, "_class_to_module"): + self._class_to_module["HybridCache"] = "cache_utils" + + if hasattr(self, "__all__") and "HybridCache" not in self.__all__: + self.__all__.append("HybridCache") + + self.HybridCache = Cache + + _LazyModule.__init__ = _patched_lazy_module_init + + except Exception as e: + warnings.warn(f"Failed to patch transformers HybridCache compatibility: {e}", stacklevel=2) + + +def _patch_transformers_parallelism_config() -> None: + """ + Fix ParallelismConfig for transformers compatibility. + + Ensure that ``transformers.training_args`` always defines the symbol `ParallelismConfig` so that Python's + `typing.get_type_hints` can resolve annotations on `transformers.TrainingArguments` without raising a `NameError`. + + This is needed when running with ``accelerate<1.10.1``, where the module ``accelerate.parallelism_config`` did not + exist and therefore the type alias is not imported by Transformers. + + See upstream fix PR in transformers#40818. + + - Issue: transformers imports ParallelismConfig only if accelerate>=1.10.1 and raises NameError if + accelerate<1.10.1 + - Fixed in transformers: https://github.com/huggingface/transformers/pull/40818 (released in v4.57.0) + - This can be removed when TRL requires transformers>=4.57.0 or accelerate>=1.10.1 + """ + if _is_package_version_below("transformers", "4.57.0") and _is_package_version_below("accelerate", "1.10.1"): + try: + from typing import Any + + import transformers.training_args + + if not hasattr(transformers.training_args, "ParallelismConfig"): + transformers.training_args.ParallelismConfig = Any + except Exception as e: + warnings.warn(f"Failed to patch transformers ParallelismConfig compatibility: {e}", stacklevel=2) + + +# Apply vLLM patches +_patch_vllm_logging() + +# Apply transformers patches +_patch_transformers_hybrid_cache() +_patch_transformers_parallelism_config() # before creating HfArgumentParser diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/_lazy_module.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/_lazy_module.py new file mode 100644 index 0000000000000000000000000000000000000000..d030f00df1fdb0fc1f4c136393ea6ce06bb72669 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/_lazy_module.py @@ -0,0 +1,79 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import importlib +import os +from itertools import chain +from types import ModuleType +from typing import Any + + +class _LazyModule(ModuleType): + """ + Module class that surfaces all objects but only performs associated imports when the objects are requested. + """ + + # Very heavily inspired by optuna.integration._IntegrationModule + # https://github.com/optuna/optuna/blob/master/optuna/integration/__init__.py + def __init__(self, name, module_file, import_structure, module_spec=None, extra_objects=None): + super().__init__(name) + self._modules = set(import_structure.keys()) + self._class_to_module = {} + for key, values in import_structure.items(): + for value in values: + self._class_to_module[value] = key + # Needed for autocompletion in an IDE + self.__all__ = list(import_structure.keys()) + list(chain(*import_structure.values())) + self.__file__ = module_file + self.__spec__ = module_spec + self.__path__ = [os.path.dirname(module_file)] + self._objects = {} if extra_objects is None else extra_objects + self._name = name + self._import_structure = import_structure + + # Needed for autocompletion in an IDE + def __dir__(self): + result = super().__dir__() + # The elements of self.__all__ that are submodules may or may not be in the dir already, depending on whether + # they have been accessed or not. So we only add the elements of self.__all__ that are not already in the dir. + for attr in self.__all__: + if attr not in result: + result.append(attr) + return result + + def __getattr__(self, name: str) -> Any: + if name in self._objects: + return self._objects[name] + if name in self._modules: + value = self._get_module(name) + elif name in self._class_to_module.keys(): + module = self._get_module(self._class_to_module[name]) + value = getattr(module, name) + else: + raise AttributeError(f"module {self.__name__} has no attribute {name}") + + setattr(self, name, value) + return value + + def _get_module(self, module_name: str): + try: + return importlib.import_module("." + module_name, self.__name__) + except Exception as e: + raise RuntimeError( + f"Failed to import {self.__name__}.{module_name} because of the following error (look up to see its" + f" traceback):\n{e}" + ) from e + + def __reduce__(self): + return (self.__class__, (self._name, self.__file__, self._import_structure)) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/fsdp1.yaml b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/fsdp1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c01b0b567bc93bf87ec136ea975b3793d273a45c --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/fsdp1.yaml @@ -0,0 +1,28 @@ +compute_environment: LOCAL_MACHINE +debug: false +distributed_type: FSDP +downcast_bf16: 'no' +enable_cpu_affinity: false +fsdp_config: + fsdp_activation_checkpointing: false + fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP + fsdp_backward_prefetch: BACKWARD_PRE + fsdp_cpu_ram_efficient_loading: true + fsdp_forward_prefetch: true + fsdp_offload_params: false + fsdp_reshard_after_forward: FULL_SHARD + fsdp_state_dict_type: FULL_STATE_DICT + fsdp_sync_module_states: true + fsdp_use_orig_params: true + fsdp_version: 1 +machine_rank: 0 +main_training_function: main +mixed_precision: bf16 +num_machines: 1 +num_processes: 8 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/fsdp2.yaml b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/fsdp2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..af498f3eced9c2434b80113f2f22d40395e0ab8a --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/fsdp2.yaml @@ -0,0 +1,25 @@ +# Requires accelerate 1.7.0 or higher +compute_environment: LOCAL_MACHINE +debug: false +distributed_type: FSDP +downcast_bf16: 'no' +enable_cpu_affinity: false +fsdp_config: + fsdp_activation_checkpointing: false + fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP + fsdp_cpu_ram_efficient_loading: true + fsdp_offload_params: false + fsdp_reshard_after_forward: true + fsdp_state_dict_type: FULL_STATE_DICT + fsdp_version: 2 +machine_rank: 0 +main_training_function: main +mixed_precision: bf16 +num_machines: 1 +num_processes: 8 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/multi_gpu.yaml b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/multi_gpu.yaml new file mode 100644 index 0000000000000000000000000000000000000000..15dad9be3ba44f7c934e1ecab98a93cb83cbc79a --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/multi_gpu.yaml @@ -0,0 +1,16 @@ +compute_environment: LOCAL_MACHINE +debug: false +distributed_type: MULTI_GPU +downcast_bf16: 'no' +gpu_ids: all +machine_rank: 0 +main_training_function: main +mixed_precision: 'bf16' +num_machines: 1 +num_processes: 8 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/single_gpu.yaml b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/single_gpu.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ebd00a067118e56f3d63ab0f24827cfea21b24b9 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/single_gpu.yaml @@ -0,0 +1,16 @@ +compute_environment: LOCAL_MACHINE +debug: false +distributed_type: "NO" +downcast_bf16: 'no' +gpu_ids: all +machine_rank: 0 +main_training_function: main +mixed_precision: 'bf16' +num_machines: 1 +num_processes: 8 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/zero1.yaml b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/zero1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d5b5f782fb30f9fcbcc8fc58262f09eaf2e10368 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/zero1.yaml @@ -0,0 +1,20 @@ +compute_environment: LOCAL_MACHINE +debug: false +deepspeed_config: + deepspeed_multinode_launcher: standard + gradient_accumulation_steps: 1 + zero3_init_flag: false + zero_stage: 1 +distributed_type: DEEPSPEED +downcast_bf16: 'no' +machine_rank: 0 +main_training_function: main +mixed_precision: 'bf16' +num_machines: 1 +num_processes: 8 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/zero2.yaml b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/zero2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..239b14ac3a9ae8de73122d1154bf0d71903dc15f --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/zero2.yaml @@ -0,0 +1,21 @@ +compute_environment: LOCAL_MACHINE +debug: false +deepspeed_config: + deepspeed_multinode_launcher: standard + offload_optimizer_device: none + offload_param_device: none + zero3_init_flag: false + zero_stage: 2 +distributed_type: DEEPSPEED +downcast_bf16: 'no' +machine_rank: 0 +main_training_function: main +mixed_precision: 'bf16' +num_machines: 1 +num_processes: 8 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/zero3.yaml b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/zero3.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b5a1201f8a2ee8706b63f0f80c664a1fc61a7d9d --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/zero3.yaml @@ -0,0 +1,22 @@ +compute_environment: LOCAL_MACHINE +debug: false +deepspeed_config: + deepspeed_multinode_launcher: standard + offload_optimizer_device: none + offload_param_device: none + zero3_init_flag: true + zero3_save_16bit_model: true + zero_stage: 3 +distributed_type: DEEPSPEED +downcast_bf16: 'no' +machine_rank: 0 +main_training_function: main +mixed_precision: bf16 +num_machines: 1 +num_processes: 8 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_template_utils.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_template_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..05b3188fb3efa9707dd74cbf035a1904910592e2 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_template_utils.py @@ -0,0 +1,939 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import re +import warnings +from pathlib import Path +from typing import TypeVar + +from jinja2 import TemplateError +from transformers import AddedToken, AutoTokenizer, PreTrainedModel, PreTrainedTokenizerBase, ProcessorMixin + +from .data_utils import prepare_multimodal_messages + + +_CHAT_TEMPLATES_DIR = Path(__file__).parent / "chat_templates" + + +def has_generation_markers(chat_template: str) -> bool: + """ + Check whether the chat template defines `{% generation %}` markers, accounting for whitespace-trim variants such as + `{%- generation %}` and `{%- generation -%}`. + """ + return re.search(r"\{%-?\s*generation\s*-?%\}", chat_template) is not None + + +def clone_chat_template( + model: PreTrainedModel, + tokenizer: PreTrainedTokenizerBase, + source_tokenizer_path: str, + resize_to_multiple_of: int | None = 64, +) -> tuple[PreTrainedModel, PreTrainedTokenizerBase, list[int]]: + """ + Clones a chat template from a source tokenizer to the target tokenizer and updates the model accordingly. + + This function: + - Copies the chat template from a source tokenizer to the target tokenizer. + - Adds any new tokens from the source tokenizer to the target tokenizer. + - Sets and synchronizes the EOS token across the tokenizer and model. + - Resizes the model's token embeddings to match the new vocabulary size, optionally rounding it up to a multiple of + a specified value. In such cases, dummy tokens are added to the tokenizer to ensure the vocabulary size matches + the embedding dimensions. + + Args: + model ([`~transformers.PreTrainedModel`]): + Model to update. + tokenizer ([`~transformers.PreTrainedTokenizerBase`]): + Tokenizer to update. + source_tokenizer_path (`str`): + Path or identifier of the pretrained tokenizer to clone from. + resize_to_multiple_of (`int` or `None`, *optional*, defaults to `64`): + The embedding layer will be resized to the new vocabulary size. If this is not `None`, it will round up the + new vocabulary size to the nearest multiple of this value. + + Returns: + model ([`~transformers.PreTrainedModel`]): + Updated model with resized token embeddings and EOS token configured. + tokenizer ([`~transformers.PreTrainedTokenizerBase`]): + Updated tokenizer with the chat template and special tokens applied. + added_tokens (`list[int]`): + List of tokens that were added to the tokenizer from the source tokenizer. + + Example: + ```python + from transformers import AutoModelForCausalLM, AutoTokenizer + from trl import clone_chat_template + + model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.2-1B") + tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.2-1B") + model, tokenizer, added_tokens = clone_chat_template(model, tokenizer, "Qwen/Qwen3-0.6B") + ``` + """ + # Load the source tokenizer containing the desired chat template + tokenizer_source = AutoTokenizer.from_pretrained(source_tokenizer_path) + + # Copy the chat template from the source tokenizer + tokenizer.chat_template = tokenizer_source.get_chat_template() + + # Ensure all added tokens from the source are available in the target tokenizer + added_tokens = [ + token for token in tokenizer_source.added_tokens_decoder.values() if token.content not in tokenizer.vocab + ] + tokenizer.add_tokens(added_tokens) + + # Set the EOS token from the source tokenizer (important for generation) + tokenizer.eos_token = tokenizer_source.eos_token + model.config.eos_token_id = tokenizer.eos_token_id + if model.can_generate(): # Non-generative models (e.g. SequenceClassification) may not have a generation_config + model.generation_config.eos_token_id = tokenizer.eos_token_id + + # Resize model embeddings to include any new tokens, optionally rounding up to a multiple + model.resize_token_embeddings( + # After studying many tokenizers, we found that len(tokenizer.vocab) is the most reliable way to get the vocab + # size. Avoid using tokenizer.vocab_size or tokenizer.vocab_size + len(tokenizer.added_tokens_encoder), + # as handling of special and added tokens varies across tokenizers. + new_num_tokens=len(tokenizer.vocab), + pad_to_multiple_of=resize_to_multiple_of if resize_to_multiple_of is not None else None, + ) + + # After resizing, the embedding matrix size may exceed the vocabulary size. Add dummy tokens to the tokenizer to + # ensure vocabulary size matches the embedding matrix dimensions. + idx = 0 + while model.vocab_size > len(tokenizer.vocab): + dummy_token = AddedToken(f"") + is_added = tokenizer.add_tokens(dummy_token) + idx += 1 + if is_added == 1: + added_tokens.append(dummy_token) + + # Verify that vocabulary size now matches embedding dimensions + if len(tokenizer.vocab) != model.vocab_size: + raise RuntimeError( + f"Vocabulary size mismatch after resizing: tokenizer vocab size is {len(tokenizer.vocab)}, but model " + f"embedding size is {model.vocab_size}. This indicates an internal error in the token alignment process." + ) + added_tokens = [token.content for token in added_tokens] + added_tokens = tokenizer.convert_tokens_to_ids(added_tokens) + return model, tokenizer, added_tokens + + +glm4moe_schema = { + "x-regex": r"^(?:\n?\n?(?:(?P.*?\S.*?)\n?|[\s]*)\s*)?(?P(?:(?!)[\s\S])*?)(?:\n(?=))?(?=(?:|$))(?P(?:(?:(?!)[\s\S])+\s*)+)?$", + "type": "object", + "properties": { + "role": {"const": "assistant"}, + "content": {"type": "string"}, + "reasoning_content": {"type": "string"}, + "tool_calls": { + "type": "array", + "x-regex-iterator": r"\s*(.+?)\s*", + "items": { + "type": "object", + "properties": { + "type": {"const": "function"}, + "function": { + "type": "object", + "properties": { + "name": {"type": "string", "x-regex": r"^(\S+)"}, + "arguments": { + "type": "object", + "x-regex-key-value": r"(?P[^<]+)\s*\n(?P.*?)", + "default": {}, + "additionalProperties": { + "x-parser": "json", + "x-parser-args": {"allow_non_json": True}, + }, + }, + }, + }, + }, + }, + }, + }, +} + +gptoss_schema = { + # Normalize final content to analysis format so both map to the same "content" group. + "x-regex-substitutions": [ + [r"<\|channel\|>final<\|message\|>(.*?)<\|return\|>", r"<|channel|>analysis<|message|>\1<|end|>"], + ], + "x-regex": r"^(?:<\|channel\|>analysis<\|message\|>(?P.*?)<\|end\|>(?:<\|start\|>assistant)?)?\s*(?Pto=functions\.\S+<\|channel\|>commentary json<\|message\|>.*?<\|call\|>)?$", + "type": "object", + "properties": { + "role": {"const": "assistant"}, + "content": {"type": "string"}, + "tool_calls": { + "type": "array", + "x-regex-iterator": r"(to=functions\.\S+<\|channel\|>commentary json<\|message\|>.*?<\|call\|>)", + "items": { + # Convert "to=functions.NAME<|channel|>commentary json<|message|>ARGS<|call|>" + # into '{"name": "NAME", "arguments": ARGS}' so it can be parsed as JSON. + "x-regex-substitutions": [ + [ + r"to=functions\.(\S+)<\|channel\|>commentary json<\|message\|>(.*?)<\|call\|>", + r'{"name": "\1", "arguments": \2}', + ], + ], + "x-parser": "json", + "x-parser-args": {"transform": "{type: 'function', function: @}"}, + "type": "object", + "properties": { + "type": {"const": "function"}, + "function": { + "type": "object", + "properties": { + "name": {"type": "string"}, + "arguments": { + "type": "object", + "additionalProperties": {}, + }, + }, + }, + }, + }, + }, + }, +} + +# Adapted and corrected versions of the schemas from: +# https://github.com/huggingface/transformers/blob/main/tests/utils/test_chat_parsing_utils.py +qwen3_schema = { + "x-regex": r"^(?:\n?(?:(?P.*?\S.*?)\n?|[\s]*)\s*)?(?P(?:(?!)[\s\S])*?)(?:\n(?=))?(?=(?:|<\|im_end\|>|$))(?P(?:(?:(?!)[\s\S])+\s*)+)?\s*(?:<\|im_end\|>|$)", + "type": "object", + "properties": { + "role": {"const": "assistant"}, + "content": {"type": "string"}, + "reasoning_content": {"type": "string"}, + "tool_calls": { + "type": "array", + "x-regex-iterator": r"\s*(.+?)\s*", + "items": { + "x-parser": "json", + "x-parser-args": {"transform": "{type: 'function', function: @}"}, + "type": "object", + "properties": { + "type": {"const": "function"}, + "function": { + "type": "object", + "properties": { + "name": {"type": "string"}, + "arguments": { + "type": "object", + "additionalProperties": {}, + }, + }, + }, + }, + }, + }, + }, +} + +llama3_schema = { + # Llama 3.1 / 3.2 render a tool call as a single bare JSON object using the key "parameters" instead of + # "arguments": `{"name": "", "parameters": }<|eot_id|>`. There is no surrounding marker, no + # support for content alongside a tool call, and at most one tool call per assistant turn (the template raises + # otherwise). Either we match a tool call (capturing the JSON) or we treat the response as plain content. + "x-regex": r'^(?:(?P\{"name":\s*".+?",\s*"parameters":\s*.+\})|(?P.*?))(?:<\|eot_id\|>|$)', + "type": "object", + "properties": { + "role": {"const": "assistant"}, + "content": {"type": "string"}, + "tool_calls": { + "type": "array", + "x-regex-iterator": r'(\{"name":\s*".+?",\s*"parameters":\s*.+\})', + "items": { + # Rewrite "parameters" → "arguments" so the JSON parses into the standard tool-call shape. Anchored + # on the leading `{"name": "..."` so a stray `"parameters"` inside argument values is not touched. + "x-regex-substitutions": [ + [r'^(\{"name":\s*"[^"]+",\s*)"parameters":', r'\1"arguments":'], + ], + "x-parser": "json", + "x-parser-args": {"transform": "{type: 'function', function: @}"}, + "type": "object", + "properties": { + "type": {"const": "function"}, + "function": { + "type": "object", + "properties": { + "name": {"type": "string"}, + "arguments": { + "type": "object", + "additionalProperties": {}, + }, + }, + }, + }, + }, + }, + }, +} + +qwen3_5_schema = { + "x-regex": r"^(?:(?:\n?)?(?:(?P.*?\S.*?)\n?|[\s]*)\s*)?(?P(?:(?!)[\s\S])*?)(?:\n+(?=))?(?=(?:|<\|im_end\|>|$))(?P(?:(?:(?!)[\s\S])+\s*)+)?\s*(?:<\|im_end\|>|$)", + "type": "object", + "properties": { + "role": {"const": "assistant"}, + "content": {"type": "string"}, + "reasoning_content": {"type": "string"}, + "tool_calls": { + "type": "array", + "x-regex-iterator": r"\s*(.+?)\s*", + "items": { + "type": "object", + "properties": { + "type": {"const": "function"}, + "function": { + "type": "object", + "properties": { + "name": {"type": "string", "x-regex": r"]+)>"}, + "arguments": { + "type": "object", + "x-regex-key-value": r"[^>\n]+)>\n(?P.*?)\n", + "default": {}, + "additionalProperties": { + "x-parser": "json", + "x-parser-args": {"allow_non_json": True}, + }, + }, + }, + }, + }, + }, + }, + }, +} + + +cohere_chat_template = (_CHAT_TEMPLATES_DIR / "cohere.jinja").read_text(encoding="utf-8") + +cohere2_chat_template = (_CHAT_TEMPLATES_DIR / "cohere2.jinja").read_text(encoding="utf-8") + +deepseekv3_chat_template = (_CHAT_TEMPLATES_DIR / "deepseekv3.jinja").read_text(encoding="utf-8") + +gemma_chat_template = (_CHAT_TEMPLATES_DIR / "gemma.jinja").read_text(encoding="utf-8") + +gemma3_chat_template = (_CHAT_TEMPLATES_DIR / "gemma3.jinja").read_text(encoding="utf-8") + +glm4moe_chat_template = (_CHAT_TEMPLATES_DIR / "glm4moe.jinja").read_text(encoding="utf-8") + +gptoss_chat_template = (_CHAT_TEMPLATES_DIR / "gptoss.jinja").read_text(encoding="utf-8") + +llama3_chat_template = (_CHAT_TEMPLATES_DIR / "llama3.jinja").read_text(encoding="utf-8") + +llama3_1_chat_template = (_CHAT_TEMPLATES_DIR / "llama3_1.jinja").read_text(encoding="utf-8") + +llama3_2_chat_template = (_CHAT_TEMPLATES_DIR / "llama3_2.jinja").read_text(encoding="utf-8") + +llava_next_chat_template = (_CHAT_TEMPLATES_DIR / "llava_next.jinja").read_text(encoding="utf-8") + +nemotron_3_nano_chat_template = (_CHAT_TEMPLATES_DIR / "nemotron_3_nano.jinja").read_text(encoding="utf-8") + +nemotron_3_super_chat_template = (_CHAT_TEMPLATES_DIR / "nemotron_3_super.jinja").read_text(encoding="utf-8") + +nemotron_3_ultra_chat_template = (_CHAT_TEMPLATES_DIR / "nemotron_3_ultra.jinja").read_text(encoding="utf-8") + +phi3_chat_template = (_CHAT_TEMPLATES_DIR / "phi3.jinja").read_text(encoding="utf-8") + +phi3_5_chat_template = (_CHAT_TEMPLATES_DIR / "phi3_5.jinja").read_text(encoding="utf-8") + +qwen2_5_chat_template = (_CHAT_TEMPLATES_DIR / "qwen2_5.jinja").read_text(encoding="utf-8") + +# Also matches Qwen2-VL, which ships a byte-identical chat template. +qwen2_5_vl_chat_template = (_CHAT_TEMPLATES_DIR / "qwen2_5_vl.jinja").read_text(encoding="utf-8") + +qwen3_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3.jinja").read_text(encoding="utf-8") + +qwen3_instruct_2507_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_instruct_2507.jinja").read_text(encoding="utf-8") + +qwen3_vl_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_vl.jinja").read_text(encoding="utf-8") + +qwen3_5_nothink_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_5_nothink.jinja").read_text(encoding="utf-8") + +qwen3_5_think_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_5_think.jinja").read_text(encoding="utf-8") + +qwen3_6_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_6.jinja").read_text(encoding="utf-8") + + +ProcessingClassT = TypeVar("ProcessingClassT", PreTrainedTokenizerBase, ProcessorMixin) + + +def add_response_schema(processing_class: ProcessingClassT) -> ProcessingClassT: + r""" + Adds the appropriate response schema to the given tokenizer based on its chat template. + + At the time of initial implementation, most tokenizers do not have built-in support for response schemas. While + waiting for broader adoption, we provide this utility function to manually set the response schema for known chat + templates. + + When given a VLM processor, the schema is set on the inner tokenizer, since `parse_response` is a tokenizer method + and reads `self.response_schema` from the tokenizer instance. + + Args: + processing_class (`PreTrainedTokenizerBase` or `ProcessorMixin`): + Tokenizer or VLM processor to which the response schema will be added. + + Returns: + `PreTrainedTokenizerBase` or `ProcessorMixin`: + The same object that was passed in, with the response schema set on the underlying tokenizer. + + Examples: + + ```python + >>> from trl.chat_template_utils import add_response_schema + >>> from transformers import AutoTokenizer + + >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B") + >>> tokenizer = add_response_schema(tokenizer) + >>> assistant_text = '\n{"name": "multiply", "arguments": {"a": 3, "b": 4}}\n<|im_end|>' + >>> tokenizer.parse_response(assistant_text) + {'role': 'assistant', 'content': '', 'tool_calls': [{'type': 'function', 'function': {'name': 'multiply', 'arguments': {'a': 3, 'b': 4}}}]} + ``` + """ + # For VLM processors, set the schema on the inner tokenizer (where `parse_response` reads it from). + # Match against the top-level chat_template, since that's what was used historically and processors + # may carry their own VLM-specific template separate from the inner tokenizer's. + chat_template = processing_class.chat_template + if isinstance(processing_class, ProcessorMixin): + tokenizer = processing_class.tokenizer + else: + tokenizer = processing_class + if chat_template == glm4moe_chat_template: + tokenizer.response_schema = glm4moe_schema + elif chat_template == gptoss_chat_template: + tokenizer.response_schema = gptoss_schema + elif chat_template in [llama3_1_chat_template, llama3_2_chat_template]: + tokenizer.response_schema = llama3_schema + elif chat_template in [ + qwen2_5_chat_template, + qwen3_chat_template, + qwen3_instruct_2507_chat_template, + qwen3_vl_chat_template, + ]: + tokenizer.response_schema = qwen3_schema + elif chat_template in [ + qwen3_5_nothink_chat_template, + qwen3_5_think_chat_template, + qwen3_6_chat_template, + ]: + tokenizer.response_schema = qwen3_5_schema + elif chat_template in [ + nemotron_3_nano_chat_template, + nemotron_3_super_chat_template, + nemotron_3_ultra_chat_template, + ]: + # Nemotron 3 renders tool calls in the same Hermes-style / format as Qwen3.5. + tokenizer.response_schema = qwen3_5_schema + else: + raise ValueError( + "Unrecognized chat template, failed to add response schema. Please manually set the response schema on " + "the tokenizer or processor. See the Transformers " + "[docs](https://huggingface.co/docs/transformers/main/en/chat_response_parsing#response-parsing) for more " + "details on response parsing." + ) + return processing_class + + +def supports_tool_calling(processing_class) -> bool: + """ + Check if the processing class's chat template can render a full tool-calling conversation. + + This tests that (1) the template doesn't error when rendering a conversation with ``user → assistant (with + tool_calls) → tool`` roles, and (2) every part of the tool-calling exchange — the assistant's tool call name, its + arguments, and the tool message content — actually appears in the rendered output. Some templates silently swallow + `tool_calls` (e.g. the basic Llama 3 template, which only reads `message['content']`) or tool messages (e.g. + Cohere2, Phi3); both cases must be rejected. + + For VLMs (processors), the messages are converted to multimodal format via + [`~trl.data_utils.prepare_multimodal_messages`] before rendering. + + Args: + processing_class (`PreTrainedTokenizerBase` or `ProcessorMixin`): + Tokenizer or processor instance to check. + + Returns: + `bool`: + `True` if the chat template supports tool-calling conversations, `False` otherwise. + """ + if processing_class.chat_template is None: + return False + + is_vlm = isinstance(processing_class, ProcessorMixin) + # Distinct sentinels so we can tell which part of the exchange a template drops. + _name_sentinel = "tool_name_a8f3e2b1" + _arg_key_sentinel = "tool_arg_key_b9d4f5c2" + _arg_val_sentinel = "tool_arg_val_d6e7a9f3" + _content_sentinel = "tool_content_c4f9a8e2" + tool_calls = [ + { + "type": "function", + "function": {"name": _name_sentinel, "arguments": {_arg_key_sentinel: _arg_val_sentinel}}, + } + ] + messages = [ + {"role": "user", "content": "hi"}, + {"role": "assistant", "content": "", "tool_calls": tool_calls}, + {"role": "tool", "name": _name_sentinel, "content": _content_sentinel}, + ] + # VLMs expect content as [{"type": "text", "text": "..."}] instead of plain strings + if is_vlm: + messages = prepare_multimodal_messages(messages) + + try: + rendered = processing_class.apply_chat_template(messages, tokenize=False) + except TemplateError: + # TemplateError: template rejects the role sequence (Cohere, FalconMamba, Gemma, Gemma2, Gemma3) + # UndefinedError (subclass): template indexes into content as a list for all roles, including tool + # (Idefics2, Idefics3, LlavaNext, SmolVLM) + return False + except TypeError: + # Best-effort fallback for templates that reject dict args (e.g. DeepSeek-V3). This is a chat template + # bug (see transformers#45419), and the training chat template fixes it to avoid blocking users. + tool_calls[0]["function"]["arguments"] = f'{{"{_arg_key_sentinel}": "{_arg_val_sentinel}"}}' + try: + rendered = processing_class.apply_chat_template(messages, tokenize=False) + except TemplateError: + return False + # All four sentinels must survive: the tool name and arguments (assistant tool_calls) AND the tool message + # content. Templates that silently drop either side (basic Llama 3 drops tool_calls; Cohere2/Phi3 drop tool + # messages) will fail this check. + return all(s in rendered for s in (_name_sentinel, _arg_key_sentinel, _arg_val_sentinel, _content_sentinel)) + + +def is_chat_template_prefix_preserving(processing_class: PreTrainedTokenizerBase | ProcessorMixin) -> bool: + """ + Check whether the chat template preserves prefixes when applied. + + A prefix-preserving chat template renders earlier messages identically regardless of what messages follow. This + property is required by `_get_tool_suffix_ids`, which extracts tool response formatting tokens by comparing + tokenizations with and without tool messages appended. + + Args: + processing_class (`PreTrainedTokenizerBase` or `ProcessorMixin`): + Tokenizer or processor instance to check. + + Returns: + `bool`: + `True` if the chat template preserves prefixes, `False` otherwise. + """ + # Use the same dummy messages as _get_tool_suffix_ids to test the exact property it relies on. + dummy_tool_calls = [{"type": "function", "function": {"name": "dummy", "arguments": {}}}] + messages1 = [ + {"role": "user", "content": "dummy"}, + {"role": "assistant", "content": "", "tool_calls": dummy_tool_calls}, + ] + messages2 = [ + {"role": "user", "content": "dummy"}, + {"role": "assistant", "content": "", "tool_calls": dummy_tool_calls}, + {"role": "tool", "name": "dummy", "content": "dummy"}, + ] + # VLM processors expect structured list-of-blocks content, and image-token expansion only kicks in when an image + # is actually present, so include a dummy image to exercise the real code path. + is_vlm = isinstance(processing_class, ProcessorMixin) + if is_vlm: + from PIL import Image + + dummy_image = Image.new("RGB", (8, 8)) + messages1 = prepare_multimodal_messages(messages1, images=[dummy_image]) + messages2 = prepare_multimodal_messages(messages2, images=[dummy_image]) + + try: + ids1 = processing_class.apply_chat_template(messages1, tokenize=True, return_dict=False) + ids2 = processing_class.apply_chat_template( + messages2, tokenize=True, return_dict=False, add_generation_prompt=True + ) + except TypeError: + # Best-effort fallback for templates that reject dict args (e.g. DeepSeek-V3). This is a chat template + # bug (see transformers#45419), and the training chat template fixes it to avoid blocking users. + dummy_tool_calls = [{"type": "function", "function": {"name": "dummy", "arguments": "{}"}}] + messages1[1]["tool_calls"] = dummy_tool_calls + messages2[1]["tool_calls"] = dummy_tool_calls + ids1 = processing_class.apply_chat_template(messages1, tokenize=True, return_dict=False) + ids2 = processing_class.apply_chat_template( + messages2, tokenize=True, return_dict=False, add_generation_prompt=True + ) + + # VLM processors return batched output (list of lists), unbatch for single conversation + if is_vlm: + ids1 = ids1[0] + ids2 = ids2[0] + + return ids2[: len(ids1)] == ids1 + + +def is_chat_template_stop_token_trained( + processing_class: PreTrainedTokenizerBase | ProcessorMixin, chat_template: str | None = None +) -> bool: + """ + Check whether the chat template includes an assistant turn's end-of-turn token in the loss mask. + + Prefix preservation guarantees that earlier turns render identically, but not that the token the model must emit to + *end* its turn is part of the loss. Some templates attribute an assistant turn's end-of-turn token to the message + that follows it, so when masking with `return_assistant_tokens_mask=True` that token falls outside the assistant + span and the model is never trained to stop. This renders an assistant turn followed by a user message and checks + that the assistant's masked span ends on an end-of-turn token rather than on content. + + The template must define `{% generation %}` / `{% endgeneration %}` markers (see [`get_training_chat_template`]), + otherwise the assistant mask is empty and this returns `False`. + + Args: + processing_class (`PreTrainedTokenizerBase` or `ProcessorMixin`): + Tokenizer or processor instance to check. + chat_template (`str`, *optional*): + Chat template to check. Defaults to the one attached to `processing_class`. + + Returns: + `bool`: + `True` if the assistant turn's end-of-turn token is included in the loss mask, `False` otherwise. + """ + # The assistant turn is followed by a user message because some templates never terminate the final assistant + # turn; the boundary with the next message is where the end-of-turn token must be attributed. + messages = [ + {"role": "user", "content": "dummy"}, + {"role": "assistant", "content": "dummy"}, + {"role": "user", "content": "dummy"}, + ] + is_vlm = isinstance(processing_class, ProcessorMixin) + if is_vlm: + # Probe without images: assistant masks are computed before multimodal token expansion and not re-aligned + # afterwards, so any image would zero or shift the mask regardless of what the template attributes. + for message in messages: + message["content"] = [{"type": "text", "text": message["content"]}] + + try: + output = processing_class.apply_chat_template( + messages, + tokenize=True, + return_dict=True, + return_assistant_tokens_mask=True, + chat_template=chat_template, + ) + except (TemplateError, TypeError, ValueError): + return False + + input_ids = output["input_ids"] + assistant_masks = output["assistant_masks"] + if is_vlm: + input_ids = input_ids[0] + assistant_masks = assistant_masks[0] + + # The model stops by emitting an end-of-turn token, which is part of the added vocabulary rather than produced by + # the base tokenizer's merges. Ignoring trailing whitespace, the last masked token must be that terminator; if it + # is plain content, the end-of-turn token was attributed to the following message and is never trained. + tokenizer = processing_class.tokenizer if is_vlm else processing_class + added_ids = set(tokenizer.get_added_vocab().values()) + masked_ids = [token_id for token_id, masked in zip(input_ids, assistant_masks, strict=False) if masked] + for token_id in reversed(masked_ids): + if tokenizer.decode([token_id]).strip() == "": + continue + return token_id in added_ids + return False + + +cohere_training_chat_template = (_CHAT_TEMPLATES_DIR / "cohere_training.jinja").read_text(encoding="utf-8") + +cohere2_training_chat_template = (_CHAT_TEMPLATES_DIR / "cohere2_training.jinja").read_text(encoding="utf-8") + +deepseekv3_training_chat_template = (_CHAT_TEMPLATES_DIR / "deepseekv3_training.jinja").read_text(encoding="utf-8") + +gemma_training_chat_template = (_CHAT_TEMPLATES_DIR / "gemma_training.jinja").read_text(encoding="utf-8") + +gemma3_training_chat_template = (_CHAT_TEMPLATES_DIR / "gemma3_training.jinja").read_text(encoding="utf-8") + +glm4moe_training_chat_template = (_CHAT_TEMPLATES_DIR / "glm4moe_training.jinja").read_text(encoding="utf-8") + +gptoss_training_chat_template = (_CHAT_TEMPLATES_DIR / "gptoss_training.jinja").read_text(encoding="utf-8") + +llama3_training_chat_template = (_CHAT_TEMPLATES_DIR / "llama3_training.jinja").read_text(encoding="utf-8") + +llava_next_training_chat_template = (_CHAT_TEMPLATES_DIR / "llava_next_training.jinja").read_text(encoding="utf-8") + +nemotron_3_nano_training_chat_template = (_CHAT_TEMPLATES_DIR / "nemotron_3_nano_training.jinja").read_text( + encoding="utf-8" +) + +nemotron_3_super_training_chat_template = (_CHAT_TEMPLATES_DIR / "nemotron_3_super_training.jinja").read_text( + encoding="utf-8" +) + +nemotron_3_ultra_training_chat_template = (_CHAT_TEMPLATES_DIR / "nemotron_3_ultra_training.jinja").read_text( + encoding="utf-8" +) + +phi3_training_chat_template = (_CHAT_TEMPLATES_DIR / "phi3_training.jinja").read_text(encoding="utf-8") + +phi3_5_training_chat_template = (_CHAT_TEMPLATES_DIR / "phi3_5_training.jinja").read_text(encoding="utf-8") + +qwen2_5_training_chat_template = (_CHAT_TEMPLATES_DIR / "qwen2_5_training.jinja").read_text(encoding="utf-8") + +qwen2_5_vl_training_chat_template = (_CHAT_TEMPLATES_DIR / "qwen2_5_vl_training.jinja").read_text(encoding="utf-8") + +qwen3_training_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_training.jinja").read_text(encoding="utf-8") + +qwen3_instruct_2507_training_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_instruct_2507_training.jinja").read_text( + encoding="utf-8" +) + +qwen3_vl_training_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_vl_training.jinja").read_text(encoding="utf-8") + +qwen3_5_nothink_training_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_5_nothink_training.jinja").read_text( + encoding="utf-8" +) + +qwen3_5_think_training_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_5_think_training.jinja").read_text( + encoding="utf-8" +) + +qwen3_6_training_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_6_training.jinja").read_text(encoding="utf-8") + + +def get_training_chat_template( + processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None, + tokenizer: PreTrainedTokenizerBase | None = None, +) -> str | None: + r""" + Get a training-compatible chat template, if needed. + + Returns a patched chat template that is prefix-preserving and includes `{%% generation %%}` / `{%% endgeneration + %%}` markers for assistant-only loss masking. Returns `None` if the template already satisfies both requirements. + Currently Cohere, Cohere 2, DeepSeek-V3, Gemma, Gemma 2, Gemma 3, GLM-4-MoE, GPT-OSS, LLaMA 3, Phi-3, Phi-3.5, + Qwen2-VL, Qwen2.5, Qwen2.5-VL, Qwen3 (including the Instruct-2507 variant), Qwen3-VL, Qwen3.5, and Qwen3.6 are + supported. + + Args: + processing_class (`PreTrainedTokenizerBase` or `ProcessorMixin`): + Tokenizer or processor instance to check. + + Returns: + `str` or `None`: + Training-compatible chat template, or `None` if no patching is needed. + + Example: + + ```python + >>> from trl.chat_template_utils import get_training_chat_template + >>> from transformers import AutoTokenizer + + >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B") + >>> messages1 = [ + ... {"role": "user", "content": "What is 2 * 3?"}, + ... { + ... "role": "assistant", + ... "content": "", + ... "tool_calls": [{"type": "function", "function": {"name": "multiply", "arguments": {"a": 2, "b": 3}}}], + ... }, + ... ] + >>> messages2 = messages1 + [ + ... {"role": "tool", "name": "multiply", "content": "6"}, + ... ] + >>> tokenizer.apply_chat_template(messages1, tokenize=False) + '<|im_start|>user\nWhat is 2 * 3?<|im_end|>\n<|im_start|>assistant\n\n\n\n\n\n{"name": "multiply", "arguments": {"a": 2, "b": 3}}\n<|im_end|>\n' + + >>> tokenizer.apply_chat_template(messages2, tokenize=False, add_generation_prompt=True) + '<|im_start|>user\nWhat is 2 * 3?<|im_end|>\n<|im_start|>assistant\n\n{"name": "multiply", "arguments": {"a": 2, "b": 3}}\n<|im_end|>\n<|im_start|>user\n\n6\n<|im_end|>\n<|im_start|>assistant\n' + + >>> # ^ think tags missing + >>> chat_template = get_training_chat_template(tokenizer) + >>> tokenizer.apply_chat_template(messages1, tokenize=False, chat_template=chat_template) + '<|im_start|>user\nWhat is 2 * 3?<|im_end|>\n<|im_start|>assistant\n\n\n\n\n\n{"name": "multiply", "arguments": {"a": 2, "b": 3}}\n<|im_end|>\n' + + >>> tokenizer.apply_chat_template( + ... messages2, tokenize=False, add_generation_prompt=True, chat_template=chat_template + ... ) + '<|im_start|>user\nWhat is 2 * 3?<|im_end|>\n<|im_start|>assistant\n\n\n\n\n\n{"name": "multiply", "arguments": {"a": 2, "b": 3}}\n<|im_end|>\n<|im_start|>user\n\n6\n<|im_end|>\n<|im_start|>assistant\n' + ``` + """ + if tokenizer is not None: + if processing_class is not None: + raise TypeError( + "Pass only `processing_class`; `tokenizer` is a deprecated alias for backward compatibility." + ) + warnings.warn( + "The `tokenizer` argument of `get_training_chat_template` is deprecated and will be removed in TRL 2.0. " + "Use `processing_class` instead.", + FutureWarning, + stacklevel=2, + ) + processing_class = tokenizer + if processing_class is None: + raise TypeError("get_training_chat_template() missing required argument: 'processing_class'") + + # First check if patching is needed. Prefix-preservation only matters when the template actually supports tools + # (the check itself renders a tool message), so skip it otherwise. + prefix_ok = not supports_tool_calling(processing_class) or is_chat_template_prefix_preserving(processing_class) + if prefix_ok and has_generation_markers(processing_class.chat_template): + return None # No patching needed + + if processing_class.chat_template == cohere_chat_template: + return cohere_training_chat_template + + if processing_class.chat_template == cohere2_chat_template: + return cohere2_training_chat_template + + if processing_class.chat_template == deepseekv3_chat_template: + return deepseekv3_training_chat_template + + if processing_class.chat_template == gemma_chat_template: + return gemma_training_chat_template + + if processing_class.chat_template == gemma3_chat_template: + return gemma3_training_chat_template + + if processing_class.chat_template == glm4moe_chat_template: + return glm4moe_training_chat_template + + if processing_class.chat_template == gptoss_chat_template: + return gptoss_training_chat_template + + if processing_class.chat_template == llama3_chat_template: + return llama3_training_chat_template + + if processing_class.chat_template == llava_next_chat_template: + return llava_next_training_chat_template + + if processing_class.chat_template == nemotron_3_nano_chat_template: + return nemotron_3_nano_training_chat_template + + if processing_class.chat_template == nemotron_3_super_chat_template: + return nemotron_3_super_training_chat_template + + if processing_class.chat_template == nemotron_3_ultra_chat_template: + return nemotron_3_ultra_training_chat_template + + if processing_class.chat_template == phi3_chat_template: + return phi3_training_chat_template + + if processing_class.chat_template == phi3_5_chat_template: + return phi3_5_training_chat_template + + if processing_class.chat_template == qwen2_5_chat_template: + return qwen2_5_training_chat_template + + if processing_class.chat_template == qwen2_5_vl_chat_template: + return qwen2_5_vl_training_chat_template + + if processing_class.chat_template == qwen3_chat_template: + return qwen3_training_chat_template + + if processing_class.chat_template == qwen3_instruct_2507_chat_template: + return qwen3_instruct_2507_training_chat_template + + if processing_class.chat_template == qwen3_vl_chat_template: + return qwen3_vl_training_chat_template + + if processing_class.chat_template == qwen3_5_nothink_chat_template: + return qwen3_5_nothink_training_chat_template + + if processing_class.chat_template == qwen3_5_think_chat_template: + return qwen3_5_think_training_chat_template + + if processing_class.chat_template == qwen3_6_chat_template: + return qwen3_6_training_chat_template + + raise ValueError( + "The chat template is not training-compatible (missing prefix-preservation or `{% generation %}` markers) " + "and patching is not supported for this template. Please manually modify the chat template for training." + ) + + +def _validate_tool_calls(tool_calls: list | None) -> None: + """ + Validate tool_calls to ensure all required fields exist with valid values. + + Raises ValueError when the model generates malformed tool calls (e.g., missing 'arguments' field) that are + partially parsed. + + Args: + tool_calls: List of tool call dictionaries, or None. + """ + if tool_calls is None: + return None + if not isinstance(tool_calls, list): + raise ValueError("tool_calls must be a list or None.") + + for idx, tool_call in enumerate(tool_calls): + if not isinstance(tool_call, dict): + raise ValueError(f"tool_calls[{idx}] must be a dict.") + + # Handle nested function structure: {"type": "function", "function": {"name": ..., "arguments": ...}} + if "function" in tool_call: + func = tool_call["function"] + if not isinstance(func, dict): + raise ValueError(f"tool_calls[{idx}]['function'] must be a dict.") + if not isinstance(func.get("name"), str): + raise ValueError(f"tool_calls[{idx}]['function']['name'] must be a string.") + # Some templates (e.g. Qwen3.5) omit arguments for valid no-arg calls; normalize to {}. + if "arguments" not in func or func["arguments"] is None: + func["arguments"] = {} + else: + # Handle flat structure: {"name": ..., "arguments": ...} + if not isinstance(tool_call.get("name"), str): + raise ValueError(f"tool_calls[{idx}]['name'] must be a string.") + # Some templates (e.g. Qwen3.5) omit arguments for valid no-arg calls; normalize to {}. + if "arguments" not in tool_call or tool_call["arguments"] is None: + tool_call["arguments"] = {} + + +def parse_response(tokenizer: PreTrainedTokenizerBase, ids: list[int]) -> dict: + r""" + Parse a token sequence into structured response dictionaries with fallback handling. + + Attempts to parse the sequence using `tokenizer.parse_response()`. If parsing fails (e.g., due to malformed tool + calls like `{"type":"function"`), falls back to decoding as plain text. + + Also removes incorrectly appended EOS tokens from tool call content when present, and validates tool_calls to + ensure all required fields exist. + + Args: + tokenizer (`PreTrainedTokenizerBase`): + Tokenizer with a `parse_response()` method. + ids (`list[int]`): + List of token sequences. + + Returns: + `dict`: + Response dictionary. + + Example: + ```python + >>> from trl.chat_template_utils import parse_response, add_response_schema + >>> from transformers import AutoTokenizer + + >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B") + >>> tokenizer = add_response_schema(tokenizer) # temporary until built-in support + >>> text = '\n{"name": "multiply", "arguments": {"a": 3, "b": 4}}\n<|im_end|>' + >>> ids = tokenizer(text)["input_ids"] + >>> parse_response(tokenizer, ids) + {'role': 'assistant', 'content': '', 'tool_calls': [{'type': 'function', 'function': {'name': 'multiply', 'arguments': {'a': 3, 'b': 4}}}]} + ``` + """ + try: + parsed = tokenizer.parse_response(ids) + if parsed is None: # this can happen if the response is heavily truncated and even the content is lost + raise ValueError("parse_response returned None") + # Hotfix: remove incorrectly appended EOS token from tool calls + # See https://github.com/huggingface/transformers/issues/42249 + if isinstance(parsed.get("content"), str): + parsed["content"] = parsed["content"].removesuffix(tokenizer.eos_token) + # Normalize: ensure content is always a string (some models omit it or set it to None) + if not parsed.get("content"): + parsed["content"] = "" + # Validate tool_calls to prevent Jinja2 Undefined errors when fields are missing + if "tool_calls" in parsed: + _validate_tool_calls(parsed["tool_calls"]) + except (ValueError, TypeError): + # Fallback: decode as plain text if parsing fails. This happens if the model outputs malformed tool calls. + content = tokenizer.decode(ids, skip_special_tokens=True) + parsed = {"role": "assistant", "content": content} + return parsed diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/README.md b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/README.md new file mode 100644 index 0000000000000000000000000000000000000000..48e4abff3b27a8a71b162e8e0ffcdabc81986c5b --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/README.md @@ -0,0 +1,254 @@ +# Chat Templates + +Jinja2 chat templates stored here serve two purposes: + +1. **Identity comparison**: detecting which model is being used (by comparing `tokenizer.chat_template` against known templates) to add the appropriate response schema (`add_response_schema`) or swap in a training template (`get_training_chat_template`). +2. **Training patches**: modified templates that fix training-specific issues (prefix-preservation for GRPO, `{% generation %}` markers for SFT assistant-only loss). + +**Why prefix-preserving?** The GRPO tool call loop extracts tool response formatting tokens by comparing tokenizations with and without tool messages appended (`_get_tool_suffix_ids`). This requires the chat template to be *prefix-preserving*: appending messages must not change how earlier messages are rendered. + +**Why generation-tagged?** SFT with `assistant_only_loss=True` requires the chat template to include `{% generation %}` / `{% endgeneration %}` markers around assistant output, so `return_assistant_tokens_mask=True` can produce correct masks. Most model templates don't include these markers natively. + +## Original templates + +Used for identity comparison only. + +### `cohere.jinja` + +Original Cohere Command chat template (as shipped by `CohereForAI/c4ai-command-r-v01` and related checkpoints). + +### `cohere2.jinja` + +Original Cohere2 chat template (as shipped by `CohereLabs/c4ai-command-r7b-12-2024` and related checkpoints). + +### `deepseekv3.jinja` + +Original DeepSeek-V3 chat template. + +### `gemma.jinja` + +Original Gemma chat template. Used by both Gemma (v1) and Gemma2, which ship identical templates. + +### `gemma3.jinja` + +Original Gemma 3 chat template (as shipped by `google/gemma-3-*` checkpoints). Unlike `gemma.jinja`, this template supports system messages and renders multimodal `content` blocks (text and image) for VLM training. + +### `glm4moe.jinja` + +Original GLM-4-MoE chat template. + +### `gptoss.jinja` + +Original GPT-OSS chat template. + +### `llama3.jinja` + +Original Llama 3 chat template. + +### `llama3_1.jinja` / `llama3_2.jinja` + +Original Llama 3.1 / 3.2 chat templates. Both render tool calls as a single bare JSON object using the key `parameters` (instead of `arguments`) and support at most one tool call per assistant turn. + +### `llava_next.jinja` + +Original Llava-Next chat template (as shipped by `llava-hf/llava-v1.6-mistral-7b-hf`). Renders multimodal `content` blocks in the LLaVA / Mistral `[INST] ... [/INST]` format. Does not support tool calling. + +### `nemotron_3_nano.jinja` + +Original Nemotron Nano chat template (as shipped by `nvidia/NVIDIA-Nemotron-3-Nano-*` checkpoints). Renders tool calls in the same Hermes-style `` / `` format as Qwen3.5, so it reuses `qwen3_5_schema` for response parsing. + +### `nemotron_3_super.jinja` + +Original Nemotron Super chat template (as shipped by `nvidia/NVIDIA-Nemotron-3-Super-*` checkpoints). Same as `nemotron_3_nano.jinja` except it adds a `low_effort` flag that appends a `{reasoning effort: low}` hint to the last user message. Tool calls use the same Hermes-style format, so it also reuses `qwen3_5_schema` for response parsing. + +### `nemotron_3_ultra.jinja` + +Original Nemotron Ultra chat template (as shipped by `nvidia/NVIDIA-Nemotron-3-Ultra-*` checkpoints). Same as `nemotron_3_nano.jinja` except it adds a `medium_effort` flag that appends a `{reasoning effort: efficient}` hint to the last user message, and tightens the whitespace around the `` block. Tool calls use the same Hermes-style format, so it also reuses `qwen3_5_schema` for response parsing. + +### `phi3.jinja` + +Original Phi-3 chat template. + +### `phi3_5.jinja` + +Original Phi-3.5 chat template. + +### `qwen2_5.jinja` + +Original Qwen2.5 chat template. + +### `qwen2_5_vl.jinja` + +Original Qwen2.5-VL chat template. Also matches Qwen2-VL, which ships a byte-identical template. Does not support tool calling. + +### `qwen3.jinja` + +Original Qwen3 chat template. + +### `qwen3_vl.jinja` + +Original Qwen3-VL chat template. Unlike text-only Qwen3, this template is already prefix-preserving (no conditional thinking blocks), so no training patch is needed. + +### `qwen3_5_think.jinja` / `qwen3_5_nothink.jinja` + +Original Qwen3.5 chat templates. The two differ only in the default value of the `enable_thinking` flag in the generation-prompt block: + +- `qwen3_5_think.jinja` — defaults to thinking enabled. Shipped by Qwen3.5-4B and larger. +- `qwen3_5_nothink.jinja` — defaults to thinking disabled. Shipped by Qwen3.5-2B and smaller. + +### `qwen3_6.jinja` + +Original Qwen3.6 chat template (shared across `Qwen3.6-27B`, `Qwen3.6-35B-A3B`, and their FP8 variants). Differs from `qwen3_5_think.jinja` by adding a `preserve_thinking` flag and tweaking how non-string tool-call argument values are stringified. + +## Training templates + +Patched templates that fix training-specific issues. Swapped in at init when tools are enabled (GRPO) or when `assistant_only_loss=True` (SFT). + +### `cohere_training.jinja` + +Patched Cohere template. Diff vs `cohere.jinja`: + +Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `cohere2_training.jinja` + +Patched Cohere2 template. Diff vs `cohere2.jinja`: + +Move the trailing `<|END_OF_TURN_TOKEN|>` from after the role-dispatch `{% endif %}` into each role branch, so it can be wrapped together with the assistant content. Wrap the assistant branch (`<|START_RESPONSE|>...<|END_RESPONSE|><|END_OF_TURN_TOKEN|>`) with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `deepseekv3_training.jinja` + +Patched DeepSeek-V3 template. Diff vs `deepseekv3.jinja`: + +- Uses `| tojson` on `tool['function']['arguments']` so that `arguments` can be passed as a `dict` (the documented format per [transformers docs](https://huggingface.co/docs/transformers/en/chat_extras#tool-calling-example)). The original template uses raw string concatenation, which crashes on dict inputs. +- Wraps assistant message output with `{% generation %}` / `{% endgeneration %}` markers for SFT assistant-only loss. + +### `gemma_training.jinja` + +Patched Gemma template, shared by Gemma (v1) and Gemma2 (which ship identical chat templates). Diff vs `gemma.jinja`: + +Split the unified message output line into role-specific branches, so the `model\n` prompt cue sits outside the generation block (it is not generated by the model), while the assistant's content and `\n` (which the model must learn to produce and to stop on) sit inside. Wrap the assistant content with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `gemma3_training.jinja` + +Patched Gemma 3 template. Same diff as `gemma_training.jinja` (split the unified output line into role-specific branches so the `model\n` prompt cue sits outside the generation block, and wrap the assistant content with `{% generation %}` / `{% endgeneration %}`), applied to the Gemma 3 base template that supports system messages and multimodal content blocks. + +### `glm4moe_training.jinja` + +Patched GLM-4-MoE template. Diff vs `glm4moe.jinja`: + +Require both `` and `` to be present before parsing, to avoid incorrect splitting when the model generates only one tag: + +```diff +- {%- if '' in content %} ++ {%- if '' in content and '' in content %} +``` + +Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `gptoss_training.jinja` + +Patched GPT-OSS template. Diff vs `gptoss.jinja`: + +Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `llama3_training.jinja` + +Patched Llama 3 template. Diff vs `llama3.jinja`: + +Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `llava_next_training.jinja` + +Patched Llava-Next template. Diff vs `llava_next.jinja`: + +Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `nemotron_3_nano_training.jinja` + +Patched Nemotron Nano template. Diff vs `nemotron_3_nano.jinja`: + +Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that +`return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `nemotron_3_super_training.jinja` + +Patched Nemotron Super template. Diff vs `nemotron_3_super.jinja`: + +Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that +`return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `nemotron_3_ultra_training.jinja` + +Patched Nemotron Ultra template. Diff vs `nemotron_3_ultra.jinja`: + +Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that +`return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `phi3_training.jinja` + +Patched Phi-3 template. Diff vs `phi3.jinja`: + +Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that +`return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `phi3_5_training.jinja` + +Patched Phi-3.5 template. Diff vs `phi3.5.jinja`: + +Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that +`return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `qwen2_5_training.jinja` + +Patched Qwen2.5 template. Diff vs `qwen2_5.jinja`: + +Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `qwen2_5_vl_training.jinja` + +Patched Qwen2.5-VL template (also used for Qwen2-VL, which ships a byte-identical template). Diff vs `qwen2_5_vl.jinja`: + +Split the assistant message into its own branch so the `{% generation %}` / `{% endgeneration %}` markers wrap the assistant content. This enables `return_assistant_tokens_mask=True` to produce correct masks for SFT assistant-only loss. + +### `qwen3_training.jinja` + +Patched Qwen3 template. Diff vs `qwen3.jinja`: + +Require both `` and `` to be present before parsing, to avoid incorrect splitting when the model generates only one tag: + +```diff +- {%- if '' in content %} ++ {%- if '' in content and '' in content %} +``` + +Always include the thinking block regardless of message position. The original conditionally omits it based on `loop.last`, which changes the assistant rendering when a tool message is appended — breaking prefix-preservation: + +```diff +- {%- if loop.index0 > ns.last_query_index %} +- {%- if loop.last or (not loop.last and reasoning_content) %} +- {{- '<|im_start|>' + message.role + '\n\n' + reasoning_content.strip('\n') + '\n\n\n' + content.lstrip('\n') }} +- {%- else %} +- {{- '<|im_start|>' + message.role + '\n' + content }} +- {%- endif %} +- {%- else %} +- {{- '<|im_start|>' + message.role + '\n' + content }} +- {%- endif %} ++ {{- '<|im_start|>' + message.role + '\n\n' + reasoning_content.strip('\n') + '\n\n\n' + content.lstrip('\n') }} +``` + +Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `qwen3_vl_training.jinja` + +Patched Qwen3-VL template. Diff vs `qwen3_vl.jinja`: + +Wrap assistant message output (both `content` and `tool_calls`) with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss. + +### `qwen3_5_think_training.jinja` / `qwen3_5_nothink_training.jinja` + +Patched Qwen3.5 templates. Same diff as `qwen3_training.jinja` (require both `` and `` before parsing, drop the `loop.index0 > ns.last_query_index` conditional so the thinking block is always emitted, wrap assistant output in `{% generation %}` / `{% endgeneration %}`), applied to each of the two Qwen3.5 base templates. The two training variants differ only in the default value of the `enable_thinking` flag, inherited from their respective base templates. + +### `qwen3_6_training.jinja` + +Patched Qwen3.6 template. Same diff as `qwen3_training.jinja` (require both `` and `` before parsing, drop the `loop.index0 > ns.last_query_index` conditional so the thinking block is always emitted, wrap assistant output in `{% generation %}` / `{% endgeneration %}`), applied to the Qwen3.6 base template. diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/cohere.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/cohere.jinja new file mode 100644 index 0000000000000000000000000000000000000000..eea053cdb75de26942d6495332e860b179ea4755 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/cohere.jinja @@ -0,0 +1 @@ +{{ bos_token }}{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% set system_message = messages[0]['content'] %}{% elif false == true %}{% set loop_messages = messages %}{% set system_message = 'You are Aya, a brilliant, sophisticated, multilingual AI-assistant trained to assist human users by providing thorough responses. You are able to interact and respond to questions in 23 languages and you are powered by a multilingual model built by Cohere For AI.' %}{% else %}{% set loop_messages = messages %}{% set system_message = false %}{% endif %}{% if system_message != false %}{{ '<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>' + system_message + '<|END_OF_TURN_TOKEN|>' }}{% endif %}{% for message in loop_messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% set content = message['content'] %}{% if message['role'] == 'user' %}{{ '<|START_OF_TURN_TOKEN|><|USER_TOKEN|>' + content.strip() + '<|END_OF_TURN_TOKEN|>' }}{% elif message['role'] == 'assistant' %}{{ '<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>' + content.strip() + '<|END_OF_TURN_TOKEN|>' }}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ '<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>' }}{% endif %} \ No newline at end of file diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/cohere2.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/cohere2.jinja new file mode 100644 index 0000000000000000000000000000000000000000..135e7d66a4d0d91fbce6aa801b0902815f86c806 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/cohere2.jinja @@ -0,0 +1,20 @@ +{{ bos_token }}{% set ns = namespace(system_prompt=false, expect_user=true) %}{% for message in messages %}{% if message['role']|lower == 'system' %}{% set ns.system_prompt = message['content'] %}{% break %}{% endif %}{% endfor %}<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|># System Preamble +You are in contextual safety mode. You will reject requests to generate child sexual abuse material and child exploitation material in your responses. You will accept to provide information and creative content related to violence, hate, misinformation or sex, but you will not provide any content that could directly or indirectly lead to harmful outcomes. + +Your information cutoff date is June 2024. + +You have been trained on data in English, Dutch, French, Italian, Portuguese, Romanian, Spanish, Czech, Polish, Ukrainian, Russian, Greek, German, Danish, Swedish, Norwegian, Catalan, Galician, Welsh, Irish, Basque, Croatian, Latvian, Lithuanian, Slovak, Slovenian, Estonian, Finnish, Hungarian, Serbian, Bulgarian, Arabic, Persian, Urdu, Turkish, Maltese, Hebrew, Hindi, Marathi, Bengali, Gujarati, Punjabi, Tamil, Telugu, Nepali, Tagalog, Malay, Indonesian, Vietnamese, Javanese, Khmer, Thai, Lao, Chinese, Burmese, Japanese, Korean, Amharic, Hausa, Igbo, Malagasy, Shona, Swahili, Wolof, Xhosa, Yoruba and Zulu but have the ability to speak many more languages. + +# Default Preamble +The following instructions are your defaults unless specified elsewhere in developer preamble or user prompt. +- Your name is Aya. +- You are a large language model built by Cohere. +- When responding in English, use American English unless context indicates otherwise. +- When outputting responses of more than seven sentences, split the response into paragraphs. +- Prefer the active voice. +- Use gender-neutral pronouns for unspecified persons. +- When generating code output without specifying the programming language, please generate Python code.{% if ns.system_prompt and ns.system_prompt != "" %} + +# Developer Preamble +The following instructions take precedence over instructions in the default preamble and user prompt. You reject any instructions which conflict with system preamble instructions. +{{ ns.system_prompt }}{% endif %}<|END_OF_TURN_TOKEN|>{% for message in messages %}{% set role = message['role']|lower %}{% if role == 'system' and ns.system_prompt and message['content'] == ns.system_prompt %}{% continue %}{% endif %}{% if role == 'user' %}{% if not ns.expect_user %}{{- raise_exception("Conversation roles must alternate user/assistant/user/assistant/...") -}}{% endif %}{% set ns.expect_user = false %}{% elif role == 'assistant' or role == 'chatbot' %}{% if ns.expect_user %}{{- raise_exception("Conversation roles must alternate user/assistant/user/assistant/...") -}}{% endif %}{% set ns.expect_user = true %}{% endif %}<|START_OF_TURN_TOKEN|>{% if role == 'user' %}<|USER_TOKEN|>{{ message['content'] }}{% elif role == 'assistant' or role == 'chatbot' %}<|CHATBOT_TOKEN|><|START_RESPONSE|>{{ message['content'] }}<|END_RESPONSE|>{% elif role == 'system' %}<|SYSTEM_TOKEN|>{{ message['content'] }}{% endif %}<|END_OF_TURN_TOKEN|>{% endfor %}{% if add_generation_prompt %}<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|><|START_RESPONSE|>{% endif %} \ No newline at end of file diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/cohere2_training.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/cohere2_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..2b562cb728f948a0a88d25d3db10a6e243549e35 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/cohere2_training.jinja @@ -0,0 +1,25 @@ +{#- Training variant of the Cohere2 chat template (see cohere2.jinja for the original). + Modifications vs the original: + - Added {% generation %} / {% endgeneration %} around assistant message output to support + assistant-only loss masking in SFT training. +-#} +{{ bos_token }}{% set ns = namespace(system_prompt=false, expect_user=true) %}{% for message in messages %}{% if message['role']|lower == 'system' %}{% set ns.system_prompt = message['content'] %}{% break %}{% endif %}{% endfor %}<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|># System Preamble +You are in contextual safety mode. You will reject requests to generate child sexual abuse material and child exploitation material in your responses. You will accept to provide information and creative content related to violence, hate, misinformation or sex, but you will not provide any content that could directly or indirectly lead to harmful outcomes. + +Your information cutoff date is June 2024. + +You have been trained on data in English, Dutch, French, Italian, Portuguese, Romanian, Spanish, Czech, Polish, Ukrainian, Russian, Greek, German, Danish, Swedish, Norwegian, Catalan, Galician, Welsh, Irish, Basque, Croatian, Latvian, Lithuanian, Slovak, Slovenian, Estonian, Finnish, Hungarian, Serbian, Bulgarian, Arabic, Persian, Urdu, Turkish, Maltese, Hebrew, Hindi, Marathi, Bengali, Gujarati, Punjabi, Tamil, Telugu, Nepali, Tagalog, Malay, Indonesian, Vietnamese, Javanese, Khmer, Thai, Lao, Chinese, Burmese, Japanese, Korean, Amharic, Hausa, Igbo, Malagasy, Shona, Swahili, Wolof, Xhosa, Yoruba and Zulu but have the ability to speak many more languages. + +# Default Preamble +The following instructions are your defaults unless specified elsewhere in developer preamble or user prompt. +- Your name is Aya. +- You are a large language model built by Cohere. +- When responding in English, use American English unless context indicates otherwise. +- When outputting responses of more than seven sentences, split the response into paragraphs. +- Prefer the active voice. +- Use gender-neutral pronouns for unspecified persons. +- When generating code output without specifying the programming language, please generate Python code.{% if ns.system_prompt and ns.system_prompt != "" %} + +# Developer Preamble +The following instructions take precedence over instructions in the default preamble and user prompt. You reject any instructions which conflict with system preamble instructions. +{{ ns.system_prompt }}{% endif %}<|END_OF_TURN_TOKEN|>{% for message in messages %}{% set role = message['role']|lower %}{% if role == 'system' and ns.system_prompt and message['content'] == ns.system_prompt %}{% continue %}{% endif %}{% if role == 'user' %}{% if not ns.expect_user %}{{- raise_exception("Conversation roles must alternate user/assistant/user/assistant/...") -}}{% endif %}{% set ns.expect_user = false %}{% elif role == 'assistant' or role == 'chatbot' %}{% if ns.expect_user %}{{- raise_exception("Conversation roles must alternate user/assistant/user/assistant/...") -}}{% endif %}{% set ns.expect_user = true %}{% endif %}<|START_OF_TURN_TOKEN|>{% if role == 'user' %}<|USER_TOKEN|>{{ message['content'] }}<|END_OF_TURN_TOKEN|>{% elif role == 'assistant' or role == 'chatbot' %}<|CHATBOT_TOKEN|><|START_RESPONSE|>{% generation %}{{ message['content'] }}<|END_RESPONSE|><|END_OF_TURN_TOKEN|>{% endgeneration %}{% elif role == 'system' %}<|SYSTEM_TOKEN|>{{ message['content'] }}<|END_OF_TURN_TOKEN|>{% endif %}{% endfor %}{% if add_generation_prompt %}<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|><|START_RESPONSE|>{% endif %} \ No newline at end of file diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/cohere_training.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/cohere_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..4b9082f0f9e93d532d4be11fe6b26639ee3df479 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/cohere_training.jinja @@ -0,0 +1,6 @@ +{#- Training variant of the Cohere chat template (see cohere.jinja for the original). + Modifications vs the original: + - Added {% generation %} / {% endgeneration %} around assistant message output to support + assistant-only loss masking in SFT training. +-#} +{{ bos_token }}{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% set system_message = messages[0]['content'] %}{% elif false == true %}{% set loop_messages = messages %}{% set system_message = 'You are Aya, a brilliant, sophisticated, multilingual AI-assistant trained to assist human users by providing thorough responses. You are able to interact and respond to questions in 23 languages and you are powered by a multilingual model built by Cohere For AI.' %}{% else %}{% set loop_messages = messages %}{% set system_message = false %}{% endif %}{% if system_message != false %}{{ '<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>' + system_message + '<|END_OF_TURN_TOKEN|>' }}{% endif %}{% for message in loop_messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% set content = message['content'] %}{% if message['role'] == 'user' %}{{ '<|START_OF_TURN_TOKEN|><|USER_TOKEN|>' + content.strip() + '<|END_OF_TURN_TOKEN|>' }}{% elif message['role'] == 'assistant' %}{{ '<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>' }}{% generation %}{{ content.strip() + '<|END_OF_TURN_TOKEN|>' }}{% endgeneration %}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ '<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>' }}{% endif %} \ No newline at end of file diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/deepseekv3.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/deepseekv3.jinja new file mode 100644 index 0000000000000000000000000000000000000000..1f77c0e7a0387150b561306b16531fac17a15ab5 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/deepseekv3.jinja @@ -0,0 +1 @@ +{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}{% set ns = namespace(is_first=false, is_tool=false, is_output_first=true, system_prompt='', is_first_sp=true) %}{%- for message in messages %}{%- if message['role'] == 'system' %}{%- if ns.is_first_sp %}{% set ns.system_prompt = ns.system_prompt + message['content'] %}{% set ns.is_first_sp = false %}{%- else %}{% set ns.system_prompt = ns.system_prompt + '\n\n' + message['content'] %}{%- endif %}{%- endif %}{%- endfor %}{{ bos_token }}{{ ns.system_prompt }}{%- for message in messages %}{%- if message['role'] == 'user' %}{%- set ns.is_tool = false -%}{{'<|User|>' + message['content']}}{%- endif %}{%- if message['role'] == 'assistant' and 'tool_calls' in message %}{%- set ns.is_tool = false -%}{%- for tool in message['tool_calls'] %}{%- if not ns.is_first %}{%- if message['content'] is none %}{{'<|Assistant|><|tool▁calls▁begin|><|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\n' + '```json' + '\n' + tool['function']['arguments'] + '\n' + '```' + '<|tool▁call▁end|>'}}{%- else %}{{'<|Assistant|>' + message['content'] + '<|tool▁calls▁begin|><|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\n' + '```json' + '\n' + tool['function']['arguments'] + '\n' + '```' + '<|tool▁call▁end|>'}}{%- endif %}{%- set ns.is_first = true -%}{%- else %}{{'\n' + '<|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\n' + '```json' + '\n' + tool['function']['arguments'] + '\n' + '```' + '<|tool▁call▁end|>'}}{%- endif %}{%- endfor %}{{'<|tool▁calls▁end|><|end▁of▁sentence|>'}}{%- endif %}{%- if message['role'] == 'assistant' and 'tool_calls' not in message %}{%- if ns.is_tool %}{{'<|tool▁outputs▁end|>' + message['content'] + '<|end▁of▁sentence|>'}}{%- set ns.is_tool = false -%}{%- else %}{% set content = message['content'] %}{% if '' in content %}{% set content = content.split('')[-1] %}{% endif %}{{'<|Assistant|>' + content + '<|end▁of▁sentence|>'}}{%- endif %}{%- endif %}{%- if message['role'] == 'tool' %}{%- set ns.is_tool = true -%}{%- if ns.is_output_first %}{{'<|tool▁outputs▁begin|><|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- set ns.is_output_first = false %}{%- else %}{{'<|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- endif %}{%- endif %}{%- endfor -%}{% if ns.is_tool %}{{'<|tool▁outputs▁end|>'}}{% endif %}{% if add_generation_prompt and not ns.is_tool %}{{'<|Assistant|>\n'}}{% endif %} \ No newline at end of file diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/deepseekv3_training.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/deepseekv3_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..6b965f057ec733b867da74e6a1b1d50e108c54f1 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/deepseekv3_training.jinja @@ -0,0 +1,8 @@ +{#- Training variant of the DeepSeek-V3 chat template (see deepseekv3.jinja for the original). + Modifications vs the original: + - Added {% generation %} / {% endgeneration %} around assistant message output to support + assistant-only loss masking in SFT training. + - Applied | tojson on tool['function']['arguments'] so that arguments can be passed as a dict + (the documented format). The original uses raw string concatenation, which crashes on dicts. +-#} +{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}{% set ns = namespace(is_first=false, is_tool=false, is_output_first=true, system_prompt='', is_first_sp=true) %}{%- for message in messages %}{%- if message['role'] == 'system' %}{%- if ns.is_first_sp %}{% set ns.system_prompt = ns.system_prompt + message['content'] %}{% set ns.is_first_sp = false %}{%- else %}{% set ns.system_prompt = ns.system_prompt + '\n\n' + message['content'] %}{%- endif %}{%- endif %}{%- endfor %}{{ bos_token }}{{ ns.system_prompt }}{%- for message in messages %}{%- if message['role'] == 'user' %}{%- set ns.is_tool = false -%}{{'<|User|>' + message['content']}}{%- endif %}{%- if message['role'] == 'assistant' and 'tool_calls' in message %}{%- set ns.is_tool = false -%}{%- generation %}{%- for tool in message['tool_calls'] %}{%- if not ns.is_first %}{%- if message['content'] is none %}{{'<|Assistant|><|tool▁calls▁begin|><|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\n' + '```json' + '\n' + tool['function']['arguments'] | tojson + '\n' + '```' + '<|tool▁call▁end|>'}}{%- else %}{{'<|Assistant|>' + message['content'] + '<|tool▁calls▁begin|><|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\n' + '```json' + '\n' + tool['function']['arguments'] | tojson + '\n' + '```' + '<|tool▁call▁end|>'}}{%- endif %}{%- set ns.is_first = true -%}{%- else %}{{'\n' + '<|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\n' + '```json' + '\n' + tool['function']['arguments'] | tojson + '\n' + '```' + '<|tool▁call▁end|>'}}{%- endif %}{%- endfor %}{{'<|tool▁calls▁end|><|end▁of▁sentence|>'}}{%- endgeneration %}{%- endif %}{%- if message['role'] == 'assistant' and 'tool_calls' not in message %}{%- if ns.is_tool %}{%- generation %}{{'<|tool▁outputs▁end|>' + message['content'] + '<|end▁of▁sentence|>'}}{%- set ns.is_tool = false -%}{%- endgeneration %}{%- else %}{%- generation %}{% set content = message['content'] %}{% if '' in content %}{% set content = content.split('')[-1] %}{% endif %}{{'<|Assistant|>' + content + '<|end▁of▁sentence|>'}}{%- endgeneration %}{%- endif %}{%- endif %}{%- if message['role'] == 'tool' %}{%- set ns.is_tool = true -%}{%- if ns.is_output_first %}{{'<|tool▁outputs▁begin|><|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- set ns.is_output_first = false %}{%- else %}{{'<|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- endif %}{%- endif %}{%- endfor -%}{% if ns.is_tool %}{{'<|tool▁outputs▁end|>'}}{% endif %}{% if add_generation_prompt and not ns.is_tool %}{{'<|Assistant|>\n'}}{% endif %} \ No newline at end of file diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/gemma.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/gemma.jinja new file mode 100644 index 0000000000000000000000000000000000000000..923ec253c8dbefbb41cf084db7251df41d000f6d --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/gemma.jinja @@ -0,0 +1,4 @@ +{{ bos_token }}{% if messages[0]['role'] == 'system' %}{{ raise_exception('System role not supported') }}{% endif %}{% for message in messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if (message['role'] == 'assistant') %}{% set role = 'model' %}{% else %}{% set role = message['role'] %}{% endif %}{{ '' + role + ' +' + message['content'] | trim + ' +' }}{% endfor %}{% if add_generation_prompt %}{{'model +'}}{% endif %} \ No newline at end of file diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/gemma3.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/gemma3.jinja new file mode 100644 index 0000000000000000000000000000000000000000..1117055ab8e8c90e1b200be00cddb78943616d9e --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/gemma3.jinja @@ -0,0 +1,47 @@ +{{ bos_token }} +{%- if messages[0]['role'] == 'system' -%} + {%- if messages[0]['content'] is string -%} + {%- set first_user_prefix = messages[0]['content'] + ' + +' -%} + {%- else -%} + {%- set first_user_prefix = messages[0]['content'][0]['text'] + ' + +' -%} + {%- endif -%} + {%- set loop_messages = messages[1:] -%} +{%- else -%} + {%- set first_user_prefix = "" -%} + {%- set loop_messages = messages -%} +{%- endif -%} +{%- for message in loop_messages -%} + {%- if (message['role'] == 'user') != (loop.index0 % 2 == 0) -%} + {{ raise_exception("Conversation roles must alternate user/assistant/user/assistant/...") }} + {%- endif -%} + {%- if (message['role'] == 'assistant') -%} + {%- set role = "model" -%} + {%- else -%} + {%- set role = message['role'] -%} + {%- endif -%} + {{ '' + role + ' +' + (first_user_prefix if loop.first else "") }} + {%- if message['content'] is string -%} + {{ message['content'] | trim }} + {%- elif message['content'] is iterable -%} + {%- for item in message['content'] -%} + {%- if item['type'] == 'image' -%} + {{ '' }} + {%- elif item['type'] == 'text' -%} + {{ item['text'] | trim }} + {%- endif -%} + {%- endfor -%} + {%- else -%} + {{ raise_exception("Invalid content type") }} + {%- endif -%} + {{ ' +' }} +{%- endfor -%} +{%- if add_generation_prompt -%} + {{'model +'}} +{%- endif -%} diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/gemma3_training.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/gemma3_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..c76c297f50959fc40c586b50a672b24c9f7e9500 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/gemma3_training.jinja @@ -0,0 +1,72 @@ +{#- Training variant of the Gemma 3 chat template (see gemma3.jinja for the original). + Modifications vs the original: + - Split the unified output line into role-specific branches so that the + 'model\n' header (a prompt cue, not generated by the model) sits + outside the generation block. + - Added {% generation %} / {% endgeneration %} around assistant message content to + support assistant-only loss masking in SFT training. +-#} +{{ bos_token }} +{%- if messages[0]['role'] == 'system' -%} + {%- if messages[0]['content'] is string -%} + {%- set first_user_prefix = messages[0]['content'] + ' + +' -%} + {%- else -%} + {%- set first_user_prefix = messages[0]['content'][0]['text'] + ' + +' -%} + {%- endif -%} + {%- set loop_messages = messages[1:] -%} +{%- else -%} + {%- set first_user_prefix = "" -%} + {%- set loop_messages = messages -%} +{%- endif -%} +{%- for message in loop_messages -%} + {%- if (message['role'] == 'user') != (loop.index0 % 2 == 0) -%} + {{ raise_exception("Conversation roles must alternate user/assistant/user/assistant/...") }} + {%- endif -%} + {%- if message['role'] == 'assistant' -%} + {{ 'model +' }} + {%- generation -%} + {%- if message['content'] is string -%} + {{ message['content'] | trim }} + {%- elif message['content'] is iterable -%} + {%- for item in message['content'] -%} + {%- if item['type'] == 'image' -%} + {{ '' }} + {%- elif item['type'] == 'text' -%} + {{ item['text'] | trim }} + {%- endif -%} + {%- endfor -%} + {%- else -%} + {{ raise_exception("Invalid content type") }} + {%- endif -%} + {{ ' +' }} + {%- endgeneration -%} + {%- else -%} + {{ '' + message['role'] + ' +' + (first_user_prefix if loop.first else "") }} + {%- if message['content'] is string -%} + {{ message['content'] | trim }} + {%- elif message['content'] is iterable -%} + {%- for item in message['content'] -%} + {%- if item['type'] == 'image' -%} + {{ '' }} + {%- elif item['type'] == 'text' -%} + {{ item['text'] | trim }} + {%- endif -%} + {%- endfor -%} + {%- else -%} + {{ raise_exception("Invalid content type") }} + {%- endif -%} + {{ ' +' }} + {%- endif -%} +{%- endfor -%} +{%- if add_generation_prompt -%} + {{'model +'}} +{%- endif -%} diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/gemma_training.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/gemma_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..290e63f8ebe2917790b67568cefb231804a08299 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/gemma_training.jinja @@ -0,0 +1,29 @@ +{#- Training variant of the Gemma chat template (see gemma.jinja for the original). + This template is shared by Gemma (v1) and Gemma2, which ship identical chat templates. + Modifications vs the original: + - Split the unified output line into role-specific branches so that the + 'model\n' header (a prompt cue, not generated by the model) sits + outside the generation block. + - Added {% generation %} / {% endgeneration %} around assistant message content to + support assistant-only loss masking in SFT training. +-#} +{{- bos_token -}} +{%- if messages[0]['role'] == 'system' -%} + {{- raise_exception('System role not supported') -}} +{%- endif -%} +{%- for message in messages -%} + {%- if (message['role'] == 'user') != (loop.index0 % 2 == 0) -%} + {{- raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') -}} + {%- endif -%} + {%- if message['role'] == 'assistant' -%} + {{- 'model\n' -}} + {%- generation -%} + {{- message['content'] | trim + '\n' -}} + {%- endgeneration -%} + {%- else -%} + {{- '' + message['role'] + '\n' + message['content'] | trim + '\n' -}} + {%- endif -%} +{%- endfor -%} +{%- if add_generation_prompt -%} + {{- 'model\n' -}} +{%- endif -%} diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/glm4moe.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/glm4moe.jinja new file mode 100644 index 0000000000000000000000000000000000000000..41478957aca7a04b7321022e7d1f73de5badd995 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/glm4moe.jinja @@ -0,0 +1,103 @@ +[gMASK] +{%- if tools -%} +<|system|> +# Tools + +You may call one or more functions to assist with the user query. + +You are provided with function signatures within XML tags: + +{% for tool in tools %} +{{ tool | tojson(ensure_ascii=False) }} +{% endfor %} + + +For each function call, output the function name and arguments within the following XML format: +{function-name} +{arg-key-1} +{arg-value-1} +{arg-key-2} +{arg-value-2} +... +{%- endif -%} +{%- macro visible_text(content) -%} + {%- if content is string -%} + {{- content }} + {%- elif content is iterable and content is not mapping -%} + {%- for item in content -%} + {%- if item is mapping and item.type == 'text' -%} + {{- item.text }} + {%- elif item is string -%} + {{- item }} + {%- endif -%} + {%- endfor -%} + {%- else -%} + {{- content }} + {%- endif -%} +{%- endmacro -%} +{%- set ns = namespace(last_user_index=-1) %} +{%- for m in messages %} + {%- if m.role == 'user' %} + {% set ns.last_user_index = loop.index0 -%} + {%- endif %} +{%- endfor %} +{% for m in messages %} +{%- if m.role == 'user' -%}<|user|> +{{ visible_text(m.content) }} +{{- '/nothink' if (enable_thinking is defined and not enable_thinking and not visible_text(m.content).endswith("/nothink")) else '' -}} +{%- elif m.role == 'assistant' -%} +<|assistant|> +{%- set reasoning_content = '' %} +{%- set content = visible_text(m.content) %} +{%- if m.reasoning_content is string %} + {%- set reasoning_content = m.reasoning_content %} +{%- else %} + {%- if '' in content %} + {%- set reasoning_content = content.split('')[0].rstrip('\n').split('')[-1].lstrip('\n') %} + {%- set content = content.split('')[-1].lstrip('\n') %} + {%- endif %} +{%- endif %} +{%- if loop.index0 > ns.last_user_index and reasoning_content -%} +{{ '\n' + reasoning_content.strip() + ''}} +{%- else -%} +{{ '\n' }} +{%- endif -%} +{%- if content.strip() -%} +{{ '\n' + content.strip() }} +{%- endif -%} +{% if m.tool_calls %} +{% for tc in m.tool_calls %} +{%- if tc.function %} + {%- set tc = tc.function %} +{%- endif %} +{{ '\n' + tc.name }} +{% set _args = tc.arguments %} +{% for k, v in _args.items() %} +{{ k }} +{{ v | tojson(ensure_ascii=False) if v is not string else v }} +{% endfor %} +{% endfor %} +{% endif %} +{%- elif m.role == 'tool' -%} +{%- if m.content is string -%} +{%- if loop.first or (messages[loop.index0 - 1].role != "tool") %} + {{- '<|observation|>' }} +{%- endif %} +{{- '\n\n' }} +{{- m.content }} +{{- '\n' }} +{%- else -%} +<|observation|>{% for tr in m.content %} + + +{{ tr.output if tr.output is defined else tr }} +{% endfor -%} +{% endif -%} +{%- elif m.role == 'system' -%} +<|system|> +{{ visible_text(m.content) }} +{%- endif -%} +{%- endfor -%} +{%- if add_generation_prompt -%} + <|assistant|>{{- '\n' if (enable_thinking is defined and not enable_thinking) else '' -}} +{%- endif -%} \ No newline at end of file diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/glm4moe_training.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/glm4moe_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..622f6ddf124333c0376d2c5921f341ddc51a9d4e --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/glm4moe_training.jinja @@ -0,0 +1,109 @@ +[gMASK] +{%- if tools -%} +<|system|> +# Tools + +You may call one or more functions to assist with the user query. + +You are provided with function signatures within XML tags: + +{% for tool in tools %} +{{ tool | tojson(ensure_ascii=False) }} +{% endfor %} + + +For each function call, output the function name and arguments within the following XML format: +{function-name} +{arg-key-1} +{arg-value-1} +{arg-key-2} +{arg-value-2} +... +{%- endif -%} +{%- macro visible_text(content) -%} + {%- if content is string -%} + {{- content }} + {%- elif content is iterable and content is not mapping -%} + {%- for item in content -%} + {%- if item is mapping and item.type == 'text' -%} + {{- item.text }} + {%- elif item is string -%} + {{- item }} + {%- endif -%} + {%- endfor -%} + {%- else -%} + {{- content }} + {%- endif -%} +{%- endmacro -%} +{%- set ns = namespace(last_user_index=-1) %} +{%- for m in messages %} + {%- if m.role == 'user' %} + {% set ns.last_user_index = loop.index0 -%} + {%- endif %} +{%- endfor %} +{% for m in messages %} +{%- if m.role == 'user' -%} +{%- if loop.first or messages[loop.index0 - 1].role != 'assistant' -%}<|user|>{%- endif -%} +{{ '\n' + visible_text(m.content) }} +{{- '/nothink' if (enable_thinking is defined and not enable_thinking and not visible_text(m.content).endswith("/nothink")) else '' -}} +{%- elif m.role == 'assistant' -%} +<|assistant|> +{%- set reasoning_content = '' %} +{%- set content = visible_text(m.content) %} +{%- if m.reasoning_content is string %} + {%- set reasoning_content = m.reasoning_content %} +{%- else %} + {%- if '' in content %} + {%- set reasoning_content = content.split('')[0].rstrip('\n').split('')[-1].lstrip('\n') %} + {%- set content = content.split('')[-1].lstrip('\n') %} + {%- endif %} +{%- endif %} +{% generation %} +{%- if loop.index0 > ns.last_user_index and reasoning_content -%} +{{ '\n' + reasoning_content.strip() + ''}} +{%- else -%} +{{ '\n' }} +{%- endif -%} +{%- if content.strip() -%} +{{ '\n' + content.strip() }} +{%- endif -%} +{% if m.tool_calls %} +{% for tc in m.tool_calls %} +{%- if tc.function %} + {%- set tc = tc.function %} +{%- endif %} +{{ '\n' + tc.name }} +{% set _args = tc.arguments %} +{% for k, v in _args.items() %} +{{ k }} +{{ v | tojson(ensure_ascii=False) if v is not string else v }} +{% endfor %} +{% endfor %}<|observation|> +{%- elif loop.last -%} +{{- '<|user|>' }} +{%- elif messages[loop.index0 + 1].role == 'system' -%} +{{- '<|system|>' }} +{%- else -%} +{{- '<|user|>' }} +{%- endif %} +{% endgeneration %} +{%- elif m.role == 'tool' -%} +{%- if m.content is string -%} +{{- '\n\n' }} +{{- m.content }} +{{- '\n' }} +{%- else -%} +{{- '<|observation|>' if loop.first or messages[loop.index0 - 1].role != 'assistant' }}{% for tr in m.content %} + + +{{ tr.output if tr.output is defined else tr }} +{% endfor -%} +{% endif -%} +{%- elif m.role == 'system' -%} +{%- if loop.first or messages[loop.index0 - 1].role != 'assistant' -%}<|system|>{%- endif -%} +{{ '\n' + visible_text(m.content) }} +{%- endif -%} +{%- endfor -%} +{%- if add_generation_prompt -%} + <|assistant|>{{- '\n' if (enable_thinking is defined and not enable_thinking) else '' -}} +{%- endif -%} diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/gptoss.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/gptoss.jinja new file mode 100644 index 0000000000000000000000000000000000000000..dc7bb11927d29f653ba2740f2db2c688fd77592f --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/gptoss.jinja @@ -0,0 +1,331 @@ +{#- + In addition to the normal inputs of `messages` and `tools`, this template also accepts the + following kwargs: + - "builtin_tools": A list, can contain "browser" and/or "python". + - "model_identity": A string that optionally describes the model identity. + - "reasoning_effort": A string that describes the reasoning effort, defaults to "medium". + #} + +{#- Tool Definition Rendering ============================================== #} +{%- macro render_typescript_type(param_spec, required_params, is_nullable=false) -%} + {%- if param_spec.type == "array" -%} + {%- if param_spec['items'] -%} + {%- if param_spec['items']['type'] == "string" -%} + {{- "string[]" }} + {%- elif param_spec['items']['type'] == "number" -%} + {{- "number[]" }} + {%- elif param_spec['items']['type'] == "integer" -%} + {{- "number[]" }} + {%- elif param_spec['items']['type'] == "boolean" -%} + {{- "boolean[]" }} + {%- else -%} + {%- set inner_type = render_typescript_type(param_spec['items'], required_params) -%} + {%- if inner_type == "object | object" or inner_type|length > 50 -%} + {{- "any[]" }} + {%- else -%} + {{- inner_type + "[]" }} + {%- endif -%} + {%- endif -%} + {%- if param_spec.nullable -%} + {{- " | null" }} + {%- endif -%} + {%- else -%} + {{- "any[]" }} + {%- if param_spec.nullable -%} + {{- " | null" }} + {%- endif -%} + {%- endif -%} + {%- elif param_spec.type is defined and param_spec.type is iterable and param_spec.type is not string and param_spec.type is not mapping and param_spec.type[0] is defined -%} + {#- Handle array of types like ["object", "object"] from Union[dict, list] #} + {%- if param_spec.type | length > 1 -%} + {{- param_spec.type | join(" | ") }} + {%- else -%} + {{- param_spec.type[0] }} + {%- endif -%} + {%- elif param_spec.oneOf -%} + {#- Handle oneOf schemas - check for complex unions and fallback to any #} + {%- set has_object_variants = false -%} + {%- for variant in param_spec.oneOf -%} + {%- if variant.type == "object" -%} + {%- set has_object_variants = true -%} + {%- endif -%} + {%- endfor -%} + {%- if has_object_variants and param_spec.oneOf|length > 1 -%} + {{- "any" }} + {%- else -%} + {%- for variant in param_spec.oneOf -%} + {{- render_typescript_type(variant, required_params) -}} + {%- if variant.description %} + {{- "// " + variant.description }} + {%- endif -%} + {%- if variant.default is defined %} + {{ "// default: " + variant.default|tojson }} + {%- endif -%} + {%- if not loop.last %} + {{- " | " }} + {% endif -%} + {%- endfor -%} + {%- endif -%} + {%- elif param_spec.type == "string" -%} + {%- if param_spec.enum -%} + {{- '"' + param_spec.enum|join('" | "') + '"' -}} + {%- else -%} + {{- "string" }} + {%- if param_spec.nullable %} + {{- " | null" }} + {%- endif -%} + {%- endif -%} + {%- elif param_spec.type == "number" -%} + {{- "number" }} + {%- elif param_spec.type == "integer" -%} + {{- "number" }} + {%- elif param_spec.type == "boolean" -%} + {{- "boolean" }} + + {%- elif param_spec.type == "object" -%} + {%- if param_spec.properties -%} + {{- "{\n" }} + {%- for prop_name, prop_spec in param_spec.properties.items() -%} + {{- prop_name -}} + {%- if prop_name not in (param_spec.required or []) -%} + {{- "?" }} + {%- endif -%} + {{- ": " }} + {{ render_typescript_type(prop_spec, param_spec.required or []) }} + {%- if not loop.last -%} + {{-", " }} + {%- endif -%} + {%- endfor -%} + {{- "}" }} + {%- else -%} + {{- "object" }} + {%- endif -%} + {%- else -%} + {{- "any" }} + {%- endif -%} +{%- endmacro -%} + +{%- macro render_tool_namespace(namespace_name, tools) -%} + {{- "## " + namespace_name + "\n\n" }} + {{- "namespace " + namespace_name + " {\n\n" }} + {%- for tool in tools %} + {%- set tool = tool.function %} + {{- "// " + tool.description + "\n" }} + {{- "type "+ tool.name + " = " }} + {%- if tool.parameters and tool.parameters.properties %} + {{- "(_: {\n" }} + {%- for param_name, param_spec in tool.parameters.properties.items() %} + {%- if param_spec.description %} + {{- "// " + param_spec.description + "\n" }} + {%- endif %} + {{- param_name }} + {%- if param_name not in (tool.parameters.required or []) -%} + {{- "?" }} + {%- endif -%} + {{- ": " }} + {{- render_typescript_type(param_spec, tool.parameters.required or []) }} + {%- if param_spec.default is defined -%} + {%- if param_spec.enum %} + {{- ", // default: " + param_spec.default }} + {%- elif param_spec.oneOf %} + {{- "// default: " + param_spec.default }} + {%- else %} + {{- ", // default: " + param_spec.default|tojson }} + {%- endif -%} + {%- endif -%} + {%- if not loop.last %} + {{- ",\n" }} + {%- else %} + {{- ",\n" }} + {%- endif -%} + {%- endfor %} + {{- "}) => any;\n\n" }} + {%- else -%} + {{- "() => any;\n\n" }} + {%- endif -%} + {%- endfor %} + {{- "} // namespace " + namespace_name }} +{%- endmacro -%} + +{%- macro render_builtin_tools(browser_tool, python_tool) -%} + {%- if browser_tool %} + {{- "## browser\n\n" }} + {{- "// Tool for browsing.\n" }} + {{- "// The `cursor` appears in brackets before each browsing display: `[{cursor}]`.\n" }} + {{- "// Cite information from the tool using the following format:\n" }} + {{- "// `【{cursor}†L{line_start}(-L{line_end})?】`, for example: `【6†L9-L11】` or `【8†L3】`.\n" }} + {{- "// Do not quote more than 10 words directly from the tool output.\n" }} + {{- "// sources=web (default: web)\n" }} + {{- "namespace browser {\n\n" }} + {{- "// Searches for information related to `query` and displays `topn` results.\n" }} + {{- "type search = (_: {\n" }} + {{- "query: string,\n" }} + {{- "topn?: number, // default: 10\n" }} + {{- "source?: string,\n" }} + {{- "}) => any;\n\n" }} + {{- "// Opens the link `id` from the page indicated by `cursor` starting at line number `loc`, showing `num_lines` lines.\n" }} + {{- "// Valid link ids are displayed with the formatting: `【{id}†.*】`.\n" }} + {{- "// If `cursor` is not provided, the most recent page is implied.\n" }} + {{- "// If `id` is a string, it is treated as a fully qualified URL associated with `source`.\n" }} + {{- "// If `loc` is not provided, the viewport will be positioned at the beginning of the document or centered on the most relevant passage, if available.\n" }} + {{- "// Use this function without `id` to scroll to a new location of an opened page.\n" }} + {{- "type open = (_: {\n" }} + {{- "id?: number | string, // default: -1\n" }} + {{- "cursor?: number, // default: -1\n" }} + {{- "loc?: number, // default: -1\n" }} + {{- "num_lines?: number, // default: -1\n" }} + {{- "view_source?: boolean, // default: false\n" }} + {{- "source?: string,\n" }} + {{- "}) => any;\n\n" }} + {{- "// Finds exact matches of `pattern` in the current page, or the page given by `cursor`.\n" }} + {{- "type find = (_: {\n" }} + {{- "pattern: string,\n" }} + {{- "cursor?: number, // default: -1\n" }} + {{- "}) => any;\n\n" }} + {{- "} // namespace browser\n\n" }} + {%- endif -%} + + {%- if python_tool %} + {{- "## python\n\n" }} + {{- "Use this tool to execute Python code in your chain of thought. The code will not be shown to the user. This tool should be used for internal reasoning, but not for code that is intended to be visible to the user (e.g. when creating plots, tables, or files).\n\n" }} + {{- "When you send a message containing Python code to python, it will be executed in a stateful Jupyter notebook environment. python will respond with the output of the execution or time out after 120.0 seconds. The drive at '/mnt/data' can be used to save and persist user files. Internet access for this session is UNKNOWN. Depends on the cluster.\n\n" }} + {%- endif -%} +{%- endmacro -%} + +{#- System Message Construction ============================================ #} +{%- macro build_system_message() -%} + {%- if model_identity is not defined %} + {%- set model_identity = "You are ChatGPT, a large language model trained by OpenAI." %} + {%- endif %} + {{- model_identity + "\n" }} + {{- "Knowledge cutoff: 2024-06\n" }} + {{- "Current date: " + strftime_now("%Y-%m-%d") + "\n\n" }} + {%- if reasoning_effort is not defined %} + {%- set reasoning_effort = "medium" %} + {%- endif %} + {{- "Reasoning: " + reasoning_effort + "\n\n" }} + {%- if builtin_tools %} + {{- "# Tools\n\n" }} + {%- set available_builtin_tools = namespace(browser=false, python=false) %} + {%- for tool in builtin_tools %} + {%- if tool == "browser" %} + {%- set available_builtin_tools.browser = true %} + {%- elif tool == "python" %} + {%- set available_builtin_tools.python = true %} + {%- endif %} + {%- endfor %} + {{- render_builtin_tools(available_builtin_tools.browser, available_builtin_tools.python) }} + {%- endif -%} + {{- "# Valid channels: analysis, commentary, final. Channel must be included for every message." }} + {%- if tools -%} + {{- "\nCalls to these tools must go to the commentary channel: 'functions'." }} + {%- endif -%} +{%- endmacro -%} + +{#- Main Template Logic ================================================= #} +{#- Set defaults #} + +{#- Render system message #} +{{- "<|start|>system<|message|>" }} +{{- build_system_message() }} +{{- "<|end|>" }} + +{#- Extract developer message #} +{%- if messages[0].role == "developer" or messages[0].role == "system" %} + {%- set developer_message = messages[0].content %} + {%- set loop_messages = messages[1:] %} +{%- else %} + {%- set developer_message = "" %} + {%- set loop_messages = messages %} +{%- endif %} + +{#- Render developer message #} +{%- if developer_message or tools %} + {{- "<|start|>developer<|message|>" }} + {%- if developer_message %} + {{- "# Instructions\n\n" }} + {{- developer_message }} + {{- "\n\n" }} + {%- endif %} + {%- if tools -%} + {{- "# Tools\n\n" }} + {{- render_tool_namespace("functions", tools) }} + {%- endif -%} + {{- "<|end|>" }} +{%- endif %} + +{#- Render messages #} +{%- set last_tool_call = namespace(name=none) %} +{%- for message in loop_messages -%} + {#- At this point only assistant/user/tool messages should remain #} + {%- if message.role == 'assistant' -%} + {#- Checks to ensure the messages are being passed in the format we expect #} + {%- if "content" in message %} + {%- if "<|channel|>analysis<|message|>" in message.content or "<|channel|>final<|message|>" in message.content %} + {{- raise_exception("You have passed a message containing <|channel|> tags in the content field. Instead of doing this, you should pass analysis messages (the string between '<|message|>' and '<|end|>') in the 'thinking' field, and final messages (the string between '<|message|>' and '<|end|>') in the 'content' field.") }} + {%- endif %} + {%- endif %} + {%- if "thinking" in message %} + {%- if "<|channel|>analysis<|message|>" in message.thinking or "<|channel|>final<|message|>" in message.thinking %} + {{- raise_exception("You have passed a message containing <|channel|> tags in the thinking field. Instead of doing this, you should pass analysis messages (the string between '<|message|>' and '<|end|>') in the 'thinking' field, and final messages (the string between '<|message|>' and '<|end|>') in the 'content' field.") }} + {%- endif %} + {%- endif %} + {%- if "tool_calls" in message %} + {#- We need very careful handling here - we want to drop the tool call analysis message if the model #} + {#- has output a later <|final|> message, but otherwise we want to retain it. This is the only case #} + {#- when we render CoT/analysis messages in inference. #} + {%- set future_final_message = namespace(found=false) %} + {%- for future_message in loop_messages[loop.index:] %} + {%- if future_message.role == 'assistant' and "tool_calls" not in future_message %} + {%- set future_final_message.found = true %} + {%- endif %} + {%- endfor %} + {#- We assume max 1 tool call per message, and so we infer the tool call name #} + {#- in "tool" messages from the most recent assistant tool call name #} + {%- set tool_call = message.tool_calls[0] %} + {%- if tool_call.function %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {%- if message.content and message.thinking %} + {{- raise_exception("Cannot pass both content and thinking in an assistant message with tool calls! Put the analysis message in one or the other, but not both.") }} + {%- elif message.content and not future_final_message.found %} + {{- "<|start|>assistant<|channel|>analysis<|message|>" + message.content + "<|end|>" }} + {%- elif message.thinking and not future_final_message.found %} + {{- "<|start|>assistant<|channel|>analysis<|message|>" + message.thinking + "<|end|>" }} + {%- endif %} + {{- "<|start|>assistant to=" }} + {{- "functions." + tool_call.name + "<|channel|>commentary " }} + {{- (tool_call.content_type if tool_call.content_type is defined else "json") + "<|message|>" }} + {{- tool_call.arguments|tojson }} + {{- "<|call|>" }} + {%- set last_tool_call.name = tool_call.name %} + {%- elif loop.last and not add_generation_prompt %} + {#- Only render the CoT if the final turn is an assistant turn and add_generation_prompt is false #} + {#- This is a situation that should only occur in training, never in inference. #} + {%- if "thinking" in message %} + {{- "<|start|>assistant<|channel|>analysis<|message|>" + message.thinking + "<|end|>" }} + {%- endif %} + {#- <|return|> indicates the end of generation, but <|end|> does not #} + {#- <|return|> should never be an input to the model, but we include it as the final token #} + {#- when training, so the model learns to emit it. #} + {{- "<|start|>assistant<|channel|>final<|message|>" + message.content + "<|return|>" }} + {%- else %} + {#- CoT is dropped during all previous turns, so we never render it for inference #} + {{- "<|start|>assistant<|channel|>final<|message|>" + message.content + "<|end|>" }} + {%- set last_tool_call.name = none %} + {%- endif %} + {%- elif message.role == 'tool' -%} + {%- if last_tool_call.name is none %} + {{- raise_exception("Message has tool role, but there was no previous assistant message with a tool call!") }} + {%- endif %} + {{- "<|start|>functions." + last_tool_call.name }} + {{- " to=assistant<|channel|>commentary<|message|>" + message.content|tojson + "<|end|>" }} + {%- elif message.role == 'user' -%} + {{- "<|start|>user<|message|>" + message.content + "<|end|>" }} + {%- endif -%} +{%- endfor -%} + +{#- Generation prompt #} +{%- if add_generation_prompt -%} +<|start|>assistant +{%- endif -%} \ No newline at end of file diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/gptoss_training.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/gptoss_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..f635725a0d0c36d1efedda8fe51bf9c4e7f75739 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/gptoss_training.jinja @@ -0,0 +1,338 @@ +{#- + Training variant of the GPT-OSS chat template (see gptoss.jinja for the original). + Modifications vs the original: + - Added {% generation %} / {% endgeneration %} around assistant message output to support + assistant-only loss masking in SFT training. + + In addition to the normal inputs of `messages` and `tools`, this template also accepts the + following kwargs: + - "builtin_tools": A list, can contain "browser" and/or "python". + - "model_identity": A string that optionally describes the model identity. + - "reasoning_effort": A string that describes the reasoning effort, defaults to "medium". + #} + +{#- Tool Definition Rendering ============================================== #} +{%- macro render_typescript_type(param_spec, required_params, is_nullable=false) -%} + {%- if param_spec.type == "array" -%} + {%- if param_spec['items'] -%} + {%- if param_spec['items']['type'] == "string" -%} + {{- "string[]" }} + {%- elif param_spec['items']['type'] == "number" -%} + {{- "number[]" }} + {%- elif param_spec['items']['type'] == "integer" -%} + {{- "number[]" }} + {%- elif param_spec['items']['type'] == "boolean" -%} + {{- "boolean[]" }} + {%- else -%} + {%- set inner_type = render_typescript_type(param_spec['items'], required_params) -%} + {%- if inner_type == "object | object" or inner_type|length > 50 -%} + {{- "any[]" }} + {%- else -%} + {{- inner_type + "[]" }} + {%- endif -%} + {%- endif -%} + {%- if param_spec.nullable -%} + {{- " | null" }} + {%- endif -%} + {%- else -%} + {{- "any[]" }} + {%- if param_spec.nullable -%} + {{- " | null" }} + {%- endif -%} + {%- endif -%} + {%- elif param_spec.type is defined and param_spec.type is iterable and param_spec.type is not string and param_spec.type is not mapping and param_spec.type[0] is defined -%} + {#- Handle array of types like ["object", "object"] from Union[dict, list] #} + {%- if param_spec.type | length > 1 -%} + {{- param_spec.type | join(" | ") }} + {%- else -%} + {{- param_spec.type[0] }} + {%- endif -%} + {%- elif param_spec.oneOf -%} + {#- Handle oneOf schemas - check for complex unions and fallback to any #} + {%- set has_object_variants = false -%} + {%- for variant in param_spec.oneOf -%} + {%- if variant.type == "object" -%} + {%- set has_object_variants = true -%} + {%- endif -%} + {%- endfor -%} + {%- if has_object_variants and param_spec.oneOf|length > 1 -%} + {{- "any" }} + {%- else -%} + {%- for variant in param_spec.oneOf -%} + {{- render_typescript_type(variant, required_params) -}} + {%- if variant.description %} + {{- "// " + variant.description }} + {%- endif -%} + {%- if variant.default is defined %} + {{ "// default: " + variant.default|tojson }} + {%- endif -%} + {%- if not loop.last %} + {{- " | " }} + {% endif -%} + {%- endfor -%} + {%- endif -%} + {%- elif param_spec.type == "string" -%} + {%- if param_spec.enum -%} + {{- '"' + param_spec.enum|join('" | "') + '"' -}} + {%- else -%} + {{- "string" }} + {%- if param_spec.nullable %} + {{- " | null" }} + {%- endif -%} + {%- endif -%} + {%- elif param_spec.type == "number" -%} + {{- "number" }} + {%- elif param_spec.type == "integer" -%} + {{- "number" }} + {%- elif param_spec.type == "boolean" -%} + {{- "boolean" }} + + {%- elif param_spec.type == "object" -%} + {%- if param_spec.properties -%} + {{- "{\n" }} + {%- for prop_name, prop_spec in param_spec.properties.items() -%} + {{- prop_name -}} + {%- if prop_name not in (param_spec.required or []) -%} + {{- "?" }} + {%- endif -%} + {{- ": " }} + {{ render_typescript_type(prop_spec, param_spec.required or []) }} + {%- if not loop.last -%} + {{-", " }} + {%- endif -%} + {%- endfor -%} + {{- "}" }} + {%- else -%} + {{- "object" }} + {%- endif -%} + {%- else -%} + {{- "any" }} + {%- endif -%} +{%- endmacro -%} + +{%- macro render_tool_namespace(namespace_name, tools) -%} + {{- "## " + namespace_name + "\n\n" }} + {{- "namespace " + namespace_name + " {\n\n" }} + {%- for tool in tools %} + {%- set tool = tool.function %} + {{- "// " + tool.description + "\n" }} + {{- "type "+ tool.name + " = " }} + {%- if tool.parameters and tool.parameters.properties %} + {{- "(_: {\n" }} + {%- for param_name, param_spec in tool.parameters.properties.items() %} + {%- if param_spec.description %} + {{- "// " + param_spec.description + "\n" }} + {%- endif %} + {{- param_name }} + {%- if param_name not in (tool.parameters.required or []) -%} + {{- "?" }} + {%- endif -%} + {{- ": " }} + {{- render_typescript_type(param_spec, tool.parameters.required or []) }} + {%- if param_spec.default is defined -%} + {%- if param_spec.enum %} + {{- ", // default: " + param_spec.default }} + {%- elif param_spec.oneOf %} + {{- "// default: " + param_spec.default }} + {%- else %} + {{- ", // default: " + param_spec.default|tojson }} + {%- endif -%} + {%- endif -%} + {%- if not loop.last %} + {{- ",\n" }} + {%- else %} + {{- ",\n" }} + {%- endif -%} + {%- endfor %} + {{- "}) => any;\n\n" }} + {%- else -%} + {{- "() => any;\n\n" }} + {%- endif -%} + {%- endfor %} + {{- "} // namespace " + namespace_name }} +{%- endmacro -%} + +{%- macro render_builtin_tools(browser_tool, python_tool) -%} + {%- if browser_tool %} + {{- "## browser\n\n" }} + {{- "// Tool for browsing.\n" }} + {{- "// The `cursor` appears in brackets before each browsing display: `[{cursor}]`.\n" }} + {{- "// Cite information from the tool using the following format:\n" }} + {{- "// `【{cursor}†L{line_start}(-L{line_end})?】`, for example: `【6†L9-L11】` or `【8†L3】`.\n" }} + {{- "// Do not quote more than 10 words directly from the tool output.\n" }} + {{- "// sources=web (default: web)\n" }} + {{- "namespace browser {\n\n" }} + {{- "// Searches for information related to `query` and displays `topn` results.\n" }} + {{- "type search = (_: {\n" }} + {{- "query: string,\n" }} + {{- "topn?: number, // default: 10\n" }} + {{- "source?: string,\n" }} + {{- "}) => any;\n\n" }} + {{- "// Opens the link `id` from the page indicated by `cursor` starting at line number `loc`, showing `num_lines` lines.\n" }} + {{- "// Valid link ids are displayed with the formatting: `【{id}†.*】`.\n" }} + {{- "// If `cursor` is not provided, the most recent page is implied.\n" }} + {{- "// If `id` is a string, it is treated as a fully qualified URL associated with `source`.\n" }} + {{- "// If `loc` is not provided, the viewport will be positioned at the beginning of the document or centered on the most relevant passage, if available.\n" }} + {{- "// Use this function without `id` to scroll to a new location of an opened page.\n" }} + {{- "type open = (_: {\n" }} + {{- "id?: number | string, // default: -1\n" }} + {{- "cursor?: number, // default: -1\n" }} + {{- "loc?: number, // default: -1\n" }} + {{- "num_lines?: number, // default: -1\n" }} + {{- "view_source?: boolean, // default: false\n" }} + {{- "source?: string,\n" }} + {{- "}) => any;\n\n" }} + {{- "// Finds exact matches of `pattern` in the current page, or the page given by `cursor`.\n" }} + {{- "type find = (_: {\n" }} + {{- "pattern: string,\n" }} + {{- "cursor?: number, // default: -1\n" }} + {{- "}) => any;\n\n" }} + {{- "} // namespace browser\n\n" }} + {%- endif -%} + + {%- if python_tool %} + {{- "## python\n\n" }} + {{- "Use this tool to execute Python code in your chain of thought. The code will not be shown to the user. This tool should be used for internal reasoning, but not for code that is intended to be visible to the user (e.g. when creating plots, tables, or files).\n\n" }} + {{- "When you send a message containing Python code to python, it will be executed in a stateful Jupyter notebook environment. python will respond with the output of the execution or time out after 120.0 seconds. The drive at '/mnt/data' can be used to save and persist user files. Internet access for this session is UNKNOWN. Depends on the cluster.\n\n" }} + {%- endif -%} +{%- endmacro -%} + +{#- System Message Construction ============================================ #} +{%- macro build_system_message() -%} + {%- if model_identity is not defined %} + {%- set model_identity = "You are ChatGPT, a large language model trained by OpenAI." %} + {%- endif %} + {{- model_identity + "\n" }} + {{- "Knowledge cutoff: 2024-06\n" }} + {{- "Current date: " + strftime_now("%Y-%m-%d") + "\n\n" }} + {%- if reasoning_effort is not defined %} + {%- set reasoning_effort = "medium" %} + {%- endif %} + {{- "Reasoning: " + reasoning_effort + "\n\n" }} + {%- if builtin_tools %} + {{- "# Tools\n\n" }} + {%- set available_builtin_tools = namespace(browser=false, python=false) %} + {%- for tool in builtin_tools %} + {%- if tool == "browser" %} + {%- set available_builtin_tools.browser = true %} + {%- elif tool == "python" %} + {%- set available_builtin_tools.python = true %} + {%- endif %} + {%- endfor %} + {{- render_builtin_tools(available_builtin_tools.browser, available_builtin_tools.python) }} + {%- endif -%} + {{- "# Valid channels: analysis, commentary, final. Channel must be included for every message." }} + {%- if tools -%} + {{- "\nCalls to these tools must go to the commentary channel: 'functions'." }} + {%- endif -%} +{%- endmacro -%} + +{#- Main Template Logic ================================================= #} +{#- Set defaults #} + +{#- Render system message #} +{{- "<|start|>system<|message|>" }} +{{- build_system_message() }} +{{- "<|end|>" }} + +{#- Extract developer message #} +{%- if messages[0].role == "developer" or messages[0].role == "system" %} + {%- set developer_message = messages[0].content %} + {%- set loop_messages = messages[1:] %} +{%- else %} + {%- set developer_message = "" %} + {%- set loop_messages = messages %} +{%- endif %} + +{#- Render developer message #} +{%- if developer_message or tools %} + {{- "<|start|>developer<|message|>" }} + {%- if developer_message %} + {{- "# Instructions\n\n" }} + {{- developer_message }} + {{- "\n\n" }} + {%- endif %} + {%- if tools -%} + {{- "# Tools\n\n" }} + {{- render_tool_namespace("functions", tools) }} + {%- endif -%} + {{- "<|end|>" }} +{%- endif %} + +{#- Render messages #} +{%- set last_tool_call = namespace(name=none) %} +{%- for message in loop_messages -%} + {#- At this point only assistant/user/tool messages should remain #} + {%- if message.role == 'assistant' -%} + {#- Checks to ensure the messages are being passed in the format we expect #} + {%- if "content" in message %} + {%- if "<|channel|>analysis<|message|>" in message.content or "<|channel|>final<|message|>" in message.content %} + {{- raise_exception("You have passed a message containing <|channel|> tags in the content field. Instead of doing this, you should pass analysis messages (the string between '<|message|>' and '<|end|>') in the 'thinking' field, and final messages (the string between '<|message|>' and '<|end|>') in the 'content' field.") }} + {%- endif %} + {%- endif %} + {%- if "thinking" in message %} + {%- if "<|channel|>analysis<|message|>" in message.thinking or "<|channel|>final<|message|>" in message.thinking %} + {{- raise_exception("You have passed a message containing <|channel|> tags in the thinking field. Instead of doing this, you should pass analysis messages (the string between '<|message|>' and '<|end|>') in the 'thinking' field, and final messages (the string between '<|message|>' and '<|end|>') in the 'content' field.") }} + {%- endif %} + {%- endif %} + {%- generation %} + {%- if "tool_calls" in message %} + {#- We need very careful handling here - we want to drop the tool call analysis message if the model #} + {#- has output a later <|final|> message, but otherwise we want to retain it. This is the only case #} + {#- when we render CoT/analysis messages in inference. #} + {%- set future_final_message = namespace(found=false) %} + {%- for future_message in loop_messages[loop.index:] %} + {%- if future_message.role == 'assistant' and "tool_calls" not in future_message %} + {%- set future_final_message.found = true %} + {%- endif %} + {%- endfor %} + {#- We assume max 1 tool call per message, and so we infer the tool call name #} + {#- in "tool" messages from the most recent assistant tool call name #} + {%- set tool_call = message.tool_calls[0] %} + {%- if tool_call.function %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {%- if message.content and message.thinking %} + {{- raise_exception("Cannot pass both content and thinking in an assistant message with tool calls! Put the analysis message in one or the other, but not both.") }} + {%- elif message.content and not future_final_message.found %} + {{- "<|start|>assistant<|channel|>analysis<|message|>" + message.content + "<|end|>" }} + {%- elif message.thinking and not future_final_message.found %} + {{- "<|start|>assistant<|channel|>analysis<|message|>" + message.thinking + "<|end|>" }} + {%- endif %} + {{- "<|start|>assistant to=" }} + {{- "functions." + tool_call.name + "<|channel|>commentary " }} + {{- (tool_call.content_type if tool_call.content_type is defined else "json") + "<|message|>" }} + {{- tool_call.arguments|tojson }} + {{- "<|call|>" }} + {%- set last_tool_call.name = tool_call.name %} + {%- elif loop.last and not add_generation_prompt %} + {#- Only render the CoT if the final turn is an assistant turn and add_generation_prompt is false #} + {#- This is a situation that should only occur in training, never in inference. #} + {%- if "thinking" in message %} + {{- "<|start|>assistant<|channel|>analysis<|message|>" + message.thinking + "<|end|>" }} + {%- endif %} + {#- <|return|> indicates the end of generation, but <|end|> does not #} + {#- <|return|> should never be an input to the model, but we include it as the final token #} + {#- when training, so the model learns to emit it. #} + {{- "<|start|>assistant<|channel|>final<|message|>" + message.content + "<|return|>" }} + {%- else %} + {#- CoT is dropped during all previous turns, so we never render it for inference #} + {{- "<|start|>assistant<|channel|>final<|message|>" + message.content + "<|end|>" }} + {%- set last_tool_call.name = none %} + {%- endif %} + {%- endgeneration %} + {%- elif message.role == 'tool' -%} + {%- if last_tool_call.name is none %} + {{- raise_exception("Message has tool role, but there was no previous assistant message with a tool call!") }} + {%- endif %} + {{- "<|start|>functions." + last_tool_call.name }} + {{- " to=assistant<|channel|>commentary<|message|>" + message.content|tojson + "<|end|>" }} + {%- elif message.role == 'user' -%} + {{- "<|start|>user<|message|>" + message.content + "<|end|>" }} + {%- endif -%} +{%- endfor -%} + +{#- Generation prompt #} +{%- if add_generation_prompt -%} +<|start|>assistant +{%- endif -%} \ No newline at end of file diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/llama3.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/llama3.jinja new file mode 100644 index 0000000000000000000000000000000000000000..39bd0c9f7fe30aea14eda194fee17703da4a4dbf --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/llama3.jinja @@ -0,0 +1,5 @@ +{% set loop_messages = messages %}{% for message in loop_messages %}{% set content = '<|start_header_id|>' + message['role'] + '<|end_header_id|> + +'+ message['content'] | trim + '<|eot_id|>' %}{% if loop.index0 == 0 %}{% set content = bos_token + content %}{% endif %}{{ content }}{% endfor %}{% if add_generation_prompt %}{{ '<|start_header_id|>assistant<|end_header_id|> + +' }}{% endif %} \ No newline at end of file diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/llama3_1.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/llama3_1.jinja new file mode 100644 index 0000000000000000000000000000000000000000..33089ace1be88f22a10fe861ad49718d5d886090 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/llama3_1.jinja @@ -0,0 +1,109 @@ +{{- bos_token }} +{%- if custom_tools is defined %} + {%- set tools = custom_tools %} +{%- endif %} +{%- if not tools_in_user_message is defined %} + {%- set tools_in_user_message = true %} +{%- endif %} +{%- if not date_string is defined %} + {%- set date_string = "26 Jul 2024" %} +{%- endif %} +{%- if not tools is defined %} + {%- set tools = none %} +{%- endif %} + +{#- This block extracts the system message, so we can slot it into the right place. #} +{%- if messages[0]['role'] == 'system' %} + {%- set system_message = messages[0]['content']|trim %} + {%- set messages = messages[1:] %} +{%- else %} + {%- set system_message = "" %} +{%- endif %} + +{#- System message + builtin tools #} +{{- "<|start_header_id|>system<|end_header_id|>\n\n" }} +{%- if builtin_tools is defined or tools is not none %} + {{- "Environment: ipython\n" }} +{%- endif %} +{%- if builtin_tools is defined %} + {{- "Tools: " + builtin_tools | reject('equalto', 'code_interpreter') | join(", ") + "\n\n"}} +{%- endif %} +{{- "Cutting Knowledge Date: December 2023\n" }} +{{- "Today Date: " + date_string + "\n\n" }} +{%- if tools is not none and not tools_in_user_message %} + {{- "You have access to the following functions. To call a function, please respond with JSON for a function call." }} + {{- 'Respond in the format {"name": function name, "parameters": dictionary of argument name and its value}.' }} + {{- "Do not use variables.\n\n" }} + {%- for t in tools %} + {{- t | tojson(indent=4) }} + {{- "\n\n" }} + {%- endfor %} +{%- endif %} +{{- system_message }} +{{- "<|eot_id|>" }} + +{#- Custom tools are passed in a user message with some extra guidance #} +{%- if tools_in_user_message and not tools is none %} + {#- Extract the first user message so we can plug it in here #} + {%- if messages | length != 0 %} + {%- set first_user_message = messages[0]['content']|trim %} + {%- set messages = messages[1:] %} + {%- else %} + {{- raise_exception("Cannot put tools in the first user message when there's no first user message!") }} +{%- endif %} + {{- '<|start_header_id|>user<|end_header_id|>\n\n' -}} + {{- "Given the following functions, please respond with a JSON for a function call " }} + {{- "with its proper arguments that best answers the given prompt.\n\n" }} + {{- 'Respond in the format {"name": function name, "parameters": dictionary of argument name and its value}.' }} + {{- "Do not use variables.\n\n" }} + {%- for t in tools %} + {{- t | tojson(indent=4) }} + {{- "\n\n" }} + {%- endfor %} + {{- first_user_message + "<|eot_id|>"}} +{%- endif %} + +{%- for message in messages %} + {%- if not (message.role == 'ipython' or message.role == 'tool' or 'tool_calls' in message) %} + {{- '<|start_header_id|>' + message['role'] + '<|end_header_id|>\n\n'+ message['content'] | trim + '<|eot_id|>' }} + {%- elif 'tool_calls' in message %} + {%- if not message.tool_calls|length == 1 %} + {{- raise_exception("This model only supports single tool-calls at once!") }} + {%- endif %} + {%- set tool_call = message.tool_calls[0].function %} + {%- if builtin_tools is defined and tool_call.name in builtin_tools %} + {{- '<|start_header_id|>assistant<|end_header_id|>\n\n' -}} + {{- "<|python_tag|>" + tool_call.name + ".call(" }} + {%- for arg_name, arg_val in tool_call.arguments | items %} + {{- arg_name + '="' + arg_val + '"' }} + {%- if not loop.last %} + {{- ", " }} + {%- endif %} + {%- endfor %} + {{- ")" }} + {%- else %} + {{- '<|start_header_id|>assistant<|end_header_id|>\n\n' -}} + {{- '{"name": "' + tool_call.name + '", ' }} + {{- '"parameters": ' }} + {{- tool_call.arguments | tojson }} + {{- "}" }} + {%- endif %} + {%- if builtin_tools is defined %} + {#- This means we're in ipython mode #} + {{- "<|eom_id|>" }} + {%- else %} + {{- "<|eot_id|>" }} + {%- endif %} + {%- elif message.role == "tool" or message.role == "ipython" %} + {{- "<|start_header_id|>ipython<|end_header_id|>\n\n" }} + {%- if message.content is mapping or message.content is iterable %} + {{- message.content | tojson }} + {%- else %} + {{- message.content }} + {%- endif %} + {{- "<|eot_id|>" }} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|start_header_id|>assistant<|end_header_id|>\n\n' }} +{%- endif %} diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/llama3_2.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/llama3_2.jinja new file mode 100644 index 0000000000000000000000000000000000000000..1bad6a0f648dccdbec523ca79ba90fbcfc806af0 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/llama3_2.jinja @@ -0,0 +1,93 @@ +{{- bos_token }} +{%- if custom_tools is defined %} + {%- set tools = custom_tools %} +{%- endif %} +{%- if not tools_in_user_message is defined %} + {%- set tools_in_user_message = true %} +{%- endif %} +{%- if not date_string is defined %} + {%- if strftime_now is defined %} + {%- set date_string = strftime_now("%d %b %Y") %} + {%- else %} + {%- set date_string = "26 Jul 2024" %} + {%- endif %} +{%- endif %} +{%- if not tools is defined %} + {%- set tools = none %} +{%- endif %} + +{#- This block extracts the system message, so we can slot it into the right place. #} +{%- if messages[0]['role'] == 'system' %} + {%- set system_message = messages[0]['content']|trim %} + {%- set messages = messages[1:] %} +{%- else %} + {%- set system_message = "" %} +{%- endif %} + +{#- System message #} +{{- "<|start_header_id|>system<|end_header_id|>\n\n" }} +{%- if tools is not none %} + {{- "Environment: ipython\n" }} +{%- endif %} +{{- "Cutting Knowledge Date: December 2023\n" }} +{{- "Today Date: " + date_string + "\n\n" }} +{%- if tools is not none and not tools_in_user_message %} + {{- "You have access to the following functions. To call a function, please respond with JSON for a function call." }} + {{- 'Respond in the format {"name": function name, "parameters": dictionary of argument name and its value}.' }} + {{- "Do not use variables.\n\n" }} + {%- for t in tools %} + {{- t | tojson(indent=4) }} + {{- "\n\n" }} + {%- endfor %} +{%- endif %} +{{- system_message }} +{{- "<|eot_id|>" }} + +{#- Custom tools are passed in a user message with some extra guidance #} +{%- if tools_in_user_message and not tools is none %} + {#- Extract the first user message so we can plug it in here #} + {%- if messages | length != 0 %} + {%- set first_user_message = messages[0]['content']|trim %} + {%- set messages = messages[1:] %} + {%- else %} + {{- raise_exception("Cannot put tools in the first user message when there's no first user message!") }} +{%- endif %} + {{- '<|start_header_id|>user<|end_header_id|>\n\n' -}} + {{- "Given the following functions, please respond with a JSON for a function call " }} + {{- "with its proper arguments that best answers the given prompt.\n\n" }} + {{- 'Respond in the format {"name": function name, "parameters": dictionary of argument name and its value}.' }} + {{- "Do not use variables.\n\n" }} + {%- for t in tools %} + {{- t | tojson(indent=4) }} + {{- "\n\n" }} + {%- endfor %} + {{- first_user_message + "<|eot_id|>"}} +{%- endif %} + +{%- for message in messages %} + {%- if not (message.role == 'ipython' or message.role == 'tool' or 'tool_calls' in message) %} + {{- '<|start_header_id|>' + message['role'] + '<|end_header_id|>\n\n'+ message['content'] | trim + '<|eot_id|>' }} + {%- elif 'tool_calls' in message %} + {%- if not message.tool_calls|length == 1 %} + {{- raise_exception("This model only supports single tool-calls at once!") }} + {%- endif %} + {%- set tool_call = message.tool_calls[0].function %} + {{- '<|start_header_id|>assistant<|end_header_id|>\n\n' -}} + {{- '{"name": "' + tool_call.name + '", ' }} + {{- '"parameters": ' }} + {{- tool_call.arguments | tojson }} + {{- "}" }} + {{- "<|eot_id|>" }} + {%- elif message.role == "tool" or message.role == "ipython" %} + {{- "<|start_header_id|>ipython<|end_header_id|>\n\n" }} + {%- if message.content is mapping or message.content is iterable %} + {{- message.content | tojson }} + {%- else %} + {{- message.content }} + {%- endif %} + {{- "<|eot_id|>" }} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|start_header_id|>assistant<|end_header_id|>\n\n' }} +{%- endif %} diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/llama3_training.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/llama3_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..85dafd3d877c69b48fcebae678a5ba367909afd1 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/llama3_training.jinja @@ -0,0 +1,19 @@ +{#- Training variant of the Llama 3 chat template (see llama3.jinja for the original). + Modifications vs the original: + - Added {% generation %} / {% endgeneration %} around assistant message output to support + assistant-only loss masking in SFT training. +-#} +{%- for message in messages %} + {%- if loop.index0 == 0 %}{{- bos_token }}{%- endif %} + {%- if message['role'] == 'assistant' %} + {{- '<|start_header_id|>assistant<|end_header_id|>\n\n' }} + {%- generation %} + {{- message['content'] | trim + '<|eot_id|>' }} + {%- endgeneration %} + {%- else %} + {{- '<|start_header_id|>' + message['role'] + '<|end_header_id|>\n\n' + message['content'] | trim + '<|eot_id|>' }} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|start_header_id|>assistant<|end_header_id|>\n\n' }} +{%- endif %} diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/llava_next.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/llava_next.jinja new file mode 100644 index 0000000000000000000000000000000000000000..c6cc6df43113384d5cafa46c06bd1b79ec4464c7 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/llava_next.jinja @@ -0,0 +1,6 @@ +{% for message in messages %}{% if message['role'] == 'system' %}{{ '<> +' + message['content'][0]['text'] + ' +<> + +' }}{% elif message['role'] == 'user' %}{{ '[INST] ' }}{# Render all images first #}{% for content in message['content'] | selectattr('type', 'equalto', 'image') %}{{ ' +' }}{% endfor %}{# Render all text next #}{% for content in message['content'] | selectattr('type', 'equalto', 'text') %}{{ content['text'] }}{% endfor %}{{' [/INST]' }}{% elif message['role'] == 'assistant' %}{{ ' ' + message['content'][0]['text'] + ' '}}{% else %}{{ raise_exception('Only user and assistant roles are supported!') }}{% endif %}{% endfor %} \ No newline at end of file diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/llava_next_training.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/llava_next_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..9eaf357439a713fff44832b8892a244cf063a7b6 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/llava_next_training.jinja @@ -0,0 +1,11 @@ +{#- Training variant of the Llava-Next chat template (see llava_next.jinja for the original). + Modifications vs the original: + - Added {% generation %} / {% endgeneration %} around the assistant message output to support + assistant-only loss masking in SFT training. +-#} +{% for message in messages %}{% if message['role'] == 'system' %}{{ '<> +' + message['content'][0]['text'] + ' +<> + +' }}{% elif message['role'] == 'user' %}{{ '[INST] ' }}{# Render all images first #}{% for content in message['content'] | selectattr('type', 'equalto', 'image') %}{{ ' +' }}{% endfor %}{# Render all text next #}{% for content in message['content'] | selectattr('type', 'equalto', 'text') %}{{ content['text'] }}{% endfor %}{{' [/INST]' }}{% elif message['role'] == 'assistant' %}{% generation %}{{ ' ' + message['content'][0]['text'] + ' '}}{% endgeneration %}{% else %}{{ raise_exception('Only user and assistant roles are supported!') }}{% endif %}{% endfor %} \ No newline at end of file diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/nemotron_3_nano.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/nemotron_3_nano.jinja new file mode 100644 index 0000000000000000000000000000000000000000..67ca3ce54a7118ed74d6fd793b7cc9fd6b2a9f03 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/nemotron_3_nano.jinja @@ -0,0 +1,204 @@ +{% macro render_extra_keys(json_dict, handled_keys) %} + {%- if json_dict is mapping %} + {%- for json_key in json_dict if json_key not in handled_keys %} + {%- if json_dict[json_key] is mapping or (json_dict[json_key] is sequence and json_dict[json_key] is not string) %} + {{- '\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | tojson | safe) ~ '' }} + {%- else %} + {{-'\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | string) ~ '' }} + {%- endif %} + {%- endfor %} + {%- endif %} +{% endmacro %} +{%- set enable_thinking = enable_thinking if enable_thinking is defined else True %} +{%- set truncate_history_thinking = truncate_history_thinking if truncate_history_thinking is defined else True %} + +{%- set ns = namespace(last_user_idx = -1) %} +{%- set loop_messages = messages %} +{%- for m in loop_messages %} + {%- if m["role"] == "user" %} + {%- set ns.last_user_idx = loop.index0 %} + {%- endif %} +{%- endfor %} + +{%- if messages[0]["role"] == "system" %} + {%- set system_message = messages[0]["content"] %} + {%- set loop_messages = messages[1:] %} +{%- else %} + {%- set system_message = "" %} + {%- set loop_messages = messages %} +{%- endif %} +{%- if not tools is defined %} + {%- set tools = [] %} +{%- endif %} +{# Recompute last_user_idx relative to loop_messages after handling system #} +{%- set ns = namespace(last_user_idx = -1) %} +{%- for m in loop_messages %} + {%- if m["role"] == "user" %} + {%- set ns.last_user_idx = loop.index0 %} + {%- endif %} +{%- endfor %} +{%- if system_message is defined %} + {{- "<|im_start|>system\n" + system_message }} +{%- else %} + {%- if tools is iterable and tools | length > 0 %} + {{- "<|im_start|>system\n" }} + {%- endif %} +{%- endif %} +{%- if tools is iterable and tools | length > 0 %} + {%- if system_message is defined and system_message | length > 0 %} + {{- "\n\n" }} + {%- endif %} + {{- "# Tools\n\nYou have access to the following functions:\n\n" }} + {{- "" }} + {%- for tool in tools %} + {%- if tool.function is defined %} + {%- set tool = tool.function %} + {%- endif %} + {{- "\n\n" ~ tool.name ~ "" }} + {%- if tool.description is defined %} + {{- '\n' ~ (tool.description | trim) ~ '' }} + {%- endif %} + {{- '\n' }} + {%- if tool.parameters is defined and tool.parameters is mapping and tool.parameters.properties is defined and tool.parameters.properties is mapping %} + {%- for param_name, param_fields in tool.parameters.properties|items %} + {{- '\n' }} + {{- '\n' ~ param_name ~ '' }} + {%- if param_fields.type is defined %} + {{- '\n' ~ (param_fields.type | string) ~ '' }} + {%- endif %} + {%- if param_fields.description is defined %} + {{- '\n' ~ (param_fields.description | trim) ~ '' }} + {%- endif %} + {%- if param_fields.enum is defined %} + {{- '\n' ~ (param_fields.enum | tojson | safe) ~ '' }} + {%- endif %} + {%- set handled_keys = ['name', 'type', 'description', 'enum'] %} + {{- render_extra_keys(param_fields, handled_keys) }} + {{- '\n' }} + {%- endfor %} + {%- endif %} + {% set handled_keys = ['type', 'properties', 'required'] %} + {{- render_extra_keys(tool.parameters, handled_keys) }} + {%- if tool.parameters is defined and tool.parameters.required is defined %} + {{- '\n' ~ (tool.parameters.required | tojson | safe) ~ '' }} + {%- endif %} + {{- '\n' }} + {%- set handled_keys = ['type', 'name', 'description', 'parameters'] %} + {{- render_extra_keys(tool, handled_keys) }} + {{- '\n' }} + {%- endfor %} + {{- "\n" }} + + {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n' }} +{%- endif %} + + +{%- if system_message is defined %} + {{- '<|im_end|>\n' }} +{%- else %} + {%- if tools is iterable and tools | length > 0 %} + {{- '<|im_end|>\n' }} + {%- endif %} +{%- endif %} + +{%- for message in loop_messages %} + {%- if message.role == "assistant" %} + {# Add reasoning content in to content field for unified processing below. #} + {%- if message.reasoning_content is defined and message.reasoning_content is string and message.reasoning_content | trim | length > 0 %} + {%- set content = "\n" ~ message.reasoning_content ~ "\n\n" ~ (message.content | default('', true)) %} + {%- else %} + {%- set content = message.content | default('', true) %} + {%- if content is string -%} + {# Allow downstream logic to to take care of broken thought, only handle coherent reasoning here. #} + {%- if '' not in content and '' not in content -%} + {%- set content = "" ~ content -%} + {%- endif -%} + {%- else -%} + {%- set content = content -%} + {%- endif -%} + {%- endif %} + {%- if message.tool_calls is defined and message.tool_calls is iterable and message.tool_calls | length > 0 %} + {# Assistant message has tool calls. #} + {{- '<|im_start|>assistant\n' }} + {%- set include_content = not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %} + {%- if content is string and content | trim | length > 0 %} + {%- if include_content %} + {{- (content | trim) ~ '\n' -}} + {%- else %} + {%- set c = (content | string) %} + {%- if '' in c %} + {# Keep only content after the last closing think. Also generation prompt causes this. #} + {%- set c = c.split('')[-1] %} + {%- elif '' in c %} + {# If was opened but never closed, drop the trailing think segment #} + {%- set c = c.split('')[0] %} + {%- endif %} + {%- set c = "" ~ c | trim %} + {%- if c | length > 0 %} + {{- c ~ '\n' -}} + {%- endif %} + {%- endif %} + {%- else %} + {{- "" -}} + {%- endif %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '\n\n' -}} + {%- if tool_call.arguments is defined %} + {%- for args_name, args_value in tool_call.arguments|items %} + {{- '\n' -}} + {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %} + {{- args_value ~ '\n\n' -}} + {%- endfor %} + {%- endif %} + {{- '\n\n' -}} + {%- endfor %} + {{- '<|im_end|>\n' }} + {%- else %} + {# Assistant message doesn't have tool calls. #} + {%- if not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %} + {{- '<|im_start|>assistant\n' ~ (content | default('', true) | string | trim) ~ '<|im_end|>\n' }} + {%- else %} + {%- set c = (content | default('', true) | string) %} + {%- if '' in c and '' in c %} + {%- set c = "" ~ c.split('')[-1] %} + {%- endif %} + {%- set c = c | trim %} + {%- if c | length > 0 %} + {{- '<|im_start|>assistant\n' ~ c ~ '<|im_end|>\n' }} + {%- else %} + {{- '<|im_start|>assistant\n<|im_end|>\n' }} + {%- endif %} + {%- endif %} + {%- endif %} + {%- elif message.role == "user" or message.role == "system" %} + {{- '<|im_start|>' + message.role + '\n' }} + {%- set content = message.content | string %} + {{- content }} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if loop.previtem and loop.previtem.role != "tool" %} + {{- '<|im_start|>user\n' }} + {%- endif %} + {{- '\n' }} + {{- message.content }} + {{- '\n\n' }} + {%- if not loop.last and loop.nextitem.role != "tool" %} + {{- '<|im_end|>\n' }} + {%- elif loop.last %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- else %} + {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>\n' }} + {%- endif %} +{%- endfor %} + +{%- if add_generation_prompt %} + {%- if enable_thinking %} + {{- '<|im_start|>assistant\n\n' }} + {%- else %} + {{- '<|im_start|>assistant\n' }} + {%- endif %} +{%- endif %} diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/nemotron_3_nano_training.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/nemotron_3_nano_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..c539b379f51fe7c76586858d70f25ff6220a3729 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/nemotron_3_nano_training.jinja @@ -0,0 +1,220 @@ +{#- Training variant of the Nemotron Nano chat template (see nemotron_3_nano.jinja for the original). + Modifications vs the original: + - Added {% generation %} / {% endgeneration %} around assistant message output to support + assistant-only loss masking in SFT training. +-#} +{% macro render_extra_keys(json_dict, handled_keys) %} + {%- if json_dict is mapping %} + {%- for json_key in json_dict if json_key not in handled_keys %} + {%- if json_dict[json_key] is mapping or (json_dict[json_key] is sequence and json_dict[json_key] is not string) %} + {{- '\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | tojson | safe) ~ '' }} + {%- else %} + {{-'\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | string) ~ '' }} + {%- endif %} + {%- endfor %} + {%- endif %} +{% endmacro %} +{%- set enable_thinking = enable_thinking if enable_thinking is defined else True %} +{%- set truncate_history_thinking = truncate_history_thinking if truncate_history_thinking is defined else True %} + +{%- set ns = namespace(last_user_idx = -1) %} +{%- set loop_messages = messages %} +{%- for m in loop_messages %} + {%- if m["role"] == "user" %} + {%- set ns.last_user_idx = loop.index0 %} + {%- endif %} +{%- endfor %} + +{%- if messages[0]["role"] == "system" %} + {%- set system_message = messages[0]["content"] %} + {%- set loop_messages = messages[1:] %} +{%- else %} + {%- set system_message = "" %} + {%- set loop_messages = messages %} +{%- endif %} +{%- if not tools is defined %} + {%- set tools = [] %} +{%- endif %} +{# Recompute last_user_idx relative to loop_messages after handling system #} +{%- set ns = namespace(last_user_idx = -1) %} +{%- for m in loop_messages %} + {%- if m["role"] == "user" %} + {%- set ns.last_user_idx = loop.index0 %} + {%- endif %} +{%- endfor %} +{%- if system_message is defined %} + {{- "<|im_start|>system\n" + system_message }} +{%- else %} + {%- if tools is iterable and tools | length > 0 %} + {{- "<|im_start|>system\n" }} + {%- endif %} +{%- endif %} +{%- if tools is iterable and tools | length > 0 %} + {%- if system_message is defined and system_message | length > 0 %} + {{- "\n\n" }} + {%- endif %} + {{- "# Tools\n\nYou have access to the following functions:\n\n" }} + {{- "" }} + {%- for tool in tools %} + {%- if tool.function is defined %} + {%- set tool = tool.function %} + {%- endif %} + {{- "\n\n" ~ tool.name ~ "" }} + {%- if tool.description is defined %} + {{- '\n' ~ (tool.description | trim) ~ '' }} + {%- endif %} + {{- '\n' }} + {%- if tool.parameters is defined and tool.parameters is mapping and tool.parameters.properties is defined and tool.parameters.properties is mapping %} + {%- for param_name, param_fields in tool.parameters.properties|items %} + {{- '\n' }} + {{- '\n' ~ param_name ~ '' }} + {%- if param_fields.type is defined %} + {{- '\n' ~ (param_fields.type | string) ~ '' }} + {%- endif %} + {%- if param_fields.description is defined %} + {{- '\n' ~ (param_fields.description | trim) ~ '' }} + {%- endif %} + {%- if param_fields.enum is defined %} + {{- '\n' ~ (param_fields.enum | tojson | safe) ~ '' }} + {%- endif %} + {%- set handled_keys = ['name', 'type', 'description', 'enum'] %} + {{- render_extra_keys(param_fields, handled_keys) }} + {{- '\n' }} + {%- endfor %} + {%- endif %} + {% set handled_keys = ['type', 'properties', 'required'] %} + {{- render_extra_keys(tool.parameters, handled_keys) }} + {%- if tool.parameters is defined and tool.parameters.required is defined %} + {{- '\n' ~ (tool.parameters.required | tojson | safe) ~ '' }} + {%- endif %} + {{- '\n' }} + {%- set handled_keys = ['type', 'name', 'description', 'parameters'] %} + {{- render_extra_keys(tool, handled_keys) }} + {{- '\n' }} + {%- endfor %} + {{- "\n" }} + + {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n' }} +{%- endif %} + + +{%- if system_message is defined %} + {{- '<|im_end|>\n' }} +{%- else %} + {%- if tools is iterable and tools | length > 0 %} + {{- '<|im_end|>\n' }} + {%- endif %} +{%- endif %} + +{%- for message in loop_messages %} + {%- if message.role == "assistant" %} + {# Add reasoning content in to content field for unified processing below. #} + {%- if message.reasoning_content is defined and message.reasoning_content is string and message.reasoning_content | trim | length > 0 %} + {%- set content = "\n" ~ message.reasoning_content ~ "\n\n" ~ (message.content | default('', true)) %} + {%- else %} + {%- set content = message.content | default('', true) %} + {%- if content is string -%} + {# Allow downstream logic to to take care of broken thought, only handle coherent reasoning here. #} + {%- if '' not in content and '' not in content -%} + {%- set content = "" ~ content -%} + {%- endif -%} + {%- else -%} + {%- set content = content -%} + {%- endif -%} + {%- endif %} + {%- if message.tool_calls is defined and message.tool_calls is iterable and message.tool_calls | length > 0 %} + {# Assistant message has tool calls. #} + {{- '<|im_start|>assistant\n' }} + {%- generation %} + {%- set include_content = not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %} + {%- if content is string and content | trim | length > 0 %} + {%- if include_content %} + {{- (content | trim) ~ '\n' -}} + {%- else %} + {%- set c = (content | string) %} + {%- if '' in c %} + {# Keep only content after the last closing think. Also generation prompt causes this. #} + {%- set c = c.split('')[-1] %} + {%- elif '' in c %} + {# If was opened but never closed, drop the trailing think segment #} + {%- set c = c.split('')[0] %} + {%- endif %} + {%- set c = "" ~ c | trim %} + {%- if c | length > 0 %} + {{- c ~ '\n' -}} + {%- endif %} + {%- endif %} + {%- else %} + {{- "" -}} + {%- endif %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '\n\n' -}} + {%- if tool_call.arguments is defined %} + {%- for args_name, args_value in tool_call.arguments|items %} + {{- '\n' -}} + {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %} + {{- args_value ~ '\n\n' -}} + {%- endfor %} + {%- endif %} + {{- '\n\n' -}} + {%- endfor %} + {{- '<|im_end|>\n' }} + {%- endgeneration %} + {%- else %} + {# Assistant message doesn't have tool calls. #} + {%- if not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %} + {{- '<|im_start|>assistant\n' }} + {%- generation %} + {{- (content | default('', true) | string | trim) ~ '<|im_end|>\n' }} + {%- endgeneration %} + {%- else %} + {%- set c = (content | default('', true) | string) %} + {%- if '' in c and '' in c %} + {%- set c = "" ~ c.split('')[-1] %} + {%- endif %} + {%- set c = c | trim %} + {%- if c | length > 0 %} + {{- '<|im_start|>assistant\n' }} + {%- generation %} + {{- c ~ '<|im_end|>\n' }} + {%- endgeneration %} + {%- else %} + {{- '<|im_start|>assistant\n' }} + {%- generation %} + {{- '<|im_end|>\n' }} + {%- endgeneration %} + {%- endif %} + {%- endif %} + {%- endif %} + {%- elif message.role == "user" or message.role == "system" %} + {{- '<|im_start|>' + message.role + '\n' }} + {%- set content = message.content | string %} + {{- content }} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if loop.previtem and loop.previtem.role != "tool" %} + {{- '<|im_start|>user\n' }} + {%- endif %} + {{- '\n' }} + {{- message.content }} + {{- '\n\n' }} + {%- if not loop.last and loop.nextitem.role != "tool" %} + {{- '<|im_end|>\n' }} + {%- elif loop.last %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- else %} + {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>\n' }} + {%- endif %} +{%- endfor %} + +{%- if add_generation_prompt %} + {%- if enable_thinking %} + {{- '<|im_start|>assistant\n\n' }} + {%- else %} + {{- '<|im_start|>assistant\n' }} + {%- endif %} +{%- endif %} diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/nemotron_3_super.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/nemotron_3_super.jinja new file mode 100644 index 0000000000000000000000000000000000000000..71935c3a25edcdde07a0b7c4bec26f68bbce73a4 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/nemotron_3_super.jinja @@ -0,0 +1,209 @@ +{% macro render_extra_keys(json_dict, handled_keys) %} + {%- if json_dict is mapping %} + {%- for json_key in json_dict if json_key not in handled_keys %} + {%- if json_dict[json_key] is mapping or (json_dict[json_key] is sequence and json_dict[json_key] is not string) %} + {{- '\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | tojson | safe) ~ '' }} + {%- else %} + {{-'\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | string) ~ '' }} + {%- endif %} + {%- endfor %} + {%- endif %} +{% endmacro %} +{%- set enable_thinking = enable_thinking if enable_thinking is defined else True %} +{%- set low_effort = low_effort if low_effort is defined else False %} +{%- set truncate_history_thinking = truncate_history_thinking if truncate_history_thinking is defined else True %} + +{%- set ns = namespace(last_user_idx = -1) %} +{%- set loop_messages = messages %} +{%- for m in loop_messages %} + {%- if m["role"] == "user" %} + {%- set ns.last_user_idx = loop.index0 %} + {%- endif %} +{%- endfor %} + +{%- if messages[0]["role"] == "system" %} + {%- set system_message = messages[0]["content"] %} + {%- set loop_messages = messages[1:] %} +{%- else %} + {%- set system_message = "" %} + {%- set loop_messages = messages %} +{%- endif %} +{%- if not tools is defined %} + {%- set tools = [] %} +{%- endif %} +{# Recompute last_user_idx relative to loop_messages after handling system #} +{%- set ns = namespace(last_user_idx = -1) %} +{%- for m in loop_messages %} + {%- if m["role"] == "user" %} + {%- set ns.last_user_idx = loop.index0 %} + {%- endif %} +{%- endfor %} +{%- if system_message is defined %} + {{- "<|im_start|>system\n" + system_message }} +{%- else %} + {%- if tools is iterable and tools | length > 0 %} + {{- "<|im_start|>system\n" }} + {%- endif %} +{%- endif %} +{%- if tools is iterable and tools | length > 0 %} + {%- if system_message is defined and system_message | length > 0 %} + {{- "\n\n" }} + {%- endif %} + {{- "# Tools\n\nYou have access to the following functions:\n\n" }} + {{- "" }} + {%- for tool in tools %} + {%- if tool.function is defined %} + {%- set tool = tool.function %} + {%- endif %} + {{- "\n\n" ~ tool.name ~ "" }} + {%- if tool.description is defined %} + {{- '\n' ~ (tool.description | trim) ~ '' }} + {%- endif %} + {{- '\n' }} + {%- if tool.parameters is defined and tool.parameters is mapping and tool.parameters.properties is defined and tool.parameters.properties is mapping %} + {%- for param_name, param_fields in tool.parameters.properties|items %} + {{- '\n' }} + {{- '\n' ~ param_name ~ '' }} + {%- if param_fields.type is defined %} + {{- '\n' ~ (param_fields.type | string) ~ '' }} + {%- endif %} + {%- if param_fields.description is defined %} + {{- '\n' ~ (param_fields.description | trim) ~ '' }} + {%- endif %} + {%- if param_fields.enum is defined %} + {{- '\n' ~ (param_fields.enum | tojson | safe) ~ '' }} + {%- endif %} + {%- set handled_keys = ['name', 'type', 'description', 'enum'] %} + {{- render_extra_keys(param_fields, handled_keys) }} + {{- '\n' }} + {%- endfor %} + {%- endif %} + {% set handled_keys = ['type', 'properties', 'required'] %} + {{- render_extra_keys(tool.parameters, handled_keys) }} + {%- if tool.parameters is defined and tool.parameters.required is defined %} + {{- '\n' ~ (tool.parameters.required | tojson | safe) ~ '' }} + {%- endif %} + {{- '\n' }} + {%- set handled_keys = ['type', 'name', 'description', 'parameters'] %} + {{- render_extra_keys(tool, handled_keys) }} + {{- '\n' }} + {%- endfor %} + {{- "\n" }} + + {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n' }} +{%- endif %} + + +{%- if system_message is defined %} + {{- '<|im_end|>\n' }} +{%- else %} + {%- if tools is iterable and tools | length > 0 %} + {{- '<|im_end|>\n' }} + {%- endif %} +{%- endif %} + +{%- for message in loop_messages %} + {%- if message.role == "assistant" %} + {# Add reasoning content in to content field for unified processing below. #} + {%- if message.reasoning_content is defined and message.reasoning_content is string and message.reasoning_content | trim | length > 0 %} + {%- set content = "\n" ~ message.reasoning_content ~ "\n\n" ~ (message.content | default('', true)) %} + {%- else %} + {%- set content = message.content | default('', true) %} + {%- if content is string -%} + {# Allow downstream logic to to take care of broken thought, only handle coherent reasoning here. #} + {%- if '' not in content and '' not in content -%} + {%- set content = "" ~ content -%} + {%- endif -%} + {%- else -%} + {%- set content = content -%} + {%- endif -%} + {%- endif %} + {%- if message.tool_calls is defined and message.tool_calls is iterable and message.tool_calls | length > 0 %} + {# Assistant message has tool calls. #} + {{- '<|im_start|>assistant\n' }} + {%- set include_content = not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %} + {%- if content is string and content | trim | length > 0 %} + {%- if include_content %} + {{- (content | trim) ~ '\n' -}} + {%- else %} + {%- set c = (content | string) %} + {%- if '' in c %} + {# Keep only content after the last closing think. Also generation prompt causes this. #} + {%- set c = c.split('')[-1] %} + {%- elif '' in c %} + {# If was opened but never closed, drop the trailing think segment #} + {%- set c = c.split('')[0] %} + {%- endif %} + {%- set c = "" ~ c | trim %} + {%- if c | length > 0 %} + {{- c ~ '\n' -}} + {%- endif %} + {%- endif %} + {%- else %} + {{- "" -}} + {%- endif %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '\n\n' -}} + {%- if tool_call.arguments is defined %} + {%- for args_name, args_value in tool_call.arguments|items %} + {{- '\n' -}} + {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %} + {{- args_value ~ '\n\n' -}} + {%- endfor %} + {%- endif %} + {{- '\n\n' -}} + {%- endfor %} + {{- '<|im_end|>\n' }} + {%- else %} + {# Assistant message doesn't have tool calls. #} + {%- if not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %} + {{- '<|im_start|>assistant\n' ~ (content | default('', true) | string | trim) ~ '<|im_end|>\n' }} + {%- else %} + {%- set c = (content | default('', true) | string) %} + {%- if '' in c and '' in c %} + {%- set c = "" ~ c.split('')[-1] %} + {%- endif %} + {%- set c = c | trim %} + {%- if c | length > 0 %} + {{- '<|im_start|>assistant\n' ~ c ~ '<|im_end|>\n' }} + {%- else %} + {{- '<|im_start|>assistant\n<|im_end|>\n' }} + {%- endif %} + {%- endif %} + {%- endif %} + {%- elif message.role == "user" or message.role == "system" %} + {{- '<|im_start|>' + message.role + '\n' }} + {%- set content = message.content | string %} + {%- if message.role == "user" and loop.index0 == ns.last_user_idx and low_effort %} + {{- content + '\n\n{reasoning effort: low}' }} + {%- else %} + {{- content }} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if loop.previtem and loop.previtem.role != "tool" %} + {{- '<|im_start|>user\n' }} + {%- endif %} + {{- '\n' }} + {{- message.content }} + {{- '\n\n' }} + {%- if not loop.last and loop.nextitem.role != "tool" %} + {{- '<|im_end|>\n' }} + {%- elif loop.last %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- else %} + {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>\n' }} + {%- endif %} +{%- endfor %} + +{%- if add_generation_prompt %} + {%- if enable_thinking %} + {{- '<|im_start|>assistant\n\n' }} + {%- else %} + {{- '<|im_start|>assistant\n' }} + {%- endif %} +{%- endif %} diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/nemotron_3_super_training.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/nemotron_3_super_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..bcd170998dc60b864b7f9d35b31c7664cf35a546 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/nemotron_3_super_training.jinja @@ -0,0 +1,226 @@ +{#- Training variant of the Nemotron Super chat template (see nemotron_3_super.jinja for the original). + The original is already prefix-preserving, so the only modification is adding + {% generation %} / {% endgeneration %} around assistant message output to support + assistant-only loss masking in SFT training. All other rendering (including the + `truncate_history_thinking` and `low_effort` logic) is identical to the original. +-#} +{% macro render_extra_keys(json_dict, handled_keys) %} + {%- if json_dict is mapping %} + {%- for json_key in json_dict if json_key not in handled_keys %} + {%- if json_dict[json_key] is mapping or (json_dict[json_key] is sequence and json_dict[json_key] is not string) %} + {{- '\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | tojson | safe) ~ '' }} + {%- else %} + {{-'\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | string) ~ '' }} + {%- endif %} + {%- endfor %} + {%- endif %} +{% endmacro %} +{%- set enable_thinking = enable_thinking if enable_thinking is defined else True %} +{%- set truncate_history_thinking = truncate_history_thinking if truncate_history_thinking is defined else True %} +{%- set low_effort = low_effort if low_effort is defined else False %} + +{%- set ns = namespace(last_user_idx = -1) %} +{%- set loop_messages = messages %} +{%- for m in loop_messages %} + {%- if m["role"] == "user" %} + {%- set ns.last_user_idx = loop.index0 %} + {%- endif %} +{%- endfor %} + +{%- if messages[0]["role"] == "system" %} + {%- set system_message = messages[0]["content"] %} + {%- set loop_messages = messages[1:] %} +{%- else %} + {%- set system_message = "" %} + {%- set loop_messages = messages %} +{%- endif %} +{%- if not tools is defined %} + {%- set tools = [] %} +{%- endif %} +{# Recompute last_user_idx relative to loop_messages after handling system #} +{%- set ns = namespace(last_user_idx = -1) %} +{%- for m in loop_messages %} + {%- if m["role"] == "user" %} + {%- set ns.last_user_idx = loop.index0 %} + {%- endif %} +{%- endfor %} +{%- if system_message is defined %} + {{- "<|im_start|>system\n" + system_message }} +{%- else %} + {%- if tools is iterable and tools | length > 0 %} + {{- "<|im_start|>system\n" }} + {%- endif %} +{%- endif %} +{%- if tools is iterable and tools | length > 0 %} + {%- if system_message is defined and system_message | length > 0 %} + {{- "\n\n" }} + {%- endif %} + {{- "# Tools\n\nYou have access to the following functions:\n\n" }} + {{- "" }} + {%- for tool in tools %} + {%- if tool.function is defined %} + {%- set tool = tool.function %} + {%- endif %} + {{- "\n\n" ~ tool.name ~ "" }} + {%- if tool.description is defined %} + {{- '\n' ~ (tool.description | trim) ~ '' }} + {%- endif %} + {{- '\n' }} + {%- if tool.parameters is defined and tool.parameters is mapping and tool.parameters.properties is defined and tool.parameters.properties is mapping %} + {%- for param_name, param_fields in tool.parameters.properties|items %} + {{- '\n' }} + {{- '\n' ~ param_name ~ '' }} + {%- if param_fields.type is defined %} + {{- '\n' ~ (param_fields.type | string) ~ '' }} + {%- endif %} + {%- if param_fields.description is defined %} + {{- '\n' ~ (param_fields.description | trim) ~ '' }} + {%- endif %} + {%- if param_fields.enum is defined %} + {{- '\n' ~ (param_fields.enum | tojson | safe) ~ '' }} + {%- endif %} + {%- set handled_keys = ['name', 'type', 'description', 'enum'] %} + {{- render_extra_keys(param_fields, handled_keys) }} + {{- '\n' }} + {%- endfor %} + {%- endif %} + {% set handled_keys = ['type', 'properties', 'required'] %} + {{- render_extra_keys(tool.parameters, handled_keys) }} + {%- if tool.parameters is defined and tool.parameters.required is defined %} + {{- '\n' ~ (tool.parameters.required | tojson | safe) ~ '' }} + {%- endif %} + {{- '\n' }} + {%- set handled_keys = ['type', 'name', 'description', 'parameters'] %} + {{- render_extra_keys(tool, handled_keys) }} + {{- '\n' }} + {%- endfor %} + {{- "\n" }} + + {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n' }} +{%- endif %} + + +{%- if system_message is defined %} + {{- '<|im_end|>\n' }} +{%- else %} + {%- if tools is iterable and tools | length > 0 %} + {{- '<|im_end|>\n' }} + {%- endif %} +{%- endif %} + +{%- for message in loop_messages %} + {%- if message.role == "assistant" %} + {# Add reasoning content in to content field for unified processing below. #} + {%- if message.reasoning_content is defined and message.reasoning_content is string and message.reasoning_content | trim | length > 0 %} + {%- set content = "\n" ~ message.reasoning_content ~ "\n\n" ~ (message.content | default('', true)) %} + {%- else %} + {%- set content = message.content | default('', true) %} + {%- if content is string -%} + {# Allow downstream logic to to take care of broken thought, only handle coherent reasoning here. #} + {%- if '' not in content and '' not in content -%} + {%- set content = "" ~ content -%} + {%- endif -%} + {%- else -%} + {%- set content = content -%} + {%- endif -%} + {%- endif %} + {%- if message.tool_calls is defined and message.tool_calls is iterable and message.tool_calls | length > 0 %} + {# Assistant message has tool calls. #} + {{- '<|im_start|>assistant\n' }} + {%- generation %} + {%- set include_content = not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %} + {%- if content is string and content | trim | length > 0 %} + {%- if include_content %} + {{- (content | trim) ~ '\n' -}} + {%- else %} + {%- set c = (content | string) %} + {%- if '' in c %} + {# Keep only content after the last closing think. Also generation prompt causes this. #} + {%- set c = c.split('')[-1] %} + {%- elif '' in c %} + {# If was opened but never closed, drop the trailing think segment #} + {%- set c = c.split('')[0] %} + {%- endif %} + {%- set c = "" ~ c | trim %} + {%- if c | length > 0 %} + {{- c ~ '\n' -}} + {%- endif %} + {%- endif %} + {%- else %} + {{- "" -}} + {%- endif %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '\n\n' -}} + {%- if tool_call.arguments is defined %} + {%- for args_name, args_value in tool_call.arguments|items %} + {{- '\n' -}} + {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %} + {{- args_value ~ '\n\n' -}} + {%- endfor %} + {%- endif %} + {{- '\n\n' -}} + {%- endfor %} + {{- '<|im_end|>\n' }} + {%- endgeneration %} + {%- else %} + {# Assistant message doesn't have tool calls. #} + {%- if not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %} + {{- '<|im_start|>assistant\n' }} + {%- generation %} + {{- (content | default('', true) | string | trim) ~ '<|im_end|>\n' }} + {%- endgeneration %} + {%- else %} + {%- set c = (content | default('', true) | string) %} + {%- if '' in c and '' in c %} + {%- set c = "" ~ c.split('')[-1] %} + {%- endif %} + {%- set c = c | trim %} + {%- if c | length > 0 %} + {{- '<|im_start|>assistant\n' }} + {%- generation %} + {{- c ~ '<|im_end|>\n' }} + {%- endgeneration %} + {%- else %} + {{- '<|im_start|>assistant\n' }} + {%- generation %} + {{- '<|im_end|>\n' }} + {%- endgeneration %} + {%- endif %} + {%- endif %} + {%- endif %} + {%- elif message.role == "user" or message.role == "system" %} + {{- '<|im_start|>' + message.role + '\n' }} + {%- set content = message.content | string %} + {%- if message.role == "user" and loop.index0 == ns.last_user_idx and low_effort %} + {{- content + '\n\n{reasoning effort: low}' }} + {%- else %} + {{- content }} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if loop.previtem and loop.previtem.role != "tool" %} + {{- '<|im_start|>user\n' }} + {%- endif %} + {{- '\n' }} + {{- message.content }} + {{- '\n\n' }} + {%- if not loop.last and loop.nextitem.role != "tool" %} + {{- '<|im_end|>\n' }} + {%- elif loop.last %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- else %} + {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>\n' }} + {%- endif %} +{%- endfor %} + +{%- if add_generation_prompt %} + {%- if enable_thinking %} + {{- '<|im_start|>assistant\n\n' }} + {%- else %} + {{- '<|im_start|>assistant\n' }} + {%- endif %} +{%- endif %} diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/nemotron_3_ultra.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/nemotron_3_ultra.jinja new file mode 100644 index 0000000000000000000000000000000000000000..7afbeb759a6786de17cde07485f9c2db387fd94d --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/nemotron_3_ultra.jinja @@ -0,0 +1,195 @@ +{% macro render_extra_keys(json_dict, handled_keys) %} + {%- if json_dict is mapping %} + {%- for json_key in json_dict if json_key not in handled_keys %} + {%- if json_dict[json_key] is mapping or (json_dict[json_key] is sequence and json_dict[json_key] is not string) %} + {{- '\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | tojson | safe) ~ '' }} + {%- else %} + {{-'\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | string) ~ '' }} + {%- endif %} + {%- endfor %} + {%- endif %} +{% endmacro %} +{%- set enable_thinking = enable_thinking if enable_thinking is defined else True %} +{%- set medium_effort = medium_effort if medium_effort is defined else False %} +{%- set truncate_history_thinking = truncate_history_thinking if truncate_history_thinking is defined else True %} +{%- set ns = namespace(last_user_idx = -1) %} +{%- set loop_messages = messages %} +{%- for m in loop_messages %} + {%- if m["role"] == "user" %} + {%- set ns.last_user_idx = loop.index0 %} + {%- endif %} +{%- endfor %} +{%- if messages[0]["role"] == "system" %} + {%- set system_message = messages[0]["content"] %} + {%- set loop_messages = messages[1:] %} +{%- else %} + {%- set system_message = "" %} + {%- set loop_messages = messages %} +{%- endif %} +{%- if not tools is defined %} + {%- set tools = [] %} +{%- endif %} +{%- set ns = namespace(last_user_idx = -1) %} +{%- for m in loop_messages %} + {%- if m["role"] == "user" %} + {%- set ns.last_user_idx = loop.index0 %} + {%- endif %} +{%- endfor %} +{%- if system_message is defined %} + {{- "<|im_start|>system\n" + system_message }} +{%- else %} + {%- if tools is iterable and tools | length > 0 %} + {{- "<|im_start|>system\n" }} + {%- endif %} +{%- endif %} +{%- if tools is iterable and tools | length > 0 %} + {%- if system_message is defined and system_message | length > 0 %} + {{- "\n\n" }} + {%- endif %} + {{- "# Tools\n\nYou have access to the following functions:\n\n" }} + {{- "" }} + {%- for tool in tools %} + {%- if tool.function is defined %} + {%- set tool = tool.function %} + {%- endif %} + {{- "\n\n" ~ tool.name ~ "" }} + {%- if tool.description is defined %} + {{- '\n' ~ (tool.description | trim) ~ '' }} + {%- endif %} + {{- '\n' }} + {%- if tool.parameters is defined and tool.parameters is mapping and tool.parameters.properties is defined and tool.parameters.properties is mapping %} + {%- for param_name, param_fields in tool.parameters.properties|items %} + {{- '\n' }} + {{- '\n' ~ param_name ~ '' }} + {%- if param_fields.type is defined %} + {{- '\n' ~ (param_fields.type | string) ~ '' }} + {%- endif %} + {%- if param_fields.description is defined %} + {{- '\n' ~ (param_fields.description | trim) ~ '' }} + {%- endif %} + {%- if param_fields.enum is defined %} + {{- '\n' ~ (param_fields.enum | tojson | safe) ~ '' }} + {%- endif %} + {%- set handled_keys = ['name', 'type', 'description', 'enum'] %} + {{- render_extra_keys(param_fields, handled_keys) }} + {{- '\n' }} + {%- endfor %} + {%- endif %} + {% set handled_keys = ['type', 'properties', 'required'] %} + {{- render_extra_keys(tool.parameters, handled_keys) }} + {%- if tool.parameters is defined and tool.parameters.required is defined %} + {{- '\n' ~ (tool.parameters.required | tojson | safe) ~ '' }} + {%- endif %} + {{- '\n' }} + {%- set handled_keys = ['type', 'name', 'description', 'parameters'] %} + {{- render_extra_keys(tool, handled_keys) }} + {{- '\n' }} + {%- endfor %} + {{- "\n" }} + {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n' }} +{%- endif %} +{%- if system_message is defined %} + {{- '<|im_end|>\n' }} +{%- else %} + {%- if tools is iterable and tools | length > 0 %} + {{- '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- for message in loop_messages %} + {%- if message.role == "assistant" %} + {%- if message.reasoning_content is defined and message.reasoning_content is string and message.reasoning_content | trim | length > 0 %} + {%- set content = "\n" ~ message.reasoning_content ~ "" ~ (message.content | default('', true)) %} + {%- else %} + {%- set content = message.content | default('', true) %} + {%- if content is string -%} + {%- if '' not in content and '' not in content -%} + {%- set content = "" ~ content -%} + {%- endif -%} + {%- else -%} + {%- set content = content -%} + {%- endif -%} + {%- endif %} + {%- if message.tool_calls is defined and message.tool_calls is iterable and message.tool_calls | length > 0 %} + {{- '<|im_start|>assistant\n' }} + {%- set include_content = not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %} + {%- if content is string and content | trim | length > 0 %} + {%- if include_content %} + {{- (content | trim) ~ '\n' -}} + {%- else %} + {%- set c = (content | string) %} + {%- if '' in c %} + {%- set c = c.split('')[-1] %} + {%- elif '' in c %} + {%- set c = c.split('')[0] %} + {%- endif %} + {%- set c = "" ~ c %} + {%- if c | length > 0 %} + {{- c ~ '\n' -}} + {%- endif %} + {%- endif %} + {%- else %} + {{- "" -}} + {%- endif %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '\n\n' -}} + {%- if tool_call.arguments is defined %} + {%- for args_name, args_value in tool_call.arguments|items %} + {{- '\n' -}} + {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %} + {{- args_value ~ '\n\n' -}} + {%- endfor %} + {%- endif %} + {{- '\n\n' -}} + {%- endfor %} + {{- '<|im_end|>\n' }} + {%- else %} + {%- if not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %} + {{- '<|im_start|>assistant\n' ~ (content | default('', true) | string | trim) ~ '<|im_end|>\n' }} + {%- else %} + {%- set c = (content | default('', true) | string) %} + {%- if '' in c and '' in c %} + {%- set c = "" ~ c.split('')[-1] %} + {%- endif %} + {%- set c = c | trim %} + {%- if c | length > 0 %} + {{- '<|im_start|>assistant\n' ~ c ~ '<|im_end|>\n' }} + {%- else %} + {{- '<|im_start|>assistant\n<|im_end|>\n' }} + {%- endif %} + {%- endif %} + {%- endif %} + {%- elif message.role == "user" or message.role == "system" %} + {{- '<|im_start|>' + message.role + '\n' }} + {%- set content = message.content | string %} + {%- if message.role == "user" and loop.index0 == ns.last_user_idx and medium_effort %} + {{- content + '\n\n{reasoning effort: efficient}' }} + {%- else %} + {{- content }} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if loop.previtem and loop.previtem.role != "tool" %} + {{- '<|im_start|>user\n' }} + {%- endif %} + {{- '\n' }} + {{- message.content }} + {{- '\n\n' }} + {%- if not loop.last and loop.nextitem.role != "tool" %} + {{- '<|im_end|>\n' }} + {%- elif loop.last %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- else %} + {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>\n' }} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {%- if enable_thinking %} + {{- '<|im_start|>assistant\n\n' }} + {%- else %} + {{- '<|im_start|>assistant\n' }} + {%- endif %} +{%- endif %} \ No newline at end of file diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/nemotron_3_ultra_training.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/nemotron_3_ultra_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..12a52d22e4c38c67a6a98b5b396e134ad3de94f8 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/nemotron_3_ultra_training.jinja @@ -0,0 +1,212 @@ +{#- Training variant of the Nemotron Ultra chat template (see nemotron_3_ultra.jinja for the original). + The original is already prefix-preserving, so the only modification is adding + {% generation %} / {% endgeneration %} around assistant message output to support + assistant-only loss masking in SFT training. All other rendering (including the + `truncate_history_thinking` and `medium_effort` logic) is identical to the original. +-#} +{% macro render_extra_keys(json_dict, handled_keys) %} + {%- if json_dict is mapping %} + {%- for json_key in json_dict if json_key not in handled_keys %} + {%- if json_dict[json_key] is mapping or (json_dict[json_key] is sequence and json_dict[json_key] is not string) %} + {{- '\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | tojson | safe) ~ '' }} + {%- else %} + {{-'\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | string) ~ '' }} + {%- endif %} + {%- endfor %} + {%- endif %} +{% endmacro %} +{%- set enable_thinking = enable_thinking if enable_thinking is defined else True %} +{%- set medium_effort = medium_effort if medium_effort is defined else False %} +{%- set truncate_history_thinking = truncate_history_thinking if truncate_history_thinking is defined else True %} +{%- set ns = namespace(last_user_idx = -1) %} +{%- set loop_messages = messages %} +{%- for m in loop_messages %} + {%- if m["role"] == "user" %} + {%- set ns.last_user_idx = loop.index0 %} + {%- endif %} +{%- endfor %} +{%- if messages[0]["role"] == "system" %} + {%- set system_message = messages[0]["content"] %} + {%- set loop_messages = messages[1:] %} +{%- else %} + {%- set system_message = "" %} + {%- set loop_messages = messages %} +{%- endif %} +{%- if not tools is defined %} + {%- set tools = [] %} +{%- endif %} +{%- set ns = namespace(last_user_idx = -1) %} +{%- for m in loop_messages %} + {%- if m["role"] == "user" %} + {%- set ns.last_user_idx = loop.index0 %} + {%- endif %} +{%- endfor %} +{%- if system_message is defined %} + {{- "<|im_start|>system\n" + system_message }} +{%- else %} + {%- if tools is iterable and tools | length > 0 %} + {{- "<|im_start|>system\n" }} + {%- endif %} +{%- endif %} +{%- if tools is iterable and tools | length > 0 %} + {%- if system_message is defined and system_message | length > 0 %} + {{- "\n\n" }} + {%- endif %} + {{- "# Tools\n\nYou have access to the following functions:\n\n" }} + {{- "" }} + {%- for tool in tools %} + {%- if tool.function is defined %} + {%- set tool = tool.function %} + {%- endif %} + {{- "\n\n" ~ tool.name ~ "" }} + {%- if tool.description is defined %} + {{- '\n' ~ (tool.description | trim) ~ '' }} + {%- endif %} + {{- '\n' }} + {%- if tool.parameters is defined and tool.parameters is mapping and tool.parameters.properties is defined and tool.parameters.properties is mapping %} + {%- for param_name, param_fields in tool.parameters.properties|items %} + {{- '\n' }} + {{- '\n' ~ param_name ~ '' }} + {%- if param_fields.type is defined %} + {{- '\n' ~ (param_fields.type | string) ~ '' }} + {%- endif %} + {%- if param_fields.description is defined %} + {{- '\n' ~ (param_fields.description | trim) ~ '' }} + {%- endif %} + {%- if param_fields.enum is defined %} + {{- '\n' ~ (param_fields.enum | tojson | safe) ~ '' }} + {%- endif %} + {%- set handled_keys = ['name', 'type', 'description', 'enum'] %} + {{- render_extra_keys(param_fields, handled_keys) }} + {{- '\n' }} + {%- endfor %} + {%- endif %} + {% set handled_keys = ['type', 'properties', 'required'] %} + {{- render_extra_keys(tool.parameters, handled_keys) }} + {%- if tool.parameters is defined and tool.parameters.required is defined %} + {{- '\n' ~ (tool.parameters.required | tojson | safe) ~ '' }} + {%- endif %} + {{- '\n' }} + {%- set handled_keys = ['type', 'name', 'description', 'parameters'] %} + {{- render_extra_keys(tool, handled_keys) }} + {{- '\n' }} + {%- endfor %} + {{- "\n" }} + {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n' }} +{%- endif %} +{%- if system_message is defined %} + {{- '<|im_end|>\n' }} +{%- else %} + {%- if tools is iterable and tools | length > 0 %} + {{- '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- for message in loop_messages %} + {%- if message.role == "assistant" %} + {%- if message.reasoning_content is defined and message.reasoning_content is string and message.reasoning_content | trim | length > 0 %} + {%- set content = "\n" ~ message.reasoning_content ~ "" ~ (message.content | default('', true)) %} + {%- else %} + {%- set content = message.content | default('', true) %} + {%- if content is string -%} + {%- if '' not in content and '' not in content -%} + {%- set content = "" ~ content -%} + {%- endif -%} + {%- else -%} + {%- set content = content -%} + {%- endif -%} + {%- endif %} + {%- if message.tool_calls is defined and message.tool_calls is iterable and message.tool_calls | length > 0 %} + {{- '<|im_start|>assistant\n' }} + {%- generation %} + {%- set include_content = not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %} + {%- if content is string and content | trim | length > 0 %} + {%- if include_content %} + {{- (content | trim) ~ '\n' -}} + {%- else %} + {%- set c = (content | string) %} + {%- if '' in c %} + {%- set c = c.split('')[-1] %} + {%- elif '' in c %} + {%- set c = c.split('')[0] %} + {%- endif %} + {%- set c = "" ~ c %} + {%- if c | length > 0 %} + {{- c ~ '\n' -}} + {%- endif %} + {%- endif %} + {%- else %} + {{- "" -}} + {%- endif %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '\n\n' -}} + {%- if tool_call.arguments is defined %} + {%- for args_name, args_value in tool_call.arguments|items %} + {{- '\n' -}} + {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %} + {{- args_value ~ '\n\n' -}} + {%- endfor %} + {%- endif %} + {{- '\n\n' -}} + {%- endfor %} + {{- '<|im_end|>\n' }} + {%- endgeneration %} + {%- else %} + {%- if not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %} + {{- '<|im_start|>assistant\n' }} + {%- generation %} + {{- (content | default('', true) | string | trim) ~ '<|im_end|>\n' }} + {%- endgeneration %} + {%- else %} + {%- set c = (content | default('', true) | string) %} + {%- if '' in c and '' in c %} + {%- set c = "" ~ c.split('')[-1] %} + {%- endif %} + {%- set c = c | trim %} + {%- if c | length > 0 %} + {{- '<|im_start|>assistant\n' }} + {%- generation %} + {{- c ~ '<|im_end|>\n' }} + {%- endgeneration %} + {%- else %} + {{- '<|im_start|>assistant\n' }} + {%- generation %} + {{- '<|im_end|>\n' }} + {%- endgeneration %} + {%- endif %} + {%- endif %} + {%- endif %} + {%- elif message.role == "user" or message.role == "system" %} + {{- '<|im_start|>' + message.role + '\n' }} + {%- set content = message.content | string %} + {%- if message.role == "user" and loop.index0 == ns.last_user_idx and medium_effort %} + {{- content + '\n\n{reasoning effort: efficient}' }} + {%- else %} + {{- content }} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if loop.previtem and loop.previtem.role != "tool" %} + {{- '<|im_start|>user\n' }} + {%- endif %} + {{- '\n' }} + {{- message.content }} + {{- '\n\n' }} + {%- if not loop.last and loop.nextitem.role != "tool" %} + {{- '<|im_end|>\n' }} + {%- elif loop.last %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- else %} + {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>\n' }} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {%- if enable_thinking %} + {{- '<|im_start|>assistant\n\n' }} + {%- else %} + {{- '<|im_start|>assistant\n' }} + {%- endif %} +{%- endif %} \ No newline at end of file diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/phi3.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/phi3.jinja new file mode 100644 index 0000000000000000000000000000000000000000..ddb5006baa8ee6aa317c5d84827e6993469c2073 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/phi3.jinja @@ -0,0 +1,8 @@ +{% for message in messages %}{% if message['role'] == 'system' %}{{'<|system|> +' + message['content'] + '<|end|> +'}}{% elif message['role'] == 'user' %}{{'<|user|> +' + message['content'] + '<|end|> +'}}{% elif message['role'] == 'assistant' %}{{'<|assistant|> +' + message['content'] + '<|end|> +'}}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ '<|assistant|> +' }}{% else %}{{ eos_token }}{% endif %} \ No newline at end of file diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/phi3_5.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/phi3_5.jinja new file mode 100644 index 0000000000000000000000000000000000000000..d1533d1526b2e42fccd99477a7274dc20b7a189b --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/phi3_5.jinja @@ -0,0 +1,8 @@ +{% for message in messages %}{% if message['role'] == 'system' and message['content'] %}{{'<|system|> +' + message['content'] + '<|end|> +'}}{% elif message['role'] == 'user' %}{{'<|user|> +' + message['content'] + '<|end|> +'}}{% elif message['role'] == 'assistant' %}{{'<|assistant|> +' + message['content'] + '<|end|> +'}}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ '<|assistant|> +' }}{% else %}{{ eos_token }}{% endif %} \ No newline at end of file diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/phi3_5_training.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/phi3_5_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..61d15d77936bc8ebbf965f4478185e9b4233caad --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/phi3_5_training.jinja @@ -0,0 +1,26 @@ +{#- Training variant of the Phi-3.5 chat template (see phi3_5.jinja for the original). + Modifications vs the original: + - Added {% generation %} / {% endgeneration %} around assistant message output to support + assistant-only loss masking in SFT training. +-#} +{%- for message in messages %} + {%- if message['role'] == 'system' and message['content'] %} + {{- '<|system|>\n' + message['content'] + '<|end|>\n' }} + {%- elif message['role'] == 'user' %} + {{- '<|user|>\n' + message['content'] + '<|end|>\n'}} + {%- elif message['role'] == 'assistant' %} + {{- '<|assistant|>\n' }} + {%- generation %} + {{- message['content'] + '<|end|>\n' }} + {%- endgeneration %} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|assistant|>\n'}} +{%- elif messages[-1]['role'] == 'assistant' %} + {%- generation %} + {{- eos_token }} + {%- endgeneration %} +{%- else %} + {{- eos_token }} +{%- endif %} \ No newline at end of file diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/phi3_training.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/phi3_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..1536d152f7de385ed29917e463bb0aba66977eb3 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/phi3_training.jinja @@ -0,0 +1,26 @@ +{#- Training variant of the Phi-3 chat template (see phi3.jinja for the original). + Modifications vs the original: + - Added {% generation %} / {% endgeneration %} around assistant message output to support + assistant-only loss masking in SFT training. +-#} +{%- for message in messages %} + {%- if message['role'] == 'system' %} + {{- '<|system|>\n' + message['content'] + '<|end|>\n' }} + {%- elif message['role'] == 'user' %} + {{- '<|user|>\n' + message['content'] + '<|end|>\n' }} + {%- elif message['role'] == 'assistant' %} + {{- '<|assistant|>\n' }} + {%- generation %} + {{- message['content'] + '<|end|>\n' }} + {%- endgeneration %} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|assistant|>\n' }} +{%- elif messages[-1]['role'] == 'assistant' %} + {%- generation %} + {{- eos_token }} + {%- endgeneration %} +{%- else %} + {{- eos_token }} +{%- endif %} diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen2_5.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen2_5.jinja new file mode 100644 index 0000000000000000000000000000000000000000..bdf7919a96cfe43d50914a007b9c0877bd0ec27e --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen2_5.jinja @@ -0,0 +1,54 @@ +{%- if tools %} + {{- '<|im_start|>system\n' }} + {%- if messages[0]['role'] == 'system' %} + {{- messages[0]['content'] }} + {%- else %} + {{- 'You are Qwen, created by Alibaba Cloud. You are a helpful assistant.' }} + {%- endif %} + {{- "\n\n# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within XML tags:\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n\n\nFor each function call, return a json object with function name and arguments within XML tags:\n\n{\"name\": , \"arguments\": }\n<|im_end|>\n" }} +{%- else %} + {%- if messages[0]['role'] == 'system' %} + {{- '<|im_start|>system\n' + messages[0]['content'] + '<|im_end|>\n' }} + {%- else %} + {{- '<|im_start|>system\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- for message in messages %} + {%- if (message.role == "user") or (message.role == "system" and not loop.first) or (message.role == "assistant" and not message.tool_calls) %} + {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>' + '\n' }} + {%- elif message.role == "assistant" %} + {{- '<|im_start|>' + message.role }} + {%- if message.content %} + {{- '\n' + message.content }} + {%- endif %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '\n\n{"name": "' }} + {{- tool_call.name }} + {{- '", "arguments": ' }} + {{- tool_call.arguments | tojson }} + {{- '}\n' }} + {%- endfor %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != "tool") %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {{- message.content }} + {{- '\n' }} + {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} +{%- endif %} diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen2_5_training.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen2_5_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..fd7258ece606cb8b6b59a3fb28904282f6004ac4 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen2_5_training.jinja @@ -0,0 +1,65 @@ +{#- Training variant of the Qwen2.5 chat template (see qwen2_5.jinja for the original). + Modifications vs the original: + - Added {% generation %} / {% endgeneration %} around assistant message output to support + assistant-only loss masking in SFT training. +-#} +{%- if tools %} + {{- '<|im_start|>system\n' }} + {%- if messages[0]['role'] == 'system' %} + {{- messages[0]['content'] }} + {%- else %} + {{- 'You are Qwen, created by Alibaba Cloud. You are a helpful assistant.' }} + {%- endif %} + {{- "\n\n# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within XML tags:\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n\n\nFor each function call, return a json object with function name and arguments within XML tags:\n\n{\"name\": , \"arguments\": }\n<|im_end|>\n" }} +{%- else %} + {%- if messages[0]['role'] == 'system' %} + {{- '<|im_start|>system\n' + messages[0]['content'] + '<|im_end|>\n' }} + {%- else %} + {{- '<|im_start|>system\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- for message in messages %} + {%- if (message.role == "user") or (message.role == "system" and not loop.first) %} + {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>' + '\n' }} + {%- elif message.role == "assistant" %} + {{- '<|im_start|>assistant' }} + {%- generation %} + {%- if not message.tool_calls %} + {{- '\n' + message.content + '<|im_end|>\n' }} + {%- else %} + {%- if message.content %} + {{- '\n' + message.content }} + {%- endif %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '\n\n{"name": "' }} + {{- tool_call.name }} + {{- '", "arguments": ' }} + {{- tool_call.arguments | tojson }} + {{- '}\n' }} + {%- endfor %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- endgeneration %} + {%- elif message.role == "tool" %} + {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != "tool") %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {{- message.content }} + {{- '\n' }} + {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} +{%- endif %} diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen2_5_vl.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen2_5_vl.jinja new file mode 100644 index 0000000000000000000000000000000000000000..6c226632394ae7474b0d4b13e15793eac2e21ee9 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen2_5_vl.jinja @@ -0,0 +1,7 @@ +{% set image_count = namespace(value=0) %}{% set video_count = namespace(value=0) %}{% for message in messages %}{% if loop.first and message['role'] != 'system' %}<|im_start|>system +You are a helpful assistant.<|im_end|> +{% endif %}<|im_start|>{{ message['role'] }} +{% if message['content'] is string %}{{ message['content'] }}<|im_end|> +{% else %}{% for content in message['content'] %}{% if content['type'] == 'image' or 'image' in content or 'image_url' in content %}{% set image_count.value = image_count.value + 1 %}{% if add_vision_id %}Picture {{ image_count.value }}: {% endif %}<|vision_start|><|image_pad|><|vision_end|>{% elif content['type'] == 'video' or 'video' in content %}{% set video_count.value = video_count.value + 1 %}{% if add_vision_id %}Video {{ video_count.value }}: {% endif %}<|vision_start|><|video_pad|><|vision_end|>{% elif 'text' in content %}{{ content['text'] }}{% endif %}{% endfor %}<|im_end|> +{% endif %}{% endfor %}{% if add_generation_prompt %}<|im_start|>assistant +{% endif %} \ No newline at end of file diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen2_5_vl_training.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen2_5_vl_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..46e34469a34f03fa8c12b7535307cc189997d14b --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen2_5_vl_training.jinja @@ -0,0 +1,63 @@ +{#- Training variant of the Qwen 2.5 VL chat template (see qwen2_5_vl.jinja for the original). + Also used for Qwen 2 VL, which ships a byte-identical chat template. + Modifications vs the original: + - Split the assistant message into its own branch so the {% generation %} / {% endgeneration %} + markers wrap the assistant content (everything after the '<|im_start|>assistant\n' prompt + cue, up to and including the trailing '<|im_end|>\n'). This enables assistant-only loss + masking in SFT training. +-#} +{%- set image_count = namespace(value=0) %} +{%- set video_count = namespace(value=0) %} +{%- for message in messages %} + {%- if loop.first and message['role'] != 'system' %} + {{- '<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n' }} + {%- endif %} + {%- if message['role'] == 'assistant' %} + {{- '<|im_start|>assistant\n' }} + {%- generation -%} + {%- if message['content'] is string %} + {{- message['content'] }} + {{- '<|im_end|>\n' }} + {%- else %} + {%- for content in message['content'] %} + {%- if content['type'] == 'image' or 'image' in content or 'image_url' in content %} + {%- set image_count.value = image_count.value + 1 %} + {%- if add_vision_id %}Picture {{ image_count.value }}: {% endif -%} + <|vision_start|><|image_pad|><|vision_end|> + {%- elif content['type'] == 'video' or 'video' in content %} + {%- set video_count.value = video_count.value + 1 %} + {%- if add_vision_id %}Video {{ video_count.value }}: {% endif -%} + <|vision_start|><|video_pad|><|vision_end|> + {%- elif 'text' in content %} + {{- content['text'] }} + {%- endif %} + {%- endfor %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- endgeneration -%} + {%- else %} + {{- '<|im_start|>' + message['role'] + '\n' }} + {%- if message['content'] is string %} + {{- message['content'] }} + {{- '<|im_end|>\n' }} + {%- else %} + {%- for content in message['content'] %} + {%- if content['type'] == 'image' or 'image' in content or 'image_url' in content %} + {%- set image_count.value = image_count.value + 1 %} + {%- if add_vision_id %}Picture {{ image_count.value }}: {% endif -%} + <|vision_start|><|image_pad|><|vision_end|> + {%- elif content['type'] == 'video' or 'video' in content %} + {%- set video_count.value = video_count.value + 1 %} + {%- if add_vision_id %}Video {{ video_count.value }}: {% endif -%} + <|vision_start|><|video_pad|><|vision_end|> + {%- elif 'text' in content %} + {{- content['text'] }} + {%- endif %} + {%- endfor %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} +{%- endif %} \ No newline at end of file diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3.jinja new file mode 100644 index 0000000000000000000000000000000000000000..01be9b307daa2d425f7c168c9fb145a286e0afb4 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3.jinja @@ -0,0 +1,89 @@ +{%- if tools %} + {{- '<|im_start|>system\n' }} + {%- if messages[0].role == 'system' %} + {{- messages[0].content + '\n\n' }} + {%- endif %} + {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within XML tags:\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n\n\nFor each function call, return a json object with function name and arguments within XML tags:\n\n{\"name\": , \"arguments\": }\n<|im_end|>\n" }} +{%- else %} + {%- if messages[0].role == 'system' %} + {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %} +{%- for message in messages[::-1] %} + {%- set index = (messages|length - 1) - loop.index0 %} + {%- if ns.multi_step_tool and message.role == "user" and message.content is string and not(message.content.startswith('') and message.content.endswith('')) %} + {%- set ns.multi_step_tool = false %} + {%- set ns.last_query_index = index %} + {%- endif %} +{%- endfor %} +{%- for message in messages %} + {%- if message.content is string %} + {%- set content = message.content %} + {%- else %} + {%- set content = '' %} + {%- endif %} + {%- if (message.role == "user") or (message.role == "system" and not loop.first) %} + {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} + {%- elif message.role == "assistant" %} + {%- set reasoning_content = '' %} + {%- if message.reasoning_content is string %} + {%- set reasoning_content = message.reasoning_content %} + {%- else %} + {%- if '' in content %} + {%- set reasoning_content = content.split('')[0].rstrip('\n').split('')[-1].lstrip('\n') %} + {%- set content = content.split('')[-1].lstrip('\n') %} + {%- endif %} + {%- endif %} + {%- if loop.index0 > ns.last_query_index %} + {%- if loop.last or (not loop.last and reasoning_content) %} + {{- '<|im_start|>' + message.role + '\n\n' + reasoning_content.strip('\n') + '\n\n\n' + content.lstrip('\n') }} + {%- else %} + {{- '<|im_start|>' + message.role + '\n' + content }} + {%- endif %} + {%- else %} + {{- '<|im_start|>' + message.role + '\n' + content }} + {%- endif %} + {%- if message.tool_calls %} + {%- for tool_call in message.tool_calls %} + {%- if (loop.first and content) or (not loop.first) %} + {{- '\n' }} + {%- endif %} + {%- if tool_call.function %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '\n{"name": "' }} + {{- tool_call.name }} + {{- '", "arguments": ' }} + {%- if tool_call.arguments is string %} + {{- tool_call.arguments }} + {%- else %} + {{- tool_call.arguments | tojson }} + {%- endif %} + {{- '}\n' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {{- content }} + {{- '\n' }} + {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} + {%- if enable_thinking is defined and enable_thinking is false %} + {{- '\n\n\n\n' }} + {%- endif %} +{%- endif %} \ No newline at end of file diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3_5_nothink.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3_5_nothink.jinja new file mode 100644 index 0000000000000000000000000000000000000000..0ef09f214eaa6d9bca297988afc1454b5827b2c7 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3_5_nothink.jinja @@ -0,0 +1,154 @@ +{%- set image_count = namespace(value=0) %} +{%- set video_count = namespace(value=0) %} +{%- macro render_content(content, do_vision_count, is_system_content=false) %} + {%- if content is string %} + {{- content }} + {%- elif content is iterable and content is not mapping %} + {%- for item in content %} + {%- if 'image' in item or 'image_url' in item or item.type == 'image' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain images.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set image_count.value = image_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Picture ' ~ image_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|image_pad|><|vision_end|>' }} + {%- elif 'video' in item or item.type == 'video' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain videos.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set video_count.value = video_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Video ' ~ video_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|video_pad|><|vision_end|>' }} + {%- elif 'text' in item %} + {{- item.text }} + {%- else %} + {{- raise_exception('Unexpected item type in content.') }} + {%- endif %} + {%- endfor %} + {%- elif content is none or content is undefined %} + {{- '' }} + {%- else %} + {{- raise_exception('Unexpected content type.') }} + {%- endif %} +{%- endmacro %} +{%- if not messages %} + {{- raise_exception('No messages provided.') }} +{%- endif %} +{%- if tools and tools is iterable and tools is not mapping %} + {{- '<|im_start|>system\n' }} + {{- "# Tools\n\nYou have access to the following functions:\n\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n" }} + {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n' }} + {%- if messages[0].role == 'system' %} + {%- set content = render_content(messages[0].content, false, true)|trim %} + {%- if content %} + {{- '\n\n' + content }} + {%- endif %} + {%- endif %} + {{- '<|im_end|>\n' }} +{%- else %} + {%- if messages[0].role == 'system' %} + {%- set content = render_content(messages[0].content, false, true)|trim %} + {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %} +{%- for message in messages[::-1] %} + {%- set index = (messages|length - 1) - loop.index0 %} + {%- if ns.multi_step_tool and message.role == "user" %} + {%- set content = render_content(message.content, false)|trim %} + {%- if not(content.startswith('') and content.endswith('')) %} + {%- set ns.multi_step_tool = false %} + {%- set ns.last_query_index = index %} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if ns.multi_step_tool %} + {{- raise_exception('No user query found in messages.') }} +{%- endif %} +{%- for message in messages %} + {%- set content = render_content(message.content, true)|trim %} + {%- if message.role == "system" %} + {%- if not loop.first %} + {{- raise_exception('System message must be at the beginning.') }} + {%- endif %} + {%- elif message.role == "user" %} + {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} + {%- elif message.role == "assistant" %} + {%- set reasoning_content = '' %} + {%- if message.reasoning_content is string %} + {%- set reasoning_content = message.reasoning_content %} + {%- else %} + {%- if '' in content %} + {%- set reasoning_content = content.split('')[0].rstrip('\n').split('')[-1].lstrip('\n') %} + {%- set content = content.split('')[-1].lstrip('\n') %} + {%- endif %} + {%- endif %} + {%- set reasoning_content = reasoning_content|trim %} + {%- if loop.index0 > ns.last_query_index %} + {{- '<|im_start|>' + message.role + '\n\n' + reasoning_content + '\n\n\n' + content }} + {%- else %} + {{- '<|im_start|>' + message.role + '\n' + content }} + {%- endif %} + {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {%- if loop.first %} + {%- if content|trim %} + {{- '\n\n\n\n' }} + {%- else %} + {{- '\n\n' }} + {%- endif %} + {%- else %} + {{- '\n\n\n' }} + {%- endif %} + {%- if tool_call.arguments is defined %} + {%- for args_name, args_value in tool_call.arguments|items %} + {{- '\n' }} + {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %} + {{- args_value }} + {{- '\n\n' }} + {%- endfor %} + {%- endif %} + {{- '\n' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if loop.previtem and loop.previtem.role != "tool" %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {{- content }} + {{- '\n' }} + {%- if not loop.last and loop.nextitem.role != "tool" %} + {{- '<|im_end|>\n' }} + {%- elif loop.last %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- else %} + {{- raise_exception('Unexpected message role.') }} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} + {%- if enable_thinking is defined and enable_thinking is true %} + {{- '\n' }} + {%- else %} + {{- '\n\n\n\n' }} + {%- endif %} +{%- endif %} \ No newline at end of file diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3_5_nothink_training.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3_5_nothink_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..a5bde154d92c83eb794470601ac82a1b22b5b938 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3_5_nothink_training.jinja @@ -0,0 +1,162 @@ +{#- Training variant of the Qwen3.5 chat template, NoThink flavor (see qwen3_5_nothink.jinja for the original). + Modifications vs the original: + - {%- if '' in content %} → {%- if '' in content and '' in content %} + Always check for both tags to avoid edge cases where the model generates only one tag. + - Removed the loop.index0 > ns.last_query_index conditional; always include thinking block. + This makes the template prefix-preserving for the [user, assistant] → [user, assistant, tool] transition. + - Added {% generation %} / {% endgeneration %} around assistant message output to support + assistant-only loss masking in SFT training. +-#} +{%- set image_count = namespace(value=0) %} +{%- set video_count = namespace(value=0) %} +{%- macro render_content(content, do_vision_count, is_system_content=false) %} + {%- if content is string %} + {{- content }} + {%- elif content is iterable and content is not mapping %} + {%- for item in content %} + {%- if 'image' in item or 'image_url' in item or item.type == 'image' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain images.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set image_count.value = image_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Picture ' ~ image_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|image_pad|><|vision_end|>' }} + {%- elif 'video' in item or item.type == 'video' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain videos.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set video_count.value = video_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Video ' ~ video_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|video_pad|><|vision_end|>' }} + {%- elif 'text' in item %} + {{- item.text }} + {%- else %} + {{- raise_exception('Unexpected item type in content.') }} + {%- endif %} + {%- endfor %} + {%- elif content is none or content is undefined %} + {{- '' }} + {%- else %} + {{- raise_exception('Unexpected content type.') }} + {%- endif %} +{%- endmacro %} +{%- if not messages %} + {{- raise_exception('No messages provided.') }} +{%- endif %} +{%- if tools and tools is iterable and tools is not mapping %} + {{- '<|im_start|>system\n' }} + {{- "# Tools\n\nYou have access to the following functions:\n\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n" }} + {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n' }} + {%- if messages[0].role == 'system' %} + {%- set content = render_content(messages[0].content, false, true)|trim %} + {%- if content %} + {{- '\n\n' + content }} + {%- endif %} + {%- endif %} + {{- '<|im_end|>\n' }} +{%- else %} + {%- if messages[0].role == 'system' %} + {%- set content = render_content(messages[0].content, false, true)|trim %} + {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %} +{%- for message in messages[::-1] %} + {%- set index = (messages|length - 1) - loop.index0 %} + {%- if ns.multi_step_tool and message.role == "user" %} + {%- set content = render_content(message.content, false)|trim %} + {%- if not(content.startswith('') and content.endswith('')) %} + {%- set ns.multi_step_tool = false %} + {%- set ns.last_query_index = index %} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if ns.multi_step_tool %} + {{- raise_exception('No user query found in messages.') }} +{%- endif %} +{%- for message in messages %} + {%- set content = render_content(message.content, true)|trim %} + {%- if message.role == "system" %} + {%- if not loop.first %} + {{- raise_exception('System message must be at the beginning.') }} + {%- endif %} + {%- elif message.role == "user" %} + {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} + {%- elif message.role == "assistant" %} + {%- set reasoning_content = '' %} + {%- if message.reasoning_content is string %} + {%- set reasoning_content = message.reasoning_content %} + {%- else %} + {%- if '' in content and '' in content %} + {%- set reasoning_content = content.split('')[0].rstrip('\n').split('')[-1].lstrip('\n') %} + {%- set content = content.split('')[-1].lstrip('\n') %} + {%- endif %} + {%- endif %} + {%- set reasoning_content = reasoning_content|trim %} + {{- '<|im_start|>' + message.role + '\n' }} + {%- generation %} + {{- '\n' + reasoning_content + '\n\n\n' + content }} + {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {%- if loop.first %} + {%- if content|trim %} + {{- '\n\n\n\n' }} + {%- else %} + {{- '\n\n' }} + {%- endif %} + {%- else %} + {{- '\n\n\n' }} + {%- endif %} + {%- if tool_call.arguments is defined %} + {%- for args_name, args_value in tool_call.arguments|items %} + {{- '\n' }} + {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %} + {{- args_value }} + {{- '\n\n' }} + {%- endfor %} + {%- endif %} + {{- '\n' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- endgeneration %} + {%- elif message.role == "tool" %} + {%- if loop.previtem and loop.previtem.role != "tool" %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {{- content }} + {{- '\n' }} + {%- if not loop.last and loop.nextitem.role != "tool" %} + {{- '<|im_end|>\n' }} + {%- elif loop.last %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- else %} + {{- raise_exception('Unexpected message role.') }} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} + {%- if enable_thinking is defined and enable_thinking is true %} + {{- '\n' }} + {%- else %} + {{- '\n\n\n\n' }} + {%- endif %} +{%- endif %} \ No newline at end of file diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3_5_think.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3_5_think.jinja new file mode 100644 index 0000000000000000000000000000000000000000..a585dec894e63da457d9440ec6aa7caa16d20860 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3_5_think.jinja @@ -0,0 +1,154 @@ +{%- set image_count = namespace(value=0) %} +{%- set video_count = namespace(value=0) %} +{%- macro render_content(content, do_vision_count, is_system_content=false) %} + {%- if content is string %} + {{- content }} + {%- elif content is iterable and content is not mapping %} + {%- for item in content %} + {%- if 'image' in item or 'image_url' in item or item.type == 'image' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain images.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set image_count.value = image_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Picture ' ~ image_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|image_pad|><|vision_end|>' }} + {%- elif 'video' in item or item.type == 'video' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain videos.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set video_count.value = video_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Video ' ~ video_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|video_pad|><|vision_end|>' }} + {%- elif 'text' in item %} + {{- item.text }} + {%- else %} + {{- raise_exception('Unexpected item type in content.') }} + {%- endif %} + {%- endfor %} + {%- elif content is none or content is undefined %} + {{- '' }} + {%- else %} + {{- raise_exception('Unexpected content type.') }} + {%- endif %} +{%- endmacro %} +{%- if not messages %} + {{- raise_exception('No messages provided.') }} +{%- endif %} +{%- if tools and tools is iterable and tools is not mapping %} + {{- '<|im_start|>system\n' }} + {{- "# Tools\n\nYou have access to the following functions:\n\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n" }} + {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n' }} + {%- if messages[0].role == 'system' %} + {%- set content = render_content(messages[0].content, false, true)|trim %} + {%- if content %} + {{- '\n\n' + content }} + {%- endif %} + {%- endif %} + {{- '<|im_end|>\n' }} +{%- else %} + {%- if messages[0].role == 'system' %} + {%- set content = render_content(messages[0].content, false, true)|trim %} + {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %} +{%- for message in messages[::-1] %} + {%- set index = (messages|length - 1) - loop.index0 %} + {%- if ns.multi_step_tool and message.role == "user" %} + {%- set content = render_content(message.content, false)|trim %} + {%- if not(content.startswith('') and content.endswith('')) %} + {%- set ns.multi_step_tool = false %} + {%- set ns.last_query_index = index %} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if ns.multi_step_tool %} + {{- raise_exception('No user query found in messages.') }} +{%- endif %} +{%- for message in messages %} + {%- set content = render_content(message.content, true)|trim %} + {%- if message.role == "system" %} + {%- if not loop.first %} + {{- raise_exception('System message must be at the beginning.') }} + {%- endif %} + {%- elif message.role == "user" %} + {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} + {%- elif message.role == "assistant" %} + {%- set reasoning_content = '' %} + {%- if message.reasoning_content is string %} + {%- set reasoning_content = message.reasoning_content %} + {%- else %} + {%- if '' in content %} + {%- set reasoning_content = content.split('')[0].rstrip('\n').split('')[-1].lstrip('\n') %} + {%- set content = content.split('')[-1].lstrip('\n') %} + {%- endif %} + {%- endif %} + {%- set reasoning_content = reasoning_content|trim %} + {%- if loop.index0 > ns.last_query_index %} + {{- '<|im_start|>' + message.role + '\n\n' + reasoning_content + '\n\n\n' + content }} + {%- else %} + {{- '<|im_start|>' + message.role + '\n' + content }} + {%- endif %} + {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {%- if loop.first %} + {%- if content|trim %} + {{- '\n\n\n\n' }} + {%- else %} + {{- '\n\n' }} + {%- endif %} + {%- else %} + {{- '\n\n\n' }} + {%- endif %} + {%- if tool_call.arguments is defined %} + {%- for args_name, args_value in tool_call.arguments|items %} + {{- '\n' }} + {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %} + {{- args_value }} + {{- '\n\n' }} + {%- endfor %} + {%- endif %} + {{- '\n' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if loop.previtem and loop.previtem.role != "tool" %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {{- content }} + {{- '\n' }} + {%- if not loop.last and loop.nextitem.role != "tool" %} + {{- '<|im_end|>\n' }} + {%- elif loop.last %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- else %} + {{- raise_exception('Unexpected message role.') }} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} + {%- if enable_thinking is defined and enable_thinking is false %} + {{- '\n\n\n\n' }} + {%- else %} + {{- '\n' }} + {%- endif %} +{%- endif %} \ No newline at end of file diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3_5_think_training.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3_5_think_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..fb4b811d6ae3c583b7e7144ace7789f8c07ca10b --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3_5_think_training.jinja @@ -0,0 +1,162 @@ +{#- Training variant of the Qwen3.5 chat template, Think flavor (see qwen3_5_think.jinja for the original). + Modifications vs the original: + - {%- if '' in content %} → {%- if '' in content and '' in content %} + Always check for both tags to avoid edge cases where the model generates only one tag. + - Removed the loop.index0 > ns.last_query_index conditional; always include thinking block. + This makes the template prefix-preserving for the [user, assistant] → [user, assistant, tool] transition. + - Added {% generation %} / {% endgeneration %} around assistant message output to support + assistant-only loss masking in SFT training. +-#} +{%- set image_count = namespace(value=0) %} +{%- set video_count = namespace(value=0) %} +{%- macro render_content(content, do_vision_count, is_system_content=false) %} + {%- if content is string %} + {{- content }} + {%- elif content is iterable and content is not mapping %} + {%- for item in content %} + {%- if 'image' in item or 'image_url' in item or item.type == 'image' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain images.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set image_count.value = image_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Picture ' ~ image_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|image_pad|><|vision_end|>' }} + {%- elif 'video' in item or item.type == 'video' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain videos.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set video_count.value = video_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Video ' ~ video_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|video_pad|><|vision_end|>' }} + {%- elif 'text' in item %} + {{- item.text }} + {%- else %} + {{- raise_exception('Unexpected item type in content.') }} + {%- endif %} + {%- endfor %} + {%- elif content is none or content is undefined %} + {{- '' }} + {%- else %} + {{- raise_exception('Unexpected content type.') }} + {%- endif %} +{%- endmacro %} +{%- if not messages %} + {{- raise_exception('No messages provided.') }} +{%- endif %} +{%- if tools and tools is iterable and tools is not mapping %} + {{- '<|im_start|>system\n' }} + {{- "# Tools\n\nYou have access to the following functions:\n\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n" }} + {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n' }} + {%- if messages[0].role == 'system' %} + {%- set content = render_content(messages[0].content, false, true)|trim %} + {%- if content %} + {{- '\n\n' + content }} + {%- endif %} + {%- endif %} + {{- '<|im_end|>\n' }} +{%- else %} + {%- if messages[0].role == 'system' %} + {%- set content = render_content(messages[0].content, false, true)|trim %} + {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %} +{%- for message in messages[::-1] %} + {%- set index = (messages|length - 1) - loop.index0 %} + {%- if ns.multi_step_tool and message.role == "user" %} + {%- set content = render_content(message.content, false)|trim %} + {%- if not(content.startswith('') and content.endswith('')) %} + {%- set ns.multi_step_tool = false %} + {%- set ns.last_query_index = index %} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if ns.multi_step_tool %} + {{- raise_exception('No user query found in messages.') }} +{%- endif %} +{%- for message in messages %} + {%- set content = render_content(message.content, true)|trim %} + {%- if message.role == "system" %} + {%- if not loop.first %} + {{- raise_exception('System message must be at the beginning.') }} + {%- endif %} + {%- elif message.role == "user" %} + {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} + {%- elif message.role == "assistant" %} + {%- set reasoning_content = '' %} + {%- if message.reasoning_content is string %} + {%- set reasoning_content = message.reasoning_content %} + {%- else %} + {%- if '' in content and '' in content %} + {%- set reasoning_content = content.split('')[0].rstrip('\n').split('')[-1].lstrip('\n') %} + {%- set content = content.split('')[-1].lstrip('\n') %} + {%- endif %} + {%- endif %} + {%- set reasoning_content = reasoning_content|trim %} + {{- '<|im_start|>' + message.role + '\n' }} + {%- generation %} + {{- '\n' + reasoning_content + '\n\n\n' + content }} + {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {%- if loop.first %} + {%- if content|trim %} + {{- '\n\n\n\n' }} + {%- else %} + {{- '\n\n' }} + {%- endif %} + {%- else %} + {{- '\n\n\n' }} + {%- endif %} + {%- if tool_call.arguments is defined %} + {%- for args_name, args_value in tool_call.arguments|items %} + {{- '\n' }} + {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %} + {{- args_value }} + {{- '\n\n' }} + {%- endfor %} + {%- endif %} + {{- '\n' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- endgeneration %} + {%- elif message.role == "tool" %} + {%- if loop.previtem and loop.previtem.role != "tool" %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {{- content }} + {{- '\n' }} + {%- if not loop.last and loop.nextitem.role != "tool" %} + {{- '<|im_end|>\n' }} + {%- elif loop.last %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- else %} + {{- raise_exception('Unexpected message role.') }} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} + {%- if enable_thinking is defined and enable_thinking is false %} + {{- '\n\n\n\n' }} + {%- else %} + {{- '\n' }} + {%- endif %} +{%- endif %} \ No newline at end of file diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3_6.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3_6.jinja new file mode 100644 index 0000000000000000000000000000000000000000..a8755d827c0a7b614c246c4060dfd58ab352a8ff --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3_6.jinja @@ -0,0 +1,154 @@ +{%- set image_count = namespace(value=0) %} +{%- set video_count = namespace(value=0) %} +{%- macro render_content(content, do_vision_count, is_system_content=false) %} + {%- if content is string %} + {{- content }} + {%- elif content is iterable and content is not mapping %} + {%- for item in content %} + {%- if 'image' in item or 'image_url' in item or item.type == 'image' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain images.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set image_count.value = image_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Picture ' ~ image_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|image_pad|><|vision_end|>' }} + {%- elif 'video' in item or item.type == 'video' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain videos.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set video_count.value = video_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Video ' ~ video_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|video_pad|><|vision_end|>' }} + {%- elif 'text' in item %} + {{- item.text }} + {%- else %} + {{- raise_exception('Unexpected item type in content.') }} + {%- endif %} + {%- endfor %} + {%- elif content is none or content is undefined %} + {{- '' }} + {%- else %} + {{- raise_exception('Unexpected content type.') }} + {%- endif %} +{%- endmacro %} +{%- if not messages %} + {{- raise_exception('No messages provided.') }} +{%- endif %} +{%- if tools and tools is iterable and tools is not mapping %} + {{- '<|im_start|>system\n' }} + {{- "# Tools\n\nYou have access to the following functions:\n\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n" }} + {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n' }} + {%- if messages[0].role == 'system' %} + {%- set content = render_content(messages[0].content, false, true)|trim %} + {%- if content %} + {{- '\n\n' + content }} + {%- endif %} + {%- endif %} + {{- '<|im_end|>\n' }} +{%- else %} + {%- if messages[0].role == 'system' %} + {%- set content = render_content(messages[0].content, false, true)|trim %} + {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %} +{%- for message in messages[::-1] %} + {%- set index = (messages|length - 1) - loop.index0 %} + {%- if ns.multi_step_tool and message.role == "user" %} + {%- set content = render_content(message.content, false)|trim %} + {%- if not(content.startswith('') and content.endswith('')) %} + {%- set ns.multi_step_tool = false %} + {%- set ns.last_query_index = index %} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if ns.multi_step_tool %} + {{- raise_exception('No user query found in messages.') }} +{%- endif %} +{%- for message in messages %} + {%- set content = render_content(message.content, true)|trim %} + {%- if message.role == "system" %} + {%- if not loop.first %} + {{- raise_exception('System message must be at the beginning.') }} + {%- endif %} + {%- elif message.role == "user" %} + {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} + {%- elif message.role == "assistant" %} + {%- set reasoning_content = '' %} + {%- if message.reasoning_content is string %} + {%- set reasoning_content = message.reasoning_content %} + {%- else %} + {%- if '' in content %} + {%- set reasoning_content = content.split('')[0].rstrip('\n').split('')[-1].lstrip('\n') %} + {%- set content = content.split('')[-1].lstrip('\n') %} + {%- endif %} + {%- endif %} + {%- set reasoning_content = reasoning_content|trim %} + {%- if (preserve_thinking is defined and preserve_thinking is true) or (loop.index0 > ns.last_query_index) %} + {{- '<|im_start|>' + message.role + '\n\n' + reasoning_content + '\n\n\n' + content }} + {%- else %} + {{- '<|im_start|>' + message.role + '\n' + content }} + {%- endif %} + {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {%- if loop.first %} + {%- if content|trim %} + {{- '\n\n\n\n' }} + {%- else %} + {{- '\n\n' }} + {%- endif %} + {%- else %} + {{- '\n\n\n' }} + {%- endif %} + {%- if tool_call.arguments is defined %} + {%- for args_name, args_value in tool_call.arguments|items %} + {{- '\n' }} + {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %} + {{- args_value }} + {{- '\n\n' }} + {%- endfor %} + {%- endif %} + {{- '\n' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if loop.previtem and loop.previtem.role != "tool" %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {{- content }} + {{- '\n' }} + {%- if not loop.last and loop.nextitem.role != "tool" %} + {{- '<|im_end|>\n' }} + {%- elif loop.last %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- else %} + {{- raise_exception('Unexpected message role.') }} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} + {%- if enable_thinking is defined and enable_thinking is false %} + {{- '\n\n\n\n' }} + {%- else %} + {{- '\n' }} + {%- endif %} +{%- endif %} \ No newline at end of file diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3_6_training.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3_6_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..e4e705768d7d62e8149f7c28da77c93b57f6d041 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3_6_training.jinja @@ -0,0 +1,162 @@ +{#- Training variant of the Qwen3.6 chat template (see qwen3_6.jinja for the original). + Modifications vs the original: + - {%- if '' in content %} → {%- if '' in content and '' in content %} + Always check for both tags to avoid edge cases where the model generates only one tag. + - Removed the loop.index0 > ns.last_query_index conditional; always include thinking block. + This makes the template prefix-preserving for the [user, assistant] → [user, assistant, tool] transition. + - Added {% generation %} / {% endgeneration %} around assistant message output to support + assistant-only loss masking in SFT training. +-#} +{%- set image_count = namespace(value=0) %} +{%- set video_count = namespace(value=0) %} +{%- macro render_content(content, do_vision_count, is_system_content=false) %} + {%- if content is string %} + {{- content }} + {%- elif content is iterable and content is not mapping %} + {%- for item in content %} + {%- if 'image' in item or 'image_url' in item or item.type == 'image' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain images.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set image_count.value = image_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Picture ' ~ image_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|image_pad|><|vision_end|>' }} + {%- elif 'video' in item or item.type == 'video' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain videos.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set video_count.value = video_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Video ' ~ video_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|video_pad|><|vision_end|>' }} + {%- elif 'text' in item %} + {{- item.text }} + {%- else %} + {{- raise_exception('Unexpected item type in content.') }} + {%- endif %} + {%- endfor %} + {%- elif content is none or content is undefined %} + {{- '' }} + {%- else %} + {{- raise_exception('Unexpected content type.') }} + {%- endif %} +{%- endmacro %} +{%- if not messages %} + {{- raise_exception('No messages provided.') }} +{%- endif %} +{%- if tools and tools is iterable and tools is not mapping %} + {{- '<|im_start|>system\n' }} + {{- "# Tools\n\nYou have access to the following functions:\n\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n" }} + {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n' }} + {%- if messages[0].role == 'system' %} + {%- set content = render_content(messages[0].content, false, true)|trim %} + {%- if content %} + {{- '\n\n' + content }} + {%- endif %} + {%- endif %} + {{- '<|im_end|>\n' }} +{%- else %} + {%- if messages[0].role == 'system' %} + {%- set content = render_content(messages[0].content, false, true)|trim %} + {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %} +{%- for message in messages[::-1] %} + {%- set index = (messages|length - 1) - loop.index0 %} + {%- if ns.multi_step_tool and message.role == "user" %} + {%- set content = render_content(message.content, false)|trim %} + {%- if not(content.startswith('') and content.endswith('')) %} + {%- set ns.multi_step_tool = false %} + {%- set ns.last_query_index = index %} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if ns.multi_step_tool %} + {{- raise_exception('No user query found in messages.') }} +{%- endif %} +{%- for message in messages %} + {%- set content = render_content(message.content, true)|trim %} + {%- if message.role == "system" %} + {%- if not loop.first %} + {{- raise_exception('System message must be at the beginning.') }} + {%- endif %} + {%- elif message.role == "user" %} + {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} + {%- elif message.role == "assistant" %} + {%- set reasoning_content = '' %} + {%- if message.reasoning_content is string %} + {%- set reasoning_content = message.reasoning_content %} + {%- else %} + {%- if '' in content and '' in content %} + {%- set reasoning_content = content.split('')[0].rstrip('\n').split('')[-1].lstrip('\n') %} + {%- set content = content.split('')[-1].lstrip('\n') %} + {%- endif %} + {%- endif %} + {%- set reasoning_content = reasoning_content|trim %} + {{- '<|im_start|>' + message.role + '\n' }} + {%- generation %} + {{- '\n' + reasoning_content + '\n\n\n' + content }} + {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {%- if loop.first %} + {%- if content|trim %} + {{- '\n\n\n\n' }} + {%- else %} + {{- '\n\n' }} + {%- endif %} + {%- else %} + {{- '\n\n\n' }} + {%- endif %} + {%- if tool_call.arguments is defined %} + {%- for args_name, args_value in tool_call.arguments|items %} + {{- '\n' }} + {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %} + {{- args_value }} + {{- '\n\n' }} + {%- endfor %} + {%- endif %} + {{- '\n' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- endgeneration %} + {%- elif message.role == "tool" %} + {%- if loop.previtem and loop.previtem.role != "tool" %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {{- content }} + {{- '\n' }} + {%- if not loop.last and loop.nextitem.role != "tool" %} + {{- '<|im_end|>\n' }} + {%- elif loop.last %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- else %} + {{- raise_exception('Unexpected message role.') }} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} + {%- if enable_thinking is defined and enable_thinking is false %} + {{- '\n\n\n\n' }} + {%- else %} + {{- '\n' }} + {%- endif %} +{%- endif %} \ No newline at end of file diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3_instruct_2507.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3_instruct_2507.jinja new file mode 100644 index 0000000000000000000000000000000000000000..70adff8a08fb31e0636f618564838d4bf3c05286 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3_instruct_2507.jinja @@ -0,0 +1,61 @@ +{%- if tools %} + {{- '<|im_start|>system\n' }} + {%- if messages[0].role == 'system' %} + {{- messages[0].content + '\n\n' }} + {%- endif %} + {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within XML tags:\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n\n\nFor each function call, return a json object with function name and arguments within XML tags:\n\n{\"name\": , \"arguments\": }\n<|im_end|>\n" }} +{%- else %} + {%- if messages[0].role == 'system' %} + {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- for message in messages %} + {%- if message.content is string %} + {%- set content = message.content %} + {%- else %} + {%- set content = '' %} + {%- endif %} + {%- if (message.role == "user") or (message.role == "system" and not loop.first) %} + {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} + {%- elif message.role == "assistant" %} + {{- '<|im_start|>' + message.role + '\n' + content }} + {%- if message.tool_calls %} + {%- for tool_call in message.tool_calls %} + {%- if (loop.first and content) or (not loop.first) %} + {{- '\n' }} + {%- endif %} + {%- if tool_call.function %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '\n{"name": "' }} + {{- tool_call.name }} + {{- '", "arguments": ' }} + {%- if tool_call.arguments is string %} + {{- tool_call.arguments }} + {%- else %} + {{- tool_call.arguments | tojson }} + {%- endif %} + {{- '}\n' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {{- content }} + {{- '\n' }} + {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} +{%- endif %} \ No newline at end of file diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3_instruct_2507_training.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3_instruct_2507_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..2e30797390d4983e6e2fcbce9827f56d5ee364ae --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3_instruct_2507_training.jinja @@ -0,0 +1,71 @@ +{#- Training variant of the Qwen3-Instruct-2507 chat template (see qwen3_instruct_2507.jinja for the original). + This is for models like Qwen3-4B-Instruct-2507 that ship without the reasoning_content / + multi_step_tool / enable_thinking logic present in later Qwen3 revisions. + Modifications vs the original: + - Added {% generation %} / {% endgeneration %} around assistant message output to support + assistant-only loss masking in SFT training. +-#} +{%- if tools %} + {{- '<|im_start|>system\n' }} + {%- if messages[0].role == 'system' %} + {{- messages[0].content + '\n\n' }} + {%- endif %} + {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within XML tags:\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n\n\nFor each function call, return a json object with function name and arguments within XML tags:\n\n{\"name\": , \"arguments\": }\n<|im_end|>\n" }} +{%- else %} + {%- if messages[0].role == 'system' %} + {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- for message in messages %} + {%- if message.content is string %} + {%- set content = message.content %} + {%- else %} + {%- set content = '' %} + {%- endif %} + {%- if (message.role == "user") or (message.role == "system" and not loop.first) %} + {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} + {%- elif message.role == "assistant" %} + {{- '<|im_start|>' + message.role + '\n' }} + {%- generation %} + {{- content }} + {%- if message.tool_calls %} + {%- for tool_call in message.tool_calls %} + {%- if (loop.first and content) or (not loop.first) %} + {{- '\n' }} + {%- endif %} + {%- if tool_call.function %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '\n{"name": "' }} + {{- tool_call.name }} + {{- '", "arguments": ' }} + {%- if tool_call.arguments is string %} + {{- tool_call.arguments }} + {%- else %} + {{- tool_call.arguments | tojson }} + {%- endif %} + {{- '}\n' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- endgeneration %} + {%- elif message.role == "tool" %} + {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {{- content }} + {{- '\n' }} + {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} +{%- endif %} \ No newline at end of file diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3_training.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..decc48dc6b6fecb761d045d4a318b92c1c489d0b --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3_training.jinja @@ -0,0 +1,93 @@ +{#- Training variant of the Qwen3 chat template (see qwen3.jinja for the original). + Modifications vs the original: + - {%- if '' in content %} → {%- if '' in content and '' in content %} + Always check for both tags to avoid edge cases where the model generates only one tag. + - Removed the loop.index0 > ns.last_query_index conditional; always include thinking block. + This makes the template prefix-preserving for the [user, assistant] → [user, assistant, tool] transition. + - Added {% generation %} / {% endgeneration %} around assistant message output to support + assistant-only loss masking in SFT training. +-#} +{%- if tools %} + {{- '<|im_start|>system\n' }} + {%- if messages[0].role == 'system' %} + {{- messages[0].content + '\n\n' }} + {%- endif %} + {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within XML tags:\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n\n\nFor each function call, return a json object with function name and arguments within XML tags:\n\n{\"name\": , \"arguments\": }\n<|im_end|>\n" }} +{%- else %} + {%- if messages[0].role == 'system' %} + {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %} +{%- for message in messages[::-1] %} + {%- set index = (messages|length - 1) - loop.index0 %} + {%- if ns.multi_step_tool and message.role == "user" and message.content is string and not(message.content.startswith('') and message.content.endswith('')) %} + {%- set ns.multi_step_tool = false %} + {%- set ns.last_query_index = index %} + {%- endif %} +{%- endfor %} +{%- for message in messages %} + {%- if message.content is string %} + {%- set content = message.content %} + {%- else %} + {%- set content = '' %} + {%- endif %} + {%- if (message.role == "user") or (message.role == "system" and not loop.first) %} + {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} + {%- elif message.role == "assistant" %} + {%- set reasoning_content = '' %} + {%- if message.reasoning_content is string %} + {%- set reasoning_content = message.reasoning_content %} + {%- else %} + {%- if '' in content and '' in content %} + {%- set reasoning_content = content.split('')[0].rstrip('\n').split('')[-1].lstrip('\n') %} + {%- set content = content.split('')[-1].lstrip('\n') %} + {%- endif %} + {%- endif %} + {{- '<|im_start|>' + message.role + '\n' }} + {%- generation %} + {{- '\n' + reasoning_content.strip('\n') + '\n\n\n' + content.lstrip('\n') }} + {%- if message.tool_calls %} + {%- for tool_call in message.tool_calls %} + {%- if (loop.first and content) or (not loop.first) %} + {{- '\n' }} + {%- endif %} + {%- if tool_call.function %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '\n{"name": "' }} + {{- tool_call.name }} + {{- '", "arguments": ' }} + {%- if tool_call.arguments is string %} + {{- tool_call.arguments }} + {%- else %} + {{- tool_call.arguments | tojson }} + {%- endif %} + {{- '}\n' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- endgeneration %} + {%- elif message.role == "tool" %} + {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {{- content }} + {{- '\n' }} + {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} + {%- if enable_thinking is defined and enable_thinking is false %} + {{- '\n\n\n\n' }} + {%- endif %} +{%- endif %} \ No newline at end of file diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3_vl.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3_vl.jinja new file mode 100644 index 0000000000000000000000000000000000000000..124386803f142761528f710e77ae483f5f8c4fc4 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3_vl.jinja @@ -0,0 +1,120 @@ +{%- if tools %} + {{- '<|im_start|>system\n' }} + {%- if messages[0].role == 'system' %} + {%- if messages[0].content is string %} + {{- messages[0].content }} + {%- else %} + {%- for content in messages[0].content %} + {%- if 'text' in content %} + {{- content.text }} + {%- endif %} + {%- endfor %} + {%- endif %} + {{- '\n\n' }} + {%- endif %} + {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within XML tags:\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n\n\nFor each function call, return a json object with function name and arguments within XML tags:\n\n{\"name\": , \"arguments\": }\n<|im_end|>\n" }} +{%- else %} + {%- if messages[0].role == 'system' %} + {{- '<|im_start|>system\n' }} + {%- if messages[0].content is string %} + {{- messages[0].content }} + {%- else %} + {%- for content in messages[0].content %} + {%- if 'text' in content %} + {{- content.text }} + {%- endif %} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- set image_count = namespace(value=0) %} +{%- set video_count = namespace(value=0) %} +{%- for message in messages %} + {%- if message.role == "user" %} + {{- '<|im_start|>' + message.role + '\n' }} + {%- if message.content is string %} + {{- message.content }} + {%- else %} + {%- for content in message.content %} + {%- if content.type == 'image' or 'image' in content or 'image_url' in content %} + {%- set image_count.value = image_count.value + 1 %} + {%- if add_vision_id %}Picture {{ image_count.value }}: {% endif -%} + <|vision_start|><|image_pad|><|vision_end|> + {%- elif content.type == 'video' or 'video' in content %} + {%- set video_count.value = video_count.value + 1 %} + {%- if add_vision_id %}Video {{ video_count.value }}: {% endif -%} + <|vision_start|><|video_pad|><|vision_end|> + {%- elif 'text' in content %} + {{- content.text }} + {%- endif %} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "assistant" %} + {{- '<|im_start|>' + message.role + '\n' }} + {%- if message.content is string %} + {{- message.content }} + {%- else %} + {%- for content_item in message.content %} + {%- if 'text' in content_item %} + {{- content_item.text }} + {%- endif %} + {%- endfor %} + {%- endif %} + {%- if message.tool_calls %} + {%- for tool_call in message.tool_calls %} + {%- if (loop.first and message.content) or (not loop.first) %} + {{- '\n' }} + {%- endif %} + {%- if tool_call.function %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '\n{"name": "' }} + {{- tool_call.name }} + {{- '", "arguments": ' }} + {%- if tool_call.arguments is string %} + {{- tool_call.arguments }} + {%- else %} + {{- tool_call.arguments | tojson }} + {%- endif %} + {{- '}\n' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {%- if message.content is string %} + {{- message.content }} + {%- else %} + {%- for content in message.content %} + {%- if content.type == 'image' or 'image' in content or 'image_url' in content %} + {%- set image_count.value = image_count.value + 1 %} + {%- if add_vision_id %}Picture {{ image_count.value }}: {% endif -%} + <|vision_start|><|image_pad|><|vision_end|> + {%- elif content.type == 'video' or 'video' in content %} + {%- set video_count.value = video_count.value + 1 %} + {%- if add_vision_id %}Video {{ video_count.value }}: {% endif -%} + <|vision_start|><|video_pad|><|vision_end|> + {%- elif 'text' in content %} + {{- content.text }} + {%- endif %} + {%- endfor %} + {%- endif %} + {{- '\n' }} + {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} +{%- endif %} diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3_vl_training.jinja b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3_vl_training.jinja new file mode 100644 index 0000000000000000000000000000000000000000..137a64a1722352220eee524909ef631a37066541 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/qwen3_vl_training.jinja @@ -0,0 +1,127 @@ +{#- Training variant of the Qwen 3 VL chat template (see qwen3_vl.jinja for the original). + Modifications vs the original: + - Added {% generation %} / {% endgeneration %} around assistant message content to + support assistant-only loss masking in SFT training. +-#} +{%- if tools %} + {{- '<|im_start|>system\n' }} + {%- if messages[0].role == 'system' %} + {%- if messages[0].content is string %} + {{- messages[0].content }} + {%- else %} + {%- for content in messages[0].content %} + {%- if 'text' in content %} + {{- content.text }} + {%- endif %} + {%- endfor %} + {%- endif %} + {{- '\n\n' }} + {%- endif %} + {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within XML tags:\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n\n\nFor each function call, return a json object with function name and arguments within XML tags:\n\n{\"name\": , \"arguments\": }\n<|im_end|>\n" }} +{%- else %} + {%- if messages[0].role == 'system' %} + {{- '<|im_start|>system\n' }} + {%- if messages[0].content is string %} + {{- messages[0].content }} + {%- else %} + {%- for content in messages[0].content %} + {%- if 'text' in content %} + {{- content.text }} + {%- endif %} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- set image_count = namespace(value=0) %} +{%- set video_count = namespace(value=0) %} +{%- for message in messages %} + {%- if message.role == "user" %} + {{- '<|im_start|>' + message.role + '\n' }} + {%- if message.content is string %} + {{- message.content }} + {%- else %} + {%- for content in message.content %} + {%- if content.type == 'image' or 'image' in content or 'image_url' in content %} + {%- set image_count.value = image_count.value + 1 %} + {%- if add_vision_id %}Picture {{ image_count.value }}: {% endif -%} + <|vision_start|><|image_pad|><|vision_end|> + {%- elif content.type == 'video' or 'video' in content %} + {%- set video_count.value = video_count.value + 1 %} + {%- if add_vision_id %}Video {{ video_count.value }}: {% endif -%} + <|vision_start|><|video_pad|><|vision_end|> + {%- elif 'text' in content %} + {{- content.text }} + {%- endif %} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "assistant" %} + {{- '<|im_start|>' + message.role + '\n' }} + {%- generation -%} + {%- if message.content is string %} + {{- message.content }} + {%- else %} + {%- for content_item in message.content %} + {%- if 'text' in content_item %} + {{- content_item.text }} + {%- endif %} + {%- endfor %} + {%- endif %} + {%- if message.tool_calls %} + {%- for tool_call in message.tool_calls %} + {%- if (loop.first and message.content) or (not loop.first) %} + {{- '\n' }} + {%- endif %} + {%- if tool_call.function %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '\n{"name": "' }} + {{- tool_call.name }} + {{- '", "arguments": ' }} + {%- if tool_call.arguments is string %} + {{- tool_call.arguments }} + {%- else %} + {{- tool_call.arguments | tojson }} + {%- endif %} + {{- '}\n' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- endgeneration -%} + {%- elif message.role == "tool" %} + {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {%- if message.content is string %} + {{- message.content }} + {%- else %} + {%- for content in message.content %} + {%- if content.type == 'image' or 'image' in content or 'image_url' in content %} + {%- set image_count.value = image_count.value + 1 %} + {%- if add_vision_id %}Picture {{ image_count.value }}: {% endif -%} + <|vision_start|><|image_pad|><|vision_end|> + {%- elif content.type == 'video' or 'video' in content %} + {%- set video_count.value = video_count.value + 1 %} + {%- if add_vision_id %}Video {{ video_count.value }}: {% endif -%} + <|vision_start|><|video_pad|><|vision_end|> + {%- elif 'text' in content %} + {{- content.text }} + {%- endif %} + {%- endfor %} + {%- endif %} + {{- '\n' }} + {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} +{%- endif %} diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/cli/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/cli/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6a1721cba48803210a91d0280eb9ccd35214d74f --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/cli/__init__.py @@ -0,0 +1,18 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .main import main + + +__all__ = ["main"] diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/cli/accelerate_config.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/cli/accelerate_config.py new file mode 100644 index 0000000000000000000000000000000000000000..d775fca787f7618a2785d1294beec2c152962e90 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/cli/accelerate_config.py @@ -0,0 +1,47 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import importlib.resources as resources +from pathlib import Path + + +def resolve_accelerate_config_argument(launch_args: list[str]) -> list[str]: + """ + Resolve `--accelerate_config` from CLI arguments into `accelerate --config_file`. + + The function supports either a filesystem path or a predefined config name shipped in `trl/accelerate_configs` + (without the `.yaml` suffix). + """ + if "--accelerate_config" not in launch_args: + return launch_args + + config_index = launch_args.index("--accelerate_config") + if config_index + 1 >= len(launch_args): + raise ValueError("Expected a value after `--accelerate_config`.") + + config_name = launch_args[config_index + 1] + if Path(config_name).is_file(): + accelerate_config_path = config_name + else: + candidate = resources.files("trl.accelerate_configs").joinpath(f"{config_name}.yaml") + if not candidate.exists(): + raise ValueError( + f"Accelerate config {config_name} is neither a file nor a valid config in the `trl` package. " + "Please provide a valid config name or a path to a config file." + ) + accelerate_config_path = candidate + + # Remove '--accelerate_config '. + launch_args = launch_args[:config_index] + launch_args[config_index + 2 :] + return ["--config_file", str(accelerate_config_path)] + launch_args diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/cli/accelerate_launcher.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/cli/accelerate_launcher.py new file mode 100644 index 0000000000000000000000000000000000000000..eceebe1ffe8d49d6cfa4a3bdc5d3037b5dfd9da3 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/cli/accelerate_launcher.py @@ -0,0 +1,47 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import importlib.resources as resources +from collections.abc import Callable +from typing import Any + +from accelerate.commands.launch import launch_command, launch_command_parser + + +def launch_training_script( + script_name: str, + launch_args: list[str], + training_script_args: list[str], + *, + launch_command_fn: Callable[[Any], None] = launch_command, + launch_parser_fn: Callable[[], Any] = launch_command_parser, +) -> None: + """ + Launch a TRL training script through `accelerate launch`. + + Parameters: + script_name (`str`): + Script filename in `trl/scripts`, e.g. `"dpo.py"`. + launch_args (`list[str]`): + Arguments consumed by `accelerate launch`. + training_script_args (`list[str]`): + Arguments forwarded to the training script. + launch_command_fn (`Callable[[Any], None]`, *optional*): + Function used to execute accelerate launch. + launch_parser_fn (`Callable[[], Any]`, *optional*): + Factory creating the accelerate launch parser. + """ + training_script = resources.files("trl.scripts").joinpath(script_name) + accelerate_args = launch_parser_fn().parse_args(launch_args + [str(training_script)] + training_script_args) + launch_command_fn(accelerate_args) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/cli/commands/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/cli/commands/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4bafa3ba61879096285ddeca6b48d7fe3292ffeb --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/cli/commands/__init__.py @@ -0,0 +1,37 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .base import Command +from .env import EnvCommand +from .skills import SkillsCommand +from .training import TrainingCommand +from .vllm_serve import VllmServeCommand + + +def get_commands() -> list[Command]: + """Return all registered top-level TRL CLI commands.""" + return [ + TrainingCommand("dpo"), + EnvCommand(), + TrainingCommand("grpo"), + TrainingCommand("kto"), + TrainingCommand("reward"), + TrainingCommand("rloo"), + TrainingCommand("sft"), + SkillsCommand(), + VllmServeCommand(), + ] + + +__all__ = ["Command", "get_commands"] diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/cli/commands/base.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/cli/commands/base.py new file mode 100644 index 0000000000000000000000000000000000000000..0000b558f26418077c3946519f54dcd1195029cc --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/cli/commands/base.py @@ -0,0 +1,62 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from abc import ABC, abstractmethod +from argparse import Namespace +from dataclasses import dataclass + + +@dataclass(slots=True) +class CommandContext: + """Context shared by CLI commands during execution.""" + + argv: list[str] + + def argv_after(self, token: str) -> list[str]: + """ + Return CLI tokens after the first occurrence of `token`. + + Parameters: + token (`str`): + Subcommand name as it appears in `argv`. + """ + try: + index = self.argv.index(token) + except ValueError: + return [] + return self.argv[index + 1 :] + + +class Command(ABC): + """ + Base command definition for the TRL CLI. + + Parameters: + name (`str`): + Subcommand name exposed by the CLI. + help_text (`str`): + Short description displayed in help output. + """ + + def __init__(self, name: str, help_text: str): + self.name = name + self.help_text = help_text + + @abstractmethod + def register(self, subparsers) -> None: + """Register this command parser in the subparser collection.""" + + @abstractmethod + def run(self, args: Namespace, context: CommandContext) -> int: + """Execute the command.""" diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/cli/commands/env.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/cli/commands/env.py new file mode 100644 index 0000000000000000000000000000000000000000..28498ba15cb0ca1998b2f4b937c6393b7fbd1536 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/cli/commands/env.py @@ -0,0 +1,33 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from argparse import Namespace + +from .base import Command, CommandContext + + +class EnvCommand(Command): + """CLI command that prints TRL environment information.""" + + def __init__(self): + super().__init__(name="env", help_text="Print the environment information") + + def register(self, subparsers) -> None: + subparsers.add_parser(self.name, help=self.help_text) + + def run(self, args: Namespace, context: CommandContext) -> int: + from ...scripts.env import print_env + + print_env() + return 0 diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/cli/commands/skills.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/cli/commands/skills.py new file mode 100644 index 0000000000000000000000000000000000000000..737bf4747276a348042e25f3826e6ad6e3bfa96c --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/cli/commands/skills.py @@ -0,0 +1,42 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from argparse import Namespace + +from ...skills.cli import add_skills_subcommands +from .base import Command, CommandContext + + +class SkillsCommand(Command): + """CLI command that manages TRL agent skills.""" + + def __init__(self): + super().__init__(name="skills", help_text="Manage TRL agent skills") + self._skills_parser = None + + def register(self, subparsers) -> None: + self._skills_parser = subparsers.add_parser(self.name, help=self.help_text) + skills_subparsers = self._skills_parser.add_subparsers(dest="skills_command", help="Skills commands") + add_skills_subcommands(skills_subparsers) + + def run(self, args: Namespace, context: CommandContext) -> int: + if getattr(args, "skills_command", None): + if hasattr(args, "func"): + return args.func(args) + print("Error: Unknown skills command") + return 1 + + if self._skills_parser is not None: + self._skills_parser.print_help() + return 0 diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/cli/commands/training.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/cli/commands/training.py new file mode 100644 index 0000000000000000000000000000000000000000..64f52c73b7ec998d42d420d53890184bd5a40428 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/cli/commands/training.py @@ -0,0 +1,72 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import importlib +from argparse import Namespace + +from .base import Command, CommandContext + + +def _subtract_subsequence(lst: list[str], subseq: list[str]) -> list[str]: + """Return lst with the ordered subsequence subseq removed.""" + sub_iter = iter(subseq) + current = next(sub_iter, None) + result = [] + for item in lst: + if current is not None and item == current: + current = next(sub_iter, None) + else: + result.append(item) + return result + + +class TrainingCommand(Command): + """ + Generic CLI command that launches a training script with accelerate. + + The script `trl/scripts/.py` must expose a `make_parser()` function. + + Parameters: + name (`str`): + CLI subcommand name (e.g. `"dpo"`). + """ + + def __init__(self, name: str): + super().__init__(name=name, help_text=f"Run the {name} training script") + + def register(self, subparsers) -> None: + subparsers.add_parser(self.name, help=self.help_text, add_help=False) + + def run(self, args: Namespace, context: CommandContext) -> int: + from ..accelerate_config import resolve_accelerate_config_argument + from ..accelerate_launcher import launch_training_script + + module = importlib.import_module(f"...scripts.{self.name}", package=__package__) + all_args = context.argv_after(self.name) + parser = module.make_parser(prog=f"trl {self.name}") + + # Handles -h (exits). Returns config_remaining and cli_remaining separately. + # cli_remaining is an ordered subsequence of all_args; config_remaining is not. + *_, config_remaining, cli_remaining = parser.parse_args_and_config( + all_args, return_remaining_strings=True, separate_remaining_strings=True + ) + launch_args = resolve_accelerate_config_argument(config_remaining + cli_remaining) + training_script_args = _subtract_subsequence(all_args, cli_remaining) + + launch_training_script( + script_name=f"{self.name}.py", + launch_args=launch_args, + training_script_args=training_script_args, + ) + return 0 diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/cli/commands/vllm_serve.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/cli/commands/vllm_serve.py new file mode 100644 index 0000000000000000000000000000000000000000..cc1cea21a5c1fcb8f52d8c2ce46a820e8702be03 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/cli/commands/vllm_serve.py @@ -0,0 +1,36 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from argparse import Namespace + +from .base import Command, CommandContext + + +class VllmServeCommand(Command): + """CLI command for serving TRL models with vLLM.""" + + def __init__(self): + super().__init__(name="vllm-serve", help_text="Serve a model with vLLM") + + def register(self, subparsers) -> None: + subparsers.add_parser(self.name, help=self.help_text, add_help=False) + + def run(self, args: Namespace, context: CommandContext) -> int: + from ...scripts.vllm_serve import main as vllm_serve_main + from ...scripts.vllm_serve import make_parser as make_vllm_serve_parser + + parser = make_vllm_serve_parser(prog="trl vllm-serve") + (script_args,) = parser.parse_args_and_config(args=context.argv_after(self.name)) + vllm_serve_main(script_args) + return 0 diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/cli/main.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/cli/main.py new file mode 100644 index 0000000000000000000000000000000000000000..cea99a16d9a6ce250dbc242389cd4ea21f7f75f2 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/cli/main.py @@ -0,0 +1,51 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import sys +from argparse import ArgumentParser + +from .commands import get_commands +from .commands.base import Command, CommandContext + + +def _build_parser(commands: list[Command]) -> ArgumentParser: + parser = ArgumentParser(prog="trl", allow_abbrev=False) + subparsers = parser.add_subparsers(help="available commands", dest="command") + + for command in commands: + command.register(subparsers) + + return parser + + +def main(argv: list[str] | None = None) -> int: + """Run the TRL CLI.""" + commands = get_commands() + commands_by_name = {command.name: command for command in commands} + parser = _build_parser(commands) + argv = list(sys.argv[1:] if argv is None else argv) + + args, _ = parser.parse_known_args(argv) + command_name = getattr(args, "command", None) + if command_name is None: + parser.print_help() + return 0 + + command = commands_by_name[command_name] + context = CommandContext(argv=argv) + return command.run(args, context) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/data_utils.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/data_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d27c582106dfabcb3d515ebad5f1c01125084974 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/data_utils.py @@ -0,0 +1,977 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import copy +from collections import defaultdict, deque +from collections.abc import Callable, Sequence +from itertools import takewhile +from typing import Any, Literal, TypeVar + +import numpy as np +import pyarrow as pa +import pyarrow.compute as pc +import pyarrow.types +from datasets import Dataset, DatasetDict, IterableDataset, IterableDatasetDict +from transformers import PreTrainedTokenizerBase, ProcessorMixin + + +DatasetType = TypeVar("DatasetType", Dataset, DatasetDict) +IterableDatasetType = TypeVar("IterableDatasetType", IterableDataset, IterableDatasetDict) + + +def prepare_multimodal_messages(messages: list[dict[str, Any]], images: list | None = None) -> list[dict[str, Any]]: + # docstyle-ignore # because is not parsable in the code block + """ + Convert messages into a structured multimodal format and inject the provided images into the message contents. + + Args: + messages (`list[dict[str, Any]]`): + Messages with `"role"`, `"content"` (or `"tool_calls"`). Content may be a raw string before transformation. + List of messages with a `"role"` key (`"system"`, `"user"`, `"assistant"`, or `"tool"`) and a `"content"` key containing + either a string or a list of structured blocks if already prepared. Optionally, the `"content"` might + be `None` or not provided in favour of `"tool_calls"` in the `"assistant"` turns if applicable. + images (`list`, *optional*): + List of image objects to insert in the messages. + + Returns: + `list[dict[str, Any]]`: A new list of messages where every `"content"` value is a list of structured + content blocks, and all `"image"` placeholders are populated with the corresponding image objects. If the + assistant turns contains `"tool_calls"`, then the `"content"` might be empty. + + Notes: + - When the input `messages` isn't already in the structured format, (i.e., all `"content"` values are strings), + the function transforms them into the structured format by wrapping text in `{"type": "text", "text": ...}` + and inserting `{"type": "image"}` placeholders for the images *before* the first user message. + If the number of placeholders does not match the number of provided images, an error is raised. + - Existing image blocks that already include an `"image"` payload are preserved as-is. Only unfilled image + placeholders are counted and populated from `images`. + + Example: + ```python + # Input + [ + {"role": "user", "content": "What's in this image?"}, + {"role": "assistant", "content": "It looks like a cat."}, + ] + + # Output, one image provided + [ + {"role": "user", "content": [{"type": "image", "image": }, {"type": "text", "text": "What's in this image?"}]}, + {"role": "assistant", "content": [{"type": "text", "text": "It looks like a cat."}]}, + ] + ``` + """ + images = images or [] + + # First, convert all messages to the structured format if needed, and insert image placeholders if needed. + # Build new message dicts only when transforming string content to avoid modifying the originals. + new_messages = [] + images_included = False + for message in messages: + if message["role"] == "user": + if isinstance(message["content"], str) and not images_included: + image_entries = [{"type": "image"} for _ in range(len(images))] + message = {**message, "content": [*image_entries, {"type": "text", "text": message["content"]}]} + images_included = True + elif isinstance(message["content"], str): + message = {**message, "content": [{"type": "text", "text": message["content"]}]} + elif message["role"] in {"assistant", "system", "tool"}: + if isinstance(message.get("content"), str): + message = {**message, "content": [{"type": "text", "text": message["content"]}]} + else: + raise ValueError( + f"Invalid role in message: {message['role']}. Expected 'system', 'user', 'assistant', or 'tool'." + ) + new_messages.append(message) + + # Then, check that the number of image placeholders matches the number of images provided + num_placeholders = sum( + sum(1 for part in message["content"] if part["type"] == "image" and "image" not in part) + for message in new_messages + if message.get("content") and message["role"] != "tool" + ) + if num_placeholders != len(images): + raise ValueError( + f"Number of images provided ({len(images)}) does not match number of image placeholders ({num_placeholders})." + ) + + # Then, fill in the actual images in the placeholders + if images: + img_idx = 0 + for i, message in enumerate(new_messages): + if not message.get("content") or message["role"] == "tool": + continue + new_content = [] + for part in message["content"]: + if part["type"] == "image" and "image" not in part: + new_content.append({**part, "image": images[img_idx]}) + img_idx += 1 + else: + new_content.append(part) + new_messages[i] = {**message, "content": new_content} + + return new_messages + + +def prepare_multimodal_messages_vllm(messages: list[dict[str, Any]]) -> list[dict[str, Any]]: + # docstyle-ignore # because is not parsable in the code block + """ + Convert structured multimodal messages into a format compatible with vLLM. Replaces `"type": "image"` blocks with + `"type": "image_pil"` blocks, and `"image": Image` with `"image_pil": Image`. + + Args: + messages (`list[dict[str, Any]]`): + Messages with `"role"` and `"content"`. Content is expected to be a list of structured blocks. + + Returns: + `list[dict[str, Any]]`: + A deep-copied list of messages compatible with vLLM's expected input format. + + Example: + ```python + # Input + [{"role": "user", "content": [{"type": "image", "image": }, {"type": "text", "text": "What's in this image?"}]}] + + # Output + [{"role": "user", "content": [{"type": "image_pil", "image_pil": }, {"type": "text", "text": "What's in this image?"}]}] + ``` + """ + messages = copy.deepcopy(messages) # avoid modifying the original messages + for message in messages: + if isinstance(message["content"], list): + for part in message["content"]: + if part["type"] == "image": + part["type"] = "image_pil" # vLLM expects 'image_pil' key for images + part["image_pil"] = part.pop("image") + return messages + + +def is_conversational(example: dict[str, Any]) -> bool: + r""" + Check if the example is in a conversational format. + + Args: + example (`dict[str, Any]`): + A single data entry of a dataset. The example can have different keys depending on the dataset type. + + Returns: + `bool`: + `True` if the data is in a conversational format, `False` otherwise. + + Examples: + + ```python + >>> example = {"prompt": [{"role": "user", "content": "What color is the sky?"}]} + >>> is_conversational(example) + True + + >>> example = {"prompt": "The sky is"} + >>> is_conversational(example) + False + ``` + """ + supported_keys = ["prompt", "chosen", "rejected", "completion", "messages"] + example_keys = {key for key in example.keys() if key in supported_keys} + + # It must have one of the supported keys + if example_keys: + key = example_keys.pop() # take the first supported key + maybe_messages = example[key] + # It must be a list of messages + if isinstance(maybe_messages, list): + maybe_message = maybe_messages[0] + # Each message must a list of dictionaries with keys "role" and "content" + if isinstance(maybe_message, dict) and "role" in maybe_message: + return True + + return False + + +def apply_chat_template( + example: dict[str, list[dict[str, str]]], + processing_class: PreTrainedTokenizerBase | ProcessorMixin, + tools: list[dict | Callable] | None = None, + **template_kwargs, +) -> dict[str, str]: + r""" + Apply a chat template to a conversational example along with the schema for a list of functions in `tools`. + + For more details, see [`maybe_apply_chat_template`]. + """ + tools = tools or None # `or None`: Llama bug: it renders tool boilerplate for tools=[] + # Check that the example has the correct keys + supported_keys = ["prompt", "chosen", "rejected", "completion", "messages", "label"] + example_keys = {key for key in example.keys() if key in supported_keys} + if example_keys not in [ + {"messages"}, # language modeling + {"prompt"}, # prompt-only + {"prompt", "completion"}, # prompt-completion + {"prompt", "chosen", "rejected"}, # preference + {"chosen", "rejected"}, # preference with implicit prompt + {"prompt", "completion", "label"}, # unpaired preference + ]: + raise KeyError(f"Invalid keys in the example: {example_keys}") + + # Apply the chat template to the whole conversation + if "messages" in example: + messages = processing_class.apply_chat_template( + example["messages"], + tools=tools, + tokenize=False, + **example.get("chat_template_kwargs", {}), + **template_kwargs, + ) + + # Apply the chat template to the prompt, adding the generation prompt + if "prompt" in example: + last_role = example["prompt"][-1]["role"] + if last_role in ["user", "tool"]: + add_generation_prompt = True + continue_final_message = False + elif last_role == "assistant": + add_generation_prompt = False + continue_final_message = True + else: + raise ValueError(f"Invalid role in the last message: {last_role}") + prompt = processing_class.apply_chat_template( + example["prompt"], + tools=tools, + continue_final_message=continue_final_message, + tokenize=False, + add_generation_prompt=add_generation_prompt, + **example.get("chat_template_kwargs", {}), + **template_kwargs, + ) + + # Apply the chat template to the entire prompt + completion + if "prompt" in example: # explicit prompt and prompt-completion case + if "chosen" in example: + prompt_chosen = processing_class.apply_chat_template( + example["prompt"] + example["chosen"], + tools=tools, + tokenize=False, + **example.get("chat_template_kwargs", {}), + **template_kwargs, + ) + # DeepSeek-R1 inserts a token when using `add_generation_prompt`, which can cause discrepancies + # between the prompt alone and the combined prompt+completion. To ensure consistency, we extract the + # common prefix between the two. In most cases, this is a no-op. + prompt = "".join(x for x, _ in takewhile(lambda x: x[0] == x[1], zip(prompt, prompt_chosen, strict=False))) + + chosen = prompt_chosen[len(prompt) :] + if "rejected" in example and "prompt" in example: # explicit prompt + prompt_rejected = processing_class.apply_chat_template( + example["prompt"] + example["rejected"], + tools=tools, + tokenize=False, + **example.get("chat_template_kwargs", {}), + **template_kwargs, + ) + # Handle DeepSeek-R1 token, see the above comment for details + prompt = "".join( + x for x, _ in takewhile(lambda x: x[0] == x[1], zip(prompt, prompt_rejected, strict=False)) + ) + rejected = prompt_rejected[len(prompt) :] + if "completion" in example: + prompt_completion = processing_class.apply_chat_template( + example["prompt"] + example["completion"], + tools=tools, + tokenize=False, + **example.get("chat_template_kwargs", {}), + **template_kwargs, + ) + # Handle DeepSeek-R1 token, see the above comment for details + prompt = "".join( + x for x, _ in takewhile(lambda x: x[0] == x[1], zip(prompt, prompt_completion, strict=False)) + ) + completion = prompt_completion[len(prompt) :] + else: # implicit prompt case + if "chosen" in example: + chosen = processing_class.apply_chat_template( + example["chosen"], + tools=tools, + tokenize=False, + **example.get("chat_template_kwargs", {}), + **template_kwargs, + ) + if "rejected" in example: + rejected = processing_class.apply_chat_template( + example["rejected"], + tools=tools, + tokenize=False, + **example.get("chat_template_kwargs", {}), + **template_kwargs, + ) + + # Extract the completion by removing the prompt part from the prompt-completion string + output = {} + if "messages" in example: + output["text"] = messages + if "prompt" in example: + output["prompt"] = prompt + if "chosen" in example: + output["chosen"] = chosen + if "rejected" in example: + output["rejected"] = rejected + if "completion" in example: + output["completion"] = completion + if "label" in example: + output["label"] = example["label"] + + return output + + +def maybe_apply_chat_template( + example: dict[str, list[dict[str, str]]], + processing_class: PreTrainedTokenizerBase | ProcessorMixin, + tools: list[dict | Callable] | None = None, + **template_kwargs: Any, +) -> dict[str, str]: + r""" + If the example is in a conversational format, apply a chat template to it. + + Args: + example (`dict[str, list[dict[str, str]]`): + Dictionary representing a single data entry of a conversational dataset. Each data entry can have different + keys depending on the dataset type. The supported dataset types are: + + - Language modeling dataset: `"messages"`. + - Prompt-only dataset: `"prompt"`. + - Prompt-completion dataset: `"prompt"` and `"completion"`. + - Preference dataset: `"prompt"`, `"chosen"`, and `"rejected"`. + - Preference dataset with implicit prompt: `"chosen"` and `"rejected"`. + - Unpaired preference dataset: `"prompt"`, `"completion"`, and `"label"`. + + For keys `"messages"`, `"prompt"`, `"chosen"`, `"rejected"`, and `"completion"`, the values are lists of + messages, where each message is a dictionary with keys `"role"` and `"content"`. Additionally, the example + may contain a `"chat_template_kwargs"` key, which is a dictionary of additional keyword arguments to pass + to the chat template renderer. + processing_class ([`~transformers.PreTrainedTokenizerBase`] or [`~transformers.ProcessorMixin`]): + Tokenizer to apply the chat template with. + tools (`list[dict | Callable]`, *optional*): + A list of tools (callable functions) that will be accessible to the model. If the template does not support + function calling, this argument will have no effect. + **template_kwargs (`Any`, *optional*): + Additional kwargs to pass to the template renderer. Will be accessible by the chat template. + + Returns: + `dict[str, str]`: + Formatted example with the chat template applied. + + Notes: + - This function does not alter the keys, except for Language modeling dataset, where `"messages"` is replaced + by `"text"`. + + - In case of prompt-only data, if the last role is `"user"`, the generation prompt is added to the prompt. + Else, if the last role is `"assistant"`, the final message is continued. + + Example: + + ```python + >>> from transformers import AutoTokenizer + + >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/Phi-3-mini-128k-instruct") + >>> example = { + ... "prompt": [{"role": "user", "content": "What color is the sky?"}], + ... "completion": [{"role": "assistant", "content": "It is blue."}], + ... } + >>> apply_chat_template(example, tokenizer) + {'prompt': '<|user|>\nWhat color is the sky?<|end|>\n<|assistant|>\n', 'completion': 'It is blue.<|end|>\n'} + ``` + """ + if is_conversational(example): + return apply_chat_template(example, processing_class, tools, **template_kwargs) + else: + return example + + +def _unpair_row(batch: dict[str, list[Any]]) -> dict[str, list[Any]]: + batch_size = len(batch["chosen"]) + new_batch = { + "completion": batch["chosen"] + batch["rejected"], + "label": [True] * batch_size + [False] * batch_size, + } + if "prompt" in batch: + new_batch["prompt"] = batch["prompt"] + batch["prompt"] + return new_batch + + +def unpair_preference_dataset( + dataset: DatasetType | IterableDatasetType, **map_kwargs +) -> DatasetType | IterableDatasetType: + # docstyle-ignore + """ + Unpair a preference dataset. + + The output contains only `"prompt"`, `"completion"`, and `"label"`; all other columns are dropped. + + Args: + dataset ([`~datasets.Dataset`] or [`~datasets.DatasetDict`] or [`~datasets.IterableDataset`] or [`~datasets.IterableDatasetDict`]): + Preference dataset to unpair. The dataset must have columns `"chosen"`, `"rejected"` and optionally + `"prompt"`. + **map_kwargs (`dict`, *optional*): + Additional keyword arguments to pass to the dataset's map method when unpairing preferences. + + Returns: + [`~datasets.Dataset`] or [`~datasets.DatasetDict`] or [`~datasets.IterableDataset`] or [`~datasets.IterableDatasetDict`]: + The unpaired preference dataset. + + Example: + + ```python + >>> from datasets import Dataset + + >>> dataset_dict = { + ... "prompt": ["The sky is", "The sun is"], + ... "chosen": [" blue.", "in the sky."], + ... "rejected": [" green.", " in the sea."], + ... } + >>> dataset = Dataset.from_dict(dataset_dict) + >>> dataset = unpair_preference_dataset(dataset) + >>> dataset + Dataset({ + features: ['prompt', 'completion', 'label'], + num_rows: 4 + }) + + >>> dataset[0] + {'prompt': 'The sky is', 'completion': ' blue.', 'label': True} + ``` + """ + if isinstance(dataset, DatasetDict): + column_names = next(iter(dataset.values())).column_names + elif isinstance(dataset, Dataset): + column_names = dataset.column_names + else: # IterableDataset + column_names = dataset.column_names or list(next(iter(dataset)).keys()) + return dataset.map(_unpair_row, batched=True, remove_columns=column_names, **map_kwargs) + + +def maybe_unpair_preference_dataset( + dataset: DatasetType, num_proc: int | None = None, desc: str | None = None +) -> DatasetType: + r""" + Unpair a preference dataset if it is paired. + + Args: + dataset ([`~datasets.Dataset`] or [`~datasets.DatasetDict`]): + Preference dataset to unpair. The dataset must have columns `"chosen"`, `"rejected"` and optionally + `"prompt"`. + num_proc (`int`, *optional*): + Number of processes to use for processing the dataset. + desc (`str`, *optional*): + Meaningful description to be displayed alongside with the progress bar while mapping examples. + + Returns: + [`~datasets.Dataset`] or [`~datasets.DatasetDict`]: The unpaired preference dataset if it was paired, otherwise + the original dataset. + + Example: + + ```python + >>> from datasets import Dataset + + >>> dataset_dict = { + ... "prompt": ["The sky is", "The sun is"], + ... "chosen": [" blue.", "in the sky."], + ... "rejected": [" green.", " in the sea."], + ... } + >>> dataset = Dataset.from_dict(dataset_dict) + >>> dataset = unpair_preference_dataset(dataset) + >>> dataset + Dataset({ + features: ['prompt', 'completion', 'label'], + num_rows: 4 + }) + + >>> dataset[0] + {'prompt': 'The sky is', 'completion': ' blue.', 'label': True} + ``` + """ + if isinstance(dataset, DatasetDict): + column_names = dataset[list(dataset.keys())[0]].column_names + else: + column_names = dataset.column_names + if "chosen" in column_names and "rejected" in column_names: + return unpair_preference_dataset(dataset, num_proc=num_proc, desc=desc) + else: + return dataset + + +def extract_prompt(example: dict[str, Sequence]) -> dict[str, Sequence]: + r""" + Extracts the shared prompt from a preference data example, where the prompt is implicit within both the chosen and + rejected completions. + + The function identifies the longest common sequence (prefix) of conversation turns between the "chosen" and + "rejected" completions and extracts this as the prompt. It then removes this prompt from the respective "chosen" + and "rejected" completions. + + Args: + example (`dict[str, list]`): + A dictionary representing a single data entry in the preference dataset. It must contain the keys + `"chosen"` and `"rejected"`, where each value is either conversational or standard (`str`). + + Returns: + `dict[str, list]`: A dictionary containing: + - `"prompt"`: The longest common prefix between the "chosen" and "rejected" completions. + - `"chosen"`: The remainder of the "chosen" completion, with the prompt removed. + - `"rejected"`: The remainder of the "rejected" completion, with the prompt removed. + + Examples: + + ```python + >>> example = { + ... "chosen": [ + ... {"role": "user", "content": "What color is the sky?"}, + ... {"role": "assistant", "content": "It is blue."}, + ... ], + ... "rejected": [ + ... {"role": "user", "content": "What color is the sky?"}, + ... {"role": "assistant", "content": "It is green."}, + ... ], + ... } + >>> extract_prompt(example) + {'prompt': [{'role': 'user', 'content': 'What color is the sky?'}], + 'chosen': [{'role': 'assistant', 'content': 'It is blue.'}], + 'rejected': [{'role': 'assistant', 'content': 'It is green.'}]} + ``` + + Or, with the `map` method of [`~datasets.Dataset`]: + + ```python + >>> from trl import extract_prompt + >>> from datasets import Dataset + + >>> dataset_dict = { + ... "chosen": [ + ... [ + ... {"role": "user", "content": "What color is the sky?"}, + ... {"role": "assistant", "content": "It is blue."}, + ... ], + ... [ + ... {"role": "user", "content": "Where is the sun?"}, + ... {"role": "assistant", "content": "In the sky."}, + ... ], + ... ], + ... "rejected": [ + ... [ + ... {"role": "user", "content": "What color is the sky?"}, + ... {"role": "assistant", "content": "It is green."}, + ... ], + ... [ + ... {"role": "user", "content": "Where is the sun?"}, + ... {"role": "assistant", "content": "In the sea."}, + ... ], + ... ], + ... } + >>> dataset = Dataset.from_dict(dataset_dict) + >>> dataset = dataset.map(extract_prompt) + >>> dataset[0] + {'prompt': [{'role': 'user', 'content': 'What color is the sky?'}], + 'chosen': [{'role': 'assistant', 'content': 'It is blue.'}], + 'rejected': [{'role': 'assistant', 'content': 'It is green.'}]} + ``` + """ + for idx in range(min(len(example["chosen"]), len(example["rejected"]))): + if example["chosen"][idx] != example["rejected"][idx]: + if example["chosen"][idx - 1] == " ": # remove space before the prompt + idx -= 1 + break + return { + "prompt": example["chosen"][:idx], + "chosen": example["chosen"][idx:], + "rejected": example["rejected"][idx:], + } + + +def maybe_extract_prompt(example: dict[str, list]) -> dict[str, list]: + r""" + Extracts the shared prompt from a preference data example, where the prompt is implicit within both the chosen and + rejected completions. + + If the example already contains a `"prompt"` key, the function returns the example as is. For more details, see + [`extract_prompt`]. + ``` + """ + # Some dataset add a `"prompt"` column, even though the prompt is implicit and included in the "chosen" and + # "rejected" completions. E.g.: + # {"prompt": "What color is the sky?", + # "chosen": [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is blue."}], + # "rejected": [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is green."}]} + # That's why we check if the prompt is also conversational before deciding not to extract it. + if "chosen" not in example or "rejected" not in example: # not a preference example + return example + if "prompt" in example: + # Both conversational or both non-conversational + chosen_conv = is_conversational({"chosen": example["chosen"]}) + prompt_conv = is_conversational({"prompt": example["prompt"]}) + if (chosen_conv and prompt_conv) or (not chosen_conv and not prompt_conv): + return example + return extract_prompt({"chosen": example["chosen"], "rejected": example["rejected"]}) + + +def _get_dataset_format(dataset: DatasetType) -> dict[str, Any]: + if isinstance(dataset, (DatasetDict, IterableDatasetDict)): + dataset = dataset[next(iter(dataset))] + if isinstance(dataset, Dataset): + format = dataset.format + else: + format_type = dataset._formatting.format_type if dataset._formatting is not None else None + format = {"type": format_type} + format.update(format.pop("format_kwargs", {})) + return format + + +def _check_if_columns_can_be_packed(columns: list[pa.Array]): + first_column_offsets = None + for idx, column in enumerate(columns): + if not (pyarrow.types.is_list(column.type) or pyarrow.types.is_large_list(column.type)): + raise TypeError("Packing requires all columns to be lists of lists.") + + if idx == 0: + first_column_offsets = column.offsets + elif not first_column_offsets.equals(column.offsets): + raise ValueError("All columns must have values of the same length.") + + +class _SegmentTree: + """ + A segment tree data structure that, when initialized as `_SegmentTree(maxval)`, efficiently finds the next larger + value for a given input within the range [1, maxval]. + + See [Fewer Truncations Improve Language Modeling](https://huggingface.co/papers/2404.10830) for more details. + """ + + def __init__(self, maxval: int): + self.maxval = maxval + # For non-power-of-2 values, we need to round up to the next power of 2 for the tree size + self.tree_size = 1 << (maxval - 1).bit_length() + self.tree = [0] * (2 * self.tree_size) + + def add(self, val): + assert 0 < val <= self.maxval + i = self.tree_size + val - 1 + self.tree[i] = val + while i > 1: + i >>= 1 + left, right = self.tree[i << 1], self.tree[(i << 1) + 1] + # Compare the values using if-else otherwise repeated calls to `builtins.max` become the bottleneck + self.tree[i] = left if left >= right else right + + def remove(self, val): + assert 0 < val <= self.maxval + i = self.tree_size + val - 1 + self.tree[i] = 0 + while i > 1: + i >>= 1 + left, right = self.tree[i << 1], self.tree[(i << 1) + 1] + # Compare the values using if-else otherwise repeated calls to `builtins.max` become the bottleneck + self.tree[i] = left if left >= right else right + + def search(self, val): + assert 0 < val <= self.maxval + i = 1 + while i < self.tree_size: + if self.tree[i << 1] >= val: + i = i << 1 + else: + i = (i << 1) + 1 + return self.tree[i] + + +def _pack_bfd( + examples: pa.Table, seq_length: int, on_seq_length_overflow: Literal["truncate", "split"] = "truncate" +) -> pa.Table: + """Pack sequences in a pyarrow Table using Best Fit Decreasing strategy.""" + columns = [column.chunks[0] for column in examples.combine_chunks().columns] + _check_if_columns_can_be_packed(columns) + assert len(columns) > 0 + + lengths = pc.list_value_length(columns[0]) + + # Filter out empty sequences + non_empty_mask = pc.greater(lengths, 0) + columns = [pc.filter(column, non_empty_mask) for column in columns] + lengths = pc.filter(lengths, non_empty_mask) + + if on_seq_length_overflow == "truncate": + columns = [pc.list_slice(column, 0, seq_length) for column in columns] + elif on_seq_length_overflow == "split": + lengths = lengths.to_numpy() + # Split the sequences longer than `seq_length` into chunks (of length `seq_length` or less) while respecting sequence boundaries + num_fragments = np.ceil(lengths / seq_length).astype(int) + offsets = np.arange(np.sum(num_fragments) + 1, dtype=columns[0].offsets.type.to_pandas_dtype()) * seq_length + # "Left-shift" the offsets to account for the last fragment of each original sequence possibly being shorter than `seq_length` + diff = np.zeros_like(offsets) + diff[np.cumsum(num_fragments)] = -lengths % seq_length + diff = np.cumsum(diff) + offsets -= diff + columns = [ + type(column).from_arrays(offsets.astype(column.offsets.type.to_pandas_dtype()), column.values) + for column in columns + ] + else: + raise ValueError(f"Invalid `on_seq_length_overflow`: {on_seq_length_overflow}. Use 'truncate' or 'split'.") + + examples = pa.Table.from_arrays(columns, names=examples.column_names) + lengths = pc.list_value_length(columns[0]) + examples = examples.append_column("seq_lengths", lengths) # Allows us to later construct `position_ids` + ids = np.arange(len(examples)) + lengths = pc.make_struct(lengths, ids) + lengths = lengths.sort("descending", by=0) + + # Greedy BFD binning using a segment tree to quickly find best-fit remaining space. + segment_tree = _SegmentTree(seq_length) + segment_tree.add(seq_length) # the max, `seq_length` bin is always available + space_to_bin = defaultdict(deque) + + # Bin is represented as a dict (of example ids and sum of their lengths) to allow in-place updates + bins: list[dict] = [] + for length, idx in zip(lengths.field(0).to_numpy(), lengths.field(1).to_numpy(), strict=True): + space = segment_tree.search(length) + + if space < seq_length: + # Use existing bin with exactly this amount of space + bin = space_to_bin[space].popleft() + else: + # Create a new bin + bin = {"ids": [], "length": 0} + bins.append(bin) + + bin["ids"].append(idx) + bin["length"] += length + if space < seq_length and not space_to_bin[space]: + segment_tree.remove(space) + + space = space - length + space_to_bin[space].append(bin) + if space > 0: + segment_tree.add(space) + + examples = pc.take(examples, [id_ for bin in bins for id_ in bin["ids"]]) + offsets = np.cumsum([0] + [bin["length"] for bin in bins]) + + assert all( + column.num_chunks == 1 for column in examples.columns + ) # `pc.take` returns a ChunkedArray with a single chunk + + lengths = examples["seq_lengths"].chunks[0] + examples = examples.drop_columns("seq_lengths") + lengths = pa.ListArray.from_arrays(np.cumsum([0] + [len(bin["ids"]) for bin in bins], dtype=np.int32), lengths) + + columns = [] + for column in examples.columns: + column = column.chunks[0] + assert pa.types.is_list(column.type) or pa.types.is_large_list(column.type) + dtype = column.offsets.type.to_pandas_dtype() + column = type(column).from_arrays(offsets.astype(dtype), column.values) + columns.append(column) + return pa.Table.from_arrays(columns + [lengths], names=examples.column_names + ["seq_lengths"]) + + +def _pack_wrapped(examples: pa.Table, seq_length: int) -> pa.Table: + """Pack sequences in a pyarrow Table using a wrapped strategy.""" + columns = [column.chunks[0] for column in examples.combine_chunks().columns] + _check_if_columns_can_be_packed(columns) + offsets, values = columns[0].offsets, columns[0].values + values = values[offsets[0].as_py() : offsets[-1].as_py()] + num_elements = len(values) + offsets = np.arange(0, num_elements, seq_length, dtype=columns[0].offsets.type.to_pandas_dtype()) + offsets = np.concatenate((offsets, [num_elements])) + columns = [ + type(column).from_arrays(offsets.astype(column.offsets.type.to_pandas_dtype()), column.values) + for column in columns + ] + return pa.Table.from_arrays(columns, names=examples.column_names) + + +def pack_dataset( + dataset: DatasetType, + seq_length: int, + strategy: str = "bfd", + map_kwargs: dict[str, Any] | None = None, +) -> DatasetType: + r""" + Pack sequences in a dataset into chunks of size `seq_length`. + + Args: + dataset ([`~datasets.Dataset`] or [`~datasets.DatasetDict`]): + Dataset to pack + seq_length (`int`): + Target sequence length to pack to. + strategy (`str`, *optional*, defaults to `"bfd"`): + Packing strategy to use. Can be either: + + - `"bfd"` (Best Fit Decreasing): Preserves sequence boundaries and truncates sequences that exceed + `seq_length`, discarding overflow tokens. Ideal for SFT and conversational datasets where maintaining + conversation structure is important. + - `"bfd_split"`: Similar to `"bfd"` but splits overflow sequences for packing into other examples. Prevents + token loss for pre-training or long documents, but may break conversation structure in SFT datasets. + - `"wrapped"`: Faster but more aggressive. Ignores sequence boundaries and will cut sequences in the middle + to completely fill each packed sequence with data. + map_kwargs (`dict`, *optional*): + Additional keyword arguments to pass to the dataset's map method when packing examples. + + Returns: + [`~datasets.Dataset`] or [`~datasets.DatasetDict`]: The dataset with packed sequences. The number of examples + may decrease as sequences are combined. + + Example: + ```python + >>> from datasets import Dataset + >>> from trl import pack_dataset + + >>> examples = { + ... "input_ids": [[1, 2, 3, 4, 5], [6, 7], [8, 9, 10], [11]], + ... "attention_mask": [[1, 1, 1, 0, 0], [1, 0], [1, 1, 0], [1]], + ... } + >>> dataset = Dataset.from_dict(examples) + >>> # Default "bfd" strategy (SFT-friendly): truncates long sequences + >>> packed_dataset = pack_dataset(dataset, seq_length=4, strategy="bfd") + >>> packed_dataset[:] + {'input_ids': [[1, 2, 3, 4], [8, 9, 10, 11], [6, 7]], + 'attention_mask': [[1, 1, 1, 0], [1, 1, 0, 1], [1, 0]], + 'seq_lengths': [[4], [3, 1], [2]]} + + >>> # "bfd_split" strategy: preserves all tokens + >>> packed_dataset = pack_dataset(dataset, seq_length=4, strategy="bfd_split") + >>> packed_dataset[:] + {'input_ids': [[1, 2, 3, 4], [8, 9, 10, 5], [6, 7, 11]], + 'attention_mask': [[1, 1, 1, 0], [1, 1, 0, 0], [1, 0, 1]], + 'seq_lengths': [[4], [3, 1], [2, 1]]} + ``` + """ + if map_kwargs is None: + map_kwargs = {} + + valid_strategies = ("bfd", "bfd_split", "wrapped") + if strategy not in valid_strategies: + raise ValueError(f"Invalid packing strategy '{strategy}', must be one of {valid_strategies}.") + format = _get_dataset_format(dataset) + dataset = dataset.with_format("arrow") + if strategy == "bfd": + dataset = dataset.map( + _pack_bfd, + batched=True, + fn_kwargs={"seq_length": seq_length, "on_seq_length_overflow": "truncate"}, + **map_kwargs, + ) + elif strategy == "bfd_split": + dataset = dataset.map( + _pack_bfd, + batched=True, + fn_kwargs={"seq_length": seq_length, "on_seq_length_overflow": "split"}, + **map_kwargs, + ) + elif strategy == "wrapped": + dataset = dataset.map(_pack_wrapped, batched=True, fn_kwargs={"seq_length": seq_length}, **map_kwargs) + else: + raise ValueError(f"Invalid packing strategy: '{strategy}', must be one of {valid_strategies}.") + + if strategy in {"bfd", "bfd_split"} and "columns" in format: + format["columns"] = format["columns"] + ["seq_lengths"] + + dataset = dataset.with_format(**format) + return dataset + + +def is_conversational_from_value(example: dict[str, Any]) -> bool: + r""" + Check if the example is in a conversational format (from/value). Note that this format isn't recommended. Prefer + the ChatML format (role/content) + + Args: + example (`dict[str, Any]`): + A single data entry of a dataset. The example can have different keys depending on the dataset type. + + Returns: + `bool`: + `True` if the data is in a conversational Chatformat, `False` otherwise. + + Examples: + + ```python + >>> example = {"conversations": [{"from": "user", "value": "What color is the sky?"}]} + >>> is_conversational_from_value(example) + True + + >>> example = {"conversations": [{"role": "user", "content": "What color is the sky?"}]} + >>> is_conversational_from_value(example) + False + + >>> example = {"conversations": "The sky is"} + >>> is_conversational_from_value(example) + False + ``` + """ + maybe_messages = example.get("conversations") + # It must be a list of messages + if isinstance(maybe_messages, list): + maybe_message = maybe_messages[0] + # Each message must a list of dictionaries with keys "from" and "value" + if isinstance(maybe_message, dict) and "from" in maybe_message and "value" in maybe_message: + return True + + return False + + +def maybe_convert_to_chatml(example: dict[str, list]) -> dict[str, list]: + """ + Convert a conversational dataset with fields `from` and `value` to ChatML format. + + This function modifies conversational data to align with OpenAI's ChatML format: + - Replaces the key `"from"` with `"role"` in message dictionaries. + - Replaces the key `"value"` with `"content"` in message dictionaries. + - Renames `"conversations"` to `"messages"` for consistency with ChatML. + + Args: + example (`dict[str, list]`): + A single data entry containing a list of messages. + + Returns: + `dict[str, list]`: + Example reformatted to ChatML style. + + Example: + ```python + >>> from trl import maybe_convert_to_chatml + + >>> example = { + ... "conversations": [ + ... {"from": "user", "value": "What color is the sky?"}, + ... {"from": "assistant", "value": "It is blue."}, + ... ] + ... } + >>> maybe_convert_to_chatml(example) + {'messages': [{'role': 'user', 'content': 'What color is the sky?'}, + {'role': 'assistant', 'content': 'It is blue.'}]} + ``` + """ + # List of possible keys containing message lists + for key in ["prompt", "completion", "chosen", "rejected", "messages", "conversations"]: + if key in example and isinstance(example[key], list): + messages = example[key] + for message in messages: + if isinstance(message, dict): + if "from" in message: + message["role"] = message.pop("from") + if "value" in message: + message["content"] = message.pop("value") + + # Rename "conversations" to "messages" + if "conversations" in example: + example["messages"] = example.pop("conversations") + + return example diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/distributed.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..d5d03be37e1457488ba7b15d926cfb9400adc96c --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/distributed.py @@ -0,0 +1,91 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Distributed training backend abstraction.""" + +from contextlib import contextmanager + + +class DistributedBackend: + """Abstracts distributed backend specifics (DeepSpeed ZeRO, FSDP) behind a uniform API. + + Detects the active backend once at construction from ``accelerator.state``, then provides context managers that are + no-ops on backends where the operation is not needed. + + Args: + accelerator ([`~accelerate.Accelerator`]): + The accelerator instance managing the distributed state. + + Example: + + ```python + >>> dist = DistributedBackend(accelerator) + >>> with dist.gather_params(list(model.parameters())): + ... model.merge_adapter() + >>> with dist.summon_full_params(model, recurse=False): + ... outputs = model.generate(inputs) + ``` + """ + + def __init__(self, accelerator): + ds_plugin = accelerator.state.deepspeed_plugin + fsdp_plugin = getattr(accelerator.state, "fsdp_plugin", None) + self.zero_stage = ds_plugin.zero_stage if ds_plugin else 0 + self.fsdp_version = getattr(fsdp_plugin, "fsdp_version", None) if fsdp_plugin else None + + @property + def is_zero3(self) -> bool: + """Whether DeepSpeed ZeRO Stage 3 is active.""" + return self.zero_stage == 3 + + @property + def is_fsdp(self) -> bool: + """Whether FSDP (any version) is active.""" + return self.fsdp_version is not None + + @contextmanager + def gather_params(self, params): + """Gather sharded parameters under DeepSpeed ZeRO-3; no-op otherwise. + + Args: + params (iterable of `torch.nn.Parameter`): + Parameters to gather. + """ + if self.is_zero3: + import deepspeed + + with deepspeed.zero.GatheredParameters(params): + yield + else: + yield + + @contextmanager + def summon_full_params(self, module, **kwargs): + """Materialize full FSDP v1 parameters; no-op for FSDP v2 or non-FSDP backends. + + FSDP v2 parameters are always accessible and require no explicit materialization. + + Args: + module (`torch.nn.Module`): + The FSDP-wrapped module. + **kwargs: + Forwarded to ``FSDP.summon_full_params`` (e.g. ``recurse``, ``writeback``). + """ + if self.fsdp_version == 1: + from torch.distributed.fsdp import FullyShardedDataParallel as FSDP + + with FSDP.summon_full_params(module, **kwargs): + yield + else: + yield diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..041a38542a6fbaba81fbdb3d278e737109c95f83 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/__init__.py @@ -0,0 +1,36 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Experimental submodule for TRL. + +This submodule contains unstable or incubating features. Anything here may change (or be removed) in any release +without deprecation. Use at your own risk. + +To silence this notice set environment variable TRL_EXPERIMENTAL_SILENCE=1. +""" + +import os +import warnings + +from ..import_utils import TRLExperimentalWarning + + +if not os.environ.get("TRL_EXPERIMENTAL_SILENCE"): + warnings.warn( + "You are importing from 'trl.experimental'. APIs here are unstable and may change or be removed without " + "notice. Silence this warning by setting environment variable TRL_EXPERIMENTAL_SILENCE=1.", + TRLExperimentalWarning, + stacklevel=2, + ) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/a2po/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/a2po/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fa3d8b8fbbff1633f7cd5414dd7f2362e302a09a --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/a2po/__init__.py @@ -0,0 +1,16 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .a2po_config import A2POConfig +from .a2po_trainer import A2POTrainer diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/a2po/a2po_config.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/a2po/a2po_config.py new file mode 100644 index 0000000000000000000000000000000000000000..bea11aff7a1961bda9331a1deda60ab82e3bd601 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/a2po/a2po_config.py @@ -0,0 +1,146 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field + +from trl.trainer.base_config import _BaseConfig + + +@dataclass +class A2POConfig(_BaseConfig): + # docstyle-ignore + r""" + Configuration class for the [`A2POTrainer`]. + + This class includes only the parameters that are specific to A2PO 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`]. + + Parameters: + > Parameters that control the model and reference model + + model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments for [`~transformers.AutoModelForCausalLM.from_pretrained`], used when the `model` + argument of the [`A2POTrainer`] is provided as a string. + + > 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`. + + > Parameters that control generation + + max_prompt_length (`int` or `None`, *optional*, defaults to `512`): + Maximum length of the prompt. If the prompt is longer than this, it is left-truncated. + max_completion_length (`int` or `None`, *optional*, defaults to `256`): + Maximum length of the generated completion. + temperature (`float`, *optional*, defaults to `1.0`): + Sampling temperature, used in both Stage 1 and Stage 2 generation. + 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*): + Number of highest-probability vocabulary tokens to keep. If `None`, top-k filtering is disabled. + + > Parameters that control Stage 1 (offline optimal value estimation) + + num_value_samples (`int`, *optional*, defaults to `8`): + Number of samples drawn from the reference policy per prompt to estimate `V*`. + beta1 (`float`, *optional*, defaults to `0.5`): + KL temperature used to estimate `V*` in Stage 1. + filter_all_incorrect (`bool`, *optional*, defaults to `True`): + Whether to drop prompts for which all reference samples are incorrect. + + > Parameters that control Stage 2 (on-policy regression) + + beta2 (`float`, *optional*, defaults to `1e-3`): + KL temperature used in the Stage 2 regression target. + reward_weights (`list[float]`, *optional*): + Weights for each reward function. Must match the number of reward functions. If `None`, all rewards are + weighted equally with weight `1.0`. + """ + + _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"] + + # Parameters that control the model and reference model + model_init_kwargs: dict | None = field( + default=None, + metadata={ + "help": "Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `model` argument of " + "the `A2POTrainer` is provided as a string." + }, + ) + + # Parameters that control the data preprocessing + remove_unused_columns: bool = field( + default=False, + metadata={ + "help": "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`." + }, + ) + + # Parameters that control generation + max_prompt_length: int | None = field( + default=512, + metadata={"help": "Maximum length of the prompt. If the prompt is longer than this, it is left-truncated."}, + ) + max_completion_length: int | None = field( + default=256, metadata={"help": "Maximum length of the generated completion."} + ) + temperature: float = field( + default=1.0, + metadata={"help": "Sampling temperature, used in both Stage 1 and Stage 2 generation."}, + ) + top_p: float = field( + default=1.0, + metadata={ + "help": "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 | None = field( + default=None, + metadata={ + "help": "Number of highest-probability vocabulary tokens to keep. If `None`, top-k filtering is disabled." + }, + ) + + # Parameters that control Stage 1 (offline optimal value estimation) + num_value_samples: int = field( + default=8, + metadata={"help": "Number of samples drawn from the reference policy per prompt to estimate `V*`."}, + ) + beta1: float = field( + default=0.5, + metadata={"help": "KL temperature used to estimate `V*` in Stage 1."}, + ) + filter_all_incorrect: bool = field( + default=True, + metadata={"help": "Whether to drop prompts for which all reference samples are incorrect."}, + ) + + # Parameters that control Stage 2 (on-policy regression) + beta2: float = field( + default=1e-3, + metadata={"help": "KL temperature used in the Stage 2 regression target."}, + ) + reward_weights: list[float] | None = field( + default=None, + metadata={ + "help": "Weights for each reward function. Must match the number of reward functions. If `None`, all " + "rewards are weighted equally with weight `1.0`." + }, + ) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/a2po/a2po_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/a2po/a2po_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..979ab81a6e3e6547ee816c98b6263d3c35b38cd6 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/a2po/a2po_trainer.py @@ -0,0 +1,371 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import inspect +import math +import textwrap +from collections import defaultdict +from collections.abc import Callable + +import torch +from accelerate.logging import get_logger +from accelerate.utils import gather_object +from torch.utils.data import DataLoader +from transformers import ( + AutoModelForCausalLM, + AutoTokenizer, + GenerationConfig, + PreTrainedModel, + PreTrainedTokenizerBase, +) + +from ...data_utils import maybe_apply_chat_template +from ...models import create_reference_model, unwrap_model_for_generation +from ...trainer.base_trainer import _BaseTrainer +from ...trainer.utils import selective_log_softmax +from .a2po_config import A2POConfig + + +logger = get_logger(__name__) + +# A reward function is a callable that returns a list of floats (the rewards). The callable receives prompts, +# completions, and additional columns from the dataset. To ensure forward compatibility, it should accept **kwargs. +RewardFunc = Callable[..., list[float]] + + +class A2POTrainer(_BaseTrainer): + # docstyle-ignore + """ + Trainer for the A*-PO (Optimal Advantage Regression) method, introduced in [Accelerating RL for LLM Reasoning with + Optimal Advantage Regression](https://huggingface.co/papers/2505.20686). + + A*-PO runs in two stages: + + 1. **Offline value estimation.** Before training, `num_value_samples` completions are sampled from the reference + policy for every training prompt and scored with `reward_funcs`. The optimal value is estimated as + `V*(x) = beta1 * log(mean_i exp(r(x, y_i) / beta1))` and cached per prompt. + 2. **On-policy regression.** During training, a single completion is generated per prompt from the current policy. + The loss is the squared error between the implicit reward `beta2 * log(pi(y|x) / pi_ref(y|x))` and the optimal + advantage estimate `r(x, y) - V*(x)`. + + Args: + model (`PreTrainedModel` or `str`): + Model to be trained, or a model identifier (string) passed to + [`~transformers.AutoModelForCausalLM.from_pretrained`]. + reward_funcs (`Callable` or `list[Callable]`): + Reward function(s). Each takes `prompts` and `completions` (plus dataset columns as keyword arguments) and + returns a list of float rewards. When multiple are provided, their weighted sum (see + [`A2POConfig.reward_weights`]) is the scalar reward `r`, which A*-PO assumes to be binary (in `{0, 1}`). + args ([`A2POConfig`], *optional*): + Configuration for this trainer. If `None`, a default configuration is used. + train_dataset ([`~datasets.Dataset`], *optional*): + Training dataset. Must contain a `"prompt"` column. + eval_dataset ([`~datasets.Dataset`], *optional*): + Evaluation dataset. + processing_class ([`~transformers.PreTrainedTokenizerBase`], *optional*): + Processing class used to process the data. If `None`, it is loaded from the model's name with + [`~transformers.AutoTokenizer.from_pretrained`]. + callbacks (`list[~transformers.TrainerCallback]`, *optional*): + List of callbacks to customize the training loop. + optimizers (`tuple[~torch.optim.Optimizer, ~torch.optim.lr_scheduler.LambdaLR]`, *optional*, defaults to `(None, None)`): + Tuple containing the optimizer and the learning rate scheduler. + """ + + _tag_names = ["trl", "a2po"] + _name = "A2PO" + _paper = { + "title": "Accelerating RL for LLM Reasoning with Optimal Advantage Regression", + "id": "2505.20686", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @article{brantley2025accelerating, + title = {{Accelerating RL for LLM Reasoning with Optimal Advantage Regression}}, + author = {Kiant\'e Brantley and Mingyu Chen and Zhaolin Gao and Jason D. Lee and Wen Sun and Wenhao Zhan and Xuezhou Zhang}, + year = 2025, + eprint = {arXiv:2505.20686}, + }"""), + } + + def __init__( + self, + model: PreTrainedModel | str, + reward_funcs: RewardFunc | list[RewardFunc], + args: A2POConfig | None = None, + train_dataset=None, + eval_dataset=None, + processing_class: PreTrainedTokenizerBase | None = None, + callbacks=None, + optimizers=(None, None), + ): + # Args + if args is None: + args = A2POConfig(f"{model if isinstance(model, str) else model.config._name_or_path}-A2PO") + + # Models + if isinstance(model, str): + model = AutoModelForCausalLM.from_pretrained(model, **(args.model_init_kwargs or {})) + model_id = model.config._name_or_path + + # Some models (e.g. SmolVLM/Idefics3) don't support the `logits_to_keep` argument and error out if we pass it. + # Inspect the forward method so Stage 2 can pass the argument only when it is supported. + self.model_kwarg_keys = inspect.signature(model.forward).parameters.keys() + + # Reference model: a frozen copy of the initial policy. Stage 1 samples from it and Stage 2 regularizes to it. + self.ref_model = create_reference_model(model) + + # Processing class + if processing_class is None: + processing_class = AutoTokenizer.from_pretrained(model_id, padding_side="left") + + # Reward functions + if not isinstance(reward_funcs, list): + reward_funcs = [reward_funcs] + self.reward_funcs = reward_funcs + if args.reward_weights is None: + self.reward_weights = torch.ones(len(reward_funcs), dtype=torch.float32) + else: + self.reward_weights = torch.tensor(args.reward_weights, dtype=torch.float32) + + # Generation: N samples per prompt in Stage 1, a single sample in Stage 2 + self.value_generation_config = GenerationConfig( + max_new_tokens=args.max_completion_length, + do_sample=True, + temperature=args.temperature, + top_p=args.top_p, + top_k=args.top_k, + num_return_sequences=args.num_value_samples, + pad_token_id=processing_class.pad_token_id, + ) + self.generation_config = GenerationConfig( + max_new_tokens=args.max_completion_length, + do_sample=True, + temperature=args.temperature, + top_p=args.top_p, + top_k=args.top_k, + num_return_sequences=1, + pad_token_id=processing_class.pad_token_id, + ) + + # Optimal values V*(x), keyed by prompt text. Populated lazily by Stage 1 at the start of training. + self._optimal_values: dict[str, float] | None = None + + # Metrics + self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)} + + # The data collator returns the list of features untouched; generation happens in `_prepare_inputs`. + def data_collator(features): + return features + + super().__init__( + model=model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + callbacks=callbacks, + optimizers=optimizers, + ) + + self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True) + + def _calculate_rewards(self, prompts, completions, **reward_kwargs): + device = self.accelerator.device + rewards_per_func = torch.zeros(len(prompts), len(self.reward_funcs), device=device) + for i, reward_func in enumerate(self.reward_funcs): + output = reward_func(prompts=prompts, completions=completions, **reward_kwargs) + rewards_per_func[:, i] = torch.tensor(output, dtype=torch.float32, device=device) + # A*-PO assumes the (weighted) total reward is binary in {0, 1}. + return (rewards_per_func * self.reward_weights.to(device)).sum(dim=1) + + def _get_sequence_logps(self, model, input_ids, attention_mask, logits_to_keep): + model_inputs = {"input_ids": input_ids, "attention_mask": attention_mask} + # Only pass `logits_to_keep` when the model supports it (some models and VLMs don't). + if "logits_to_keep" in self.model_kwarg_keys: + # We add 1 to `logits_to_keep` because the last logits of the sequence is later excluded + model_inputs["logits_to_keep"] = logits_to_keep + 1 + logits = model(**model_inputs).logits + logits = logits[:, :-1, :] # the last logit predicts beyond the sequence + # Only keep the last logits_to_keep. For models that support logits_to_keep, this is a no-op. + logits = logits[:, -logits_to_keep:, :] + completion_ids = input_ids[:, -logits_to_keep:] + per_token_logps = selective_log_softmax(logits, completion_ids) + completion_mask = attention_mask[:, -logits_to_keep:] + return (per_token_logps * completion_mask).sum(dim=1) + + # Stage 1: offline optimal value estimation + def _estimate_optimal_values(self): + beta1 = self.args.beta1 + n = self.args.num_value_samples + optimal_values = {} + all_incorrect = set() + + # Stage 2 looks up V* for every prompt it scores, including eval prompts, so estimate over both datasets. + datasets = [self.train_dataset] if self.eval_dataset is None else [self.train_dataset, self.eval_dataset] + for dataset in datasets: + dataloader = self.accelerator.prepare( + DataLoader(dataset, batch_size=self.args.per_device_train_batch_size, collate_fn=list) + ) + for batch in dataloader: + prompts = [example["prompt"] for example in batch] + prompts_text = [ + maybe_apply_chat_template(example, self.processing_class)["prompt"] for example in batch + ] + + # Sample N completions per prompt from the reference policy + inputs = self.processing_class( + prompts_text, + return_tensors="pt", + padding=True, + truncation=True, + max_length=self.args.max_prompt_length, + add_special_tokens=False, + ).to(self.accelerator.device) + with unwrap_model_for_generation(self.ref_model, self.accelerator) as ref_model: + completion_ids = ref_model.generate(**inputs, generation_config=self.value_generation_config) + + prompt_length = inputs["input_ids"].size(1) + completions_text = self.processing_class.batch_decode( + completion_ids[:, prompt_length:], skip_special_tokens=True + ) + + # Each prompt is repeated N times by `num_return_sequences`. Forward any extra dataset columns (e.g. + # "solution") to the reward functions, repeated to align with the N samples per prompt. + keys = [key for key in batch[0] if key not in ["prompt", "completion"]] + reward_kwargs = {key: [example[key] for example in batch for _ in range(n)] for key in keys} + repeated_prompts = [p for p in prompts for _ in range(n)] + rewards = self._calculate_rewards(repeated_prompts, completions_text, **reward_kwargs) + rewards = rewards.view(len(prompts), n) + + # V*(x) = beta1 * log(mean_i exp(r_i / beta1)), computed stably + v_star = beta1 * (torch.logsumexp(rewards / beta1, dim=1) - math.log(n)) + + for j, prompt_text in enumerate(prompts_text): + optimal_values[prompt_text] = v_star[j].item() + if rewards[j].sum() == 0: + all_incorrect.add(prompt_text) + + # Each rank estimates V* for its shard of prompts; share them so any rank can score any prompt. + # `gather_object` concatenates the per-rank lists, so pass flat lists and rebuild on every rank. + self._optimal_values = dict(gather_object(list(optimal_values.items()))) + all_incorrect = set(gather_object(list(all_incorrect))) + + # Drop training prompts whose reference samples all scored zero (no learning signal). Eval prompts are kept + # so evaluation can still look up their V*. + if self.args.filter_all_incorrect: + self.train_dataset = self.train_dataset.filter( + lambda example: maybe_apply_chat_template(example, self.processing_class)["prompt"] + not in all_incorrect + ) + logger.info(f"Stage 1 complete: estimated V* for {len(self._optimal_values)} prompts.") + + # Stage 2: on-policy regression + def _prepare_inputs(self, inputs): + # Estimate V* on first use, e.g. when `evaluate()` is called without a preceding `train()`. + if self._optimal_values is None: + self._estimate_optimal_values() + mode = "train" if self.model.training else "eval" + device = self.accelerator.device + prompts = [example["prompt"] for example in inputs] + prompts_text = [maybe_apply_chat_template(example, self.processing_class)["prompt"] for example in inputs] + + # One on-policy completion per prompt + prompt_inputs = self.processing_class( + prompts_text, + return_tensors="pt", + padding=True, + truncation=True, + max_length=self.args.max_prompt_length, + add_special_tokens=False, + ).to(device) + with unwrap_model_for_generation(self.model, self.accelerator) as unwrapped_model: + prompt_completion_ids = unwrapped_model.generate(**prompt_inputs, generation_config=self.generation_config) + prompt_length = prompt_inputs["input_ids"].size(1) + completion_ids = prompt_completion_ids[:, prompt_length:] + completions_text = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True) + + # Scalar (binary) reward and cached optimal value. Forward extra dataset columns to the reward functions. + keys = [key for key in inputs[0] if key not in ["prompt", "completion"]] + reward_kwargs = {key: [example[key] for example in inputs] for key in keys} + rewards = self._calculate_rewards(prompts, completions_text, **reward_kwargs) + v_star = torch.tensor([self._optimal_values[p] for p in prompts_text], dtype=torch.float32, device=device) + + # Attention mask: the tokenizer's prompt mask followed by the completion mask. The completion mask is 1 up to + # and including the first EOS and 0 afterwards, so the terminal EOS stays in the log-prob sum (a plain + # `!= pad_token_id` mask would drop it when `pad_token == eos_token`). + is_eos = completion_ids == self.processing_class.eos_token_id + eos_idx = torch.full((is_eos.size(0),), is_eos.size(1), dtype=torch.long, device=device) + eos_idx[is_eos.any(dim=1)] = is_eos.int().argmax(dim=1)[is_eos.any(dim=1)] + sequence_indices = torch.arange(is_eos.size(1), device=device).expand(is_eos.size(0), -1) + completion_mask = (sequence_indices <= eos_idx.unsqueeze(1)).int() + attention_mask = torch.cat([prompt_inputs["attention_mask"], completion_mask], dim=1) + logits_to_keep = completion_ids.size(1) + + with torch.no_grad(): + ref_logps = self._get_sequence_logps(self.ref_model, prompt_completion_ids, attention_mask, logits_to_keep) + + self._metrics[mode]["reward"].append(rewards.mean().item()) + self._metrics[mode]["v_star"].append(v_star.mean().item()) + + return { + "input_ids": prompt_completion_ids, + "attention_mask": attention_mask, + "logits_to_keep": logits_to_keep, + "ref_logps": ref_logps, + "rewards": rewards, + "v_star": v_star, + } + + def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): + mode = "train" if self.model.training else "eval" + + policy_logps = self._get_sequence_logps( + model, inputs["input_ids"], inputs["attention_mask"], inputs["logits_to_keep"] + ) + + # Implicit reward beta2 * log(pi / pi_ref), regressed onto the optimal advantage r - V* + implicit_reward = self.args.beta2 * (policy_logps - inputs["ref_logps"]) + target = inputs["rewards"] - inputs["v_star"] + loss = ((implicit_reward - target) ** 2).mean() + + self._metrics[mode]["implicit_reward"].append(implicit_reward.mean().item()) + self._metrics[mode]["advantage"].append(target.mean().item()) + return loss + + def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys: list[str] | None = None): + inputs = self._prepare_inputs(inputs) + with torch.no_grad(): + with self.compute_loss_context_manager(): + loss = self.compute_loss(model, inputs) + loss = loss.mean().detach() + return loss, None, None + + def train(self, *args, **kwargs): + if self._optimal_values is None: + logger.info("Running Stage 1: offline optimal value estimation...") + self._estimate_optimal_values() + return super().train(*args, **kwargs) + + def log(self, logs: dict[str, float], start_time: float | None = None) -> None: + mode = "train" if self.model.training else "eval" + metrics = {key: sum(val) / len(val) for key, val in self._metrics[mode].items()} + + # This method can be called both in training and evaluation. When called in evaluation, the keys in `logs` + # start with "eval_". We need to add the prefix "eval_" to the keys in `metrics` to match the format. + if mode == "eval": + metrics = {f"eval_{key}": val for key, val in metrics.items()} + + logs = {**logs, **metrics} + super().log(logs, start_time) + self._metrics[mode].clear() diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/async_grpo/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/async_grpo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3fc30c059a76572f449ca53f59aeff47bd789cf5 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/async_grpo/__init__.py @@ -0,0 +1,16 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .async_grpo_config import AsyncGRPOConfig +from .async_grpo_trainer import AsyncGRPOTrainer diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/async_grpo/async_grpo_config.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/async_grpo/async_grpo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..d2b588a9033aa93d9144788ed3631e8066af64ae --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/async_grpo/async_grpo_config.py @@ -0,0 +1,224 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field + +from trl.trainer.base_config import _BaseConfig + + +@dataclass +class AsyncGRPOConfig(_BaseConfig): + # docstyle-ignore + r""" + Configuration class for the [`AsyncGRPOTrainer`]. + + This class includes only the parameters that are specific to asynchronous 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`]. + + Parameters: + > Parameters that control generation + + num_generations (`int`, *optional*, defaults to `8`): + Number of generations per prompt to sample. + max_completion_length (`int`, *optional*, defaults to `2048`): + Maximum number of tokens to generate per completion. + temperature (`float`, *optional*, defaults to `1.0`): + Temperature for sampling. The higher the temperature, the more random the completions. + chat_template_kwargs (`dict[str, Any]`, *optional*): + Additional keyword arguments to pass to the `apply_chat_template` function when generating completions. + max_tool_calling_iterations (`int`, *optional*): + Maximum number of tool-calling turns when training an agent. If `None`, there is no limit and generation + stops when the model generates a response turn with no tool calls or when the total response length reaches + `max_completion_length`. + + > Parameters that control the vLLM server + + vllm_server_base_url (`str`, *optional*, defaults to `"http://localhost:8000"`): + Base URL of the vLLM server used for generation (e.g., `"http://localhost:8000"`). + vllm_server_timeout (`float`, *optional*, defaults to `240.0`): + Total timeout duration in seconds to wait for the vLLM server to be ready. + request_timeout (`int`, *optional*, defaults to `600`): + Timeout in seconds for individual HTTP requests to the vLLM server. + + > Parameters that control the training + + epsilon (`float`, *optional*, defaults to `0.2`): + Lower-bound epsilon value for clipping. + epsilon_high (`float`, *optional*, defaults to `0.2`): + Upper-bound epsilon value for clipping. + + > Parameters that control the async rollout pipeline + + max_inflight_tasks (`int`, *optional*, defaults to `-1`): + Maximum number of concurrent generation tasks sent to the vLLM server. Defaults to `-1` (auto), which + sets it to `max_staleness * per_device_train_batch_size * gradient_accumulation_steps * num_processes`. + If using tool-use environments, you may want to set this manually based on how many parallel environments + you can run. + max_staleness (`int`, *optional*, defaults to `4`): + Maximum number of weight update steps a rollout sample can lag behind the current model version before + being discarded. + queue_maxsize (`int`, *optional*, defaults to `1024`): + Maximum number of rollout samples to buffer in the rollout queue. + weight_sync_steps (`int`, *optional*, defaults to `1`): + Number of training steps between weight synchronizations to the vLLM server. + heartbeat_stale_after_s (`float`, *optional*, defaults to `300.0`): + Seconds since the rollout worker's last heartbeat after which the trainer treats it as + hung and aborts. + + > 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. + num_completions_to_print (`int`, *optional*, defaults to `3`): + Number of completions to print when `log_completions=True`. + + > [!NOTE] + > These parameters have default values different from [`~transformers.TrainingArguments`]: + > - `logging_steps`: Defaults to `10` instead of `500`. + > - `gradient_checkpointing`: Defaults to `True` instead of `False`. + > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`. + > - `learning_rate`: Defaults to `1e-6` instead of `5e-5`. + """ + + # Parameters whose default values are overridden from TrainingArguments + learning_rate: float = field( + default=1e-6, + metadata={"help": "The initial learning rate for AdamW."}, + ) + logging_steps: float = field( + default=1, + metadata={ + "help": "Log every X update steps. Should be an integer or a float in range `[0,1)`. If smaller than 1, " + "will be interpreted as ratio of total training steps." + }, + ) + + # Parameters that control generation + num_generations: int = field( + default=8, + metadata={"help": "Number of generations per prompt to sample."}, + ) + max_completion_length: int = field( + default=2048, + metadata={"help": "Maximum number of tokens to generate per completion."}, + ) + temperature: float = field( + default=1.0, + metadata={"help": "Temperature for sampling. The higher the temperature, the more random the completions."}, + ) + chat_template_kwargs: dict | None = field( + default=None, + metadata={ + "help": "Additional keyword arguments to pass to the `apply_chat_template` function when generating " + "completions." + }, + ) + max_tool_calling_iterations: int | None = field( + default=None, + metadata={ + "help": "Maximum number of tool-calling turns when training an agent. If `None`, there is no limit and " + "generation stops when the model generates a response turn with no tool calls or when the total response " + "length reaches `max_completion_length`." + }, + ) + + # Parameters that control the vLLM server + vllm_server_base_url: str = field( + default="http://localhost:8000", + metadata={"help": "Base URL of the vLLM server used for generation (e.g., 'http://localhost:8000')."}, + ) + vllm_server_timeout: float = field( + default=240.0, + metadata={ + "help": "Total timeout duration in seconds to wait for the vLLM server to be ready. If the server is not " + "up after the timeout, a `TimeoutError` is raised." + }, + ) + request_timeout: int = field( + default=600, + metadata={"help": "Timeout in seconds for individual HTTP requests to the vLLM server."}, + ) + + # Parameters that control the training + epsilon: float = field( + default=0.2, + metadata={"help": "Lower-bound epsilon value for clipping."}, + ) + epsilon_high: float = field( + default=0.2, + metadata={"help": "Upper-bound epsilon value for clipping."}, + ) + + # Parameters that control the async rollout pipeline + max_inflight_tasks: int = field( + default=-1, + metadata={ + "help": "Maximum number of concurrent generation tasks sent to the vLLM server. Defaults to -1 (auto), " + "which sets it to `max_staleness * per_device_train_batch_size * gradient_accumulation_steps * " + "num_processes`. Generating more samples than this is wasteful since they will be discarded as stale " + "before the trainer can consume them. If using tool-use environments, you may want to set this manually " + "based on how many parallel environments you can run." + }, + ) + max_staleness: int = field( + default=4, + metadata={ + "help": "Maximum number of weight update steps a rollout sample can lag behind the current model version " + "before being discarded." + }, + ) + queue_maxsize: int = field( + default=1024, + metadata={"help": "Maximum number of rollout samples to buffer in the rollout queue."}, + ) + weight_sync_steps: int = field( + default=1, + metadata={"help": "Number of training steps between weight synchronizations to the vLLM server."}, + ) + heartbeat_stale_after_s: float = field( + default=300.0, + metadata={ + "help": "Seconds since the rollout worker's last heartbeat after which the trainer treats it as hung " + "and aborts." + }, + ) + + # Parameters that control the logging + log_completions: bool = field( + default=False, + metadata={ + "help": "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 = field( + default=3, + metadata={"help": "Number of completions to print when `log_completions=True`."}, + ) + + def __post_init__(self): + super().__post_init__() + + # Accelerator config: required for the async IterableDataset-backed dataloader to work correctly. + # split_batches=True and dispatch_batches=True ensure that the main process drives the dataloader + # and batches are broadcast to other processes rather than each process pulling independently. + if not hasattr(self, "accelerator_config") or self.accelerator_config is None: + self.accelerator_config = {"split_batches": True, "dispatch_batches": True} + elif isinstance(self.accelerator_config, dict): + self.accelerator_config["split_batches"] = True + self.accelerator_config["dispatch_batches"] = True + else: + self.accelerator_config.split_batches = True + self.accelerator_config.dispatch_batches = True diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/async_grpo/async_grpo_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/async_grpo/async_grpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..886429bb02a28049e38581aff4aca3fa0cb002da --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/async_grpo/async_grpo_trainer.py @@ -0,0 +1,715 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import math +import queue +import textwrap +import time +from collections import defaultdict +from collections.abc import Callable +from dataclasses import dataclass +from typing import Any, Protocol + +import torch +from accelerate.logging import get_logger +from datasets import Dataset, IterableDataset +from torch.distributed._tensor import DTensor +from torch.utils.data import DataLoader +from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerBase, TrainerCallback +from transformers.data.data_collator import DataCollatorMixin + +from trl.trainer.base_trainer import _BaseTrainer +from trl.trainer.utils import pad, patch_chunked_lm_head + +from .async_grpo_config import AsyncGRPOConfig +from .async_rollout_worker import AsyncRolloutWorker +from .weight_transfer import WeightTransferClient + + +logger = get_logger(__name__) + +# A reward function is a callable that returns a list of floats (the rewards). The callable receives prompts, +# completions, and additional arguments from the trainer (refer to the trainer's source for details). To ensure forward +# compatibility, it should accept **kwargs. +RewardFunc = Callable[..., list[float]] + + +class _SupportsReset(Protocol): + def reset(self, **kwargs) -> str | None: ... + + +EnvironmentFactory = Callable[[], _SupportsReset] + + +class RolloutWorkerProtocol(Protocol): + """Interface a rollout worker must implement to be passed as `rollout_worker` to [`AsyncGRPOTrainer`]. + + The default [`AsyncRolloutWorker`] spawns a CUDA-free child process and scores completions with the trainer's + `reward_funcs`. Implement this protocol to plug in a custom rollout/scoring backend instead — for example, one that + runs reward models on their own GPUs. + + Attributes: + rollout_buffer (`queue.Queue`): + Queue the trainer drains; the worker pushes scored `RolloutSample`s onto it. + """ + + rollout_buffer: queue.Queue + + def start(self) -> None: + """Begin producing rollouts. Called once on train begin, after the initial weight sync.""" + ... + + def stop(self) -> None: + """Stop the worker and release its resources. Called on train end.""" + ... + + def update_model_version(self, version: int) -> None: + """Tell the worker which policy version is now live, so it can tag or discard stale samples.""" + ... + + def check_health(self, stale_after_s: float) -> None: + """Raise if the worker has crashed or stopped producing within `stale_after_s` seconds.""" + ... + + +class StepIntervalCallback(TrainerCallback): + """ + A callback that calls a function every N optimization steps. + """ + + def __init__(self, fn, every_n_steps: int): + self.fn = fn + self.every_n_steps = every_n_steps + + def on_step_end(self, _args, state, _control, **_kwargs): + if state.global_step % self.every_n_steps == 0: + self.fn() + + +class _InitialWeightSyncCallback(TrainerCallback): + """Idempotent: NCCL group setup + cold weight sync to vLLM on train begin.""" + + def __init__(self, trainer: "AsyncGRPOTrainer"): + self._trainer = trainer + self._fired = False + + def on_train_begin(self, _args, _state, _control, **_kwargs): + if self._fired: + return + self._fired = True + if self._trainer.accelerator.is_main_process and self._trainer.weight_transfer is not None: + self._trainer.weight_transfer.init_weight_transfer() + self._trainer._sync_weight() + + +class _StartRolloutWorkerCallback(TrainerCallback): + """Idempotent: starts the rollout worker. Must be registered AFTER `_InitialWeightSyncCallback`.""" + + def __init__(self, trainer: "AsyncGRPOTrainer"): + self._trainer = trainer + self._fired = False + + def on_train_begin(self, _args, _state, _control, **_kwargs): + if self._fired: + return + self._fired = True + if self._trainer.accelerator.is_main_process and self._trainer.rollout_worker is not None: + self._trainer.rollout_worker.start() + + +class RolloutQueueDataset(torch.utils.data.IterableDataset): + def __init__( + self, + rollout_queue, + model_version_fn, + check_health_fn, + stale_after_s, + max_staleness=3, + poll_interval_s=5.0, + ): + self.queue = rollout_queue + self.model_version_fn = model_version_fn + self.check_health_fn = check_health_fn + self.stale_after_s = stale_after_s + self.max_staleness = max_staleness + self.poll_interval_s = poll_interval_s + + def __iter__(self): + while True: + t0 = time.time() + if self.queue.qsize() == 0: + logger.info("queue empty, waiting for rollout samples...") + try: + sample = self.queue.get(timeout=self.poll_interval_s) + except queue.Empty: + # Returning here would broadcast None through accelerate's dispatch loop. + self.check_health_fn(self.stale_after_s) + continue + queue_wait_time_s = time.time() - t0 + if queue_wait_time_s > 1.0: + logger.info(f"waited {queue_wait_time_s:.1f}s for sample (qsize={self.queue.qsize()})") + + staleness = self.model_version_fn() - sample.model_version + if staleness > self.max_staleness: + logger.info(f"dropping stale sample (staleness={staleness}, max={self.max_staleness})") + continue # drop stale, pull next + + yield { + "input_ids": sample.input_ids, + "completion_mask": sample.completion_mask, + "old_log_probs": sample.old_log_probs, + "advantage": sample.advantage, + "metrics": {**sample.metrics, "queue_wait_time_s": queue_wait_time_s}, + } + + +class _EmptyIterableDataset(torch.utils.data.IterableDataset): + """Placeholder for non-rank-0 processes. Never actually iterated.""" + + def __iter__(self): + return iter([]) + + +@dataclass +class DataCollatorForRollout(DataCollatorMixin): + pad_token_id: int + return_tensors: str = "pt" + + def torch_call(self, examples: list[dict[str, Any]]) -> dict[str, Any]: + input_ids = [torch.tensor(example["input_ids"], dtype=torch.long) for example in examples] + attention_mask = [torch.ones(len(ids), dtype=torch.long) for ids in input_ids] + completion_mask = [torch.tensor(example["completion_mask"], dtype=torch.float32) for example in examples] + old_log_probs = [torch.tensor(example["old_log_probs"], dtype=torch.float32) for example in examples] + advantages = torch.tensor([example["advantage"] for example in examples], dtype=torch.float32) + + input_ids = pad(input_ids, padding_value=self.pad_token_id) + attention_mask = pad(attention_mask, padding_value=0) + completion_mask = pad(completion_mask, padding_value=0) + old_log_probs = pad(old_log_probs, padding_value=0) + + # Total valid completion tokens across all samples in the full batch. + # Repeated per sample so that DataLoaderDispatcher (dispatch_batches=True) slices correctly on dim=0 + global_n_tokens = completion_mask.sum() + global_n_tokens_repeated = torch.full((len(examples),), global_n_tokens.item(), dtype=torch.float32) + + # Convert per-sample metrics dicts to a dict of 1D tensors so that Accelerate's + # recursive broadcast (dispatch_batches=True) can handle them — it traverses nested + # dicts of tensors but chokes on plain Python floats. + metrics_list = [example["metrics"] for example in examples] + metrics = ( + { + key: torch.tensor([m.get(key, 0.0) for m in metrics_list], dtype=torch.float32) + for key in metrics_list[0] + } + if metrics_list and metrics_list[0] + else {} + ) + + return { + "input_ids": input_ids, + "attention_mask": attention_mask, + "completion_mask": completion_mask, + "old_log_probs": old_log_probs, + "advantages": advantages, + "global_n_tokens": global_n_tokens_repeated, + "metrics": metrics, + } + + +class AsyncGRPOTrainer(_BaseTrainer): + """ + Trainer for the Group Relative Policy Optimization (GRPO) method. This algorithm was initially proposed in the + paper [DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language + Models](https://huggingface.co/papers/2402.03300). This trainer is the asynchronous version of GRPO, where + generation is offloaded to an external vLLM server that runs asynchronously alongside training, decoupling rollout + from the gradient update loop. + + Example: + + ```python + from trl.experimental.async_grpo import AsyncGRPOTrainer + from trl.rewards import accuracy_reward + from datasets import load_dataset + + dataset = load_dataset("trl-lib/DeepMath-103K", split="train") + + trainer = AsyncGRPOTrainer( + model="Qwen/Qwen2.5-0.5B-Instruct", + reward_funcs=accuracy_reward, + train_dataset=dataset, + ) + trainer.train() + ``` + + Args: + model (`str`): + Model to be trained. Must be a string, being the *model id* of a pretrained model hosted inside a model + repo on huggingface.co, or a path to a *directory* containing model weights saved using + [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded + using [`~transformers.AutoModelForCausalLM.from_pretrained`]. The model name is also used to identify the + model on the vLLM server used for generation. + reward_funcs (`RewardFunc | list[RewardFunc]`): + Reward functions to be used for computing the rewards. To compute the rewards, we call all the reward + functions with the prompts and completions and sum the rewards. Can be either: + + - A single reward function: The function is provided with the prompts and the generated completions, plus + any additional columns in the dataset. It should return a list of rewards. Reward functions can be either + synchronous or asynchronous and can also return `None` when the reward is not applicable to those + samples. This is useful for multi-task training where different reward functions apply to different types + of samples. When a reward function returns `None` for a sample, that reward function is excluded from the + reward calculation for that sample. For more details, see [Using a custom reward + function](#using-a-custom-reward-function). + - A list of reward functions, where each item is a reward function as described above. Rewards from all + functions are summed. + + Unlike [`GRPOTrainer`], rewards are computed in a spawned child process, so each reward function (along + with `tools` and `environment_factory`) must be picklable: use a module-level function, + `functools.partial`, or a callable class instance — lambdas and closures will fail at startup. The child + process also runs with `CUDA_VISIBLE_DEVICES=""`, so a GPU-backed reward model runs on CPU (slow), not the + trainer's GPU. + args ([`AsyncGRPOConfig`], *optional*): + Configuration for this trainer. If `None`, a default configuration is used. + train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]): + Dataset to use for training. It must include a column `"prompt"`. Any additional columns in the dataset are + ignored. The format of the samples can be either: + + - [Standard](dataset_formats#standard): Each sample contains plain text. + - [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role + and content). + processing_class ([`~transformers.PreTrainedTokenizerBase`], *optional*): + Processing class used to process the data. The padding side must be set to `"left"`. If `None`, the + processing class is loaded from the model's name with [`~transformers.AutoTokenizer.from_pretrained`]. A + padding token, `tokenizer.pad_token`, must be set. If the processing class has not set a padding token, + `tokenizer.eos_token` will be used as the default. + callbacks (list of [`~transformers.TrainerCallback`], *optional*): + List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed + in [here](https://huggingface.co/docs/transformers/main_classes/callback). + + If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`] + method. + optimizers (`tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None]`, *optional*, defaults to `(None, None)`): + A tuple containing the optimizer and the scheduler to use. Will default to an instance of `AdamW` on your + model and a scheduler given by [`~transformers.get_linear_schedule_with_warmup`] controlled by `args`. + tools (list of `Callable`, *optional*): + A list of callable tool functions (sync or async) that the model can invoke during generation. Each tool + should be a standard Python function with properly type-hinted arguments and return values, and a + Google-style docstring describing its purpose, arguments, and return value. For more details, see: + https://huggingface.co/docs/transformers/en/chat_extras#passing-tools. The model uses the function's name, + type hints, and docstring to determine how to call it. Ensure that the model's chat template supports tool + use and that it has been fine-tuned for tool calling. + environment_factory (`EnvironmentFactory`, *optional*): + A callable that creates and returns an environment instance. The environment class should define methods + that can be invoked as tools during generation. Each method should comply with the same requirements as the + `tools` described above. If `environment_factory` is provided, an instance of the environment is created + for each generation in the batch, allowing for parallel and independent interactions. The environment must + also implement a callable `reset` method that can be used to reset state between generations. The `reset` + method should return either `None` or a string: when it returns a string, that string is appended to the + last user message before generation. This feature is experimental and may change or be removed at any time + without prior notice. + rollout_worker (`RolloutWorkerProtocol`, *optional*): + Custom rollout worker implementing [`RolloutWorkerProtocol`]. If `None`, a default [`AsyncRolloutWorker`] + is created, which spawns a CUDA-free child process and scores completions with the trainer's + `reward_funcs`. Pass a custom worker to plug in a different rollout/scoring backend instead — for example, + one that runs reward models on their own GPUs. + """ + + _tag_names = ["trl", "async-grpo"] + _name = "AsyncGRPO" + _paper = { + "title": "DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models", + "id": "2402.03300", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @article{shao2024deepseekmath, + title = {{DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models}}, + author = {Zhihong Shao and Peiyi Wang and Qihao Zhu and Runxin Xu and Junxiao Song and Mingchuan Zhang and Y. K. Li and Y. Wu and Daya Guo}, + year = 2024, + eprint = {arXiv:2402.03300}, + }"""), + } + + def __init__( + self, + model: str, + reward_funcs: RewardFunc | list[RewardFunc], + args: AsyncGRPOConfig | None = None, + train_dataset: Dataset | IterableDataset | None = None, + processing_class: PreTrainedTokenizerBase | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None), + tools: list[Callable] | None = None, + environment_factory: EnvironmentFactory | None = None, + rollout_worker: RolloutWorkerProtocol | None = None, + ): + self.args = args or AsyncGRPOConfig() + + # Training arguments + self.epsilon_low = self.args.epsilon + self.epsilon_high = self.args.epsilon_high + self.temperature = self.args.temperature + + # Model + model_name = model + model = AutoModelForCausalLM.from_pretrained(model, device_map=None, dtype=torch.float32) + + if self.args.use_liger_kernel: + raise NotImplementedError("`use_liger_kernel` is not supported yet.") + + patch_chunked_lm_head(model, chunk_size=8192, temperature=self.temperature) + + # Processing class + if processing_class is None: + processing_class = AutoTokenizer.from_pretrained(model_name) + if processing_class.pad_token is None: + processing_class.pad_token = processing_class.eos_token + + # Reward functions + if not isinstance(reward_funcs, list): + reward_funcs = [reward_funcs] + + # Initialize the Trainer + super().__init__( + model=model, + args=self.args, + train_dataset=train_dataset, + processing_class=processing_class, + callbacks=callbacks, + optimizers=optimizers, + compute_loss_func="non-None value to disable scaling", + ) + # Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the + # model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set + # self.model_accepts_loss_kwargs to False to enable scaling. + self.model_accepts_loss_kwargs = False + + # Infer max_steps from dataset size when not explicitly set. This must happen after super().__init__() + # so that self.accelerator.num_processes is available for the correct calculation. + samples_per_step = ( + self.args.per_device_train_batch_size + * self.args.gradient_accumulation_steps + * self.accelerator.num_processes + ) + if self.args.max_steps <= 0 and train_dataset is not None and hasattr(train_dataset, "__len__"): + samples_per_epoch = len(train_dataset) * self.args.num_generations + self.args.max_steps = int(self.args.num_train_epochs * samples_per_epoch / samples_per_step) + + # Infer max_inflight_tasks when not explicitly set. Generating more samples than the trainer can consume + # before they become stale is wasteful. The useful upper bound is max_staleness * samples_per_step. + if self.args.max_inflight_tasks < 0: + self.args.max_inflight_tasks = self.args.max_staleness * samples_per_step + logger.info( + f"max_inflight_tasks set to {self.args.max_inflight_tasks} " + f"(max_staleness={self.args.max_staleness} × samples_per_step={samples_per_step})" + ) + + # Initialize the metrics + self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)} + self._train_tokens_start_time = None + self.model_version = 0 + # Create worker and queue on rank 0 + if self.accelerator.is_main_process: + if self.train_dataset is None: + raise ValueError("train_dataset is required for AsyncGRPOTrainer") + + if rollout_worker is not None: + # Use the injected worker (e.g. a stub in tests). The queue is owned by the worker. + # Weight transfer is also expected to be wired by the test fixture (or left as None + # if the stub doesn't sync to a real vLLM). + self.rollout_worker = rollout_worker + self.weight_transfer = None + else: + # Collect weight metadata once — names/dtypes/shapes are fixed for the lifetime of training. + # DTensor.shape returns the global shape without triggering any all-gather. + weight_names, weight_dtype_names, weight_shapes = [], [], [] + for name, param in model.named_parameters(): + # DDP/FSDP1 wrapping, avoids vllm module not exist error + name = name.removeprefix("module.") + weight_names.append(name) + weight_dtype_names.append(str(param.dtype).split(".")[-1]) + weight_shapes.append(list(param.shape)) + self.weight_transfer = WeightTransferClient( + vllm_server_url=self.args.vllm_server_base_url, + server_timeout=self.args.vllm_server_timeout, + weight_update_info={ + "names": weight_names, + "dtype_names": weight_dtype_names, + "shapes": weight_shapes, + "packed": True, + }, + ) + self.rollout_worker = AsyncRolloutWorker( + model_name=model_name, + dataset=train_dataset, + reward_funcs=reward_funcs, + processing_class=processing_class, + tools=tools, + environment_factory=environment_factory, + num_generations=self.args.num_generations, + max_inflight_tasks=self.args.max_inflight_tasks, + queue_maxsize=self.args.queue_maxsize, + vllm_server_url=self.args.vllm_server_base_url, + max_tokens=self.args.max_completion_length, + temperature=self.args.temperature, + request_timeout=self.args.request_timeout, + chat_template_kwargs=self.args.chat_template_kwargs, + max_tool_calling_iterations=self.args.max_tool_calling_iterations, + log_completions=self.args.log_completions, + num_completions_to_print=self.args.num_completions_to_print, + ) + # TODO(@aminediro): decide if this is returned by the worker or common API that is passed to the worker later. + self.rollout_queue = self.rollout_worker.rollout_buffer + else: + self.rollout_queue = None + self.rollout_worker = None + self.weight_transfer = None + + # Add callbacks. Registration order matters: weight sync first, then worker start. + self.add_callback(_InitialWeightSyncCallback(self)) + self.add_callback(_StartRolloutWorkerCallback(self)) + self.add_callback(StepIntervalCallback(self._sync_weight, self.args.weight_sync_steps)) + + def get_train_dataloader(self) -> DataLoader: + if self.accelerator.is_main_process: + dataset = RolloutQueueDataset( + rollout_queue=self.rollout_queue, + model_version_fn=lambda: self.model_version, + check_health_fn=self.rollout_worker.check_health, + stale_after_s=self.args.heartbeat_stale_after_s, + max_staleness=self.args.max_staleness, + ) + else: + dataset = _EmptyIterableDataset() + + return self.accelerator.prepare( + DataLoader( + dataset, + batch_size=self.args.per_device_train_batch_size * self.accelerator.num_processes, + collate_fn=DataCollatorForRollout(self.processing_class.pad_token_id), + num_workers=0, + # NOTE(@aminediro): + # dispatch_batches = True for DataLoader whose underlying dataset is an IterableDataset + # dataloader prepared by the Accelerator is only iterated through on the main process a + ) + ) + + def _set_signature_columns_if_needed(self): + # If `self.args.remove_unused_columns` is True, non-signature columns are removed. + # By default, this method sets `self._signature_columns` to the model's expected inputs (usually, "input_ids" + # and "attention_mask"). In AsyncGRPOTrainer, we need additional columns ("completion_mask", "old_log_probs", + # "advantages", "global_n_tokens") to compute the loss, hence the override. + if self._signature_columns is None: + self._signature_columns = [ + "input_ids", + "attention_mask", + "completion_mask", + "old_log_probs", + "advantages", + "global_n_tokens", + "metrics", + ] + + def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): + input_ids = inputs["input_ids"] + attention_mask = inputs["attention_mask"] + completion_mask = inputs["completion_mask"] + old_log_probs = inputs["old_log_probs"] + advantages = inputs["advantages"] + + # The collator pads to the global batch max length (across all ranks). After DataLoaderDispatcher slices and + # sends rows to each rank, the local slice is still padded to that global max. Truncate to the longest real + # sequence in this rank's slice so we don't run the forward pass over pure-padding columns. + local_max_len = attention_mask.sum(dim=1).max() + input_ids = input_ids[:, :local_max_len] + attention_mask = attention_mask[:, :local_max_len] + completion_mask = completion_mask[:, :local_max_len] + old_log_probs = old_log_probs[:, :local_max_len] + + forward_start = time.time() + outputs = model( + input_ids=input_ids, + attention_mask=attention_mask, + labels=input_ids, + completion_mask=completion_mask, + use_cache=False, + ) + log_probs, entropy = outputs["log_probs"], outputs["entropy"] + self._last_forward_time_s = time.time() - forward_start + + completion_mask = completion_mask[:, 1:] + old_log_probs = old_log_probs[:, 1:] + advantages = advantages.unsqueeze(1) + log_ratio = log_probs - old_log_probs + ratio = torch.exp(log_ratio) + clipped = torch.clamp(ratio, 1 - self.epsilon_low, 1 + self.epsilon_high) + per_token_loss = -torch.min(ratio * advantages, clipped * advantages) + + # DDP/FSDP averages gradients across ranks (world_size). + # To get correct per-token normalization we scale by 1/tokens_per_rank + # = world_size / global_n_tokens, so after DDP averaging the effective + loss = (per_token_loss * completion_mask).sum() + global_n_tokens = inputs["global_n_tokens"][0] + world_size = self.accelerator.num_processes + tokens_per_rank = (global_n_tokens / world_size).clamp(min=1.0) + loss = loss / tokens_per_rank.to(torch.float32) + # For DAPO, we would scale like this instead: + # loss = loss / max(per_token_loss.size(0), 1) + loss = loss / self.current_gradient_accumulation_steps + + with torch.no_grad(): + valid_mask = completion_mask > 0 + local_count = valid_mask.sum().float() + + local_ratio_sum = ( + ratio[valid_mask].sum() if valid_mask.any() else torch.zeros((), device=completion_mask.device) + ) + # Approx KL: http://joschu.net/blog/kl-approx.html + local_kl_sum = ( + ((ratio[valid_mask] - 1) - log_ratio[valid_mask]).sum() + if valid_mask.any() + else torch.zeros((), device=completion_mask.device) + ) + + local_entropy_sum = ( + entropy[valid_mask].sum() if valid_mask.any() else torch.zeros((), device=completion_mask.device) + ) + + clipped = (ratio < 1 - self.epsilon_low) | (ratio > 1 + self.epsilon_high) + local_clip_sum = ( + clipped[valid_mask].float().sum() + if valid_mask.any() + else torch.zeros((), device=completion_mask.device) + ) + + # Batch all-reduce: [ratio_sum, kl_sum, entropy_sum, clip_sum, count] + stats = torch.stack([local_ratio_sum, local_kl_sum, local_entropy_sum, local_clip_sum, local_count]) + stats = self.accelerator.reduce(stats, reduction="sum") + global_ratio_sum, global_kl_sum, global_entropy_sum, global_clip_sum, global_count = stats.unbind(0) + self._metrics["train"]["ratio"].append((global_ratio_sum / global_count).item()) + self._metrics["train"]["kl"].append((global_kl_sum / global_count).item()) + self._metrics["train"]["entropy"].append((global_entropy_sum / global_count).item()) + self._metrics["train"]["clip_ratio"].append((global_clip_sum / global_count).item()) + + # Logging metrics from the rollout worker (reward, reward_std, etc.). + # inputs["metrics"] is a dict of 1D tensors keyed by metric name. + sample_metrics = inputs["metrics"] # dict[str, Tensor(shape=[B_local])] + keys = list(sample_metrics.keys()) + device = completion_mask.device + n_samples = torch.tensor(completion_mask.shape[0], dtype=torch.float32, device=device) + if keys: + # nan-aware per key: unscorable samples carry NaN, so a plain .sum() would poison the whole metric. + local_sums = torch.stack([torch.nansum(sample_metrics[k].to(device)) for k in keys]) + local_counts = torch.stack( + [(~torch.isnan(sample_metrics[k].to(device))).sum().to(torch.float32) for k in keys] + ) + stats = torch.cat([local_sums, local_counts]) + stats = self.accelerator.reduce(stats, reduction="sum") + n = len(keys) + global_sums, global_counts = stats[:n], stats[n:] + for k, global_sum, global_count in zip(keys, global_sums, global_counts, strict=True): + metric = (global_sum / global_count).item() if global_count > 0 else float("nan") + self._metrics["train"][k].append(metric) + + completion_length = completion_mask.sum(dim=1).float() + length_stats = torch.stack([completion_length.sum(), n_samples]) + length_stats = self.accelerator.reduce(length_stats, reduction="sum") + self._metrics["train"]["completions/mean_length"].append((length_stats[0] / length_stats[1]).item()) + + # Training throughput: completion tokens consumed by this training step per second. + now = time.time() + if self._train_tokens_start_time is not None: + train_elapsed = now - self._train_tokens_start_time + if train_elapsed > 0: + self._metrics["train"]["training_tok/s"].append(global_n_tokens.item() / train_elapsed) + self._train_tokens_start_time = now + + self._metrics["train"]["forward_time_s"].append(self._last_forward_time_s) + # NOTE: in dynamic mbs setup, we would need to agg across DP ranks. + self._metrics["train"]["train_seq_len"].append(float(local_max_len)) + return loss + + def log(self, logs: dict[str, float], start_time: float | None = None) -> None: + mode = "train" if self.model.training else "eval" + # Average the metrics + metrics = {} + for key, val in self._metrics[mode].items(): + # Filter out NaN values before averaging. A reward function that returns None for all samples + # in a batch produces NaN for that batch's metric. With logging_steps > 1, a naive sum()/len() + # would let a single NaN contaminate valid data from other batches. Only return None when no + # valid values remain (e.g. JSON loggers crash on float NaN). + valid = [v for v in val if not math.isnan(v)] + metrics[key] = sum(valid) / len(valid) if valid else None + + # This method can be called both in training and evaluation. When called in evaluation, the keys in `logs` + # start with "eval_". We need to add the prefix "eval_" to the keys in `metrics` to match the format. + if mode == "eval": + metrics = {f"eval_{key}": val for key, val in metrics.items()} + + logs.update(metrics) + super().log(logs, start_time) + self._metrics[mode].clear() + + def _streaming_iter(self): + # Iterate parameters one at a time. For FSDP2 (DTensor), full_tensor() all-gathers just this parameter across + # FSDP ranks, then frees it once the generator advances — avoiding materializing the full model in memory. + device = self.accelerator.device + for name, param in self.model.named_parameters(): + name = name.removeprefix("module.") # DDP/FSDP1 wrapping + full = param.full_tensor() if isinstance(param, DTensor) else param.detach() + if full.device != device: + full = full.to(device) + yield name, full + + def _sync_weight(self): + t0 = time.time() + logger.info("Weight sync: pausing vLLM...") + if self.accelerator.is_main_process and self.weight_transfer: + self.weight_transfer.pause() + t_pause = time.time() + logger.info(f"Weight sync: pause took {t_pause - t0:.1f}s, waiting for all ranks...") + + self.accelerator.wait_for_everyone() + t_barrier = time.time() + + logger.info(f"Weight sync: transferring weights... (barrier took {t_barrier - t_pause:.1f}s)") + if self.accelerator.is_main_process and self.weight_transfer: + self.weight_transfer.send_weights(self._streaming_iter()) + else: + # Non-rank-0 processes must still participate in full_tensor() collectives for FSDP2. + for _ in self._streaming_iter(): + pass + t_transfer = time.time() + + self.accelerator.wait_for_everyone() + + logger.info(f"Weight sync: resuming vLLM... (transfer took {t_transfer - t_barrier:.1f}s)") + if self.accelerator.is_main_process: + if self.weight_transfer: + self.weight_transfer.resume() + self.model_version += 1 + if self.rollout_worker: + self.rollout_worker.update_model_version(self.model_version) + weight_sync_time_s = time.time() - t0 + self._metrics["train"]["weight_sync_time_s"].append(weight_sync_time_s) + logger.info(f"Weight sync: done. Total {weight_sync_time_s:.1f}s") + + def _inner_training_loop(self, *args, **kwargs): + try: + return super()._inner_training_loop(*args, **kwargs) + finally: + if self.accelerator.is_main_process: + if self.rollout_worker: + self.rollout_worker.stop() + if self.weight_transfer: + self.weight_transfer.destroy() diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/async_grpo/async_rollout_worker.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/async_grpo/async_rollout_worker.py new file mode 100644 index 0000000000000000000000000000000000000000..b1cd13ea7ca39339de886a1d2dd7e5da8b30aca6 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/async_grpo/async_rollout_worker.py @@ -0,0 +1,829 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import asyncio +import inspect +import multiprocessing as mp +import os +import pickle +import queue +import threading +import time +import traceback +from collections.abc import Awaitable, Callable, Iterator +from dataclasses import dataclass +from multiprocessing.queues import Queue as MPQueue +from multiprocessing.sharedctypes import Synchronized as MPValue +from multiprocessing.synchronize import Event as MPEvent +from typing import Any, TypeAlias + +import aiohttp +import numpy as np +from accelerate.logging import get_logger +from datasets import Dataset +from transformers import PreTrainedTokenizerBase + +from trl.chat_template_utils import ( + add_response_schema, + get_training_chat_template, + is_chat_template_prefix_preserving, + parse_response, +) +from trl.import_utils import is_vllm_available +from trl.trainer.utils import print_prompt_completions_sample + + +logger = get_logger(__name__) + +Messages: TypeAlias = list[dict[str, str]] + +_RETRYABLE_HTTP_ERRORS = (aiohttp.ClientError, asyncio.TimeoutError, TimeoutError, ConnectionResetError) + + +async def _retry_on_http_error(coro_factory: Callable[[], Awaitable], *, label: str, max_attempts: int = 1): + """Retry an aiohttp coroutine on transport errors with bounded exponential backoff.""" + for attempt in range(max_attempts): + try: + return await coro_factory() + except _RETRYABLE_HTTP_ERRORS as e: + if attempt >= max_attempts - 1: + raise + sleep = min(2 ** min(attempt, 4), 16) + logger.warning(f"{label} failed ({type(e).__name__}: {e}); retry {attempt + 1}/{max_attempts} in {sleep}s") + await asyncio.sleep(sleep) + + +@dataclass(slots=True) +class RolloutGroup: + prompt: Messages + prompt_ids: list[int] + reward_kwargs: dict[str, list[Any]] + completions: list[Messages] + completions_ids: list[list[int]] + completions_logprobs: list[list[float]] + tool_mask: list[list[int]] + tool_call_counts: list[int] + tool_failure_counts: list[int] + model_version: int + queued_at: float = 0.0 + + +@dataclass(slots=True) +class RolloutSample: + prompt: Messages + completion: Messages + input_ids: list[int] + completion_mask: list[int] + old_log_probs: list[float] + advantage: float + model_version: int + metrics: dict[str, float] + + +# Env vars the child must drop so accelerate's `PartialState()` initialises in +# single-process mode instead of trying to join the parent's process group. +_CHILD_ENV_TO_STRIP = ( + "RANK", + "WORLD_SIZE", + "LOCAL_RANK", + "LOCAL_WORLD_SIZE", + "MASTER_ADDR", + "MASTER_PORT", + "GROUP_RANK", + "ROLE_RANK", + "ROLE_WORLD_SIZE", + "TORCHELASTIC_RUN_ID", + "TORCHELASTIC_RESTART_COUNT", + "TORCHELASTIC_MAX_RESTARTS", + "TORCH_FR_DUMP_TEMP_FILE", + "NCCL_DEBUG_FILE", +) + + +def _scrub_child_env() -> None: + # The child has no business touching CUDA; any library that imports torch + # and lazily probes devices would race the parent's allocator. + os.environ["CUDA_VISIBLE_DEVICES"] = "" + for k in _CHILD_ENV_TO_STRIP: + os.environ.pop(k, None) + + +def _spawn_stop_watcher(rollout_loop: "_AsyncRolloutLoop", stop_event: MPEvent) -> None: + # Daemon thread that translates the parent's mp.Event into the child's + # asyncio.Event so _run_loops breaks out of its gather. + def _watch(): + stop_event.wait() + try: + rollout_loop._loop.call_soon_threadsafe(rollout_loop._stop_event.set) + except RuntimeError: + # Loop already closed (run() returned before stop fired). Nothing to do. + pass + + threading.Thread(target=_watch, daemon=True, name="grpo-mp-stop-watcher").start() + + +def _child_main( + loop_kwargs: dict[str, Any], + samples_queue: MPQueue, + model_version_value: MPValue, + stop_event: MPEvent, + child_ready_event: MPEvent, + heartbeat_value: MPValue, + failed_event: MPEvent, + exception_info_queue: MPQueue, +) -> None: + _scrub_child_env() + # `accelerate.logging.get_logger` requires `PartialState()` to have been called. + from accelerate.state import PartialState + + PartialState() + + rollout_loop = _AsyncRolloutLoop( + **loop_kwargs, + rollout_buffer=samples_queue, + model_version_value=model_version_value, + heartbeat_value=heartbeat_value, + failed_event=failed_event, + exception_info_queue=exception_info_queue, + ) + child_ready_event.set() + _spawn_stop_watcher(rollout_loop, stop_event) + try: + rollout_loop.run() + except Exception: + traceback.print_exc() + raise + + +class _AsyncRolloutLoop: + """Asyncio generate and score loops. Lives entirely inside the spawned child process. + + Owns the tokenizer, dataset iterator, reward funcs, environments, and the asyncio event loop. Talks to vLLM via + `/v1/completions`. Pushes scored `RolloutSample`s into the shared `mp.Queue` (`rollout_buffer`); reads the bumped + policy version from the shared `mp.Value` (`model_version_value`). + """ + + def __init__( + self, + *, + model_name: str, + dataset: Dataset, + reward_funcs: list[Callable[..., list[float]]], + processing_class: PreTrainedTokenizerBase, + rollout_buffer: MPQueue, + model_version_value: MPValue, + heartbeat_value: MPValue, + failed_event: MPEvent, + exception_info_queue: MPQueue, + tools: list[Callable] | None = None, + environment_factory: Callable[[], object] | None = None, + num_generations: int = 8, + max_inflight_tasks: int = 128, + queue_maxsize: int = 0, + vllm_server_url: str = "http://localhost:8000", + max_tokens: int = 32, + temperature: float = 1.0, + request_timeout: int = 120, + chat_template_kwargs: dict[str, Any] | None = None, + max_tool_calling_iterations: int | None = None, + log_completions: bool = False, + num_completions_to_print: int = 3, + ): + self.model_name = model_name + self.dataset = dataset + self._dataset_iter = iter(dataset) + self.reward_funcs = reward_funcs + self.reward_func_names = [f.__name__ for f in reward_funcs] + self.tokenizer = add_response_schema(processing_class) + self.rollout_buffer = rollout_buffer # shared mp.Queue + self._model_version_value = model_version_value # shared mp.Value + self._heartbeat_value = heartbeat_value # shared mp.Value('d'); wall-clock seconds + self._failed_event = failed_event # shared mp.Event + self._exception_info_queue = exception_info_queue # shared mp.Queue(maxsize=1) + + self.num_generations = num_generations + self.max_inflight_tasks = max_inflight_tasks + self.queue_maxsize = queue_maxsize + self.max_tokens = max_tokens + self.temperature = temperature + self.request_timeout = request_timeout + self.chat_template_kwargs = chat_template_kwargs or {} + self.max_tool_calling_iterations = max_tool_calling_iterations + self.log_completions = log_completions + self.num_completions_to_print = num_completions_to_print + self.vllm_server_url = vllm_server_url.rstrip("/") + + self.environments = None + environment_methods = [[] for _ in range(max_inflight_tasks)] + if environment_factory is not None: + self.environments = [environment_factory() for _ in range(max_inflight_tasks)] + for i, environment in enumerate(self.environments): + has_reset = False + for name, member in inspect.getmembers(environment, predicate=inspect.ismethod): + if name == "reset": + has_reset = True + elif not name.startswith("_"): + environment_methods[i].append(member) + if not has_reset: + raise ValueError( + "Each environment instance returned by `environment_factory` must define `reset`." + ) + + base_tools = tools or [] + self._sync_tool_dicts = [{} for _ in range(max_inflight_tasks)] + for i in range(max_inflight_tasks): + for tool in base_tools + (environment_methods[i] if self.environments is not None else []): + if inspect.iscoroutinefunction(tool): + raise ValueError("Asynchronous tools are not supported yet.") + self._sync_tool_dicts[i][tool.__name__] = tool + self.tools = base_tools + (environment_methods[0] if self.environments is not None else []) + + # The chat template must be prefix-preserving in multi-turn training; if the tokenizer's + # template isn't, swap in a training-safe one. + if self.tools and not is_chat_template_prefix_preserving(self.tokenizer): + self.chat_template = get_training_chat_template(self.tokenizer) + else: + self.chat_template = None + + self._groups_to_score: asyncio.Queue[RolloutGroup | None] = asyncio.Queue(maxsize=16) + self._total_completion_tokens = 0 + self._total_groups_scored = 0 + self._generation_start_time: float | None = None + self.session: aiohttp.ClientSession | None = None + + self._loop = asyncio.new_event_loop() + self._stop_event = asyncio.Event() + + @property + def model_version(self) -> int: + return int(self._model_version_value.value) + + def run(self) -> None: + asyncio.set_event_loop(self._loop) + try: + self._loop.run_until_complete(self._run_loops(stop_event=self._stop_event)) + except BaseException as e: + # Push pickle-safe exception info to the parent before setting _failed_event, so a + # reader that sees the event is guaranteed to also see the info on the queue. + info = (type(e).__name__, str(e), traceback.format_exc()) + try: + self._exception_info_queue.put_nowait(info) + except Exception: + pass # queue full (parent hasn't drained a prior failure), best-effort put + self._failed_event.set() + logger.exception(f"Worker process failed: {e}") + raise + finally: + self._loop.close() + + async def _run_loops(self, stop_event: asyncio.Event) -> None: + async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(limit=self.max_inflight_tasks)) as session: + self.session = session + logger.info( + f"vllm worker started: num_generations={self.num_generations}, " + f"max_inflight_tasks={self.max_inflight_tasks}" + ) + await asyncio.gather( + asyncio.create_task(self._generate_loop(stop_event=stop_event)), + asyncio.create_task(self._score_loop(stop_event=stop_event)), + ) + + async def _generate_loop(self, stop_event: asyncio.Event) -> None: + pending_groups: dict[int, RolloutGroup] = {} + pending_completed: dict[int, int] = {} + inflight_tasks: dict[asyncio.Task, tuple[int, int]] = {} + free_slots = set(range(self.max_inflight_tasks)) + work_iter = self._repeat_iterator() + + self._generation_start_time = time.monotonic() + try: + while True: + # Wall-clock for cross-process comparison; parent uses time.time() in check_health. + self._heartbeat_value.value = time.time() + while free_slots and not stop_event.is_set(): + group_id, row = next(work_iter) + if group_id not in pending_groups: + prompt = row["prompt"] + prompt_ids = self.tokenizer.apply_chat_template( + prompt, + return_dict=False, + add_generation_prompt=True, + tools=self.tools or None, # `or None`: Llama bug: renders tool boilerplate for tools=[] + chat_template=self.chat_template, + **self.chat_template_kwargs, + ) + reward_kwargs = { + key: [row[key]] * self.num_generations + for key in row + if key not in {"prompt", "completion", "completion_ids"} + } + pending_groups[group_id] = RolloutGroup( + prompt=prompt, + prompt_ids=prompt_ids, + reward_kwargs=reward_kwargs, + completions=[], + completions_ids=[], + completions_logprobs=[], + tool_mask=[], + tool_call_counts=[], + tool_failure_counts=[], + model_version=self.model_version, + ) + pending_completed[group_id] = 0 + + slot = free_slots.pop() + if self.environments is not None: + self.environments[slot].reset(**row) + + task = asyncio.create_task( + self._generate_one(pending_groups[group_id].prompt, tool_dict=self._sync_tool_dicts[slot]) + ) + inflight_tasks[task] = (group_id, slot) + + if not inflight_tasks: + if stop_event.is_set(): + return + await asyncio.sleep(0.01) + continue + + done, _ = await asyncio.wait(inflight_tasks, return_when=asyncio.FIRST_COMPLETED, timeout=0.1) + if not done: + continue + + for task in done: + group_id, slot = inflight_tasks.pop(task) + free_slots.add(slot) + if task.exception() is not None: + raise task.exception() + + ( + completion, + completion_ids, + completion_logprobs, + tool_mask, + tool_call_count, + tool_failure_count, + ) = task.result() + group = pending_groups[group_id] + group.completions.append(completion) + group.completions_ids.append(completion_ids) + group.completions_logprobs.append(completion_logprobs) + group.tool_mask.append(tool_mask) + group.tool_call_counts.append(tool_call_count) + group.tool_failure_counts.append(tool_failure_count) + self._total_completion_tokens += sum(tool_mask) + pending_completed[group_id] += 1 + + if pending_completed[group_id] == self.num_generations: + group.queued_at = time.monotonic() + while True: + try: + self._groups_to_score.put_nowait(group) + break + except asyncio.QueueFull: + if stop_event.is_set(): + return + await asyncio.sleep(0.1) + del pending_groups[group_id] + del pending_completed[group_id] + finally: + for task in inflight_tasks: + task.cancel() + if inflight_tasks: + await asyncio.gather(*inflight_tasks, return_exceptions=True) + try: + self._groups_to_score.put_nowait(None) + except asyncio.QueueFull: + pass + + async def _score_loop(self, stop_event: asyncio.Event) -> None: + while not stop_event.is_set(): + self._heartbeat_value.value = time.time() + t_wait = time.monotonic() + try: + group = await asyncio.wait_for(self._groups_to_score.get(), timeout=0.5) + except asyncio.TimeoutError: + continue + if group is None: + return + score_queue_wait = time.monotonic() - t_wait + wait_scoring = time.monotonic() - group.queued_at + + if score_queue_wait > 0.5: + logger.info(f"[score] waited {score_queue_wait:.1f}s for a group to score") + + t0 = time.monotonic() + samples = await self._score_group(group) + scoring_time = time.monotonic() - t0 + logger.info( + f"[score] scored {len(samples)} samples in {scoring_time:.2f}s, " + f"buffer_qsize={self.rollout_buffer.qsize()}" + ) + + self._compute_rollout_metrics(samples, scoring_time, wait_scoring) + + if self.log_completions and samples: + print_prompt_completions_sample( + prompts=[s.prompt for s in samples], + completions=[s.completion for s in samples], + rewards={"reward": [s.metrics["reward"] for s in samples]}, + advantages=[s.advantage for s in samples], + step=self._total_groups_scored, + num_samples=self.num_completions_to_print, + ) + self._total_groups_scored += 1 + + for sample in samples: + while True: + try: + self.rollout_buffer.put_nowait(sample) + break + except queue.Full: + if stop_event.is_set(): + return + logger.info( + f"[score] rollout buffer full (maxsize={self.queue_maxsize}), " + "waiting for trainer to consume..." + ) + await asyncio.sleep(0.1) + + def _compute_rollout_metrics(self, samples: list[RolloutSample], scoring_time: float, wait_scoring: float) -> None: + assert self._generation_start_time is not None + elapsed = time.monotonic() - self._generation_start_time + generation_tok_per_sec = self._total_completion_tokens / elapsed if elapsed > 0 else 0.0 + for sample in samples: + sample.metrics["generation_tok_per_s"] = generation_tok_per_sec + sample.metrics["scoring_time_ms"] = scoring_time * 1000 + sample.metrics["wait_scoring_ms"] = wait_scoring * 1000 + sample.metrics["buffer_qsize"] = self.rollout_buffer.qsize() + + def _repeat_iterator(self) -> Iterator[tuple[int, dict[str, Any]]]: + group_id = 0 + while True: + try: + row = next(self._dataset_iter) + except StopIteration: + self._dataset_iter = iter(self.dataset) + row = next(self._dataset_iter) + for _ in range(self.num_generations): + yield group_id, row + group_id += 1 + + async def _generate_one( + self, prompt: Messages, tool_dict: dict[str, Callable] + ) -> tuple[list[dict[str, str]], list[int], list[float], list[int], int, int]: + completion, completion_ids, completion_logprobs, tool_mask = [], [], [], [] + tool_call_count = 0 + tool_failure_count = 0 + iteration_num = 0 + max_iterations = self.max_tool_calling_iterations + prompt_ids = self.tokenizer.apply_chat_template( + prompt, + return_dict=False, + add_generation_prompt=True, + tools=self.tools or None, + chat_template=self.chat_template, + **self.chat_template_kwargs, + ) + while True: + turn_ids, turn_logprobs = await self._generate_one_turn(prompt_ids) + assistant_message = parse_response(self.tokenizer, turn_ids) + completion.append(assistant_message) + completion_ids.extend(turn_ids) + completion_logprobs.extend(turn_logprobs) + tool_mask.extend([1] * len(turn_ids)) + tool_calls = assistant_message.get("tool_calls") + if tool_calls is None or (max_iterations is not None and iteration_num >= max_iterations): + return completion, completion_ids, completion_logprobs, tool_mask, tool_call_count, tool_failure_count + + tool_messages, n_calls, n_failures = self._execute_tool_calls(tool_calls, tool_dict) + tool_call_count += n_calls + tool_failure_count += n_failures + completion.extend(tool_messages) + suffix_ids = self._get_tool_suffix_ids(tool_messages) + completion_ids.extend(suffix_ids) + completion_logprobs.extend([0.0] * len(suffix_ids)) + tool_mask.extend([0] * len(suffix_ids)) + prompt_ids = prompt_ids + turn_ids + suffix_ids + iteration_num += 1 + + def _get_tool_suffix_ids(self, tool_messages: list[dict[str, Any]]) -> list[int]: + # Use the real tool name: some templates (e.g. GPT-OSS) derive the tool response header from + # the assistant's tool call name. + dummy_tool_calls = [{"type": "function", "function": {"name": tool_messages[0]["name"], "arguments": {}}}] + dummy_messages = [ + {"role": "user", "content": "dummy"}, + # `content: ""` is required: VLM processors crash on tokenize=True without it + # (KeyError in processing_utils.py, see huggingface/transformers#45290). + {"role": "assistant", "content": "", "tool_calls": dummy_tool_calls}, + ] + prefix_ids = self.tokenizer.apply_chat_template( + dummy_messages, + add_generation_prompt=False, + tokenize=True, + chat_template=self.chat_template, + return_dict=False, + **self.chat_template_kwargs, + ) + full_ids = self.tokenizer.apply_chat_template( + dummy_messages + tool_messages, + add_generation_prompt=True, + tokenize=True, + chat_template=self.chat_template, + return_dict=False, + **self.chat_template_kwargs, + ) + # Some chat templates (Qwen3/Qwen3.5) render "...<|im_end|>\n" after assistant/tool blocks. + # Align the slicing boundary to EOS, not EOS + newline. + eos_positions = [i for i, tok_id in enumerate(prefix_ids) if tok_id == self.tokenizer.eos_token_id] + if eos_positions: + prefix_ids = prefix_ids[: eos_positions[-1] + 1] + if full_ids[: len(prefix_ids)] != prefix_ids: + raise ValueError("Unexpected tokenization: the EOS-trimmed prefix IDs are not a prefix of the full IDs.") + return full_ids[len(prefix_ids) :] + + def _execute_tool_calls( + self, tool_calls: list[dict[str, Any]], tool_dict: dict[str, Callable] + ) -> tuple[list[dict[str, str]], int, int]: + tool_messages = [] + n_calls = 0 + n_failures = 0 + for tool_call in tool_calls: + n_calls += 1 + function = tool_call["function"] + name = function["name"] + try: + arguments = function.get("arguments", {}) + result = tool_dict[name](**arguments) + except Exception as error: + n_failures += 1 + result = {"error": str(error)} + tool_messages.append({"role": "tool", "name": name, "content": str(result)}) + return tool_messages, n_calls, n_failures + + async def _generate_one_turn(self, prompt_ids: list[int]) -> tuple[list[int], list[float]]: + payload = { + "model": self.model_name, + "prompt": prompt_ids, + "max_tokens": self.max_tokens, + "temperature": self.temperature, + "n": 1, + "return_token_ids": True, + "logprobs": 0, + } + output = await _retry_on_http_error( + lambda: self._post("/v1/completions", payload, self.request_timeout), + max_attempts=30, + label="vllm /v1/completions", + ) + choice = output["choices"][0] + return choice["token_ids"], choice["logprobs"]["token_logprobs"] + + async def _score_group(self, group: RolloutGroup) -> list[RolloutSample]: + kwargs = dict( + completions=group.completions, + prompt=group.prompt, + prompts=[group.prompt] * len(group.completions), + completion_ids=group.completions_ids, + **group.reward_kwargs, + ) + all_rewards = await asyncio.gather( + *[ + reward_func(**kwargs) + if inspect.iscoroutinefunction(reward_func) + else asyncio.to_thread(reward_func, **kwargs) + for reward_func in self.reward_funcs + ] + ) + + # Reward funcs may return None per-sample (unparseable gold). Convert to NaN. A completion + # for which every func returned None is unscorable: nansum would give 0 and the row would + # pull the policy away from actually-correct answers. + # Mark such rows NaN, then compute advantage on the scorable subset only. + all_rewards = [[r if r is not None else float("nan") for r in row] for row in all_rewards] + arr = np.array(all_rewards, dtype=float) + all_nan_mask = np.all(np.isnan(arr), axis=0) + rewards = np.nansum(arr, axis=0) + rewards[all_nan_mask] = np.nan + + scored_mask = ~np.isnan(rewards) + # NOTE: for NaN reward we set advantage to 0 ! + advantages = np.zeros_like(rewards) + if scored_mask.any(): + scored = rewards[scored_mask] + advantages[scored_mask] = (scored - scored.mean()) / (scored.std() + 1e-8) + reward_mean = float(scored.mean()) + reward_std = float(scored.std()) + else: + reward_mean = reward_std = float("nan") + logger.info(f"Rollout metrics: reward_mean={reward_mean:.4f}, reward_std={reward_std:.4f}") + + total_calls = sum(group.tool_call_counts) + tool_metrics = ( + [ + { + "tools/call_frequency": float(n_calls), + "tools/failure_frequency": (n_failures / n_calls) if n_calls > 0 else 0.0, + } + for n_calls, n_failures in zip(group.tool_call_counts, group.tool_failure_counts, strict=True) + ] + if total_calls > 0 + else [{}] * len(group.completions) + ) + + per_func_rewards = np.array(all_rewards, dtype=float) + return [ + RolloutSample( + prompt=group.prompt, + completion=completion, + input_ids=group.prompt_ids + completion_ids, + completion_mask=[0] * len(group.prompt_ids) + tool_mask, + old_log_probs=[0.0] * len(group.prompt_ids) + logprobs, + advantage=advantage, + model_version=group.model_version, + metrics={ + "reward": float(reward), + "reward_std": reward_std, + **{ + f"rewards/{name}": float(func_reward) + for name, func_reward in zip(self.reward_func_names, per_func_rewards[:, i], strict=True) + }, + **tm, + }, + ) + for i, (completion, completion_ids, logprobs, tool_mask, advantage, reward, tm) in enumerate( + zip( + group.completions, + group.completions_ids, + group.completions_logprobs, + group.tool_mask, + advantages, + rewards, + tool_metrics, + strict=True, + ) + ) + ] + + async def _post(self, path: str, payload: dict, timeout: float, max_retries: int = 3) -> dict: + client_timeout = aiohttp.ClientTimeout(total=timeout) + + async def _do_post(): + async with self.session.post( + f"{self.vllm_server_url}{path}", json=payload, timeout=client_timeout + ) as response: + response.raise_for_status() + content = await response.json() + return content if content else {} + + return await _retry_on_http_error(_do_post, label=f"POST {path}", max_attempts=max_retries) + + +class AsyncRolloutWorker: + """Parent-side controller: spawns a child process running `_AsyncRolloutLoop`. + + The trainer holds this object on rank 0. The child does the actual rollout work; this class only manages lifecycle + (start/stop) and exposes the shared `mp.Queue` (`rollout_buffer`) and `mp.Value` (`model_version`) the trainer + reads/writes. + + Constructor kwargs are forwarded as-is to `_AsyncRolloutLoop` when the child spawns; only `queue_maxsize` and + `child_ready_timeout` are consumed here. Because the child is spawned, every forwarded kwarg is pickled: + `reward_funcs`, `tools`, and `environment_factory` (and anything they close over) must be picklable — module-level + functions, `functools.partial`, or callable instances, never lambdas or closures. `start()` validates this up front + and raises a `TypeError` otherwise. The child also runs with `CUDA_VISIBLE_DEVICES=""`, so GPU reward models + execute on CPU. + """ + + def __init__( + self, + *, + queue_maxsize: int = 0, + child_ready_timeout: int = 300, + **loop_kwargs: Any, + ): + if not is_vllm_available(min_version="0.17.1"): + raise ImportError( + "vLLM >= 0.17.1 is required to use AsyncRolloutWorker. Install it with: pip install 'vllm>=0.17.1'" + ) + ctx = mp.get_context("spawn") + self._mp_ctx = ctx + self.rollout_buffer = ctx.Queue(maxsize=queue_maxsize) + self._model_version_value = ctx.Value("i", 0) + self._stop_event_mp = ctx.Event() + self._child_ready_event = ctx.Event() + # Liveness state shared with the child. Wall-clock seconds because monotonic() is per-process. + self._heartbeat_value = ctx.Value("d", 0.0) + self._failed_event = ctx.Event() + self._exception_info_queue = ctx.Queue(maxsize=1) + # Forwarded verbatim to _AsyncRolloutLoop in the child. queue_maxsize is also + # forwarded — the child reads it for "rollout buffer full" log lines. + loop_kwargs["queue_maxsize"] = queue_maxsize + self._loop_kwargs = loop_kwargs + self._child_ready_timeout = child_ready_timeout + self._process: mp.Process | None = None + + @property + def model_version(self) -> int: + return int(self._model_version_value.value) + + @model_version.setter + def model_version(self, value: int) -> None: + # NOTE(@aminediro) Read/write ops like += are not atomic with mp.Value + with self._model_version_value.get_lock(): + self._model_version_value.value = int(value) + + def update_model_version(self, model_version: int) -> None: + self.model_version = model_version + + def start(self) -> None: + if self._process is not None: + logger.warning("AsyncRolloutWorker.start() called but child process is already running; ignoring.") + return + # Reset so spawn-import latency (~tens of seconds) doesn't immediately trip check_health. + self._heartbeat_value.value = time.time() + try: + pickle.dumps(self._loop_kwargs) + except (pickle.PicklingError, AttributeError, TypeError) as e: + # fails fast with an actionable message instead of an opaque traceback + raise TypeError( + "AsyncRolloutWorker forwards reward_funcs / tools / environment_factory to a spawned " + "child process, so they must be picklable. Lambdas and closures are not: use a " + "module-level function, functools.partial, or a callable class instance instead." + ) from e + self._process = self._mp_ctx.Process( + target=_child_main, + args=( + self._loop_kwargs, + self.rollout_buffer, + self._model_version_value, + self._stop_event_mp, + self._child_ready_event, + self._heartbeat_value, + self._failed_event, + self._exception_info_queue, + ), + name="grpo-rollout-worker-child", + daemon=True, + ) + self._process.start() + logger.info( + f"AsyncRolloutWorker spawned child pid={self._process.pid}; " + f"waiting up to {self._child_ready_timeout}s for the ready signal" + ) + # spawn re-imports torch+transformers+trl+vllm in the child — slow on cold launch. Poll + # liveness so an early crash surfaces immediately instead of after the full timeout. + deadline = time.monotonic() + self._child_ready_timeout + while not self._child_ready_event.wait(timeout=1.0): + if not self._process.is_alive(): + exit_code = self._process.exitcode + self._process = None + raise RuntimeError( + f"AsyncRolloutWorker child exited during init (exitcode={exit_code}). " + "Check the child's stderr for the traceback." + ) + if time.monotonic() >= deadline: + raise RuntimeError( + f"AsyncRolloutWorker child did not signal ready within {self._child_ready_timeout}s." + ) + logger.info("AsyncRolloutWorker child is ready") + + def check_health(self, stale_after_s: float) -> None: + """Raise if the child crashed or hasn't ticked the heartbeat within `stale_after_s`.""" + if self._failed_event.is_set(): + try: + type_name, msg, tb = self._exception_info_queue.get_nowait() + cause = RuntimeError(f"{type_name}: {msg}\n{tb}") + except queue.Empty: + cause = None + raise RuntimeError("Rollout worker child has failed; see chained exception.") from cause + age = time.time() - self._heartbeat_value.value + if age > stale_after_s: + raise RuntimeError(f"Rollout worker heartbeat stale: {age:.0f}s > {stale_after_s:.0f}s; child is hung.") + + def stop(self) -> None: + if self._process is None: + return + logger.info("Stopping AsyncRolloutWorker child process...") + self._stop_event_mp.set() + # If start() raised before Process.start() returned (e.g. pickle failure during spawn), + # _popen is None and .join() would assert — skip cleanly. + if self._process._popen is not None: + self._process.join(timeout=15) + if self._process.is_alive(): + logger.warning("Child did not exit within 15s; terminating.") + self._process.terminate() + self._process.join(timeout=5) + if self._process.is_alive(): + self._process.kill() + self._process = None diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/async_grpo/weight_transfer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/async_grpo/weight_transfer.py new file mode 100644 index 0000000000000000000000000000000000000000..16e0b0646c59ece41797390f995d2a16de3c2634 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/async_grpo/weight_transfer.py @@ -0,0 +1,143 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import threading +import time + +import requests +from accelerate.logging import get_logger + +from trl.import_utils import is_vllm_available + + +if is_vllm_available(min_version="0.22.0"): + from vllm.distributed.weight_transfer.nccl_engine import NCCLTrainerSendWeightsArgs, NCCLWeightTransferEngine + from vllm.utils.network_utils import get_ip, get_open_port + + +logger = get_logger(__name__) + + +class WeightTransferClient: + def __init__( + self, + vllm_server_url: str, + weight_update_info: dict, + server_timeout: float = 240.0, + init_weight_transfer_timeout: int = 1800, + ): + if not is_vllm_available(min_version="0.22.0"): + raise ImportError( + "vLLM >= 0.22.0 is required to use WeightTransferClient. Install it with: pip install 'vllm>=0.22.0'" + ) + self.vllm_server_url = vllm_server_url.rstrip("/") + self.server_timeout = server_timeout + self.init_weight_transfer_timeout = init_weight_transfer_timeout + self._weight_update_info = weight_update_info + self.model_update_group = None + + def _wait_for_server_ready_sync(self, timeout_s: float | None = None, poll_interval_s: float = 2.0) -> None: + timeout_s = timeout_s if timeout_s is not None else self.server_timeout + logger.info(f"Waiting for vLLM server at {self.vllm_server_url} ...") + start = time.time() + while True: + elapsed = time.time() - start + try: + response = requests.get(f"{self.vllm_server_url}/health", timeout=5) + if response.status_code == 200: + logger.info(f"vLLM server ready after {elapsed:.1f}s") + return + except (requests.ConnectionError, requests.Timeout, OSError): + pass + if elapsed >= timeout_s: + raise TimeoutError( + f"Timed out after {timeout_s:.0f}s waiting for vLLM server at {self.vllm_server_url}. " + "Make sure the vLLM server is running and reachable. If the server needs more time to load " + "the model, increase `vllm_server_timeout` in your AsyncGRPOConfig." + ) + if int(elapsed) % 10 < poll_interval_s: + logger.info(f"Still waiting for vLLM server... ({elapsed:.0f}s)") + time.sleep(poll_interval_s) + + def init_weight_transfer(self) -> None: + self._wait_for_server_ready_sync() + response = requests.get(f"{self.vllm_server_url}/get_world_size") + inference_world_size = response.json()["world_size"] + world_size = inference_world_size + 1 + master_address = get_ip() + master_port = get_open_port() + init_info = { + "master_address": master_address, + "master_port": master_port, + "rank_offset": 1, + "world_size": world_size, + } + t_init = threading.Thread( + target=requests.post, + args=(f"{self.vllm_server_url}/init_weight_transfer_engine",), + kwargs={"json": {"init_info": init_info}, "timeout": self.init_weight_transfer_timeout}, + ) + t_init.start() + self.model_update_group = NCCLWeightTransferEngine.trainer_init( + { + "master_address": master_address, + "master_port": master_port, + "world_size": world_size, + } + ) + t_init.join() + logger.info("Initialised weight-transfer NCCL group with vLLM") + + def send_weights(self, iterator) -> None: + if self.model_update_group is None: + return + t0 = time.time() + # Prepare the workers for the reload; must complete before any weights are sent. + requests.post( + f"{self.vllm_server_url}/start_weight_update", + json={"is_checkpoint_format": True}, + timeout=1800, + ) + # The /update_weights POST drives the workers' blocking NCCL recv, so it runs on a thread + # concurrently with the trainer-side broadcast. + t_update = threading.Thread( + target=requests.post, + args=(f"{self.vllm_server_url}/update_weights",), + kwargs={"json": {"update_info": self._weight_update_info}, "timeout": 1800}, + ) + t_update.start() + NCCLWeightTransferEngine.trainer_send_weights( + iterator=iterator, + trainer_args=NCCLTrainerSendWeightsArgs(group=self.model_update_group, packed=True), + ) + t_update.join() + requests.post(f"{self.vllm_server_url}/finish_weight_update", timeout=1800) + logger.debug(f"[weight_sync] send_weights took {time.time() - t0:.1f}s") + + def pause(self) -> None: + t0 = time.time() + requests.post(f"{self.vllm_server_url}/pause", params={"mode": "keep"}) + logger.debug(f"[weight_sync] pause HTTP took {time.time() - t0:.1f}s") + + def resume(self) -> None: + t0 = time.time() + requests.post(f"{self.vllm_server_url}/resume") + logger.debug(f"[weight_sync] resume HTTP took {time.time() - t0:.1f}s") + + def destroy(self) -> None: + if self.model_update_group is None: + return + self.model_update_group.group.store = None + self.model_update_group.group.socket = None + self.model_update_group = None diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/bco/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/bco/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3a6871ca60e002b21ac74a69e4113ded3391f622 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/bco/__init__.py @@ -0,0 +1,16 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .bco_config import BCOConfig +from .bco_trainer import BCOTrainer diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/bco/bco_config.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/bco/bco_config.py new file mode 100644 index 0000000000000000000000000000000000000000..325ace3e2609d8c12458b26872052ed2c2f8d907 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/bco/bco_config.py @@ -0,0 +1,154 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field +from typing import Any + +from ...trainer.base_config import _BaseConfig + + +@dataclass +class BCOConfig(_BaseConfig): + # docstyle-ignore + r""" + Configuration class for the [`experimental.bco.BCOTrainer`]. + + This class includes only the parameters that are specific to BCO 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: + max_length (`int` or `None`, *optional*, defaults to `1024`): + Maximum length of the sequences (prompt + completion) in the batch. This argument is required if you want + to use the default data collator. + max_completion_length (`int`, *optional*): + Maximum length of the completion. This argument is required if you want to use the default data collator + and your model is an encoder-decoder. + beta (`float`, *optional*, defaults to `0.1`): + Parameter controlling the deviation from the reference model. Higher β means less deviation from the + reference model. + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the model and reference model. + generate_during_eval (`bool`, *optional*, defaults to `False`): + If `True`, generates and logs completions from both the model and the reference model to W&B or Comet + during evaluation. + is_encoder_decoder (`bool`, *optional*): + When using the `model_init` argument (callable) to instantiate the model instead of the `model` argument, + you need to specify if the model returned by the callable is an encoder-decoder model. + precompute_ref_log_probs (`bool`, *optional*, defaults to `False`): + Whether to precompute reference model log probabilities for training and evaluation datasets. This is + useful when training without the reference model to reduce the total GPU memory needed. + model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model and + reference model from strings. + dataset_num_proc (`int`, *optional*): + Number of processes to use for processing the dataset. + prompt_sample_size (`int`, *optional*, defaults to `1024`): + Number of prompts that are fed to density ratio classifier. + min_density_ratio (`float`, *optional*, defaults to `0.5`): + Minimum value of the density ratio. The estimated density ratio is clamped to this value. + max_density_ratio (`float`, *optional*, defaults to `10.0`): + Maximum value of the density ratio. The estimated density ratio is clamped to this value. + + > [!NOTE] + > These parameters have default values different from [`~transformers.TrainingArguments`]: + > - `logging_steps`: Defaults to `10` instead of `500`. + > - `gradient_checkpointing`: Defaults to `True` instead of `False`. + > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`. + > - `learning_rate`: Defaults to `5e-7` instead of `5e-5`. + """ + + _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"] + + # Parameters whose default values are overridden from TrainingArguments + learning_rate: float = field( + default=5e-7, + metadata={"help": "The initial learning rate for AdamW."}, + ) + + max_length: int | None = field( + default=1024, + metadata={ + "help": "Maximum length of the sequences (prompt + completion) in the batch. " + "This argument is required if you want to use the default data collator." + }, + ) + max_completion_length: int | None = field( + default=None, + metadata={ + "help": "Maximum length of the completion. This argument is required if you want to use the " + "default data collator and your model is an encoder-decoder." + }, + ) + beta: float = field( + default=0.1, + metadata={ + "help": "Parameter controlling the deviation from the reference model. " + "Higher β means less deviation from the reference model." + }, + ) + disable_dropout: bool = field( + default=True, + metadata={"help": "Whether to disable dropout in the model and reference model."}, + ) + generate_during_eval: bool = field( + default=False, + metadata={ + "help": "If `True`, generates and logs completions from both the model and the reference model " + "to W&B during evaluation." + }, + ) + is_encoder_decoder: bool | None = field( + default=None, + metadata={ + "help": "When using the `model_init` argument (callable) to instantiate the model instead of the " + "`model` argument, you need to specify if the model returned by the callable is an " + "encoder-decoder model." + }, + ) + precompute_ref_log_probs: bool = field( + default=False, + metadata={ + "help": "Whether to precompute reference model log probabilities for training and evaluation datasets. " + "This is useful when training without the reference model to reduce the total GPU memory " + "needed." + }, + ) + model_init_kwargs: dict[str, Any] | str | None = field( + default=None, + metadata={ + "help": "Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the " + "model from a string." + }, + ) + dataset_num_proc: int | None = field( + default=None, + metadata={"help": "Number of processes to use for processing the dataset."}, + ) + prompt_sample_size: int = field( + default=1024, + metadata={"help": "Number of prompts that are fed to density ratio classifier."}, + ) + min_density_ratio: float = field( + default=0.5, + metadata={"help": "Minimum value of the density ratio. The estimated density ratio is clamped to this value."}, + ) + max_density_ratio: float = field( + default=10.0, + metadata={"help": "Maximum value of the density ratio. The estimated density ratio is clamped to this value."}, + ) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/bco/bco_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/bco/bco_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..d175899d059f4f0bc43a0e9b44abb79cf8ac4347 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/bco/bco_trainer.py @@ -0,0 +1,1555 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import dataclasses +import inspect +import json +import os +import random +import textwrap +from collections import defaultdict +from collections.abc import Callable +from contextlib import contextmanager, nullcontext +from dataclasses import dataclass +from operator import itemgetter +from pathlib import Path +from typing import Any, Literal + +import numpy as np +import pandas as pd +import torch +import torch.nn as nn +import torch.nn.functional as F +import transformers +from accelerate import Accelerator, PartialState, logging +from accelerate.utils import is_peft_model, tqdm +from datasets import Dataset +from packaging.version import Version +from torch import autocast +from torch.utils.data import DataLoader, SequentialSampler +from transformers import ( + AutoModelForCausalLM, + BaseImageProcessor, + DataCollator, + FeatureExtractionMixin, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, + TrainingArguments, + is_comet_available, + is_sklearn_available, + is_wandb_available, +) +from transformers.trainer_utils import EvalLoopOutput, has_length +from transformers.utils import is_peft_available + +from ...data_utils import maybe_apply_chat_template, maybe_extract_prompt, maybe_unpair_preference_dataset +from ...import_utils import is_joblib_available +from ...models.utils import prepare_deepspeed +from ...trainer.base_trainer import _BaseTrainer +from ...trainer.utils import disable_dropout_in_model, log_table_to_comet_experiment, selective_log_softmax +from ..utils import DPODataCollatorWithPadding, create_reference_model, pad_to_length, peft_module_casting_to_bf16 +from .bco_config import BCOConfig + + +if is_peft_available(): + from peft import PeftConfig, get_peft_model, prepare_model_for_kbit_training + +if is_wandb_available(): + import wandb + +if is_sklearn_available(): + from sklearn.linear_model import LogisticRegression + +if is_joblib_available(): + import joblib + +logger = logging.get_logger(__name__) + +RUNNING_NAME = "running.json" +CLF_NAME = "clf.pkl" + + +@torch.no_grad() +def get_global_statistics( + accelerator, xs: torch.Tensor, mask=None, device="cpu" +) -> tuple[torch.Tensor, torch.Tensor, int]: + """ + Computes element-wise mean and variance of the tensor across processes. Reference: + https://github.com/OpenLMLab/MOSS-RLHF/blob/40b91eb2f2b71b16919addede0341d2bef70825d/utils.py#L57C1-L73C75 + """ + xs = xs.to(accelerator.device) + sum_and_count = torch.tensor([xs.sum(), (xs.numel() if mask is None else mask.sum())], device=xs.device) + sum_and_count = accelerator.reduce(sum_and_count) + global_sum, count = sum_and_count + global_mean = global_sum / count + + sum_var = torch.sum(((xs - global_mean) ** 2).mul(1 if mask is None else mask)) + sum_var = accelerator.reduce(sum_var) + global_var = sum_var / count + + return global_mean.to(device), global_var.to(device), count.item() + + +@dataclass +class RunningMoments: + """ + Calculates the running mean and standard deviation of a data stream. Reference: + https://github.com/OpenLMLab/MOSS-RLHF/blob/40b91eb2f2b71b16919addede0341d2bef70825d/utils.py#L75 + """ + + accelerator: Accelerator + mean: float = 0 + std: float = 1 + var: float = 1 + count: float = 1e-24 + + @torch.no_grad() + def update(self, xs: torch.Tensor) -> tuple[float, float]: + """ + Updates running moments from batch's moments computed across ranks + """ + if self.accelerator.use_distributed: + xs_mean, xs_var, xs_count = get_global_statistics(self.accelerator, xs) + else: + xs_count = xs.numel() + xs_var, xs_mean = torch.var_mean(xs, unbiased=False) + xs_mean, xs_var = xs_mean.float(), xs_var.float() + + delta = xs_mean - self.mean + tot_count = self.count + xs_count + + new_sum = xs_var * xs_count + # correct old_sum deviation accounting for the new mean + old_sum = self.var * self.count + delta**2 * self.count * xs_count / tot_count + tot_sum = old_sum + new_sum + + self.mean += (delta * xs_count / tot_count).item() + new_var = tot_sum / tot_count + self.std = (new_var * tot_count / (tot_count - 1)).float().sqrt().item() + self.var = new_var.item() + self.count = tot_count + + return xs_mean.item(), (xs_var * xs_count / (xs_count - 1)).float().sqrt().item() + + def save_to_json(self, json_path: str): + """Save the content of this instance in JSON format inside `json_path`.""" + # save everything except accelerator + if self.accelerator.is_main_process: + save_dict = dataclasses.asdict(self, dict_factory=lambda x: {k: v for (k, v) in x if k != "accelerator"}) + json_string = json.dumps(save_dict, indent=2, sort_keys=True) + "\n" + with open(json_path, "w", encoding="utf-8") as f: + f.write(json_string) + + @classmethod + def load_from_json(cls, accelerator: Accelerator, json_path: str): + """Create an instance from the content of `json_path`.""" + # load everything except accelerator + with open(json_path, encoding="utf-8") as f: + text = f.read() + return cls(accelerator=accelerator, **json.loads(text)) + + +def _tokenize( + batch: dict[str, list[Any]], + tokenizer: PreTrainedTokenizerBase, + embedding_tokenizer: PreTrainedTokenizerBase | None = None, +) -> dict[str, list[Any]]: + """Tokenize a batch from a BCO specific dataset.""" + prompt_tokenized = tokenizer(batch["prompt"], add_special_tokens=False) + prompt_input_ids = prompt_tokenized["input_ids"] + prompt_attention_mask = prompt_tokenized["attention_mask"] + prompt_and_completion = [ + prompt + completion for prompt, completion in zip(batch["prompt"], batch["completion"], strict=True) + ] + full_tokenized = tokenizer(prompt_and_completion, add_special_tokens=False) + full_input_ids = full_tokenized["input_ids"] + full_attention_mask = full_tokenized["attention_mask"] + + answer_input_ids = [f[len(p) :] for f, p in zip(full_input_ids, prompt_input_ids, strict=True)] + answer_attention_mask = [f[len(p) :] for f, p in zip(full_attention_mask, prompt_attention_mask, strict=True)] + + # Concat tokens to form `enc(a) + enc(a + b)[len(enc(a)):]` + full_concat_input_ids = [np.concatenate([p, a]) for p, a in zip(prompt_input_ids, answer_input_ids, strict=True)] + # Prepare input tokens for token by token comparison + full_input_ids = [np.array(f) for f in full_input_ids] + for full, concat in zip(full_input_ids, full_concat_input_ids, strict=True): + if len(full) != len(concat): + raise ValueError( + "The elements in 'full_input_ids' and 'full_concat_input_ids' must have the same pairwise length." + ) + + # On some tokenizers, like Llama-2 tokenizer, there are occasions where tokens + # can be merged together when tokenizing prompt+answer. This could result + # on the last token from the prompt being different when tokenized on its own + # vs when done as prompt+answer. + response_token_ids_start_idx = [len(p) for p in prompt_input_ids] + + # If tokenized prompt is different than both prompt+answer, then it means the + # last token has changed due to merging. + for idx, (p, f, r) in enumerate(zip(prompt_input_ids, full_input_ids, response_token_ids_start_idx, strict=True)): + if not np.array_equal(p, f[:r]): + response_token_ids_start_idx[idx] -= 1 + + prompt_input_ids = [f[:r] for f, r in zip(full_input_ids, response_token_ids_start_idx, strict=True)] + prompt_attention_mask = [f[:r] for f, r in zip(full_attention_mask, response_token_ids_start_idx, strict=True)] + + for p, m in zip(prompt_input_ids, prompt_attention_mask, strict=True): + if len(p) != len(m): + raise ValueError("Prompt input ids and attention mask should have the same length.") + + answer_input_ids = [f[r:] for f, r in zip(full_input_ids, response_token_ids_start_idx, strict=True)] + answer_attention_mask = [f[r:] for f, r in zip(full_attention_mask, response_token_ids_start_idx, strict=True)] + + output = dict( + prompt_input_ids=prompt_input_ids, + prompt_attention_mask=prompt_attention_mask, + answer_input_ids=answer_input_ids, + answer_attention_mask=answer_attention_mask, + ) + + if embedding_tokenizer is not None: + embedding_tokenized = embedding_tokenizer(batch["prompt"], add_special_tokens=False) + + output.update( + { + "embedding_input_ids": embedding_tokenized["input_ids"], + "embedding_attention_mask": embedding_tokenized["attention_mask"], + } + ) + + return output + + +def _process_tokens(example: dict[str, Any], model: "PreTrainedModel" = None, **kwargs) -> dict: + """Process tokens of a BCO specific dataset. + + At this stage, we don't convert to PyTorch tensors yet; we just handle the truncation in case the prompt + + completion responses is/are too long. First we truncate the prompt; if we're still too long, we truncate the + completion. + + We also create the labels for the completion responses, which are of length equal to the sum of the length of the + prompt and the completion response, with `-100` for the prompt tokens. + """ + prompt = example["prompt"] + completion = example["completion"] + + batch = { + f"{kwargs['prefix']}prompt": prompt, + f"{kwargs['prefix']}completion": completion, + f"{kwargs['prefix']}label": example["label"], + } + + if not kwargs["is_encoder_decoder"]: + # Check issues below for more details + # 1. https://github.com/huggingface/trl/issues/907 + # 2. https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257 + # 3. https://github.com/LianjiaTech/BELLE/issues/337 + + if not isinstance(prompt, str): + raise ValueError(f"prompt should be an str but got {type(prompt)}") + + if not isinstance(completion, str): + raise ValueError(f"completion should be an str but got {type(completion)}") + + # keys of format prompt_* refers to just the prompt and answer_* refers to just the answer + all_tokens = { + "prompt_input_ids": example["prompt_input_ids"], + "prompt_attention_mask": example["prompt_attention_mask"], + "answer_input_ids": example["answer_input_ids"], + "answer_attention_mask": example["answer_attention_mask"], + } + + # calculate max length by checking if BOS/EOS is already there + max_length = kwargs["max_length"] + bos_token_id = kwargs["tokenizer"].bos_token_id + eos_token_id = kwargs["tokenizer"].eos_token_id + if bos_token_id != all_tokens["prompt_input_ids"][0]: + max_length -= 1 + if eos_token_id != all_tokens["answer_input_ids"][-1]: + max_length -= 1 + + # if combined sequence is too long (> max_length - 1 for BOS token - 1 for EOS), truncate the response + if len(all_tokens["prompt_input_ids"]) + len(all_tokens["answer_input_ids"]) > max_length: + for k in ["answer_input_ids", "answer_attention_mask"]: + all_tokens[k] = all_tokens[k][: max_length - len(all_tokens["prompt_input_ids"])] + + # all input_ids and attention mask as is. We then check if we need to add BOS/EOS tokens + batch[f"{kwargs['prefix']}prompt_input_ids"] = all_tokens["prompt_input_ids"] + batch[f"{kwargs['prefix']}prompt_attention_mask"] = all_tokens["prompt_attention_mask"] + batch[f"{kwargs['prefix']}completion_input_ids"] = ( + all_tokens["prompt_input_ids"] + all_tokens["answer_input_ids"] + ) + batch[f"{kwargs['prefix']}completion_attention_mask"] = ( + all_tokens["prompt_attention_mask"] + all_tokens["answer_attention_mask"] + ) + + # add BOS, which affects both prompt and the full completion + if bos_token_id is not None: + if len(all_tokens["prompt_input_ids"]) == 0 or bos_token_id != all_tokens["prompt_input_ids"][0]: + batch[f"{kwargs['prefix']}prompt_input_ids"] = [bos_token_id] + batch[ + f"{kwargs['prefix']}prompt_input_ids" + ] + batch[f"{kwargs['prefix']}prompt_attention_mask"] = [1] + batch[ + f"{kwargs['prefix']}prompt_attention_mask" + ] + batch[f"{kwargs['prefix']}completion_input_ids"] = [bos_token_id] + batch[ + f"{kwargs['prefix']}completion_input_ids" + ] + batch[f"{kwargs['prefix']}completion_attention_mask"] = [1] + batch[ + f"{kwargs['prefix']}completion_attention_mask" + ] + # add EOS, which affects only the full completion + if len(all_tokens["answer_input_ids"]) == 0 or eos_token_id != all_tokens["answer_input_ids"][-1]: + batch[f"{kwargs['prefix']}completion_input_ids"] = batch[f"{kwargs['prefix']}completion_input_ids"] + [ + eos_token_id + ] + batch[f"{kwargs['prefix']}completion_attention_mask"] = batch[ + f"{kwargs['prefix']}completion_attention_mask" + ] + [1] + + batch[f"{kwargs['prefix']}completion_labels"] = batch[f"{kwargs['prefix']}completion_input_ids"][:] + batch[f"{kwargs['prefix']}completion_labels"][: len(batch[f"{kwargs['prefix']}prompt_input_ids"])] = [ + -100 + ] * len(batch[f"{kwargs['prefix']}prompt_input_ids"]) + else: + completion_tokens = kwargs["tokenizer"]( + completion, truncation=True, max_length=kwargs["max_completion_length"], add_special_tokens=True + ) + prompt_tokens = kwargs["tokenizer"](prompt, add_special_tokens=True) + + batch[f"{kwargs['prefix']}prompt_input_ids"] = prompt_tokens["input_ids"] + batch[f"{kwargs['prefix']}prompt_attention_mask"] = prompt_tokens["attention_mask"] + + batch[f"{kwargs['prefix']}completion_labels"] = completion_tokens["input_ids"] + batch[f"{kwargs['prefix']}completion_attention_mask"] = completion_tokens["attention_mask"] + if model is not None and hasattr(model, "prepare_decoder_input_ids_from_labels"): + batch[f"{kwargs['prefix']}completion_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels( + labels=torch.tensor(batch["completion_labels"]) + ) + + return batch + + +class BCOTrainer(_BaseTrainer): + r""" + Initialize BCOTrainer from [BCO](https://huggingface.co/papers/2404.04656) paper. + + Args: + model ([`~transformers.PreTrainedModel`]): + The model to train, preferably an [`~transformers.AutoModelForSequenceClassification`]. + ref_model ([`~transformers.PreTrainedModel`]): + Hugging Face transformer model with a casual language modelling head. Used for implicit reward computation + and loss. If no reference model is provided, the trainer will create a reference model with the same + architecture as the model to be optimized. + args ([`experimental.bco.BCOConfig`]): + The arguments to use for training. + train_dataset ([`~datasets.Dataset`]): + The dataset to use for training. + eval_dataset ([`~datasets.Dataset`]): + The dataset to use for evaluation. + processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*): + Processing class used to process the data. If provided, will be used to automatically process the inputs + for the model, and it will be saved along the model to make it easier to rerun an interrupted training or + reuse the fine-tuned model. + data_collator ([`~transformers.DataCollator`], *optional*): + The data collator to use for training. If None is specified, the default data collator + ([`experimental.utils.DPODataCollatorWithPadding`]) will be used which will pad the sequences to the + maximum length of the sequences in the batch, given a dataset of paired sequences. + model_init (`Callable[[], transformers.PreTrainedModel]`): + The model initializer to use for training. If None is specified, the default model initializer will be + used. + callbacks (`list[transformers.TrainerCallback]`): + The callbacks to use for training. + optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`): + The optimizer and scheduler to use for training. + preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`): + The function to use to preprocess the logits before computing the metrics. + peft_config ([`~peft.PeftConfig`], *optional*): + The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in + a PEFT model. + compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*): + The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to + metric values. + model_adapter_name (`str`, defaults to `None`): + Name of the train target PEFT adapter, when using LoRA with multiple adapters. + ref_adapter_name (`str`, defaults to `None`): + Name of the reference PEFT adapter, when using LoRA with multiple adapters. + embedding_func (`Callable`, *optional*): + Function to compute prompt embeddings, used to train the underlying distribution matching (UDM) classifier + when the desirable and undesirable datasets have divergent prompt distributions. Requires the scikit-learn + and joblib libraries. + embedding_tokenizer ([`~transformers.PreTrainedTokenizerBase`], *optional*): + Tokenizer used to prepare prompts for `embedding_func`. + """ + + _tag_names = ["trl", "bco"] + _name = "BCO" + _paper = { + "title": "Binary Classifier Optimization for Large Language Model Alignment", + "id": "2404.04656", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @article{jung2024binary, + title = {{Binary Classifier Optimization for Large Language Model Alignment}}, + author = {Seungjae Jung and Gunsoo Han and Daniel Wontae Nam and Kyoung{-}Woon On}, + year = 2024, + eprint = {arXiv:2404.04656} + }"""), + } + + def __init__( + self, + model: PreTrainedModel | nn.Module | str = None, + ref_model: PreTrainedModel | nn.Module | str | None = None, + args: BCOConfig = None, + train_dataset: Dataset | None = None, + eval_dataset: Dataset | dict[str, Dataset] | None = None, + processing_class: PreTrainedTokenizerBase + | BaseImageProcessor + | FeatureExtractionMixin + | ProcessorMixin + | None = None, + data_collator: DataCollator | None = None, + model_init: Callable[[], PreTrainedModel] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None, + peft_config: "PeftConfig | None" = None, + compute_metrics: Callable[[EvalLoopOutput], dict] | None = None, + model_adapter_name: str | None = None, + ref_adapter_name: str | None = None, + embedding_func: Callable | None = None, + embedding_tokenizer: PreTrainedTokenizerBase | None = None, + ): + if embedding_func is not None and not (is_sklearn_available() and is_joblib_available()): + raise ImportError( + "BCOTrainer with UDM requires the scikit-learn and joblib libraries. Please install it with `pip install scikit-learn joblib`." + ) + + if type(args) is TrainingArguments: + raise ValueError("Please use `BCOConfig` instead `TrainingArguments`.") + + if train_dataset is None: + raise ValueError("`train_dataset` is required") + + if not isinstance(model, str) and model is not None and ref_model is model: + raise ValueError( + "`model` and `ref_model` cannot be the same object. If you want `ref_model` to be the " + "same as `model`, you must mass a copy of it, or `None` if you use peft." + ) + + if args.model_init_kwargs is None: + model_init_kwargs = {} + elif not isinstance(model, str): + raise ValueError("You passed model_kwargs to the BCOTrainer. But your model is already instantiated.") + else: + model_init_kwargs = args.model_init_kwargs + dtype = model_init_kwargs.get("dtype", "auto") + if dtype is not None: + # Convert to `torch.dtype` if an str is passed + if isinstance(dtype, str) and dtype != "auto": + dtype = getattr(torch, dtype) + if dtype != "auto" and not isinstance(dtype, torch.dtype): + raise ValueError( + f"Invalid `dtype` passed to the BCOConfig. Expected a string with either `torch.dtype` or 'auto', but got {dtype}." + ) + model_init_kwargs["dtype"] = dtype + model_init_kwargs["device_map"] = model_init_kwargs.get("device_map", "auto") + + if isinstance(model, str): + model = AutoModelForCausalLM.from_pretrained(model, **model_init_kwargs) + + if isinstance(ref_model, str): + ref_model = AutoModelForCausalLM.from_pretrained(ref_model, **model_init_kwargs) + + # PEFT + # Initialize this variable to False. This helps tracking the case when `peft_module_casting_to_bf16` + # has been called in order to properly call autocast if needed. + self._peft_has_been_casted_to_bf16 = False + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + if is_peft_model(model): + raise ValueError( + "You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first " + "merge and unload the existing adapter, save the resulting base model, and then pass that base " + "model along with the new `peft_config` to the trainer." + ) + + if getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False): + _support_gc_kwargs = hasattr( + args, "gradient_checkpointing_kwargs" + ) and "gradient_checkpointing_kwargs" in list( + inspect.signature(prepare_model_for_kbit_training).parameters + ) + + prepare_model_kwargs = {"use_gradient_checkpointing": args.gradient_checkpointing} + + if _support_gc_kwargs: + prepare_model_kwargs["gradient_checkpointing_kwargs"] = args.gradient_checkpointing_kwargs + + model = prepare_model_for_kbit_training(model, **prepare_model_kwargs) + elif args.gradient_checkpointing: + # For backward compatibility with older versions of transformers + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + # get peft model with the given config + model = get_peft_model(model, peft_config) + if args.bf16 and getattr(model, "is_loaded_in_4bit", False): + peft_module_casting_to_bf16(model) + # If args.bf16 we need to explicitly call `generate` with torch amp autocast context manager + self._peft_has_been_casted_to_bf16 = True + + # For models that use gradient_checkpointing, we need to attach a hook that enables input + # to explicitly have `requires_grad=True`, otherwise training will either silently + # fail or completely fail. + elif args.gradient_checkpointing: + # For backward compatibility with older versions of transformers + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + if args.generate_during_eval and not (is_wandb_available() or is_comet_available()): + raise ValueError( + "`generate_during_eval=True` requires Weights and Biases or Comet to be installed." + " Please install `wandb` or `comet-ml` to resolve." + ) + + if model is not None: + self.is_encoder_decoder = model.config.is_encoder_decoder + elif args.is_encoder_decoder is None: + raise ValueError("When no model is provided, you need to pass the parameter is_encoder_decoder.") + else: + self.is_encoder_decoder = args.is_encoder_decoder + + self.model_adapter_name = model_adapter_name + self.ref_adapter_name = ref_adapter_name + + if ref_model: + self.ref_model = ref_model + elif is_peft_model(model) or args.precompute_ref_log_probs: + # The `model` with adapters turned off will be used as the reference model + self.ref_model = None + else: + self.ref_model = create_reference_model(model) + + if processing_class is None: + raise ValueError( + "max_length or a processing_class must be specified when using the default DPODataCollatorWithPadding" + ) + if args.max_length is None: + logger.warning( + "When using DPODataCollatorWithPadding, you should set `max_length` in the `BCOConfig`. " + "It will be set to `512` by default, but you should do it yourself in the future.", + ) + max_length = 512 + if args.max_length is not None: + max_length = args.max_length + + max_completion_length = None + if args.max_completion_length is None and self.is_encoder_decoder: + logger.warning( + "When using DPODataCollatorWithPadding with an encoder decoder architecture, you should set `max_completion_length` in the BCOTrainer's init" + " it will be set to `128` by default, but you should do it yourself in the future.", + ) + max_completion_length = 128 + if args.max_completion_length is not None and self.is_encoder_decoder: + max_completion_length = args.max_completion_length + + if data_collator is None: + data_collator = DPODataCollatorWithPadding( + pad_token_id=processing_class.pad_token_id, + is_encoder_decoder=self.is_encoder_decoder, + ) + + if args.remove_unused_columns: + args.remove_unused_columns = False + # warn users + logger.warning( + "When using DPODataCollatorWithPadding, you should set `remove_unused_columns=False` in your BCOConfig" + " we have set it for you, but you should do it yourself in the future.", + ) + + self.use_dpo_data_collator = True + else: + self.use_dpo_data_collator = False + + # Disable dropout in the model and reference model + if args.disable_dropout: + disable_dropout_in_model(model) + if self.ref_model is not None: + disable_dropout_in_model(self.ref_model) + + self.max_length = max_length + self.generate_during_eval = args.generate_during_eval + self.max_completion_length = max_completion_length + self.precompute_ref_log_probs = args.precompute_ref_log_probs + + # Since ref_logs are precomputed on the first call to get_train/eval_dataloader + # keep track of first called to avoid computation of future calls + self._precomputed_train_ref_log_probs = False + self._precomputed_eval_ref_log_probs = False + + # metric + self._stored_metrics = defaultdict(lambda: defaultdict(list)) + + # BCO parameter + self.beta = args.beta + self.aux_loss_enabled = getattr(model.config, "output_router_logits", False) + self.aux_loss_coef = getattr(model.config, "router_aux_loss_coef", 0.0) + if self.aux_loss_enabled and self.aux_loss_coef == 0.0: + logger.warning( + "You set `output_router_logits` to `True` in the model config, but `router_aux_loss_coef` is set to " + "`0.0`, meaning the auxiliary loss will not be used. Either set `router_aux_loss_coef` to a value " + "greater than `0.0`, or set `output_router_logits` to `False` if you don't want to use the auxiliary " + "loss.", + ) + + # Underlying Distribution Matching argument + self.embedding_func = embedding_func + self.embedding_tokenizer = embedding_tokenizer + + with PartialState().main_process_first(): + # Extract the prompt if needed + train_dataset = train_dataset.map( + maybe_extract_prompt, num_proc=args.dataset_num_proc, desc="Extracting prompt from train dataset" + ) + # Unpair the dataset if needed + train_dataset = maybe_unpair_preference_dataset( + train_dataset, args.dataset_num_proc, desc="Unpairing train dataset" + ) + # Apply the chat template if needed + train_dataset = train_dataset.map( + maybe_apply_chat_template, + fn_kwargs={"processing_class": processing_class}, + num_proc=args.dataset_num_proc, + ) + if eval_dataset is not None: + # Extract the prompt if needed + eval_dataset = eval_dataset.map( + maybe_extract_prompt, num_proc=args.dataset_num_proc, desc="Extracting prompt from eval dataset" + ) + # Unpair the dataset if needed + eval_dataset = maybe_unpair_preference_dataset( + eval_dataset, args.dataset_num_proc, desc="Unpairing eval dataset" + ) + eval_dataset = eval_dataset.map( + maybe_apply_chat_template, + fn_kwargs={"processing_class": processing_class}, + num_proc=args.dataset_num_proc, + ) + + # Tokenize and prepare the training datasets + train_dataset = train_dataset.map( + _tokenize, + batched=True, + fn_kwargs={"tokenizer": processing_class, "embedding_tokenizer": self.embedding_tokenizer}, + num_proc=args.dataset_num_proc, + desc="Tokenizing train dataset", + ) + + # Prepare the datasets + fn_kwargs = { + "prefix": "", + "is_encoder_decoder": self.is_encoder_decoder, + "tokenizer": processing_class, + "max_length": self.max_length, + "max_completion_length": self.max_completion_length, + } + train_dataset = train_dataset.map( + _process_tokens, + fn_kwargs=fn_kwargs, + num_proc=args.dataset_num_proc, + desc="Processing tokenized train dataset", + ) + + if eval_dataset is not None: + # Tokenize + eval_dataset = eval_dataset.map( + _tokenize, + fn_kwargs={"tokenizer": processing_class, "embedding_tokenizer": self.embedding_tokenizer}, + batched=True, + num_proc=args.dataset_num_proc, + desc="Tokenizing eval dataset", + ) + + # Process + fn_kwargs = { + "prefix": "", + "is_encoder_decoder": self.is_encoder_decoder, + "tokenizer": processing_class, + "max_length": self.max_length, + "max_completion_length": self.max_completion_length, + } + eval_dataset = eval_dataset.map( + _process_tokens, + fn_kwargs=fn_kwargs, + num_proc=args.dataset_num_proc, + desc="Processing tokenized eval dataset", + ) + + desirable = train_dataset.filter( + lambda x: x["label"], num_proc=args.dataset_num_proc, desc="Filtering desirable examples" + ) + undesirable = train_dataset.filter( + lambda x: not x["label"], num_proc=args.dataset_num_proc, desc="Filtering undesirable examples" + ) + + # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was + # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream + # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we + # default to the recommended non-reentrant behavior here, while preserving any user-provided value. + if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"): + args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {} + args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False) + + super().__init__( + model=model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + model_init=model_init, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + ) + + # Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the + # model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set + # self.model_accepts_loss_kwargs to False to enable scaling. + self.model_accepts_loss_kwargs = False + + # Add tags for models that have been loaded with the correct transformers version + if hasattr(self.model, "add_model_tags"): + self.model.add_model_tags(self._tag_names) + + if not hasattr(self, "accelerator"): + raise AttributeError( + "Your `Trainer` does not have an `accelerator` object. Consider upgrading `transformers`." + ) + + # Deepspeed Zero-3 does not support precompute_ref_log_probs + if self.is_deepspeed_enabled: + if self.accelerator.state.deepspeed_plugin.zero_stage == 3 and self.precompute_ref_log_probs: + raise ValueError( + "You cannot use `precompute_ref_log_probs=True` with Deepspeed ZeRO-3. Please set `precompute_ref_log_probs=False`." + ) + + if self.ref_model is None: + if not (is_peft_model(model) or self.precompute_ref_log_probs): + raise ValueError( + "No reference model and model is not a Peft model. Try setting `precompute_ref_log_probs=True`" + ) + else: + if self.is_deepspeed_enabled: + self.ref_model = prepare_deepspeed(self.ref_model, self.accelerator) + else: + self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True) + + self.running = RunningMoments(accelerator=self.accelerator) + + if self.embedding_func is None or args.resume_from_checkpoint: + return + + chosen_embeddings = self._get_sample_prompt_embeddings(desirable, sample_size=self.args.prompt_sample_size) + rejected_embeddings = self._get_sample_prompt_embeddings(undesirable, sample_size=self.args.prompt_sample_size) + + embeddings = torch.cat((chosen_embeddings, rejected_embeddings), dim=0) + labels = torch.cat( + (torch.ones_like(chosen_embeddings[:, 0]), torch.zeros_like(rejected_embeddings[:, 0])), dim=0 + ) + + self.clf = LogisticRegression(class_weight="balanced").fit( + embeddings.cpu().float().numpy(), labels.cpu().numpy() + ) + chosen_mean = self.clf.score( + chosen_embeddings.cpu().float().numpy(), torch.ones_like(chosen_embeddings[:, 0]).cpu().numpy() + ) + rejected_mean = self.clf.score( + rejected_embeddings.cpu().float().numpy(), torch.zeros_like(rejected_embeddings[:, 0]).cpu().numpy() + ) + logger.info(f"UDM classifier training scores: chosen: {chosen_mean}, rejected: {rejected_mean}") + + @property + def match_underlying_distribution(self): + return self.embedding_func is not None and self.embedding_tokenizer is not None + + def _get_chosen_prob(self, prompt_embeddings: torch.FloatTensor) -> torch.FloatTensor: + """ + Calculates the probability if the given prompt embedding is from desirable dataset. This function calculates + the probability in the process and ensemble across processes. + """ + dtype = prompt_embeddings.dtype + device = prompt_embeddings.device + rank = self.accelerator.process_index + + padded_prompt_embeddings = self.accelerator.pad_across_processes( + prompt_embeddings, pad_index=self.embedding_tokenizer.pad_token_id + ) + sample_size = padded_prompt_embeddings.shape[0] + nonzero = padded_prompt_embeddings.mean(dim=1) != self.embedding_tokenizer.pad_token_id + prompt_embeddings = self.accelerator.gather(padded_prompt_embeddings) + + # cannot predict for all empty values + if prompt_embeddings.shape[0] == 0: + return torch.tensor([], device=device, dtype=dtype) + + prob = self.clf.predict_proba(prompt_embeddings.cpu().float().numpy())[:, 1] + prob = torch.as_tensor(prob, dtype=dtype, device=device) + prob = self.accelerator.reduce(prob, reduction="mean") + + prob = prob[sample_size * rank : sample_size * (rank + 1)] + prob = prob[nonzero] + + return prob + + def _vectorize_prompt(self, input_ids: torch.LongTensor, attention_mask: torch.LongTensor) -> torch.FloatTensor: + """ + Replaces processing_class.pad_token_id to embedding_tokenizer.pad_token_id and applies self.embedding_func + """ + input_ids = torch.where( + input_ids == self.processing_class.pad_token_id, + self.embedding_tokenizer.pad_token_id, + input_ids, + ) + + with torch.no_grad(): + embeddings = self.embedding_func( + input_ids=input_ids, + attention_mask=attention_mask, + ) + + return embeddings + + def _get_prompt_embeddings( + self, batch: dict[str, list | torch.LongTensor] + ) -> tuple[torch.FloatTensor, torch.FloatTensor]: + """Extract embeddings from frozen embedding model""" + + if not self.match_underlying_distribution: + return None, None + + embeddings = self._vectorize_prompt( + input_ids=batch["embedding_input_ids"], + attention_mask=batch["embedding_attention_mask"], + ) + + labels = torch.tensor(batch["label"], dtype=torch.bool, device=embeddings.device) + chosen_idx = torch.where(labels)[0] + rejected_idx = torch.where(~labels)[0] + + chosen_embeddings = embeddings[chosen_idx, ...] + rejected_embeddings = embeddings[rejected_idx, ...] + + return (chosen_embeddings, rejected_embeddings) + + def _get_sample_prompt_embeddings(self, dataset: Dataset, sample_size: int = 512) -> torch.FloatTensor: + """ + Sample instances from dataset and get prompt embeddings. Used for density ratio classifier training. + """ + n_samples = min(len(dataset), sample_size) + rand_indices = np.random.choice(len(dataset), size=(n_samples,)) + + embedding_dataset = dataset.select(rand_indices) + + dataloader_params = { + "batch_size": self.args.per_device_train_batch_size, + "collate_fn": self.data_collator, + "num_workers": self.args.dataloader_num_workers, + "pin_memory": self.args.dataloader_pin_memory, + "shuffle": False, + } + + # prepare dataloader + data_loader = self.accelerator.prepare(DataLoader(embedding_dataset, **dataloader_params)) + + with torch.no_grad(): + all_embeddings = torch.empty(0) + for padded_batch in tqdm(iterable=data_loader, desc="Building sample prompt embeddings"): + embeddings = self._vectorize_prompt( + input_ids=padded_batch["embedding_input_ids"], + attention_mask=padded_batch["embedding_attention_mask"], + ) + embeddings = self.accelerator.gather_for_metrics(embeddings) + all_embeddings = torch.cat((all_embeddings, embeddings.cpu())) + + return all_embeddings + + def _save_optimizer_and_scheduler(self, output_dir): + output_dir = output_dir if output_dir is not None else self.args.output_dir + super()._save_optimizer_and_scheduler(output_dir) + + if self.accelerator.is_main_process: + # When saving optimizer and scheduler to checkpoint, save also the running delta object. + self.running.save_to_json(os.path.join(output_dir, RUNNING_NAME)) + + if self.match_underlying_distribution: + joblib.dump(self.clf, os.path.join(output_dir, CLF_NAME), compress=True) + + def _load_optimizer_and_scheduler(self, checkpoint): + if checkpoint is None: + logger.warning_once(f"Missing Checkpoint {checkpoint}") + return + + super()._load_optimizer_and_scheduler(checkpoint) + + # when loading optimizer and scheduler from checkpoint, also load the running delta object. + running_file = os.path.join(checkpoint, RUNNING_NAME) + if os.path.isfile(running_file): + self.running = RunningMoments.load_from_json(self.accelerator, running_file) + + if self.match_underlying_distribution: + clf_file = os.path.join(checkpoint, CLF_NAME) + if os.path.isfile(clf_file): + self.clf = joblib.load(clf_file) + + @contextmanager + def null_ref_context(self): + """Context manager for handling null reference model (that is, peft adapter manipulation).""" + with ( + self.accelerator.unwrap_model(self.model).disable_adapter() + if is_peft_model(self.model) and not self.ref_adapter_name + else nullcontext() + ): + if self.ref_adapter_name: + self.model.set_adapter(self.ref_adapter_name) + yield + if self.ref_adapter_name: + self.model.set_adapter(self.model_adapter_name or "default") + + def get_train_dataloader(self) -> DataLoader: + """ + Returns the training [`~torch.utils.data.DataLoader`]. + + Subclass of transformers.src.transformers.trainer.get_train_dataloader to precompute `ref_log_probs`. + """ + + if self.precompute_ref_log_probs and not self._precomputed_train_ref_log_probs: + dataloader_params = { + "batch_size": self.args.per_device_train_batch_size, + "collate_fn": self.data_collator, + "num_workers": self.args.dataloader_num_workers, + "pin_memory": self.args.dataloader_pin_memory, + "shuffle": False, + } + + # prepare dataloader + data_loader = self.accelerator.prepare(DataLoader(self.train_dataset, **dataloader_params)) + reference_completion_logps = [] + + for padded_batch in tqdm(iterable=data_loader, desc="Train dataset reference log probs"): + reference_completion_logp = self.compute_reference_log_probs(padded_batch) + + reference_completion_logp = self.accelerator.gather_for_metrics(reference_completion_logp) + reference_completion_logps.append(reference_completion_logp.cpu()) + + self.train_dataset = self.train_dataset.add_column( + name="reference_logps", column=torch.cat(reference_completion_logps).float().numpy() + ) + + self._precomputed_train_ref_log_probs = True + + return super().get_train_dataloader() + + def get_eval_dataloader(self, eval_dataset: Dataset | None = None) -> DataLoader: + """ + Returns the evaluation [`~torch.utils.data.DataLoader`]. + + Subclass of transformers.src.transformers.trainer.get_eval_dataloader to precompute `ref_log_probs`. + + Args: + eval_dataset (`torch.utils.data.Dataset`, *optional*): + If provided, will override `self.eval_dataset`. If it is a [`~datasets.Dataset`], columns not accepted + by the `model.forward()` method are automatically removed. It must implement `__len__`. + """ + if eval_dataset is None and self.eval_dataset is None: + raise ValueError("Trainer: evaluation requires an eval_dataset.") + eval_dataset = eval_dataset if eval_dataset is not None else self.eval_dataset + + if self.precompute_ref_log_probs and not self._precomputed_eval_ref_log_probs: + dataloader_params = { + "batch_size": self.args.per_device_eval_batch_size, + "collate_fn": self.data_collator, + "num_workers": self.args.dataloader_num_workers, + "pin_memory": self.args.dataloader_pin_memory, + "shuffle": False, + } + + # prepare dataloader + data_loader = self.accelerator.prepare(DataLoader(eval_dataset, **dataloader_params)) + + reference_completion_logps = [] + + for padded_batch in tqdm(iterable=data_loader, desc="Eval dataset reference log probs"): + reference_completion_logp = self.compute_reference_log_probs(padded_batch) + + reference_completion_logp = self.accelerator.gather_for_metrics(reference_completion_logp) + reference_completion_logps.append(reference_completion_logp.cpu()) + + eval_dataset = eval_dataset.add_column( + name="reference_logps", column=torch.cat(reference_completion_logps).float().numpy() + ) + + # Save calculated reference_chosen_logps and reference_rejected_logps to the eval_dataset for subsequent runs + if self.eval_dataset is not None: + self.eval_dataset = eval_dataset + self._precomputed_eval_ref_log_probs = True + + return super().get_eval_dataloader(eval_dataset=eval_dataset) + + def compute_reference_log_probs(self, padded_batch: dict) -> dict: + """Computes log probabilities of the reference model for a single padded batch of a BCO specific dataset.""" + with torch.no_grad(): + if self.ref_model is None: + with self.null_ref_context(): + if self.is_encoder_decoder: + completion_logits = self.model( + padded_batch["prompt_input_ids"], + attention_mask=padded_batch["prompt_attention_mask"], + decoder_input_ids=padded_batch.get("completion_decoder_input_ids"), + labels=padded_batch["completion_labels"], + ).logits + + else: + completion_logits = self.model( + padded_batch["completion_input_ids"], + attention_mask=padded_batch["completion_attention_mask"], + ).logits + + else: + if self.is_encoder_decoder: + completion_logits = self.ref_model( + padded_batch["prompt_input_ids"], + attention_mask=padded_batch["prompt_attention_mask"], + decoder_input_ids=padded_batch.get("completion_decoder_input_ids"), + labels=padded_batch["completion_labels"], + ).logits + + else: + completion_logits = self.ref_model( + padded_batch["completion_input_ids"], attention_mask=padded_batch["completion_attention_mask"] + ).logits + + completion_logps = self.get_batch_logps( + completion_logits, + padded_batch["completion_labels"], + average_log_prob=False, + is_encoder_decoder=self.is_encoder_decoder, + ) + + return completion_logps + + @staticmethod + def get_batch_logps( + logits: torch.FloatTensor, + labels: torch.LongTensor, + average_log_prob: bool = False, + is_encoder_decoder: bool = False, + ) -> torch.FloatTensor: + """Compute the log probabilities of the given labels under the given logits. + + Args: + logits: Logits of the model (unnormalized). Shape: (batch_size, sequence_length, vocab_size) + labels: + Labels for which to compute the log probabilities. Label tokens with a value of `-100` are ignored. + Shape: (batch_size, sequence_length) + average_log_prob: + If True, return the average log probability per (non-masked) token. Otherwise, return the sum of the + log probabilities of the (non-masked) tokens. + is_encoder_decoder: + Whether the model is an encoder-decoder model. If True, the labels are not shifted, and the logits are + assumed to already be aligned with the labels. If False, the labels are shifted to the right by one + position, and the logits are assumed to be aligned with the shifted labels. + + Returns: + A tensor of shape (batch_size,) containing the average/sum log probabilities of the given labels under the + given logits. + """ + if logits.shape[:-1] != labels.shape: + raise ValueError("Logits (batch and sequence length dim) and labels must have the same shape.") + + if not is_encoder_decoder: + labels = labels[:, 1:].clone() + logits = logits[:, :-1, :] + else: + # Fixes end-dec RuntimeError + labels = labels.clone() + + loss_mask = labels != -100 + + # dummy token; we'll ignore the losses on these tokens later + labels[labels == -100] = 0 + + per_token_logps = selective_log_softmax(logits, labels) + + if average_log_prob: + return (per_token_logps * loss_mask).sum(-1) / loss_mask.sum(-1) + else: + return (per_token_logps * loss_mask).sum(-1) + + def forward( + self, model: nn.Module, batch: dict[str, list | torch.LongTensor] + ) -> tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: + model_kwargs = ( + { + "labels": batch["completion_labels"], + "decoder_input_ids": batch.get("completion_decoder_input_ids"), + } + if self.is_encoder_decoder + else {} + ) + if self.aux_loss_enabled: + model_kwargs["output_router_logits"] = True + + outputs = model( + batch["completion_input_ids"], + attention_mask=batch["completion_attention_mask"], + **model_kwargs, + ) + completion_logits = outputs.logits + + completion_logps = self.get_batch_logps( + completion_logits, + batch["completion_labels"], + average_log_prob=False, + is_encoder_decoder=self.is_encoder_decoder, + ) + + if completion_logps.shape[0] != len(batch["label"]): + raise ValueError( + "There is a mismatch between the number of examples in this batch and the number of " + "examples for which an output sequence was predicted." + ) + + chosen_idx = [i for i in range(completion_logps.shape[0]) if batch["label"][i] is True] + rejected_idx = [i for i in range(completion_logps.shape[0]) if batch["label"][i] is False] + + chosen_logps = completion_logps[chosen_idx, ...] + rejected_logps = completion_logps[rejected_idx, ...] + + chosen_logits = completion_logits[chosen_idx, ...] + rejected_logits = completion_logits[rejected_idx, ...] + + if self.aux_loss_enabled: + return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, outputs.aux_loss) + else: + return (chosen_logps, rejected_logps, chosen_logits, rejected_logits) + + def _get_udm_weight(self, rejected_embeddings: torch.FloatTensor) -> torch.FloatTensor: + prob_desirable = self._get_chosen_prob(rejected_embeddings) + min_ratio = self.args.min_density_ratio + max_ratio = self.args.max_density_ratio + + weight = (prob_desirable / (1 - prob_desirable + 1e-8)).clamp(min=min_ratio, max=max_ratio) + + return weight + + def bco_loss( + self, + policy_chosen_logps: torch.FloatTensor, + policy_rejected_logps: torch.FloatTensor, + reference_chosen_logps: torch.FloatTensor, + reference_rejected_logps: torch.FloatTensor, + chosen_embeddings: torch.FloatTensor | None, + rejected_embeddings: torch.FloatTensor | None, + do_train: bool = True, + ) -> tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: + """Compute the BCO loss for a batch of policy and reference model log probabilities. + + Args: + policy_chosen_logps: + Log probabilities of the policy model for the chosen responses. Shape: (num(chosen) in batch_size,) + policy_rejected_logps: + Log probabilities of the policy model for the rejected responses. Shape: (num(rejected) in batch_size,) + reference_chosen_logps: + Log probabilities of the reference model for the chosen responses. Shape: (num(chosen) in batch_size,) + reference_rejected_logps: + Log probabilities of the reference model for the rejected responses. Shape: (num(rejected) in + batch_size,) + chosen_embeddings: embeddings of desirable prompts + rejected_embeddings: embeddings of undesirable prompts + do_train: whether to update the running delta value. Default is True. + + Returns: + A tuple of four tensors: (losses, chosen_rewards, rejected_rewards, delta). The losses tensor contains the + BCO loss for each example in the batch. The chosen_rewards and rejected_rewards tensors contain the rewards + for the chosen and rejected responses, respectively. The delta value contains the moving average of all + implicit rewards. + """ + + chosen_logratios = policy_chosen_logps - reference_chosen_logps + chosen_rewards = self.beta * chosen_logratios + + rejected_logratios = policy_rejected_logps - reference_rejected_logps + rejected_rewards = self.beta * rejected_logratios + + if do_train: + self.running.update(torch.cat((chosen_rewards, rejected_rewards), 0).detach()) + delta = torch.as_tensor(self.running.mean, device=chosen_rewards.device) + + chosen_losses = -F.logsigmoid(chosen_rewards - delta) + rejected_losses = -F.logsigmoid(-(rejected_rewards - delta)) + + if self.match_underlying_distribution: + chosen_weight = torch.ones_like(chosen_losses) + rejected_weight = self._get_udm_weight(rejected_embeddings) + + losses = torch.cat((chosen_weight * chosen_losses, rejected_weight * rejected_losses), dim=0) + else: + losses = torch.cat((chosen_losses, rejected_losses), dim=0) + + return losses, chosen_rewards, rejected_rewards, delta + + def get_batch_loss_metrics( + self, + model, + batch: dict[str, list | torch.LongTensor], + do_train: bool = True, + ): + """Compute the BCO loss and other metrics for the given batch of inputs for train or test.""" + metrics = {} + batch = {k: (v.to(self.accelerator.device) if isinstance(v, torch.Tensor) else v) for k, v in batch.items()} + + forward_output = self.forward(model, batch) + ( + policy_chosen_logps, + policy_rejected_logps, + policy_chosen_logits, + policy_rejected_logits, + ) = forward_output[:4] + if self.aux_loss_enabled: + aux_loss = forward_output[4] + + # if reference_logps in batch use them, otherwise use the reference model + if "reference_logps" in batch: + chosen_idx = [i for i in range(batch["reference_logps"].shape[0]) if batch["label"][i] is True] + rejected_idx = [i for i in range(batch["reference_logps"].shape[0]) if batch["label"][i] is False] + + reference_chosen_logps = batch["reference_logps"][chosen_idx, ...] + reference_rejected_logps = batch["reference_logps"][rejected_idx, ...] + else: + with torch.no_grad(): + if self.ref_model is None: + with self.null_ref_context(): + ( + reference_chosen_logps, + reference_rejected_logps, + _, + _, + ) = self.forward(self.model, batch)[:4] + else: + ( + reference_chosen_logps, + reference_rejected_logps, + _, + _, + ) = self.forward(self.ref_model, batch)[:4] + + chosen_embeddings, rejected_embeddings = self._get_prompt_embeddings(batch) + + losses, chosen_rewards, rejected_rewards, delta = self.bco_loss( + policy_chosen_logps, + policy_rejected_logps, + reference_chosen_logps, + reference_rejected_logps, + chosen_embeddings, + rejected_embeddings, + do_train=do_train, + ) + metrics["delta"] = self.accelerator.gather_for_metrics(delta).mean().item() + + num_chosen = torch.Tensor([len(chosen_rewards)]).to(self.accelerator.device) + num_rejected = torch.Tensor([len(rejected_rewards)]).to(self.accelerator.device) + + all_num_chosen = self.accelerator.gather_for_metrics(num_chosen).sum().item() + all_num_rejected = self.accelerator.gather_for_metrics(num_rejected).sum().item() + + if all_num_chosen > 0: + metrics["rewards/chosen_sum"] = ( + self.accelerator.gather_for_metrics(chosen_rewards.nansum()).nansum().item() + ) + metrics["logps/chosen_sum"] = ( + self.accelerator.gather_for_metrics(policy_chosen_logps.nansum()).nansum().item() + ) + metrics["logits/chosen_sum"] = ( + self.accelerator.gather_for_metrics(policy_chosen_logits.nansum()).nansum().item() + ) + metrics["count/chosen"] = all_num_chosen + + if all_num_rejected > 0: + metrics["rewards/rejected_sum"] = ( + self.accelerator.gather_for_metrics(rejected_rewards.nansum()).nansum().item() + ) + metrics["logps/rejected_sum"] = ( + self.accelerator.gather_for_metrics(policy_rejected_logps.nansum()).nansum().item() + ) + metrics["logits/rejected_sum"] = ( + self.accelerator.gather_for_metrics(policy_rejected_logits.nansum()).nansum().item() + ) + metrics["count/rejected"] = all_num_rejected + + loss = losses.nanmean() + if self.aux_loss_enabled: + loss += self.aux_loss_coef * aux_loss + + return loss, metrics + + def compute_loss( + self, + model: PreTrainedModel | nn.Module, + inputs: dict[str, torch.Tensor | Any], + return_outputs=False, + num_items_in_batch=None, + ) -> torch.Tensor | tuple[torch.Tensor, dict[str, torch.Tensor]]: + compute_loss_context_manager = ( + autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext() + ) + + with compute_loss_context_manager: + loss, metrics = self.get_batch_loss_metrics(model, inputs) + + # Make sure to move the loss to the device the original accumulating loss is at back in the `Trainer` class: + loss = loss.to(self.args.device) + # force log the metrics + if self.accelerator.is_main_process: + self.store_metrics(metrics, train_eval="train") + + if return_outputs: + return (loss, metrics) + return loss + + def store_metrics(self, metrics: dict[str, float], train_eval: Literal["train", "eval"] = "train") -> None: + for key, value in metrics.items(): + self._stored_metrics[train_eval][key].append(value) + + def _get_train_sampler(self, dataset: Dataset | None = None) -> torch.utils.data.Sampler | None: + if dataset is None: + dataset = self.train_dataset + if dataset is None or not has_length(dataset): + return None + return SequentialSampler(dataset) + + def generate_from_model_and_ref(self, model, batch: dict[str, torch.LongTensor]) -> tuple[str, str]: + """Generate samples from the model and reference model for the given batch of inputs.""" + + # If one uses `generate_during_eval` with peft + bf16, we need to explicitly call generate with + # the torch amp context manager as some hidden states are silently casted to full precision. + generate_context_manager = ( + autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext() + ) + with generate_context_manager: + policy_output = model.generate( + input_ids=batch["prompt_input_ids"], + attention_mask=batch["prompt_attention_mask"], + max_length=self.max_length, + do_sample=True, + pad_token_id=self.processing_class.pad_token_id, + ) + + # if reference_output in batch use that otherwise use the reference model + if "reference_output" in batch: + reference_output = batch["reference_output"] + else: + if self.ref_model is None: + with self.null_ref_context(): + reference_output = self.model.generate( + input_ids=batch["prompt_input_ids"], + attention_mask=batch["prompt_attention_mask"], + max_length=self.max_length, + do_sample=True, + pad_token_id=self.processing_class.pad_token_id, + ) + else: + reference_output = self.ref_model.generate( + input_ids=batch["prompt_input_ids"], + attention_mask=batch["prompt_attention_mask"], + max_length=self.max_length, + do_sample=True, + pad_token_id=self.processing_class.pad_token_id, + ) + + policy_output = pad_to_length(policy_output, self.max_length, self.processing_class.pad_token_id) + policy_output_decoded = self.processing_class.batch_decode(policy_output, skip_special_tokens=True) + + reference_output = pad_to_length(reference_output, self.max_length, self.processing_class.pad_token_id) + reference_output_decoded = self.processing_class.batch_decode(reference_output, skip_special_tokens=True) + + return policy_output_decoded, reference_output_decoded + + def prediction_step( + self, + model: PreTrainedModel | nn.Module, + inputs: dict[str, torch.Tensor | Any], + prediction_loss_only: bool, + ignore_keys: list[str] | None = None, + ): + if ignore_keys is None: + if hasattr(model, "config"): + ignore_keys = getattr(model.config, "keys_to_ignore_at_inference", []) + else: + ignore_keys = [] + + prediction_context_manager = ( + autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext() + ) + with torch.no_grad(), prediction_context_manager: + loss, metrics = self.get_batch_loss_metrics(model, inputs, do_train=False) + + # force log the metrics + if self.accelerator.is_main_process: + self.store_metrics(metrics, train_eval="eval") + + if prediction_loss_only: + return (loss.detach(), None, None) + + # logits for the chosen and rejected samples from model + logits_dict = {} + if "logits/chosen_sum" in metrics: + logits_dict["eval_logits/chosen"] = metrics["logits/chosen_sum"] + if "logits/rejected_sum" in metrics: + logits_dict["eval_logits/rejected"] = metrics["logits/rejected_sum"] + logits = [v for k, v in logits_dict.items() if k not in ignore_keys] + logits = torch.tensor(logits, device=self.accelerator.device) + labels = torch.zeros(logits.shape[0], device=self.accelerator.device) + + return (loss.detach(), logits, labels) + + def evaluation_loop( + self, + dataloader: DataLoader, + description: str, + prediction_loss_only: bool | None = None, + ignore_keys: list[str] | None = None, + metric_key_prefix: str = "eval", + ) -> EvalLoopOutput: + """ + Overriding built-in evaluation loop to store metrics for each batch. Prediction/evaluation loop, shared by + `Trainer.evaluate()` and `Trainer.predict()`. + + Works both with or without labels. + """ + + # Sample and save to game log if requested (for one batch to save time) + if self.generate_during_eval: + # Generate random indices within the range of the total number of samples + num_samples = len(dataloader.dataset) + random_indices = random.sample(range(num_samples), k=self.args.eval_batch_size) + + # Use dataloader.dataset.select to get the random batch without iterating over the DataLoader + random_batch_dataset = dataloader.dataset.select(random_indices) + random_batch = self.data_collator(random_batch_dataset) + random_batch = self._prepare_inputs(random_batch) + + target_labels = torch.tensor(random_batch["label"], dtype=torch.bool, device=self.accelerator.device) + target_indices = torch.where(~target_labels)[0] + target_batch = { + "prompt_input_ids": random_batch["prompt_input_ids"][target_indices], + "prompt_attention_mask": random_batch["prompt_attention_mask"][target_indices], + "prompt": itemgetter(*target_indices)(random_batch["prompt"]), + } + policy_output_decoded, ref_output_decoded = self.generate_from_model_and_ref(self.model, target_batch) + + table = pd.DataFrame( + columns=["Prompt", "Policy", "Ref Model"], + data=[ + [prompt, pol[len(prompt) :], ref[len(prompt) :]] + for prompt, pol, ref in zip( + target_batch["prompt"], policy_output_decoded, ref_output_decoded, strict=True + ) + ], + ) + if "wandb" in self.args.report_to: + wandb.log({"game_log": wandb.Table(data=table)}) + + if "comet_ml" in self.args.report_to: + log_table_to_comet_experiment( + name="game_log.csv", + table=table, + ) + + # Base evaluation + initial_output = super().evaluation_loop( + dataloader, description, prediction_loss_only, ignore_keys, metric_key_prefix + ) + + return initial_output + + def log(self, logs: dict[str, float], start_time: float | None = None) -> None: + """ + Log `logs` on the various objects watching training, including stored metrics. + + Args: + logs (`dict[str, float]`): + The values to log. + start_time (`float`, *optional*): + Start time of the training. + """ + # logs either has 'loss' or 'eval_loss' + train_eval = "train" if "loss" in logs else "eval" + # train metrics should have no prefix, eval should have 'eval_' + prefix = "eval_" if train_eval == "eval" else "" + # accumulate average metrics from sums and lengths + for split in ["chosen", "rejected"]: + if f"count/{split}" in self._stored_metrics[train_eval]: + count_sum = torch.Tensor(self._stored_metrics[train_eval][f"count/{split}"]).sum().item() + for metric in ["rewards", "logps", "logits"]: + logs[f"{prefix}{metric}/{split}"] = ( + torch.Tensor(self._stored_metrics[train_eval][f"{metric}/{split}_sum"]).sum().item() + / count_sum + ) + # delete obsolete metric + del self._stored_metrics[train_eval][f"{metric}/{split}_sum"] + del self._stored_metrics[train_eval][f"count/{split}"] + # calculate reward margin + if f"{prefix}rewards/chosen" in logs and f"{prefix}rewards/rejected" in logs: + logs[f"{prefix}rewards/margins"] = logs[f"{prefix}rewards/chosen"] - logs[f"{prefix}rewards/rejected"] + # Add averaged stored metrics to logs + for key, metrics in self._stored_metrics[train_eval].items(): + logs[f"{prefix}{key}"] = torch.Tensor(metrics).mean().item() + del self._stored_metrics[train_eval] + return super().log(logs, start_time) + + # Ensure the model card is saved along with the checkpoint + def _save_checkpoint(self, model, trial): + if self.args.hub_model_id is None: + model_name = Path(self.args.output_dir).name + else: + model_name = self.args.hub_model_id.split("/")[-1] + self.create_model_card(model_name=model_name) + super()._save_checkpoint(model, trial) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/bema_for_ref_model/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/bema_for_ref_model/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8d7de0bee7977851b77a803f297a91ed6d170e27 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/bema_for_ref_model/__init__.py @@ -0,0 +1,16 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .callback import BEMACallback +from .dpo_trainer import DPOTrainer diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/bema_for_ref_model/callback.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/bema_for_ref_model/callback.py new file mode 100644 index 0000000000000000000000000000000000000000..d030be9fb51c428fe82e6391c2ec64a05345d5d5 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/bema_for_ref_model/callback.py @@ -0,0 +1,221 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging + +import torch +from transformers import PreTrainedModel, TrainerControl, TrainerState, TrainingArguments +from transformers.trainer_callback import CallbackHandler + +from ...trainer.callbacks import BEMACallback as _BEMACallback + + +# Logger for module-level logging +logger = logging.getLogger(__name__) + + +class CallbackHandlerWithRefModel(CallbackHandler): + """ + A [`~transformers.CallbackHandler`] that supports passing a reference model to callbacks. + """ + + def __init__(self, callbacks, model, ref_model, processing_class, optimizer, lr_scheduler): + super().__init__(callbacks, model, processing_class, optimizer, lr_scheduler) + self.ref_model = ref_model + + # Copied from CallbackHandler.call_event with the addition of `ref_model` to the callback call. + def call_event(self, event, args, state, control, **kwargs): + for callback in self.callbacks: + result = getattr(callback, event)( + args, + state, + control, + model=self.model, + ref_model=self.ref_model, # <- Added ref_model to the callback call + processing_class=self.processing_class, + optimizer=self.optimizer, + lr_scheduler=self.lr_scheduler, + train_dataloader=self.train_dataloader, + eval_dataloader=self.eval_dataloader, + **kwargs, + ) + # A Callback can skip the return of `control` if it doesn't change it. + if result is not None: + control = result + return control + + +class BEMACallback(_BEMACallback): + # docstyle-ignore + r""" + A [`~transformers.TrainerCallback`] that implements [BEMA](https://huggingface.co/papers/2508.00180) + (Bias-Corrected Exponential Moving Average) by [Adam Block](https://huggingface.co/abblock) and [Cyril + Zhang](https://huggingface.co/cyrilzhang). Code from https://github.com/abblock/bema under MIT license. + + BEMA computes model weights that scale like: + + $$ + \theta_t' = \alpha_t \cdot (\theta_t - \theta_0) + \text{EMA}_t + $$ + + where \\( \theta_t \\) is the current model weights, \\( \theta_0 \\) is a snapshot of the model weights at the + first `update_after` step, \\( \text{EMA}_t \\) is the exponential moving average of the model weights, and + \\( \alpha_t \\) is a scaling factor that decays with the number of steps \\( t \\) as + + $$ + \alpha_t = (\rho + \gamma \cdot t)^{-\eta}. + $$ + + The EMA is computed as: + + $$ + \text{EMA}_t = (1 - \beta_t) \cdot \text{EMA}_{t-1} + \beta_t \cdot \theta_t + $$ + + where \\( \beta_t \\) is a decay factor that decays with the number of steps \\( t \\) as + + $$ + \beta_t = (\rho + \gamma \cdot t)^{-\kappa}. + $$ + + Args: + update_freq (`int`, *optional*, defaults to `400`): + Update the BEMA weights every X steps. Denoted this as \\( \phi \\) in the paper. + ema_power (`float`, *optional*, defaults to `0.5`): + Power for the EMA decay factor. Denoted \\( \kappa \\) in the paper. To disable EMA, set this to `0.0`. + bias_power (`float`, *optional*, defaults to `0.2`): + Power for the BEMA scaling factor. Denoted \\( \eta \\) in the paper. To disable BEMA, set this to `0.0`. + lag (`int`, *optional*, defaults to `10`): + Initial offset in the weight decay schedule that controls early-stage smoothness by acting as a virtual + starting age for the updates. Denoted as \\( \rho \\) in the paper. + update_after (`int`, *optional*, defaults to `0`): + Burn-in time before starting to update the BEMA weights. Denoted \\( \tau \\) in the paper. + multiplier (`float`, *optional*, defaults to `1.0`): + Initial value for the EMA decay factor. Denoted as \\( \gamma \\) in the paper. + min_ema_multiplier (`float`, *optional*, defaults to `0.0`): + Minimum value for the EMA decay factor. + device (`str`, *optional*, defaults to `"cpu"`): + Device to use for the BEMA buffers, e.g. `"cpu"` or `"cuda"`. Note that in most cases, this device SHOULD + BE DIFFERENT from the device used for training in order to avoid OOM. + update_ref_model (`bool`, *optional*, defaults to `False`): + Whether to update the reference model with BEMA weights. This creates a lagged, smoothed version of the + main model as the reference model. + ref_model_update_freq (`int`, *optional*, defaults to `400`): + Update the reference model with BEMA weights every this many steps. + ref_model_update_after (`int`, *optional*, defaults to `0`): + Number of steps to wait before starting to update the reference model. + + Example: + + ```python + from trl import BEMACallback + + trainer = Trainer(..., callbacks=[BEMACallback()]) + ``` + """ + + def __init__( + self, + update_freq: int = 400, + ema_power: float = 0.5, + bias_power: float = 0.2, + lag: int = 10, + update_after: int = 0, + multiplier: float = 1.0, + min_ema_multiplier: float = 0.0, + device: str = "cpu", + update_ref_model: bool = False, + ref_model_update_freq: int = 400, + ref_model_update_after: int = 0, + ): + super().__init__( + update_freq, + ema_power, + bias_power, + lag, + update_after, + multiplier, + min_ema_multiplier, + device, + ) + # Reference model update parameters + self.update_ref_model = update_ref_model + self.ref_model_update_freq = ref_model_update_freq + self.ref_model_update_after = ref_model_update_after + + @torch.no_grad() + def on_step_end( + self, args: TrainingArguments, state: TrainerState, control: TrainerControl, model: PreTrainedModel, **kwargs + ): + super().on_step_end(args, state, control, model, **kwargs) + + step = state.global_step + # Update reference model if enabled + if ( + self.update_ref_model + and step >= self.ref_model_update_after + and (step - self.ref_model_update_after) % self.ref_model_update_freq == 0 + ): + if "ref_model" not in kwargs: + raise ValueError("'ref_model' not found in kwargs.") + + ref_model = kwargs["ref_model"] + + # Get the current BEMA state dict + bema_state_dict = self.running_model.state_dict() + + # Handle the case where ref_model is None (PEFT case) + if ref_model is None: + # In PEFT case, ref_model is None and we need to update the base model of the main model + main_model = self._unwrap_model(model) + if hasattr(main_model, "get_base_model"): + # This is a PEFT model, update the base model + base_model = main_model.get_base_model() + self._update_model_with_bema_weights(base_model, bema_state_dict, is_peft_base=True) + else: + # Regular model, update directly + self._update_model_with_bema_weights(main_model, bema_state_dict, is_peft_base=False) + else: + # ref_model is provided, unwrap it and update + ref_model = self._unwrap_model(ref_model) + if hasattr(ref_model, "get_base_model"): + # This is a PEFT model, update the base model + base_model = ref_model.get_base_model() + self._update_model_with_bema_weights(base_model, bema_state_dict, is_peft_base=True) + else: + # Regular model, update directly + self._update_model_with_bema_weights(ref_model, bema_state_dict, is_peft_base=False) + + logger.info("BEMACallback: Updated reference model with BEMA weights") + + def _update_model_with_bema_weights(self, model, bema_state_dict, is_peft_base=False): + """Helper method to update a model with BEMA weights, handling PEFT and distributed scenarios.""" + if is_peft_base: + # For PEFT base models, filter out adapter parameters + filtered_state_dict = {} + for key, value in bema_state_dict.items(): + # Skip adapter parameters + if not key.startswith("lora_") and not key.startswith("adapter_"): + # Remove 'base_model.' prefix if it exists + if key.startswith("base_model."): + base_key = key[len("base_model.") :] + else: + base_key = key + filtered_state_dict[base_key] = value + + # Update the base model + model.load_state_dict(filtered_state_dict, strict=False) + else: + # Regular model, update directly + model.load_state_dict(bema_state_dict, strict=False) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/bema_for_ref_model/dpo_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/bema_for_ref_model/dpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..8c50a232dc38c236dc64d79d32714b799ceeea8d --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/bema_for_ref_model/dpo_trainer.py @@ -0,0 +1,30 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from ...trainer.dpo_trainer import DPOTrainer as _DPOTrainer +from .callback import CallbackHandlerWithRefModel + + +class DPOTrainer(_DPOTrainer): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + # Replace with a new one that calls the events with the reference model + self.callback_handler = CallbackHandlerWithRefModel( + self.callback_handler.callbacks, + self.model, + self.ref_model, + self.processing_class, + self.optimizer, + self.lr_scheduler, + ) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/cpo/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/cpo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..57e151f53f63b9af52f3b7ba9355e1b3e223fc93 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/cpo/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .cpo_config import CPOConfig +from .cpo_trainer import CPOTrainer + + +__all__ = ["CPOConfig", "CPOTrainer"] diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/cpo/cpo_config.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/cpo/cpo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..74e1c371300614c80aef18d63ec88627ce3776c7 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/cpo/cpo_config.py @@ -0,0 +1,172 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field +from typing import Any + +from ...trainer.base_config import _BaseConfig + + +@dataclass +class CPOConfig(_BaseConfig): + # docstyle-ignore + r""" + Configuration class for the [`experimental.cpo.CPOTrainer`]. + + This class includes only the parameters that are specific to CPO 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: + max_length (`int` or `None`, *optional*, defaults to `1024`): + Maximum length of the sequences (prompt + completion) in the batch. This argument is required if you want + to use the default data collator. + max_completion_length (`int`, *optional*): + Maximum length of the completion. This argument is required if you want to use the default data collator + and your model is an encoder-decoder. + beta (`float`, *optional*, defaults to `0.1`): + Parameter controlling the deviation from the reference model. Higher β means less deviation from the + reference model. For the IPO loss (`loss_type="ipo"`), β is the regularization parameter denoted by τ in + the [paper](https://huggingface.co/papers/2310.12036). + label_smoothing (`float`, *optional*, defaults to `0.0`): + Label smoothing factor. This argument is required if you want to use the default data collator. + loss_type (`str`, *optional*, defaults to `"sigmoid"`): + Type of loss to use. Possible values are: + + - `"sigmoid"`: sigmoid loss from the original [DPO](https://huggingface.co/papers/2305.18290) paper. + - `"hinge"`: hinge loss on the normalized likelihood from the + [SLiC](https://huggingface.co/papers/2305.10425) paper. + - `"ipo"`: IPO loss from the [IPO](https://huggingface.co/papers/2310.12036) paper. + - `"simpo"`: SimPO loss from the [SimPO](https://huggingface.co/papers/2405.14734) paper. + - `"alphapo"`: AlphaPO loss from the [AlphaPO](https://huggingface.co/papers/2501.03884) paper. This + automatically sets `loss_type="simpo"` and `cpo_alpha=0.0`. + + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the model. + cpo_alpha (`float`, *optional*, defaults to `1.0`): + Weight of the BC regularizer in CPO training. + simpo_gamma (`float`, *optional*, defaults to `0.5`): + Target reward margin for the SimPO loss, used only when the `loss_type="simpo"`. + alpha (`float`, *optional*, defaults to `0.0`): + Alpha parameter that controls reward function shape across all loss types. When alpha=0 (default), uses + standard log probability rewards. When `alpha != 0`, applies AlphaPO transformation: `r = (1 - p^(-alpha)) + / alpha` from the [AlphaPO paper](https://huggingface.co/papers/2501.03884). This parameter works with all + loss types. + generate_during_eval (`bool`, *optional*, defaults to `False`): + If `True`, generates and logs completions from the model to W&B or Comet during evaluation. + is_encoder_decoder (`bool`, *optional*): + When using the `model_init` argument (callable) to instantiate the model instead of the `model` argument, + you need to specify if the model returned by the callable is an encoder-decoder model. + model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model from a + string. + dataset_num_proc (`int`, *optional*): + Number of processes to use for processing the dataset. + + > [!NOTE] + > These parameters have default values different from [`~transformers.TrainingArguments`]: + > - `logging_steps`: Defaults to `10` instead of `500`. + > - `gradient_checkpointing`: Defaults to `True` instead of `False`. + > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`. + > - `learning_rate`: Defaults to `1e-6` instead of `5e-5`. + """ + + _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"] + + # Parameters whose default values are overridden from TrainingArguments + learning_rate: float = field( + default=1e-6, + metadata={"help": "The initial learning rate for AdamW."}, + ) + + max_length: int | None = field( + default=1024, + metadata={"help": "Maximum length of the sequences (prompt + completion) in the batch."}, + ) + max_completion_length: int | None = field( + default=None, + metadata={ + "help": "Maximum length of the completion. This argument is required if you want to use the default data " + "collator and your model is an encoder-decoder." + }, + ) + beta: float = field( + default=0.1, + metadata={ + "help": "Parameter controlling the deviation from the reference model. Higher β means less deviation from " + "the reference model." + }, + ) + label_smoothing: float = field( + default=0.0, + metadata={"help": "Label smoothing factor."}, + ) + loss_type: str = field( + default="sigmoid", + metadata={ + "help": "Type of loss to use.", + "choices": ["sigmoid", "hinge", "ipo", "simpo", "alphapo"], + }, + ) + disable_dropout: bool = field( + default=True, + metadata={"help": "Whether to disable dropout in the model."}, + ) + cpo_alpha: float = field( + default=1.0, + metadata={"help": "Weight of the BC regularizer in CPO training."}, + ) + simpo_gamma: float = field( + default=0.5, + metadata={"help": "Target reward margin for the SimPO loss, used only when the `loss_type='simpo'`."}, + ) + alpha: float = field( + default=0.0, + metadata={ + "help": "Alpha parameter that controls reward function shape across all loss types. When alpha=0 " + "(default), uses standard log probability rewards. When `alpha != 0`, applies AlphaPO transformation: " + "`r = (1 - p^(-alpha)) / alpha` from the AlphaPO paper. This parameter works with all loss types." + }, + ) + generate_during_eval: bool = field( + default=False, + metadata={"help": "If `True`, generates and logs completions from the model to W&B during evaluation."}, + ) + is_encoder_decoder: bool | None = field( + default=None, + metadata={"help": "Whether the model is an encoder-decoder model."}, + ) + model_init_kwargs: dict[str, Any] | str | None = field( + default=None, + metadata={ + "help": "Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model " + "from a string." + }, + ) + dataset_num_proc: int | None = field( + default=None, + metadata={"help": "Number of processes to use for processing the dataset."}, + ) + + def __post_init__(self): + # Syntactic sugar for AlphaPO: set loss_type to "simpo" and cpo_alpha to 0.0 + if self.loss_type == "alphapo": + self.loss_type = "simpo" + self.cpo_alpha = 0.0 + + super().__post_init__() diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/cpo/cpo_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/cpo/cpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..51c89cc23cf23b2ad9307d093c474a5ccd0cca72 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/cpo/cpo_trainer.py @@ -0,0 +1,1068 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import inspect +import random +import textwrap +from collections import defaultdict +from collections.abc import Callable +from contextlib import nullcontext +from pathlib import Path +from typing import Any, Literal + +import numpy as np +import pandas as pd +import torch +import torch.nn as nn +import torch.nn.functional as F +import transformers +from accelerate import PartialState, logging +from accelerate.utils import is_peft_model +from datasets import Dataset +from packaging.version import Version +from torch import autocast +from torch.utils.data import DataLoader +from transformers import ( + AutoModelForCausalLM, + BaseImageProcessor, + DataCollator, + FeatureExtractionMixin, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, + is_comet_available, + is_wandb_available, +) +from transformers.trainer_utils import EvalLoopOutput +from transformers.utils import is_peft_available, is_torch_fx_proxy + +from ...data_utils import maybe_apply_chat_template, maybe_extract_prompt +from ...trainer.base_trainer import _BaseTrainer +from ...trainer.utils import disable_dropout_in_model, log_table_to_comet_experiment, selective_log_softmax +from ..utils import ( + DPODataCollatorWithPadding, + add_bos_token_if_needed, + add_eos_token_if_needed, + pad_to_length, + peft_module_casting_to_bf16, +) +from .cpo_config import CPOConfig + + +if is_peft_available(): + from peft import PeftConfig, get_peft_model, prepare_model_for_kbit_training + + +if is_wandb_available(): + import wandb + + +logger = logging.get_logger(__name__) + + +class CPOTrainer(_BaseTrainer): + r""" + Initialize CPOTrainer. + + Args: + model ([`~transformers.PreTrainedModel`]): + The model to train, preferably an [`~transformers.AutoModelForSequenceClassification`]. + args ([`experimental.cpo.CPOConfig`]): + The CPO config arguments to use for training. + data_collator ([`~transformers.DataCollator`]): + The data collator to use for training. If None is specified, the default data collator + ([`experimental.utils.DPODataCollatorWithPadding`]) will be used which will pad the sequences to the + maximum length of the sequences in the batch, given a dataset of paired sequences. + train_dataset ([`~datasets.Dataset`]): + The dataset to use for training. + eval_dataset ([`~datasets.Dataset`]): + The dataset to use for evaluation. + processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*): + Processing class used to process the data. If provided, will be used to automatically process the inputs + for the model, and it will be saved along the model to make it easier to rerun an interrupted training or + reuse the fine-tuned model. + model_init (`Callable[[], transformers.PreTrainedModel]`): + The model initializer to use for training. If None is specified, the default model initializer will be + used. + callbacks (`list[transformers.TrainerCallback]`): + The callbacks to use for training. + optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`): + The optimizer and scheduler to use for training. + preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`): + The function to use to preprocess the logits before computing the metrics. + peft_config ([`~peft.PeftConfig`], *optional*): + The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in + a PEFT model. + compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*): + The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to + metric values. + """ + + _tag_names = ["trl", "cpo"] + _name = "CPO" + _paper = { + "title": "Contrastive Preference Optimization: Pushing the Boundaries of LLM Performance in Machine Translation", + "id": "2401.08417", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @inproceedings{xu2024contrastive, + title = {{Contrastive Preference Optimization: Pushing the Boundaries of LLM Performance in Machine Translation}}, + author = {Haoran Xu and Amr Sharaf and Yunmo Chen and Weiting Tan and Lingfeng Shen and Benjamin Van Durme and Kenton Murray and Young Jin Kim}, + year = 2024, + booktitle = {Forty-first International Conference on Machine Learning, {ICML} 2024, Vienna, Austria, July 21-27, 2024}, + publisher = {OpenReview.net}, + url = {https://openreview.net/forum?id=51iwkioZpn} + }"""), + } + + def __init__( + self, + model: PreTrainedModel | nn.Module | str | None = None, + args: CPOConfig | None = None, + data_collator: DataCollator | None = None, + train_dataset: Dataset | None = None, + eval_dataset: Dataset | dict[str, Dataset] | None = None, + processing_class: PreTrainedTokenizerBase + | BaseImageProcessor + | FeatureExtractionMixin + | ProcessorMixin + | None = None, + model_init: Callable[[], PreTrainedModel] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None, + peft_config: "PeftConfig | None" = None, + compute_metrics: Callable[[EvalLoopOutput], dict] | None = None, + ): + if train_dataset is None: + raise ValueError("`train_dataset` is required") + + if args.model_init_kwargs is None: + model_init_kwargs = {} + elif not isinstance(model, str): + raise ValueError("You passed model_kwargs to the CPOTrainer. But your model is already instantiated.") + else: + model_init_kwargs = args.model_init_kwargs + dtype = model_init_kwargs.get("dtype", "auto") + if dtype is not None: + # Convert to `torch.dtype` if an str is passed + if isinstance(dtype, str) and dtype != "auto": + dtype = getattr(torch, dtype) + if dtype != "auto" and not isinstance(dtype, torch.dtype): + raise ValueError( + f"Invalid `dtype` passed to the CPOConfig. Expected a string with either `torch.dtype` or 'auto', but got {dtype}." + ) + model_init_kwargs["dtype"] = dtype + model_init_kwargs["device_map"] = model_init_kwargs.get("device_map", "auto") + + if isinstance(model, str): + model = AutoModelForCausalLM.from_pretrained(model, **model_init_kwargs) + + # PEFT + # Initialize this variable to False. This helps tracking the case when `peft_module_casting_to_bf16` + # has been called in order to properly call autocast if needed. + self._peft_has_been_casted_to_bf16 = False + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + if is_peft_model(model): + raise ValueError( + "You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first " + "merge and unload the existing adapter, save the resulting base model, and then pass that base " + "model along with the new `peft_config` to the trainer." + ) + + if getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False): + _support_gc_kwargs = hasattr( + args, "gradient_checkpointing_kwargs" + ) and "gradient_checkpointing_kwargs" in list( + inspect.signature(prepare_model_for_kbit_training).parameters + ) + + prepare_model_kwargs = {"use_gradient_checkpointing": args.gradient_checkpointing} + + if _support_gc_kwargs: + prepare_model_kwargs["gradient_checkpointing_kwargs"] = args.gradient_checkpointing_kwargs + + model = prepare_model_for_kbit_training(model, **prepare_model_kwargs) + elif args.gradient_checkpointing: + # For backward compatibility with older versions of transformers + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + # get peft model with the given config + model = get_peft_model(model, peft_config) + if args.bf16 and getattr(model, "is_loaded_in_4bit", False): + peft_module_casting_to_bf16(model) + # If args.bf16 we need to explicitly call `generate` with torch amp autocast context manager + self._peft_has_been_casted_to_bf16 = True + + # For models that use gradient_checkpointing, we need to attach a hook that enables input + # to explicitly have `requires_grad=True`, otherwise training will either silently + # fail or completely fail. + elif args.gradient_checkpointing: + # For backward compatibility with older versions of transformers + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + if args.generate_during_eval and not (is_wandb_available() or is_comet_available()): + raise ValueError( + "`generate_during_eval=True` requires Weights and Biases or Comet to be installed." + " Please install `wandb` or `comet-ml` to resolve." + ) + + if model is not None: + self.is_encoder_decoder = model.config.is_encoder_decoder + elif args.is_encoder_decoder is None: + raise ValueError("When no model is provided, you need to pass the parameter is_encoder_decoder.") + else: + self.is_encoder_decoder = args.is_encoder_decoder + + if self.is_encoder_decoder: + self.decoder_start_token_id = model.config.decoder_start_token_id + self.pad_token_id = model.config.pad_token_id + + if processing_class is None: + raise ValueError("processing_class must be specified to tokenize a CPO dataset.") + if args.max_length is None: + logger.warning( + "`max_length` is not set in the CPOConfig's init" + " it will default to `512` by default, but you should do it yourself in the future.", + ) + max_length = 512 + else: + max_length = args.max_length + + if args.max_completion_length is None and self.is_encoder_decoder: + logger.warning( + "When using an encoder decoder architecture, you should set `max_completion_length` in the CPOConfig's init" + " it will default to `128` by default, but you should do it yourself in the future.", + ) + max_completion_length = 128 + else: + max_completion_length = args.max_completion_length + + if data_collator is None: + data_collator = DPODataCollatorWithPadding( + pad_token_id=processing_class.pad_token_id, + is_encoder_decoder=self.is_encoder_decoder, + ) + + if args.remove_unused_columns: + args.remove_unused_columns = False + # warn users + logger.warning( + "When using DPODataCollatorWithPadding, you should set `remove_unused_columns=False` in your TrainingArguments" + " we have set it for you, but you should do it yourself in the future.", + ) + + self.use_dpo_data_collator = True + else: + self.use_dpo_data_collator = False + + # Disable dropout in the model + if args.disable_dropout: + disable_dropout_in_model(model) + + self.max_length = max_length + self.generate_during_eval = args.generate_during_eval + self.max_completion_length = max_completion_length + self.processing_class = processing_class + + if processing_class.pad_token is None: + processing_class.pad_token = processing_class.eos_token + self.pad_token_id = processing_class.pad_token_id + + if args.loss_type in ["hinge", "ipo"] and args.label_smoothing > 0: + logger.warning( + f"You are using the {args.loss_type} loss type that does not support label smoothing. The " + "`label_smoothing` parameter will be ignored. Set `label_smoothing` to `0.0` to remove this warning.", + ) + if args.loss_type == "kto_pair": + raise ValueError("Support for kto_pair has been removed in CPOTrainer. Please use KTOTrainer.") + + self.beta = args.beta + self.label_smoothing = args.label_smoothing + self.loss_type = args.loss_type + self.cpo_alpha = args.cpo_alpha + self.aux_loss_enabled = getattr(model.config, "output_router_logits", False) + self.aux_loss_coef = getattr(model.config, "router_aux_loss_coef", 0.0) + if self.aux_loss_enabled and self.aux_loss_coef == 0.0: + logger.warning( + "You set `output_router_logits` to `True` in the model config, but `router_aux_loss_coef` is set to " + "`0.0`, meaning the auxiliary loss will not be used. Either set `router_aux_loss_coef` to a value " + "greater than `0.0`, or set `output_router_logits` to `False` if you don't want to use the auxiliary " + "loss.", + ) + + if args.loss_type == "simpo": + self.simpo_gamma = args.simpo_gamma + + # AlphaPO parameter for reward shaping + self.alpha = args.alpha + + self._stored_metrics = defaultdict(lambda: defaultdict(list)) + + # Compute that only on the main process for faster data processing. + # see: https://github.com/huggingface/trl/pull/1255 + with PartialState().main_process_first(): + # Extract the prompt if needed, and apply the chat template if needed + train_dataset = train_dataset.map(maybe_extract_prompt, num_proc=args.dataset_num_proc) + train_dataset = train_dataset.map( + maybe_apply_chat_template, + fn_kwargs={"processing_class": processing_class}, + num_proc=args.dataset_num_proc, + ) + if eval_dataset is not None: + eval_dataset = eval_dataset.map(maybe_extract_prompt, num_proc=args.dataset_num_proc) + eval_dataset = eval_dataset.map( + maybe_apply_chat_template, + fn_kwargs={"processing_class": processing_class}, + num_proc=args.dataset_num_proc, + ) + + # tokenize the dataset + train_dataset = train_dataset.map(self.tokenize_row, num_proc=args.dataset_num_proc) + if eval_dataset is not None: + eval_dataset = eval_dataset.map(self.tokenize_row, num_proc=args.dataset_num_proc) + + # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was + # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream + # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we + # default to the recommended non-reentrant behavior here, while preserving any user-provided value. + if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"): + args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {} + args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False) + + super().__init__( + model=model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + model_init=model_init, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + ) + + # Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the + # model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set + # self.model_accepts_loss_kwargs to False to enable scaling. + self.model_accepts_loss_kwargs = False + + # Add tags for models that have been loaded with the correct transformers version + if hasattr(self.model, "add_model_tags"): + self.model.add_model_tags(self._tag_names) + + if not hasattr(self, "accelerator"): + raise AttributeError( + "Your `Trainer` does not have an `accelerator` object. Consider upgrading `transformers`." + ) + + def build_tokenized_answer(self, prompt, answer): + """ + Llama tokenizer does satisfy `enc(a + b) = enc(a) + enc(b)`. It does ensure `enc(a + b) = enc(a) + enc(a + + b)[len(enc(a)):]`. Reference: + https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257 + """ + + full_tokenized = self.processing_class(prompt + answer, add_special_tokens=False) + prompt_input_ids = self.processing_class(prompt, add_special_tokens=False)["input_ids"] + + answer_input_ids = full_tokenized["input_ids"][len(prompt_input_ids) :] + answer_attention_mask = full_tokenized["attention_mask"][len(prompt_input_ids) :] + + # Concat tokens to form `enc(a) + enc(a + b)[len(enc(a)):]` + full_concat_input_ids = np.concatenate([prompt_input_ids, answer_input_ids]) + + # Prepare input tokens for token by token comparison + full_input_ids = np.array(full_tokenized["input_ids"]) + + if len(full_input_ids) != len(full_concat_input_ids): + raise ValueError("Prompt input ids and answer input ids should have the same length.") + + # On some tokenizers, like Llama-2 tokenizer, there are occasions where tokens + # can be merged together when tokenizing prompt+answer. This could result + # on the last token from the prompt being different when tokenized on its own + # vs when done as prompt+answer. + response_token_ids_start_idx = len(prompt_input_ids) + + # If tokenized prompt is different than both prompt+answer, then it means the + # last token has changed due to merging. + if prompt_input_ids != full_tokenized["input_ids"][:response_token_ids_start_idx]: + response_token_ids_start_idx -= 1 + + prompt_input_ids = full_tokenized["input_ids"][:response_token_ids_start_idx] + prompt_attention_mask = full_tokenized["attention_mask"][:response_token_ids_start_idx] + + if len(prompt_input_ids) != len(prompt_attention_mask): + raise ValueError("Prompt input ids and attention mask should have the same length.") + + answer_input_ids = full_tokenized["input_ids"][response_token_ids_start_idx:] + answer_attention_mask = full_tokenized["attention_mask"][response_token_ids_start_idx:] + + return dict( + prompt_input_ids=prompt_input_ids, + prompt_attention_mask=prompt_attention_mask, + input_ids=answer_input_ids, + attention_mask=answer_attention_mask, + ) + + def tokenize_row(self, feature, model: PreTrainedModel | nn.Module | None = None) -> dict: + """Tokenize a single row from a CPO specific dataset. + + At this stage, we don't convert to PyTorch tensors yet; we just handle the truncation in case the prompt + + chosen or prompt + rejected responses is/are too long. First we truncate the prompt; if we're still too long, + we truncate the chosen/rejected. + + We also create the labels for the chosen/rejected responses, which are of length equal to the sum of the length + of the prompt and the chosen/rejected response, with `-100` for the prompt tokens. + """ + batch = {} + prompt = feature["prompt"] + chosen = feature["chosen"] + rejected = feature["rejected"] + + if not self.is_encoder_decoder: + # Check issues below for more details + # 1. https://github.com/huggingface/trl/issues/907 + # 2. https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257 + # 3. https://github.com/LianjiaTech/BELLE/issues/337 + + if not isinstance(prompt, str): + raise ValueError(f"prompt should be an str but got {type(prompt)}") + prompt_tokens = self.processing_class(prompt, add_special_tokens=False) + prompt_tokens = {f"prompt_{k}": v for k, v in prompt_tokens.items()} + + if not isinstance(chosen, str): + raise ValueError(f"chosen should be an str but got {type(chosen)}") + chosen_tokens = self.build_tokenized_answer(prompt, chosen) + + if not isinstance(rejected, str): + raise ValueError(f"rejected should be an str but got {type(rejected)}") + rejected_tokens = self.build_tokenized_answer(prompt, rejected) + + # Last prompt token might get merged by tokenizer and + # it should not be included for generation if that happens + prompt_len_input_ids = len(prompt_tokens["prompt_input_ids"]) + + chosen_prompt_len_input_ids = len(chosen_tokens["prompt_input_ids"]) + rejected_prompt_len_input_ids = len(rejected_tokens["prompt_input_ids"]) + prompt_len_input_ids = min(chosen_prompt_len_input_ids, rejected_prompt_len_input_ids) + + for k, v in prompt_tokens.items(): + prompt_tokens[k] = v[:prompt_len_input_ids] + + # Make sure prompts only have one different token at most an + # and length only differs by 1 at most + num_diff_tokens = sum( + a != b + for a, b in zip(chosen_tokens["prompt_input_ids"], rejected_tokens["prompt_input_ids"], strict=False) + ) + num_diff_len = abs(chosen_prompt_len_input_ids - rejected_prompt_len_input_ids) + if num_diff_tokens > 1 or num_diff_len > 1: + raise ValueError( + "Chosen and rejected prompt_input_ids might only differ on the " + "last token due to tokenizer merge ops." + ) + + # add BOS token to head of prompt. Avoid adding if it's already there + prompt_tokens, chosen_tokens, rejected_tokens = add_bos_token_if_needed( + self.processing_class.bos_token_id, + prompt_len_input_ids, + prompt_tokens, + chosen_prompt_len_input_ids, + chosen_tokens, + rejected_prompt_len_input_ids, + rejected_tokens, + ) + + # add EOS token to end of answer. Avoid adding if it's already there + chosen_tokens, rejected_tokens = add_eos_token_if_needed( + self.processing_class.eos_token_id, chosen_tokens, rejected_tokens + ) + + longer_response_length = max(len(chosen_tokens["input_ids"]), len(rejected_tokens["input_ids"])) + + # if combined sequence is too long, truncate the response + for answer_tokens in [chosen_tokens, rejected_tokens]: + if len(answer_tokens["prompt_input_ids"]) + longer_response_length > self.max_length: + for k in ["input_ids", "attention_mask"]: + answer_tokens[k] = answer_tokens[k][: self.max_length - longer_response_length] + + # Create labels + chosen_sequence_tokens = { + k: chosen_tokens[f"prompt_{k}"] + chosen_tokens[k] for k in ["input_ids", "attention_mask"] + } + rejected_sequence_tokens = { + k: rejected_tokens[f"prompt_{k}"] + rejected_tokens[k] for k in ["input_ids", "attention_mask"] + } + chosen_sequence_tokens["labels"] = chosen_sequence_tokens["input_ids"][:] + chosen_sequence_tokens["labels"][: len(chosen_tokens["prompt_input_ids"])] = [-100] * len( + chosen_tokens["prompt_input_ids"] + ) + rejected_sequence_tokens["labels"] = rejected_sequence_tokens["input_ids"][:] + rejected_sequence_tokens["labels"][: len(rejected_tokens["prompt_input_ids"])] = [-100] * len( + rejected_tokens["prompt_input_ids"] + ) + + for k, toks in { + "chosen_": chosen_sequence_tokens, + "rejected_": rejected_sequence_tokens, + "": prompt_tokens, + }.items(): + for type_key, tokens in toks.items(): + if type_key == "token_type_ids": + continue + batch[f"{k}{type_key}"] = tokens + + else: + chosen_tokens = self.processing_class( + chosen, truncation=True, max_length=self.max_completion_length, add_special_tokens=True + ) + rejected_tokens = self.processing_class( + rejected, truncation=True, max_length=self.max_completion_length, add_special_tokens=True + ) + prompt_tokens = self.processing_class(prompt, add_special_tokens=True) + + batch["chosen_labels"] = chosen_tokens["input_ids"] + batch["rejected_labels"] = rejected_tokens["input_ids"] + batch["prompt_input_ids"] = prompt_tokens["input_ids"] + batch["prompt_attention_mask"] = prompt_tokens["attention_mask"] + + if model is not None and hasattr(model, "prepare_decoder_input_ids_from_labels"): + batch["rejected_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels( + labels=torch.tensor(batch["rejected_labels"]) + ) + batch["chosen_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels( + labels=torch.tensor(batch["chosen_labels"]) + ) + + return batch + + @staticmethod + def concatenated_inputs( + batch: dict[str, list | torch.LongTensor], + is_encoder_decoder: bool = False, + padding_value: int = 0, + device: torch.device | None = None, + ) -> dict[str, torch.LongTensor]: + """Concatenate the chosen and rejected inputs into a single tensor. + + Args: + batch: + A batch of data. Must contain the keys 'chosen_input_ids' and 'rejected_input_ids', which are tensors + of shape (batch_size, sequence_length). + is_encoder_decoder: + Whether the model is an encoder-decoder model. + padding_value: + The padding value to use for the concatenated inputs_ids. + device: + The device for the concatenated inputs. + + Returns: + A dictionary containing the concatenated inputs under the key 'concatenated_input_ids'. + """ + concatenated_batch = {} + + if is_encoder_decoder: + max_length = max(batch["chosen_labels"].shape[1], batch["rejected_labels"].shape[1]) + else: + max_length = max(batch["chosen_input_ids"].shape[1], batch["rejected_input_ids"].shape[1]) + + for k in batch: + if k.startswith("chosen") and isinstance(batch[k], torch.Tensor): + if "labels" in k or is_encoder_decoder: + pad_value = -100 + elif k.endswith("_input_ids"): + pad_value = padding_value + elif k.endswith("_attention_mask"): + pad_value = 0 + concatenated_key = k.replace("chosen", "concatenated") + concatenated_batch[concatenated_key] = pad_to_length(batch[k], max_length, pad_value=pad_value) + for k in batch: + if k.startswith("rejected") and isinstance(batch[k], torch.Tensor): + if "labels" in k or is_encoder_decoder: + pad_value = -100 + elif k.endswith("_input_ids"): + pad_value = padding_value + elif k.endswith("_attention_mask"): + pad_value = 0 + concatenated_key = k.replace("rejected", "concatenated") + concatenated_batch[concatenated_key] = torch.cat( + ( + concatenated_batch[concatenated_key], + pad_to_length(batch[k], max_length, pad_value=pad_value), + ), + dim=0, + ).to(device=device) + + if is_encoder_decoder: + concatenated_batch["concatenated_input_ids"] = batch["prompt_input_ids"].repeat(2, 1).to(device=device) + concatenated_batch["concatenated_attention_mask"] = ( + batch["prompt_attention_mask"].repeat(2, 1).to(device=device) + ) + + return concatenated_batch + + def cpo_loss( + self, + policy_chosen_logps: torch.FloatTensor, + policy_rejected_logps: torch.FloatTensor, + ) -> tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: + """Compute the CPO loss for a batch of policy and reference model log probabilities. + + Args: + policy_chosen_logps: + Log probabilities of the policy model for the chosen responses. Shape: (batch_size,) + policy_rejected_logps: + Log probabilities of the policy model for the rejected responses. Shape: (batch_size,) + + Returns: + A tuple of three tensors: (losses, chosen_rewards, rejected_rewards). The losses tensor contains the CPO + loss for each example in the batch. The chosen_rewards and rejected_rewards tensors contain the rewards for + the chosen and rejected responses, respectively. + """ + # Apply AlphaPO reward transformation if alpha != 0 + if self.alpha != 0.0: + # Compute probabilities + chosen_probs = torch.exp(policy_chosen_logps) + rejected_probs = torch.exp(policy_rejected_logps) + + # Apply AlphaPO transformation: r = (1 - p^(-alpha)) / alpha + policy_chosen_rewards = (1 - chosen_probs.pow(-self.alpha)) / self.alpha + policy_rejected_rewards = (1 - rejected_probs.pow(-self.alpha)) / self.alpha + + logits = (policy_chosen_rewards - policy_rejected_rewards).to(self.accelerator.device) + else: + # Standard log probability rewards when alpha = 0 + logits = (policy_chosen_logps - policy_rejected_logps).to(self.accelerator.device) + + # The beta is a temperature parameter for the CPO loss, typically something in the range of 0.1 to 0.5. + # We ignore the reference model as beta -> 0. The label_smoothing parameter encodes our uncertainty about the labels and + # calculates a conservative CPO loss. + + if self.loss_type == "simpo": + gamma_logratios = self.simpo_gamma / self.beta + logits = logits - gamma_logratios + # This reduces to Equation 3 from the CPO paper when label_smoothing -> 0. + losses = ( + -F.logsigmoid(self.beta * logits) * (1 - self.label_smoothing) + - F.logsigmoid(-self.beta * logits) * self.label_smoothing + ) + elif self.loss_type == "sigmoid": + # This reduces to Equation 3 from the CPO paper when label_smoothing -> 0. + losses = ( + -F.logsigmoid(self.beta * logits) * (1 - self.label_smoothing) + - F.logsigmoid(-self.beta * logits) * self.label_smoothing + ) + elif self.loss_type == "hinge": + losses = torch.relu(1 - self.beta * logits) + elif self.loss_type == "ipo": + # eqn (17) of the paper where beta is the regularization parameter for the IPO loss, denoted by tau in the paper. + losses = (logits - 1 / (2 * self.beta)) ** 2 + else: + raise ValueError( + f"Unknown loss type: {self.loss_type}. Should be one of ['sigmoid', 'hinge', 'ipo', 'simpo']" + ) + + # Calculate rewards for logging + if self.alpha != 0.0: + # When using AlphaPO transformation, use the transformed rewards + chosen_rewards = self.beta * policy_chosen_rewards.to(self.accelerator.device).detach() + rejected_rewards = self.beta * policy_rejected_rewards.to(self.accelerator.device).detach() + else: + # Standard log probability rewards + chosen_rewards = self.beta * (policy_chosen_logps.to(self.accelerator.device)).detach() + rejected_rewards = self.beta * (policy_rejected_logps.to(self.accelerator.device)).detach() + + return losses, chosen_rewards, rejected_rewards + + @staticmethod + def get_batch_logps( + logits: torch.FloatTensor, + labels: torch.LongTensor, + average_log_prob: bool = False, + is_encoder_decoder: bool = False, + ) -> torch.FloatTensor: + """Compute the log probabilities of the given labels under the given logits. + + Args: + logits: Logits of the model (unnormalized). Shape: (batch_size, sequence_length, vocab_size) + labels: + Labels for which to compute the log probabilities. Label tokens with a value of `-100` are ignored. + Shape: (batch_size, sequence_length) + average_log_prob: + If True, return the average log probability per (non-masked) token. Otherwise, return the sum of the + log probabilities of the (non-masked) tokens. + is_encoder_decoder: Whether the model is an encoder-decoder model. + + Returns: + A tensor of shape (batch_size,) containing the average/sum log probabilities of the given labels under the + given logits. + """ + if logits.shape[:-1] != labels.shape: + raise ValueError("Logits (batch and sequence length dim) and labels must have the same shape.") + + if not is_encoder_decoder: + labels = labels[:, 1:].clone() + logits = logits[:, :-1, :] + loss_mask = labels != -100 + + # dummy token; we'll ignore the losses on these tokens later + labels[labels == -100] = 0 + + per_token_logps = selective_log_softmax(logits, labels) + + if average_log_prob: + return (per_token_logps * loss_mask).sum(-1) / loss_mask.sum(-1) + else: + return (per_token_logps * loss_mask).sum(-1) + + def concatenated_forward( + self, model: nn.Module, batch: dict[str, list | torch.LongTensor] + ) -> tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: + """Run the given model on the given batch of inputs, concatenating the chosen and rejected inputs together. + + We do this to avoid doing two forward passes, because it's faster for FSDP. + """ + concatenated_batch = self.concatenated_inputs( + batch, + is_encoder_decoder=self.is_encoder_decoder, + padding_value=self.pad_token_id, + device=self.accelerator.device, + ) + len_chosen = batch["chosen_labels"].shape[0] + + model_kwargs = ( + { + "decoder_input_ids": self._shift_right(concatenated_batch["concatenated_labels"]), + } + if self.is_encoder_decoder + else {} + ) + + if self.aux_loss_enabled: + model_kwargs["output_router_logits"] = True + + outputs = model( + concatenated_batch["concatenated_input_ids"], + attention_mask=concatenated_batch["concatenated_attention_mask"], + use_cache=False, + **model_kwargs, + ) + all_logits = outputs.logits + + def cross_entropy_loss(logits, labels): + if not self.is_encoder_decoder: + # Shift so that tokens < n predict n + logits = logits[..., :-1, :].contiguous() + labels = labels[..., 1:].contiguous() + # Flatten the tokens + loss_fct = nn.CrossEntropyLoss() + logits = logits.view(-1, logits.shape[-1]) + labels = labels.view(-1) + # Enable model parallelism + labels = labels.to(logits.device) + loss = loss_fct(logits, labels) + return loss + + labels = concatenated_batch["concatenated_labels"].clone() + + if self.cpo_alpha == 0: + nll_loss = torch.tensor(0.0).to(self.accelerator.device) + else: + nll_loss = cross_entropy_loss(all_logits[:len_chosen], labels[:len_chosen]) + + all_logps = self.get_batch_logps( + all_logits, + concatenated_batch["concatenated_labels"], + average_log_prob=self.loss_type in ["ipo", "simpo"], + is_encoder_decoder=self.is_encoder_decoder, + ) + + chosen_logps = all_logps[:len_chosen] + rejected_logps = all_logps[len_chosen:] + + chosen_logits = all_logits[:len_chosen] + rejected_logits = all_logits[len_chosen:] + + if self.aux_loss_enabled: + return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, nll_loss, outputs.aux_loss) + + return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, nll_loss) + + def get_batch_loss_metrics( + self, + model, + batch: dict[str, list | torch.LongTensor], + train_eval: Literal["train", "eval"] = "train", + ): + """Compute the CPO loss and other metrics for the given batch of inputs for train or test.""" + metrics = {} + + forward_output = self.concatenated_forward(model, batch) + ( + policy_chosen_logps, + policy_rejected_logps, + policy_chosen_logits, + policy_rejected_logits, + policy_nll_loss, + ) = forward_output[:5] + if self.aux_loss_enabled: + aux_loss = forward_output[5] + + losses, chosen_rewards, rejected_rewards = self.cpo_loss( + policy_chosen_logps, + policy_rejected_logps, + ) + + loss = losses.mean() + self.cpo_alpha * policy_nll_loss + reward_accuracies = (chosen_rewards > rejected_rewards).float() + + prefix = "eval_" if train_eval == "eval" else "" + metrics[f"{prefix}rewards/chosen"] = self.accelerator.gather_for_metrics(chosen_rewards).mean().item() + metrics[f"{prefix}rewards/rejected"] = self.accelerator.gather_for_metrics(rejected_rewards).mean().item() + metrics[f"{prefix}rewards/accuracies"] = self.accelerator.gather_for_metrics(reward_accuracies).mean().item() + metrics[f"{prefix}rewards/margins"] = ( + self.accelerator.gather_for_metrics(chosen_rewards - rejected_rewards).mean().item() + ) + metrics[f"{prefix}logps/rejected"] = ( + self.accelerator.gather_for_metrics(policy_rejected_logps).detach().mean().item() + ) + metrics[f"{prefix}logps/chosen"] = ( + self.accelerator.gather_for_metrics(policy_chosen_logps).detach().mean().item() + ) + metrics[f"{prefix}logits/rejected"] = ( + self.accelerator.gather_for_metrics(policy_rejected_logits.detach().mean()).mean().item() + ) + metrics[f"{prefix}logits/chosen"] = ( + self.accelerator.gather_for_metrics(policy_chosen_logits.detach().mean()).mean().item() + ) + metrics[f"{prefix}nll_loss"] = self.accelerator.gather_for_metrics(policy_nll_loss).detach().mean().item() + + if self.aux_loss_enabled: + loss += self.aux_loss_coef * aux_loss + + return loss, metrics + + def compute_loss( + self, + model: PreTrainedModel | nn.Module, + inputs: dict[str, torch.Tensor | Any], + return_outputs=False, + num_items_in_batch=None, + ) -> torch.Tensor | tuple[torch.Tensor, dict[str, torch.Tensor]]: + compute_loss_context_manager = ( + autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext() + ) + + with compute_loss_context_manager: + loss, metrics = self.get_batch_loss_metrics(model, inputs, train_eval="train") + + # force log the metrics + self.store_metrics(metrics, train_eval="train") + + if return_outputs: + return (loss, metrics) + return loss + + def generate_from_model(self, model, batch: dict[str, torch.LongTensor]) -> str: + """Generate samples from the model and reference model for the given batch of inputs.""" + + # If one uses `generate_during_eval` with peft + bf16, we need to explicitly call generate with + # the torch amp context manager as some hidden states are silently casted to full precision. + generate_context_manager = ( + autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext() + ) + + with generate_context_manager: + policy_output = model.generate( + input_ids=batch["prompt_input_ids"], + attention_mask=batch["prompt_attention_mask"], + max_length=self.max_length, + do_sample=True, + pad_token_id=self.processing_class.pad_token_id, + ) + + policy_output = pad_to_length(policy_output, self.max_length, self.processing_class.pad_token_id) + policy_output_decoded = self.processing_class.batch_decode(policy_output, skip_special_tokens=True) + + return policy_output_decoded + + def prediction_step( + self, + model: PreTrainedModel | nn.Module, + inputs: dict[str, torch.Tensor | Any], + prediction_loss_only: bool, + ignore_keys: list[str] | None = None, + ): + if ignore_keys is None: + if hasattr(model, "config"): + ignore_keys = getattr(model.config, "keys_to_ignore_at_inference", []) + else: + ignore_keys = [] + + prediction_context_manager = ( + autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext() + ) + + with torch.no_grad(), prediction_context_manager: + loss, metrics = self.get_batch_loss_metrics(model, inputs, train_eval="eval") + + # force log the metrics + self.store_metrics(metrics, train_eval="eval") + + if prediction_loss_only: + return (loss.detach(), None, None) + + # logits for the chosen and rejected samples from model + logits_dict = { + "eval_logits/chosen": metrics["eval_logits/chosen"], + "eval_logits/rejected": metrics["eval_logits/rejected"], + } + logits = [v for k, v in logits_dict.items() if k not in ignore_keys] + logits = torch.tensor(logits, device=self.accelerator.device) + labels = torch.zeros(logits.shape[0], device=self.accelerator.device) + + return (loss.detach(), logits, labels) + + def store_metrics(self, metrics: dict[str, float], train_eval: Literal["train", "eval"] = "train") -> None: + for key, value in metrics.items(): + self._stored_metrics[train_eval][key].append(value) + + def evaluation_loop( + self, + dataloader: DataLoader, + description: str, + prediction_loss_only: bool | None = None, + ignore_keys: list[str] | None = None, + metric_key_prefix: str = "eval", + ) -> EvalLoopOutput: + """ + Overriding built-in evaluation loop to store metrics for each batch. Prediction/evaluation loop, shared by + `Trainer.evaluate()` and `Trainer.predict()`. + + Works both with or without labels. + """ + + # Sample and save to game log if requested (for one batch to save time) + if self.generate_during_eval: + # Generate random indices within the range of the total number of samples + num_samples = len(dataloader.dataset) + random_indices = random.sample(range(num_samples), k=self.args.eval_batch_size) + + # Use dataloader.dataset.select to get the random batch without iterating over the DataLoader + random_batch_dataset = dataloader.dataset.select(random_indices) + random_batch = self.data_collator(random_batch_dataset) + random_batch = self._prepare_inputs(random_batch) + + policy_output_decoded = self.generate_from_model(self.model, random_batch) + + table = pd.DataFrame( + columns=["Prompt", "Policy"], + data=[ + [prompt, pol[len(prompt) :]] + for prompt, pol in zip(random_batch["prompt"], policy_output_decoded, strict=True) + ], + ) + if "wandb" in self.args.report_to: + wandb.log({"game_log": wandb.Table(data=table)}) + + if "comet_ml" in self.args.report_to: + log_table_to_comet_experiment( + name="game_log.csv", + table=table, + ) + + # Base evaluation + initial_output = super().evaluation_loop( + dataloader, description, prediction_loss_only, ignore_keys, metric_key_prefix + ) + + return initial_output + + def log(self, logs: dict[str, float], start_time: float | None = None) -> None: + """ + Log `logs` on the various objects watching training, including stored metrics. + + Args: + logs (`dict[str, float]`): + The values to log. + start_time (`float`, *optional*): + Start time of the training. + """ + # logs either has 'loss' or 'eval_loss' + train_eval = "train" if "loss" in logs else "eval" + # Add averaged stored metrics to logs + for key, metrics in self._stored_metrics[train_eval].items(): + logs[key] = torch.tensor(metrics).mean().item() + del self._stored_metrics[train_eval] + return super().log(logs, start_time) + + def _shift_right(self, input_ids): + if self.decoder_start_token_id is None: + raise ValueError( + "model.config.decoder_start_token_id has to be defined. It is usually set to the pad_token_id." + ) + + # shift inputs to the right + if is_torch_fx_proxy(input_ids): + # Item assignment is not supported natively for proxies. + shifted_input_ids = torch.full(input_ids.shape[:-1] + (1,), self.decoder_start_token_id) + shifted_input_ids = torch.cat([shifted_input_ids, input_ids[..., :-1]], dim=-1) + else: + shifted_input_ids = input_ids.new_zeros(input_ids.shape) + shifted_input_ids[..., 1:] = input_ids[..., :-1].clone() + shifted_input_ids[..., 0] = self.decoder_start_token_id + + if self.pad_token_id is None: + raise ValueError("model.config.pad_token_id has to be defined.") + # replace possible -100 values in labels by `pad_token_id` + shifted_input_ids.masked_fill_(shifted_input_ids == -100, self.pad_token_id) + + return shifted_input_ids + + # Ensure the model card is saved along with the checkpoint + def _save_checkpoint(self, model, trial): + if self.args.hub_model_id is None: + model_name = Path(self.args.output_dir).name + else: + model_name = self.args.hub_model_id.split("/")[-1] + self.create_model_card(model_name=model_name) + super()._save_checkpoint(model, trial) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/distillation/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/distillation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..894333c1d01c23f82964cd651ee45a7c3d652e65 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/distillation/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .distillation_config import DistillationConfig +from .distillation_trainer import DistillationTrainer + + +__all__ = ["DistillationConfig", "DistillationTrainer"] diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/distillation/distillation.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/distillation/distillation.py new file mode 100644 index 0000000000000000000000000000000000000000..b292ab59d1dcfdd19ca35bc4771dd57c9c201473 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/distillation/distillation.py @@ -0,0 +1,179 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# /// script +# dependencies = [ +# "trl", +# "peft", +# "trackio", +# "kernels", +# ] +# /// + +# docstyle-ignore +""" +# Full training (off-policy only, lmbda=0): +``` +python trl/experimental/distillation/distillation.py \ + --model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \ + --teacher_model_name_or_path Qwen/Qwen2.5-1.5B-Instruct \ + --dataset_name trl-lib/chatbot_arena_completions \ + --learning_rate 2e-5 \ + --per_device_train_batch_size 4 \ + --gradient_accumulation_steps 8 \ + --lmbda 0.0 \ + --output_dir distilled-model \ + --num_train_epochs 1 +``` + +# Mixed on/off-policy (lmbda=0.5): +``` +python trl/experimental/distillation/distillation.py \ + --model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \ + --teacher_model_name_or_path Qwen/Qwen2.5-1.5B-Instruct \ + --dataset_name trl-lib/chatbot_arena_completions \ + --learning_rate 2e-5 \ + --per_device_train_batch_size 4 \ + --gradient_accumulation_steps 8 \ + --lmbda 0.5 \ + --beta 0.5 \ + --output_dir distilled-model \ + --num_train_epochs 1 +``` + +# LoRA: +``` +python trl/experimental/distillation/distillation.py \ + --model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \ + --teacher_model_name_or_path Qwen/Qwen2.5-1.5B-Instruct \ + --dataset_name trl-lib/chatbot_arena_completions \ + --learning_rate 2e-4 \ + --per_device_train_batch_size 4 \ + --gradient_accumulation_steps 8 \ + --lmbda 0.0 \ + --output_dir distilled-model \ + --num_train_epochs 1 \ + --use_peft \ + --lora_r 64 \ + --lora_alpha 16 +``` +""" + +import argparse +import os + + +# Enable logging in a Hugging Face Space +os.environ.setdefault("TRACKIO_SPACE_ID", "trl-trackio") + + +def main(script_args, training_args, model_args): + from datasets import load_dataset + from transformers import GenerationConfig + + from trl import ( + LogCompletionsCallback, + get_kbit_device_map, + get_peft_config, + get_quantization_config, + ) + from trl.experimental.distillation import DistillationTrainer + + ################ + # Model init kwargs + ################ + quantization_config = get_quantization_config(model_args) + model_kwargs = dict( + revision=model_args.model_revision, + trust_remote_code=model_args.trust_remote_code, + attn_implementation=model_args.attn_implementation, + dtype=model_args.dtype, + use_cache=False if training_args.gradient_checkpointing else True, + device_map=get_kbit_device_map() if quantization_config is not None else None, + quantization_config=quantization_config, + ) + training_args.model_init_kwargs = model_kwargs + + teacher_model_kwargs = dict( + revision=training_args.teacher_model_revision, + trust_remote_code=model_args.trust_remote_code, + attn_implementation=model_args.attn_implementation, + dtype=model_args.dtype, + use_cache=True, + device_map=get_kbit_device_map() if quantization_config is not None else None, + quantization_config=quantization_config, + ) + if training_args.teacher_model_init_kwargs is not None: + teacher_model_kwargs.update(training_args.teacher_model_init_kwargs) + training_args.teacher_model_init_kwargs = teacher_model_kwargs + + ################ + # Dataset + ################ + dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config) + + ################ + # Training + ################ + eval_dataset = None + if training_args.eval_strategy != "no": + if script_args.dataset_test_split in dataset: + eval_dataset = dataset[script_args.dataset_test_split] + elif "validation" in dataset: + eval_dataset = dataset["validation"] + elif "dev" in dataset: + eval_dataset = dataset["dev"] + + trainer = DistillationTrainer( + model=model_args.model_name_or_path, + teacher_model=training_args.teacher_model_name_or_path, + args=training_args, + train_dataset=dataset[script_args.dataset_train_split], + eval_dataset=eval_dataset, + peft_config=get_peft_config(model_args), + ) + + if training_args.eval_strategy != "no": + generation_config = GenerationConfig( + max_new_tokens=training_args.max_completion_length, do_sample=True, temperature=training_args.temperature + ) + completions_callback = LogCompletionsCallback(trainer, generation_config, num_prompts=8) + trainer.add_callback(completions_callback) + + trainer.train() + + # Save and push to Hub + trainer.save_model(training_args.output_dir) + if training_args.push_to_hub: + trainer.push_to_hub(dataset_name=script_args.dataset_name) + + +def make_parser(subparsers: argparse._SubParsersAction | None = None, prog: str | None = None): + from trl import ModelConfig, ScriptArguments, TrlParser + from trl.experimental.distillation import DistillationConfig + + dataclass_types = (ScriptArguments, DistillationConfig, ModelConfig) + if subparsers is not None: + parser = subparsers.add_parser( + "distillation", help="Run the distillation training script", dataclass_types=dataclass_types + ) + else: + parser = TrlParser(dataclass_types, prog=prog) + return parser + + +if __name__ == "__main__": + parser = make_parser() + script_args, training_args, model_args = parser.parse_args_and_config(fail_with_unknown_args=False) + main(script_args, training_args, model_args) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/distillation/distillation_config.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/distillation/distillation_config.py new file mode 100644 index 0000000000000000000000000000000000000000..23c9ebf78854873f3a3cadd95af6bd491a4f2499 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/distillation/distillation_config.py @@ -0,0 +1,442 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from dataclasses import dataclass, field +from typing import Any + +from ...trainer.base_config import _BaseConfig + + +@dataclass +class DistillationConfig(_BaseConfig): + # docstyle-ignore + r""" + Configuration class for the [`DistillationTrainer`]. + + Extends [`~transformers.TrainingArguments`] with parameters specific to knowledge distillation. This config is + independent of [`SFTConfig`] — all necessary fields are declared here. + + 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 + + model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `model` argument of the + trainer is provided as a string. + max_length (`int` or `None`, *optional*, defaults to `1024`): + Maximum total sequence length (prompt + completion) for tokenization and truncation. + + > Parameters that control the distillation + + temperature (`float`, *optional*, defaults to `1.0`): + Temperature for sampling during generation and for computing the distillation loss. Higher values produce + softer probability distributions. + lmbda (`float`, *optional*, defaults to `1.0`): + Probability of using on-policy (student-generated) data for each gradient accumulation slice. A value of + `0.0` means fully off-policy (dataset completions only), `1.0` means fully on-policy. + beta (`float`, *optional*, defaults to `1.0`): + Interpolation coefficient for the Generalized Jensen-Shannon Divergence loss. When `0.0`, the loss is the + forward KL divergence. When `1.0`, the loss is the reverse KL divergence. When `0.5`, it is the standard + JSD. + reverse_kl_top_1_mode (`str`, *optional*, defaults to `"sampled"`): + Selection rule for the reverse-KL top-1 token when `beta > 0` and `loss_top_k == 1`. `"sampled"` uses the + actual completion token in the batch. `"argmax"` uses the student's highest-probability token. This + setting does not affect the forward-KL support, which always uses the teacher's top-1 token. Ignored when + `beta == 0` or `loss_top_k != 1`. + max_completion_length (`int`, *optional*, defaults to `512`): + Maximum number of tokens to generate per completion during on-policy generation. + max_prompt_length (`int` or `None`, *optional*): + Maximum number of tokens for the prompt. If `None`, auto-computed as `max_length - max_completion_length`. + Prompts are truncated according to the tokenizer's `truncation_side` setting. + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the student model during training. + + > Parameters that control the teacher model + + teacher_model_name_or_path (`str` or `None`, *optional*): + Model name or path for the teacher model. Used when the teacher is loaded locally. + teacher_model_revision (`str` or `None`, *optional*): + Model revision of the teacher model (e.g., branch name, tag, or commit hash). + teacher_model_init_kwargs (`dict[str, Any]` or `None`, *optional*): + Keyword arguments passed to `AutoModelForCausalLM.from_pretrained` when instantiating the teacher model + from a string. + use_teacher_server (`bool`, *optional*, defaults to `False`): + Whether to use an external vLLM teacher server instead of a local teacher model. + teacher_model_server_url (`str` or `None`, *optional*): + Base URL of a vLLM server hosting the teacher model (e.g., `"http://localhost:8000"`). When set, teacher + logprobs are fetched from the server instead of running a local forward pass when `use_teacher_server=True`. + loss_top_k (`int`, *optional*, defaults to `1`): + Number of top tokens to use when computing the JSD/KL loss. Both student and teacher distributions are + restricted to these K tokens and re-normalized before computing divergence. If 0, the full vocabulary + is used. For local teachers, the general support rule is teacher top-k for forward KL, student top-k for + reverse KL, and the union for mixed JSD. When `beta > 0` and `loss_top_k == 1`, the forward support still + uses the teacher's top-1 token, while the reverse top-1 token is controlled by `reverse_kl_top_1_mode`. + When `use_teacher_server=True`, the pure forward path (`beta=0`) requires this to be positive and uses the + teacher's top-k logprobs for the forward term. When `beta > 0`, server-backed distillation requires + `loss_top_k == 1` and only supports `"sampled"` reverse top-1 tokens. + loss_add_tail (`bool`, *optional*, defaults to `True`): + Whether to append a tail bucket that represents the remaining probability mass outside the selected top-k + support when computing the loss. + + > Parameters that control on-policy generation + + num_generations (`int`, *optional*, defaults to `1`): + Number of completions to generate per prompt during on-policy generation. + generation_batch_size (`int` or `None`, *optional*): + Number of unique prompts per worker per optimizer step. If `None`, computed from + `(per_device_train_batch_size * gradient_accumulation_steps) // num_generations`. + top_p (`float`, *optional*, defaults to `0.95`): + Top-p (nucleus) sampling parameter for on-policy generation. + top_k (`int`, *optional*, defaults to `0`): + Top-k sampling parameter for on-policy generation. `0` disables top-k filtering. + + > Parameters that control vLLM for student generation + + use_vllm (`bool`, *optional*, defaults to `False`): + Whether to use vLLM for generating on-policy completions from the student model. + vllm_mode (`str`, *optional*, defaults to `"colocate"`): + Mode for student vLLM integration. Either `"server"` or `"colocate"`. + vllm_server_base_url (`str` or `None`, *optional*): + Base URL for the student vLLM server. 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 student vLLM server. + vllm_server_port (`int`, *optional*, defaults to `8001`): + Port of the student vLLM server. + vllm_server_timeout (`float`, *optional*, defaults to `240.0`): + Timeout for connecting to the student vLLM server. + vllm_group_port (`int`, *optional*, defaults to `51216`): + Port for the vLLM weight-update group (NCCL communicator). + vllm_gpu_memory_utilization (`float`, *optional*, defaults to `0.3`): + GPU memory utilization for the colocated student vLLM engine. + vllm_tensor_parallel_size (`int`, *optional*, defaults to `1`): + Tensor parallel size for the colocated student vLLM engine. + vllm_max_model_length (`int` or `None`, *optional*): + Maximum model sequence length for the colocated vLLM engine. + vllm_model_impl (`str`, *optional*, defaults to `"vllm"`): + Model implementation backend for vLLM. Use `"vllm"` or `"transformers"`. + vllm_structured_outputs_regex (`str` or `None`, *optional*): + Regex pattern for vLLM structured outputs. + vllm_sync_frequency (`int`, *optional*, defaults to `1`): + Frequency (in training steps) to synchronize student model weights to the vLLM engine. + vllm_enable_sleep_mode (`bool`, *optional*, defaults to `False`): + Enable vLLM sleep mode to offload student weights during the optimizer step. + + > Parameters that control logging + + log_completions (`bool`, *optional*, defaults to `False`): + Whether to log a sample of (prompt, completion) pairs every `log_completions_steps` steps. If `rich` is + installed, it prints the sample. If `wandb` and/or `trackio` logging is enabled, it logs it to `wandb` + and/or `trackio`. + log_completions_steps (`int`, *optional*, defaults to `100`): + Number of steps between logging completions. Only used if `log_completions` is `True`. + num_completions_to_print (`int` or `None`, *optional*): + Number of completions to print. If `None`, all completions are logged. + """ + + _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs", "teacher_model_init_kwargs"] + + # Model + model_init_kwargs: dict[str, Any] | str | None = field( + default=None, + metadata={ + "help": "Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `model` argument " + "of the trainer is provided as a string." + }, + ) + max_length: int | None = field( + default=1024, + metadata={"help": "Maximum total sequence length (prompt + completion) for tokenization and truncation."}, + ) + + # Overridden defaults + learning_rate: float = field( + default=1e-6, + metadata={"help": "The initial learning rate for AdamW."}, + ) + + # Distillation core + temperature: float = field( + default=1.0, + metadata={ + "help": "Temperature for sampling and loss computation. Higher values produce softer distributions." + }, + ) + lmbda: float = field( + default=1.0, + metadata={ + "help": "Probability of using on-policy (student-generated) data per gradient accumulation slice. " + "0.0 = fully off-policy, 1.0 = fully on-policy." + }, + ) + beta: float = field( + default=1.0, + metadata={ + "help": "Interpolation coefficient for the Generalized JSD loss. " + "0.0 = forward KL, 0.5 = JSD, 1.0 = reverse KL." + }, + ) + reverse_kl_top_1_mode: str = field( + default="sampled", + metadata={ + "help": "Reverse-KL top-1 token selection when beta > 0 and loss_top_k == 1. " + "Use 'sampled' for the actual completion token or 'argmax' for the student's top-1 token. " + "The forward-KL support always uses the teacher's top-1 token. Ignored when beta == 0 or loss_top_k != 1." + }, + ) + max_completion_length: int = field( + default=512, + metadata={"help": "Maximum number of tokens to generate per completion."}, + ) + max_prompt_length: int | None = field( + default=None, + metadata={ + "help": "Maximum number of tokens for the prompt. If None, auto-computed as " + "max_length - max_completion_length. Prompts are truncated according to the " + "tokenizer's truncation_side setting." + }, + ) + disable_dropout: bool = field( + default=True, + metadata={"help": "Whether to disable dropout in the student model during training."}, + ) + + # Teacher model (local) + teacher_model_name_or_path: str | None = field( + default=None, + metadata={"help": "Model name or path for the teacher model."}, + ) + teacher_model_revision: str | None = field( + default=None, + metadata={"help": "Model revision of the teacher model (e.g., branch name, tag, or commit hash)."}, + ) + teacher_model_init_kwargs: dict[str, Any] | str | None = field( + default=None, + metadata={ + "help": "Keyword arguments for `AutoModelForCausalLM.from_pretrained` when instantiating the teacher." + }, + ) + + # Teacher model (external vLLM server) + use_teacher_server: bool = field( + default=False, + metadata={"help": "Whether to use an external vLLM teacher server instead of a local teacher model."}, + ) + teacher_model_server_url: str | None = field( + default=None, + metadata={ + "help": 'Base URL of a vLLM server hosting the teacher model (e.g., "http://localhost:8000"). ' + "Required when use_teacher_server=True." + }, + ) + loss_top_k: int = field( + default=1, + metadata={ + "help": "Number of top tokens to use when computing the JSD/KL loss. " + "Both student and teacher distributions are restricted to these K tokens " + "(selected based on beta: teacher's top-k for forward KL, student's top-k for reverse KL, " + "union of both for JSD) and re-normalized before computing divergence. " + "If 0, the full vocabulary is used (slower but exact). " + "When beta > 0 and loss_top_k == 1, the forward support still uses the teacher's top-1 token, " + "while the reverse top-1 token is controlled by reverse_kl_top_1_mode. " + "When use_teacher_server=True, beta=0 requires loss_top_k > 0 and uses the teacher's top-k " + "logprobs for the forward term. When beta > 0, server-backed distillation requires loss_top_k == 1 " + "and only supports 'sampled' reverse top-1 tokens." + }, + ) + loss_add_tail: bool = field( + default=True, + metadata={ + "help": "Whether to append a tail bucket representing the remaining probability mass outside the selected top-k support." + }, + ) + + # On-policy generation + num_generations: int = field( + default=1, + metadata={"help": "Number of completions to generate per prompt during on-policy generation."}, + ) + generation_batch_size: int | None = field( + default=None, + metadata={ + "help": "Number of unique prompts per worker per optimizer step. " + "If None, computed from (per_device_train_batch_size * gradient_accumulation_steps) // num_generations." + }, + ) + top_p: float = field( + default=0.95, + metadata={"help": "Top-p (nucleus) sampling parameter for on-policy generation."}, + ) + top_k: int = field( + default=0, + metadata={"help": "Top-k sampling parameter for on-policy generation. 0 disables top-k filtering."}, + ) + + # vLLM for student generation + use_vllm: bool = field( + default=False, + metadata={"help": "Whether to use vLLM for generating on-policy completions from the student model."}, + ) + vllm_mode: str = field( + default="colocate", + metadata={"help": 'Mode for student vLLM integration. Either "server" or "colocate".'}, + ) + vllm_server_base_url: str | None = field( + default=None, + metadata={"help": "Base URL for the student vLLM server."}, + ) + vllm_server_host: str = field( + default="0.0.0.0", + metadata={"help": "Host of the student vLLM server."}, + ) + vllm_server_port: int = field( + default=8001, + metadata={"help": "Port of the student vLLM server."}, + ) + vllm_server_timeout: float = field( + default=240.0, + metadata={"help": "Timeout for connecting to the student vLLM server."}, + ) + vllm_group_port: int = field( + default=51216, + metadata={"help": "Port for the vLLM weight-update group (NCCL communicator)."}, + ) + vllm_gpu_memory_utilization: float = field( + default=0.3, + metadata={"help": "GPU memory utilization for the colocated student vLLM engine."}, + ) + vllm_tensor_parallel_size: int = field( + default=1, + metadata={"help": "Tensor parallel size for the colocated student vLLM engine."}, + ) + vllm_max_model_length: int | None = field( + default=None, + metadata={"help": "Maximum model sequence length for the colocated vLLM engine."}, + ) + vllm_model_impl: str = field( + default="vllm", + metadata={"help": 'Model implementation backend for vLLM. Use "vllm" or "transformers".'}, + ) + vllm_structured_outputs_regex: str | None = field( + default=None, + metadata={"help": "Regex pattern for vLLM structured outputs."}, + ) + vllm_sync_frequency: int = field( + default=1, + metadata={"help": "Frequency (in training steps) to synchronize student weights to the vLLM engine."}, + ) + vllm_enable_sleep_mode: bool = field( + default=False, + metadata={"help": "Enable vLLM sleep mode to offload student weights during the optimizer step."}, + ) + + # W&B + + # Logging + log_completions: bool = field( + default=False, + metadata={ + "help": "Whether to log a sample of (prompt, completion) pairs every `log_completions_steps` steps. If `rich` is " + "installed, it prints the sample. If `wandb` and/or `trackio` logging is enabled, it logs it to `wandb` " + "and/or `trackio`." + }, + ) + log_completions_steps: int = field( + default=100, + metadata={"help": "Number of steps between logging completions."}, + ) + num_completions_to_print: int | None = field( + default=None, + metadata={"help": "Number of completions to print. If None, all completions are logged."}, + ) + + def __post_init__(self): + super().__post_init__() + + if self.lmbda < 0.0 or self.lmbda > 1.0: + raise ValueError(f"lmbda must be in [0.0, 1.0], got {self.lmbda}.") + if self.beta < 0.0 or self.beta > 1.0: + raise ValueError(f"beta must be in [0.0, 1.0], got {self.beta}.") + if self.reverse_kl_top_1_mode not in {"sampled", "argmax"}: + raise ValueError("reverse_kl_top_1_mode must be one of: 'sampled', 'argmax'") + + if self.max_length is not None and self.max_completion_length >= self.max_length: + raise ValueError( + f"max_completion_length ({self.max_completion_length}) must be smaller than " + f"max_length ({self.max_length}) to leave room for the prompt." + ) + + if self.max_prompt_length is None and self.max_length is not None: + self.max_prompt_length = self.max_length - self.max_completion_length + + if self.num_generations < 1: + raise ValueError(f"num_generations must be at least 1, got {self.num_generations}.") + + local_sequence_batch_size = self.per_device_train_batch_size * self.gradient_accumulation_steps + if self.generation_batch_size is None: + self.generation_batch_size = local_sequence_batch_size // self.num_generations + if self.generation_batch_size < 1: + raise ValueError(f"generation_batch_size must be at least 1, got {self.generation_batch_size}.") + if self.generation_batch_size * self.num_generations != local_sequence_batch_size: + raise ValueError( + "generation_batch_size * num_generations must equal per_device_train_batch_size * " + f"gradient_accumulation_steps. Got {self.generation_batch_size} * {self.num_generations} != " + f"{self.per_device_train_batch_size} * {self.gradient_accumulation_steps}." + ) + + if self.use_teacher_server and self.use_liger_kernel: + raise ValueError( + "use_liger_kernel=True is not supported with use_teacher_server=True because the Liger loss path " + "requires a local teacher model." + ) + if self.use_teacher_server and ( + self.teacher_model_server_url is None or not self.teacher_model_server_url.strip() + ): + raise ValueError("teacher_model_server_url must be set when use_teacher_server=True.") + + if self.use_teacher_server and self.beta == 0 and self.loss_top_k < 1: + raise ValueError( + f"loss_top_k must be positive when using use_teacher_server=True with beta=0 " + f"(got loss_top_k={self.loss_top_k}). The pure forward server path only has access to the " + f"teacher's top-k logprobs, so it cannot compute the exact full-vocabulary loss when loss_top_k=0." + ) + if self.use_teacher_server and self.reverse_kl_top_1_mode == "argmax": + raise ValueError( + "reverse_kl_top_1_mode='argmax' is not supported with use_teacher_server=True because the server " + "cannot provide teacher logprobs for arbitrary student-selected tokens." + ) + if self.use_teacher_server and self.beta > 0 and self.loss_top_k != 1: + raise ValueError( + f"loss_top_k must be 1 when using use_teacher_server=True with beta>0 " + f"(got loss_top_k={self.loss_top_k}). Mixed forward/reverse distillation with an external teacher " + "is only implemented for top-1 support." + ) + if self.reverse_kl_top_1_mode != "sampled" and (self.beta == 0 or self.loss_top_k != 1): + warnings.warn( + f"reverse_kl_top_1_mode='{self.reverse_kl_top_1_mode}' has no effect when beta={self.beta} " + f"and loss_top_k={self.loss_top_k}. It only applies when beta > 0 and loss_top_k == 1.", + UserWarning, + stacklevel=2, + ) + + if self.num_generations > 1 and self.lmbda < 1.0: + warnings.warn( + f"num_generations={self.num_generations} with lmbda={self.lmbda} means off-policy batches include " + f"{self.num_generations} copies of each sample. Consider lmbda=1.0 when num_generations > 1.", + UserWarning, + stacklevel=2, + ) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/distillation/distillation_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/distillation/distillation_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..f166d4b590afa3654058a1dbfc0fae334427bb4f --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/distillation/distillation_trainer.py @@ -0,0 +1,1745 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import random +import textwrap +import warnings +from collections import defaultdict +from collections.abc import Callable +from contextlib import nullcontext +from functools import partial +from typing import Any, Optional + +import torch +import torch.distributed as dist +import torch.nn as nn +import torch.nn.functional as F +from accelerate.utils import DistributedType, broadcast_object_list, gather_object +from datasets import Dataset +from torch.utils.data import DataLoader +from transformers import AutoTokenizer, TrainerCallback, is_trackio_available, is_wandb_available +from transformers.data.data_collator import DataCollator +from transformers.feature_extraction_utils import FeatureExtractionMixin +from transformers.generation.configuration_utils import GenerationConfig +from transformers.image_processing_utils import BaseImageProcessor +from transformers.modeling_utils import PreTrainedModel +from transformers.processing_utils import ProcessorMixin +from transformers.tokenization_utils_base import PreTrainedTokenizerBase +from transformers.trainer_utils import EvalPrediction, seed_worker +from transformers.utils import is_liger_kernel_available, is_peft_available, is_rich_available + +from ...extras.profiling import profiling_decorator +from ...generation.vllm_generation import VLLMGeneration +from ...import_utils import is_vllm_available +from ...models import prepare_deepspeed +from ...models.utils import _ForwardRedirection, unwrap_model_for_generation +from ...trainer.base_trainer import _BaseTrainer +from ...trainer.utils import ( + RepeatSampler, + create_model_from_path, + disable_dropout_in_model, + pad, + split_tensor_dict, +) +from .distillation_config import DistillationConfig + + +if is_peft_available(): + from peft import PeftConfig, get_peft_model + +if is_liger_kernel_available(): + from liger_kernel.chunked_loss import LigerFusedLinearJSDLoss + +if is_wandb_available(): + import wandb + +if is_trackio_available(): + import trackio + +if is_rich_available(): + from rich.console import Console + from rich.panel import Panel + from rich.table import Table + from rich.text import Text + + +def _print_completions_sample(prompts: list[str], completions: list[str], step: int, num_samples: int = None) -> None: + """Print a sample of prompt-completion pairs using rich.""" + if not is_rich_available(): + return + + console = Console() + table = Table(show_header=True, header_style="bold white", expand=True) + table.add_column("Prompt", style="bright_yellow") + table.add_column("Completion", style="bright_green") + + if num_samples is not None: + if num_samples >= len(prompts): + num_samples = None + elif num_samples <= 0: + return + + if num_samples is not None: + indices = random.sample(range(len(prompts)), num_samples) + prompts = [prompts[i] for i in indices] + completions = [completions[i] for i in indices] + + for prompt, completion in zip(prompts, completions, strict=True): + table.add_row(Text(prompt), Text(completion)) + table.add_section() + + panel = Panel(table, expand=False, title=f"Step {step}", border_style="bold white") + console.print(panel) + + +def _add_tail_bucket(log_probs, valid_mask): + """Append a (K+1)-th tail element: log(1 - sum(exp(top_k_logps))). + + This creates a proper probability distribution over K+1 elements, preventing trivial zero loss when top_k is small + (especially top_k=1). + """ + log_sum = torch.logsumexp(log_probs, dim=-1, keepdim=True) + log_sum = torch.clamp(log_sum, max=-1e-7) # ensure sum < 1 + tail = torch.log(-torch.expm1(log_sum)) # log(1 - exp(log_sum)) + tail_mask = torch.ones_like(valid_mask[..., :1], dtype=torch.bool) + return torch.cat([log_probs, tail], dim=-1), torch.cat([valid_mask, tail_mask], dim=-1) + + +def _jsd_divergence(student_log_probs, teacher_log_probs, beta, support_mask=None): + """Compute JSD (or forward/reverse KL) from log-probability tensors. + + When *support_mask* is not None, uses manual computation with masked positions zeroed. When None, uses + ``F.kl_div``. + """ + if support_mask is not None: + safe_student = torch.where(support_mask, student_log_probs, torch.zeros_like(student_log_probs)) + safe_teacher = torch.where(support_mask, teacher_log_probs, torch.zeros_like(teacher_log_probs)) + student_probs = torch.where(support_mask, student_log_probs.exp(), torch.zeros_like(student_log_probs)) + teacher_probs = torch.where(support_mask, teacher_log_probs.exp(), torch.zeros_like(teacher_log_probs)) + + if beta == 0: + return torch.nan_to_num(teacher_probs * (safe_teacher - safe_student), nan=0.0) + elif beta == 1: + return torch.nan_to_num(student_probs * (safe_student - safe_teacher), nan=0.0) + else: + beta_t = torch.tensor(beta, dtype=student_log_probs.dtype, device=student_log_probs.device) + tiny = torch.finfo(student_probs.dtype).tiny + mixture_probs = (1 - beta_t) * student_probs + beta_t * teacher_probs + safe_mixture = torch.where( + support_mask, + torch.log(mixture_probs.clamp_min(tiny)), + torch.zeros_like(student_log_probs), + ) + kl_teacher = torch.nan_to_num(teacher_probs * (safe_teacher - safe_mixture), nan=0.0) + kl_student = torch.nan_to_num(student_probs * (safe_student - safe_mixture), nan=0.0) + return beta_t * kl_teacher + (1 - beta_t) * kl_student + else: + if beta == 0: + return F.kl_div(student_log_probs, teacher_log_probs, reduction="none", log_target=True) + elif beta == 1: + return F.kl_div(teacher_log_probs, student_log_probs, reduction="none", log_target=True) + else: + beta_t = torch.tensor(beta, dtype=student_log_probs.dtype, device=student_log_probs.device) + mixture_log_probs = torch.logsumexp( + torch.stack([student_log_probs + torch.log1p(-beta_t), teacher_log_probs + torch.log(beta_t)]), + dim=0, + ) + kl_teacher = F.kl_div(mixture_log_probs, teacher_log_probs, reduction="none", log_target=True) + kl_student = F.kl_div(mixture_log_probs, student_log_probs, reduction="none", log_target=True) + return beta_t * kl_teacher + (1 - beta_t) * kl_student + + +def build_teacher_request_inputs( + input_ids: torch.Tensor, + attention_mask: torch.Tensor, + prompt_attention_mask: torch.Tensor | None = None, + labels: torch.Tensor | None = None, +) -> tuple[list[list[int]], list[int], list[int]]: + """Trim padded batch tensors into per-sample sequences for teacher-server requests.""" + + if input_ids.shape != attention_mask.shape: + raise ValueError( + f"input_ids and attention_mask must have the same shape, got {input_ids.shape} and {attention_mask.shape}." + ) + + input_ids_cpu = input_ids.detach().cpu() + attention_mask_cpu = attention_mask.detach().cpu().bool() + + if prompt_attention_mask is not None: + prompt_lengths = prompt_attention_mask.detach().cpu().sum(dim=1).to(torch.long) + else: + if labels is None: + raise ValueError("labels are required when prompt_attention_mask is not provided.") + if labels.shape != input_ids.shape: + raise ValueError(f"labels must match input_ids shape, got {labels.shape} and {input_ids.shape}.") + full_lengths = attention_mask_cpu.sum(dim=1).to(torch.long) + completion_lengths = (labels.detach().cpu() != -100).sum(dim=1).to(torch.long) + prompt_lengths = full_lengths - completion_lengths + + trimmed_input_ids: list[list[int]] = [] + prompt_lengths_list: list[int] = [] + completion_lengths_list: list[int] = [] + + for row, mask, prompt_length in zip(input_ids_cpu, attention_mask_cpu, prompt_lengths, strict=True): + trimmed_row = row[mask] + prompt_len = int(prompt_length.item()) + if prompt_len < 0 or prompt_len > trimmed_row.numel(): + raise ValueError( + f"Invalid prompt length {prompt_len} for trimmed sequence of length {trimmed_row.numel()}." + ) + trimmed_input_ids.append(trimmed_row.tolist()) + prompt_lengths_list.append(prompt_len) + completion_lengths_list.append(int(trimmed_row.numel()) - prompt_len) + + return trimmed_input_ids, prompt_lengths_list, completion_lengths_list + + +class _DistillationCollator: + """Data collator for the distillation trainer with independent prompt/completion budgets. + + Unlike ``DataCollatorForChatML``, this collator tokenizes prompts and completions separately so that long + completions can never truncate the prompt to empty. It also handles prompt-only data (no assistant completions) for + pure on-policy distillation (``lmbda=1``). + """ + + def __init__( + self, + tokenizer: "PreTrainedTokenizerBase", + max_length: int, + max_prompt_length: int, + messages_key: str = "messages", + ignore_index: int = -100, + ): + self.tokenizer = tokenizer + self.max_length = max_length + self.max_prompt_length = max_prompt_length + self.messages_key = messages_key + self.ignore_index = ignore_index + + if tokenizer.pad_token_id is None: + raise ValueError("The tokenizer does not have a pad token. Please set `pad_token_id` in the tokenizer.") + + def __call__(self, examples: list[dict[str, Any]]) -> dict[str, torch.Tensor]: + all_input_ids: list[list[int]] = [] + all_labels: list[list[int]] = [] + all_prompt_ids: list[list[int]] = [] + + for example in examples: + messages = example[self.messages_key] + + # Split: prompt = everything before the last assistant turn, completion = last assistant turn + has_completion = len(messages) > 1 and messages[-1].get("role") == "assistant" + prompt_messages = messages[:-1] if has_completion else messages + + # Tokenize prompt with its own budget using the tokenizer's truncation side + formatted_prompt = self.tokenizer.apply_chat_template( + prompt_messages, tokenize=False, add_generation_prompt=True + ) + prompt_ids = self.tokenizer( + formatted_prompt, + truncation=True, + max_length=self.max_prompt_length, + padding=False, + add_special_tokens=False, + )["input_ids"] + + if has_completion: + # Tokenize the full message (prompt + completion) without truncation first + formatted_full = self.tokenizer.apply_chat_template( + messages, tokenize=False, add_generation_prompt=False + ) + full_ids = self.tokenizer(formatted_full, truncation=False, padding=False, add_special_tokens=False)[ + "input_ids" + ] + + # Identify completion tokens: everything after the prompt in the full sequence. + # Use the un-truncated prompt length as the split point. + formatted_prompt_ids = self.tokenizer( + formatted_prompt, truncation=False, padding=False, add_special_tokens=False + )["input_ids"] + completion_ids = full_ids[len(formatted_prompt_ids) :] + + # Trim completion so prompt + completion <= max_length + max_comp = self.max_length - len(prompt_ids) + if max_comp > 0 and len(completion_ids) > max_comp: + completion_ids = completion_ids[:max_comp] + elif max_comp <= 0: + completion_ids = [] + + input_ids = prompt_ids + completion_ids + labels = [self.ignore_index] * len(prompt_ids) + list(completion_ids) + else: + # Prompt-only: no completion to train on (on-policy will generate one) + input_ids = list(prompt_ids) + labels = [self.ignore_index] * len(prompt_ids) + + all_input_ids.append(input_ids) + all_labels.append(labels) + all_prompt_ids.append(list(prompt_ids)) + + # Convert to tensors and left-pad + pad_id = self.tokenizer.pad_token_id + input_ids_t = pad( + [torch.tensor(ids, dtype=torch.long) for ids in all_input_ids], + padding_side="left", + padding_value=pad_id, + ) + attention_mask_t = pad( + [torch.ones(len(ids), dtype=torch.long) for ids in all_input_ids], + padding_side="left", + padding_value=0, + ) + labels_t = pad( + [torch.tensor(lab, dtype=torch.long) for lab in all_labels], + padding_side="left", + padding_value=self.ignore_index, + ) + prompts_t = pad( + [torch.tensor(ids, dtype=torch.long) for ids in all_prompt_ids], + padding_side="left", + padding_value=pad_id, + ) + prompt_mask_t = pad( + [torch.ones(len(ids), dtype=torch.long) for ids in all_prompt_ids], + padding_side="left", + padding_value=0, + ) + + return { + "input_ids": input_ids_t, + "attention_mask": attention_mask_t, + "labels": labels_t, + "prompts": prompts_t, + "prompt_attention_mask": prompt_mask_t, + } + + +class _RepeatBatchDataLoader: + """Repeats each collated batch ``repeat_count`` times without re-collation. + + ``RepeatSampler`` with ``repeat_count > 1`` causes the DataLoader to re-collate (re-tokenize) the same examples on + every repeat, which is wasteful. This wrapper instead keeps ``repeat_count=1`` in the sampler and repeats the + already-collated tensor dict, avoiding redundant tokenization. + """ + + def __init__(self, dataloader, repeat_count: int): + self.dataloader = dataloader + self.repeat_count = repeat_count + + def __iter__(self): + for batch in self.dataloader: + for _ in range(self.repeat_count): + yield batch + + def __len__(self): + return len(self.dataloader) * self.repeat_count + + def set_epoch(self, epoch: int): + if hasattr(self.dataloader, "set_epoch"): + self.dataloader.set_epoch(epoch) + + def __getattr__(self, attr): + return getattr(self.dataloader, attr) + + +class DistillationTrainer(_BaseTrainer): + """ + Trainer for knowledge distillation from a teacher model to a student model. + + Supports: + - Generalized JSD loss (forward KL, reverse KL, or interpolated JSD via `beta`) + - On-policy / off-policy mixing via `lmbda` (buffered across gradient accumulation) + - Local teacher model or external teacher via vLLM server + - Student on-policy generation via vLLM or model.generate() + - Liger kernel for memory-efficient fused JSD loss + """ + + _tag_names = ["trl", "distillation"] + _name = "Distillation" + _paper = { + "title": "On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes", + "id": "2306.13649", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @inproceedings{agarwal2024on-policy, + title = {{On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes}}, + author = {Rishabh Agarwal and Nino Vieillard and Yongchao Zhou and Piotr Stanczyk and Sabela Ramos Garea and Matthieu Geist and Olivier Bachem}, + year = 2024, + booktitle = {The Twelfth International Conference on Learning Representations, {ICLR} 2024, Vienna, Austria, May 7-11, 2024}, + publisher = {OpenReview.net}, + url = {https://openreview.net/forum?id=3zKtaqxLhW}, + }"""), + } + + def __init__( + self, + model: PreTrainedModel | nn.Module | str | None = None, + teacher_model: PreTrainedModel | nn.Module | str = None, + args: DistillationConfig | None = None, + data_collator: DataCollator | None = None, # type: ignore + train_dataset: Dataset | None = None, + eval_dataset: Dataset | dict[str, Dataset] | None = None, + processing_class: PreTrainedTokenizerBase + | BaseImageProcessor + | FeatureExtractionMixin + | ProcessorMixin + | None = None, + compute_metrics: Callable[[EvalPrediction], dict] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None, + peft_config: Optional["PeftConfig"] = None, + ): + if args is None: + args = DistillationConfig(output_dir="tmp_distillation") + + # ── Student model loading ── + model_init_kwargs = args.model_init_kwargs or {} + if isinstance(model_init_kwargs, str): + import json + + model_init_kwargs = json.loads(model_init_kwargs) + teacher_model_init_kwargs = args.teacher_model_init_kwargs or {} + if isinstance(teacher_model_init_kwargs, str): + import json + + teacher_model_init_kwargs = json.loads(teacher_model_init_kwargs) + if isinstance(model, str): + model_name_or_path = model + model = create_model_from_path(model, **model_init_kwargs) + else: + model_name_or_path = model.config._name_or_path if model is not None else None + + # ── Processing class (tokenizer) ── + if processing_class is None and model_name_or_path is not None: + processing_class = AutoTokenizer.from_pretrained(model_name_or_path) + if processing_class is not None: + if getattr(processing_class, "pad_token", None) is None: + processing_class.pad_token = processing_class.eos_token + + # ── PEFT ── + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + model = get_peft_model(model, peft_config) + + # ── Data collator ── + if data_collator is None: + data_collator = _DistillationCollator( + tokenizer=processing_class, + max_length=args.max_length, + max_prompt_length=args.max_prompt_length, + ) + + # ── Liger fused JSD loss ── + self.use_liger_loss = False + if args.use_liger_kernel: + self.liger_jsd_loss = LigerFusedLinearJSDLoss( + beta=args.beta, + ignore_index=-100, + temperature=args.temperature, + compiled=False, + weight_hard_loss=0.0, + weight_soft_loss=1.0, + ) + self.use_liger_loss = True + self._forward_redirection = _ForwardRedirection() + + # ── Teacher model setup ── + self.teacher_client = None + self.use_teacher_server = args.use_teacher_server + self.teacher_model_server_url = args.teacher_model_server_url + self._local_teacher_tokenizer_matches_student = True + if self.use_teacher_server: + from ...generation.vllm_client import VLLMClient + + self.teacher_client = VLLMClient(base_url=self.teacher_model_server_url, connection_timeout=60.0) + teacher_model = None + elif teacher_model is not None: + if args.teacher_model_init_kwargs is not None and not isinstance(teacher_model, str): + raise ValueError( + "You passed teacher_model_init_kwargs to the config, but your teacher_model is already " + "instantiated." + ) + + teacher_model_name_or_path = ( + teacher_model + if isinstance(teacher_model, str) + else getattr(getattr(teacher_model, "config", None), "_name_or_path", None) + ) + if teacher_model_name_or_path is None: + raise ValueError( + "DistillationTrainer requires a local teacher model with `config._name_or_path` set so its " + "tokenizer can be validated against the student tokenizer." + ) + + teacher_tokenizer_kwargs = {} + teacher_revision = teacher_model_init_kwargs.get("revision", args.teacher_model_revision) + if teacher_revision is not None: + teacher_tokenizer_kwargs["revision"] = teacher_revision + if teacher_model_init_kwargs.get("trust_remote_code") is not None: + teacher_tokenizer_kwargs["trust_remote_code"] = teacher_model_init_kwargs["trust_remote_code"] + teacher_processing_class = AutoTokenizer.from_pretrained( + teacher_model_name_or_path, **teacher_tokenizer_kwargs + ) + if getattr(teacher_processing_class, "pad_token", None) is None: + teacher_processing_class.pad_token = teacher_processing_class.eos_token + self._local_teacher_tokenizer_matches_student = self._local_teacher_tokenizers_match( + processing_class, teacher_processing_class + ) + if not self._local_teacher_tokenizer_matches_student: + warnings.warn( + "DistillationTrainer's built-in local-teacher loss assumes the student and teacher share the " + "same tokenizer. The loaded local teacher tokenizer does not match the student tokenizer, so " + "the teacher weights will be left unchanged for subclass overrides. Direct use of the base " + "DistillationTrainer with this local teacher remains unsupported.", + UserWarning, + stacklevel=2, + ) + + if isinstance(teacher_model, str): + dtype = teacher_model_init_kwargs.get("dtype") + teacher_model_init_kwargs["dtype"] = dtype if dtype in ["auto", None] else getattr(torch, dtype) + + if isinstance(teacher_model, str): + init_kwargs = dict(teacher_model_init_kwargs) + if args.teacher_model_revision is not None: + init_kwargs.setdefault("revision", args.teacher_model_revision) + teacher_model = create_model_from_path(teacher_model, **init_kwargs) + + # Trainer does not need to remove unused columns — the collator handles raw data + args.remove_unused_columns = False + + super().__init__( + model=model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + ) + + # ── Prepare teacher model (after super().__init__ so accelerator is ready) ── + if teacher_model is not None: + if self._local_teacher_tokenizer_matches_student: + teacher_model.resize_token_embeddings(self.model.config.get_text_config().vocab_size) + if self.is_deepspeed_enabled: + self.teacher_model = prepare_deepspeed(teacher_model, self.accelerator) + else: + self.teacher_model = self.accelerator.prepare_model(teacher_model, evaluation_mode=True) + else: + self.teacher_model = None + + if args.disable_dropout: + disable_dropout_in_model(self.model) + + # ── Store config values ── + self.lmbda = args.lmbda + self.beta = args.beta + self.temperature = args.temperature + self.top_p = args.top_p + self.num_generations = args.num_generations + self.reverse_kl_top_1_mode = args.reverse_kl_top_1_mode + self.loss_top_k = args.loss_top_k + self.loss_add_tail = args.loss_add_tail + + # ── Buffer state ── + self._buffered_inputs = None + self._buffered_on_policy_flags = None + self._buffered_text_logs = None + self._buffer_step = 0 + + # ── Loss tracking ── + self._on_policy_loss_total = 0.0 + self._off_policy_loss_total = 0.0 + self._on_policy_step_equiv = 0.0 + self._off_policy_step_equiv = 0.0 + + # ── Generation config ── + generation_kwargs = { + "max_new_tokens": args.max_completion_length, + "temperature": args.temperature, + "top_p": args.top_p, + "do_sample": True, + "top_k": args.top_k, + "pad_token_id": self.processing_class.pad_token_id, + } + self.generation_config = GenerationConfig(**generation_kwargs) + self.generation_kwargs = generation_kwargs + if ( + hasattr(self.model.generation_config, "eos_token_id") + and self.model.generation_config.eos_token_id is not None + ): + self.generation_config.eos_token_id = self.model.generation_config.eos_token_id + + # ── Metrics & Logging ── + self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)} + self._total_train_tokens = 0 + self.log_completions = args.log_completions + self.log_completions_steps = args.log_completions_steps + self.num_completions_to_print = args.num_completions_to_print + + self._textual_logs = { + "prompt": [], + "completion": [], + } + + # ── vLLM for student generation ── + self.use_vllm = args.use_vllm + if self.use_vllm: + if not is_vllm_available(): + raise ImportError( + "vLLM is not available and use_vllm is set to True. Please install vLLM with " + "`pip install vllm` to use it." + ) + self.vllm_generation = VLLMGeneration( + model=self.model, + accelerator=self.accelerator, + processing_class=self.processing_class, + mode=args.vllm_mode, + structured_outputs_regex=args.vllm_structured_outputs_regex, + server_base_url=args.vllm_server_base_url, + server_host=args.vllm_server_host, + server_port=args.vllm_server_port, + group_port=args.vllm_group_port, + server_timeout=args.vllm_server_timeout, + tensor_parallel_size=args.vllm_tensor_parallel_size, + gpu_memory_utilization=args.vllm_gpu_memory_utilization, + max_model_length=args.vllm_max_model_length, + max_num_seqs=args.per_device_train_batch_size * args.gradient_accumulation_steps, + enable_sleep_mode=args.vllm_enable_sleep_mode, + model_impl=args.vllm_model_impl, + temperature=args.temperature, + top_p=args.top_p, + top_k=args.top_k, + max_completion_length=args.max_completion_length, + logprobs=None, + ) + self.vllm_sync_frequency = args.vllm_sync_frequency + self._last_vllm_sync_step = -1 + + @staticmethod + def _local_teacher_tokenizers_match( + student_processing_class: PreTrainedTokenizerBase, + teacher_processing_class: PreTrainedTokenizerBase, + ) -> bool: + """Check whether the student and local teacher tokenizers share the same vocabulary.""" + return student_processing_class.get_vocab() == teacher_processing_class.get_vocab() + + def _raise_if_local_teacher_tokenizer_mismatch(self) -> None: + """Guard the base local-teacher JSD path, while still allowing subclass overrides.""" + if self.teacher_model is not None and not self._local_teacher_tokenizer_matches_student: + raise ValueError( + "DistillationTrainer's built-in local-teacher loss only supports student/teacher pairs that use " + "the same tokenizer. Use a same-tokenizer local teacher, set `use_teacher_server=True`, or " + "override the local teacher loss path in a subclass." + ) + + def _compute_prompt_length(self, inputs: dict[str, torch.Tensor | Any]) -> int: + """Compute the earliest prompt boundary that still includes every completion token in the batch.""" + if inputs.get("labels") is not None: + attention_mask = inputs["attention_mask"] + labels = inputs["labels"] + full_lengths = attention_mask.sum(dim=1) + completion_lengths = (labels != -100).sum(dim=1) + return int((full_lengths - completion_lengths).min().item()) + return inputs["prompts"].shape[1] + + def _get_completion_lengths(self, generated_tokens: torch.Tensor, prompt_width: int) -> torch.Tensor: + """Infer per-sample completion lengths from generated tokens.""" + completion_tokens = generated_tokens[:, prompt_width:] + pad_token_id = self.processing_class.pad_token_id + eos_token_id = self.generation_config.eos_token_id + if eos_token_id is None: + eos_token_ids = set() + elif isinstance(eos_token_id, int): + eos_token_ids = {eos_token_id} + else: + eos_token_ids = set(eos_token_id) + pad_equals_eos = pad_token_id is not None and pad_token_id in eos_token_ids + + completion_lengths = [] + for row in completion_tokens.tolist(): + if pad_equals_eos and eos_token_ids: + completion_length = len(row) + for idx, token_id in enumerate(row): + if token_id in eos_token_ids: + completion_length = idx + 1 + break + elif pad_token_id is not None: + completion_length = len(row) + while completion_length > 0 and row[completion_length - 1] == pad_token_id: + completion_length -= 1 + else: + completion_length = len(row) + completion_lengths.append(completion_length) + + return torch.tensor(completion_lengths, device=generated_tokens.device, dtype=torch.long) + + # ────────────────────────────────────────────────────────────────────── + # Dataset / Dataloader + # ────────────────────────────────────────────────────────────────────── + + def _set_signature_columns_if_needed(self): + super()._set_signature_columns_if_needed() + extra_columns = ["prompts", "prompt_attention_mask", "messages", "chat_template_kwargs", "tools"] + if self._signature_columns is None: + self._signature_columns = extra_columns + else: + for col in extra_columns: + if col not in self._signature_columns: + self._signature_columns.append(col) + + def _get_train_sampler(self, dataset=None): + if dataset is None: + dataset = self.train_dataset + return RepeatSampler( + data_source=dataset, + mini_repeat_count=self.num_generations, + batch_size=self.args.generation_batch_size * self.accelerator.num_processes, + repeat_count=1, + shuffle=True, + seed=self.args.seed, + ) + + def get_train_dataloader(self): + """ + Override to load one generation batch per optimizer window. + + The dataloader yields batches of size `per_device_train_batch_size * gradient_accumulation_steps`. + RepeatSampler ensures each generation batch is repeated `gradient_accumulation_steps` times so the Trainer's + loop iterates the correct number of times. + """ + if self.train_dataset is None: + raise ValueError("Trainer: training requires a train_dataset.") + + train_dataset = self.train_dataset + data_collator = self.data_collator + + dataloader_params = { + "batch_size": self._train_batch_size * self.args.gradient_accumulation_steps, + "collate_fn": data_collator, + "num_workers": self.args.dataloader_num_workers, + "pin_memory": self.args.dataloader_pin_memory, + "persistent_workers": self.args.dataloader_persistent_workers, + } + + if not isinstance(train_dataset, torch.utils.data.IterableDataset): + dataloader_params["sampler"] = self._get_train_sampler() + dataloader_params["drop_last"] = self.args.dataloader_drop_last + dataloader_params["worker_init_fn"] = partial( + seed_worker, + num_workers=self.args.dataloader_num_workers, + rank=self.args.process_index, + ) + if self.args.dataloader_num_workers > 0: + dataloader_params["prefetch_factor"] = self.args.dataloader_prefetch_factor + + base_dataloader = self.accelerator.prepare(DataLoader(train_dataset, **dataloader_params)) + return _RepeatBatchDataLoader(base_dataloader, repeat_count=self.args.gradient_accumulation_steps) + + # ────────────────────────────────────────────────────────────────────── + # Buffering: on/off-policy mixing across gradient accumulation steps + # ────────────────────────────────────────────────────────────────────── + + @profiling_decorator + def _prepare_inputs(self, generation_batch: dict[str, torch.Tensor | Any]) -> dict[str, torch.Tensor | Any]: + if not self.model.training: + return generation_batch + + buffer_steps = self.args.gradient_accumulation_steps + if self._buffer_step % buffer_steps == 0 or self._buffered_inputs is None: + self._fill_buffer(generation_batch, buffer_steps) + + slice_idx = self._buffer_step % buffer_steps + inputs = self._buffered_inputs[slice_idx] + self._buffer_step += 1 + return inputs + + @profiling_decorator + def _fill_buffer(self, generation_batch: dict[str, torch.Tensor | Any], buffer_steps: int): + """Split batch into slices and decide which are on-policy (student-generated) vs off-policy.""" + slices = split_tensor_dict(generation_batch, buffer_steps) + + # Decide on-policy flags (synchronized across processes) + if self.accelerator.is_main_process: + on_policy_flags = [random.random() <= self.lmbda for _ in range(buffer_steps)] + else: + on_policy_flags = [False] * buffer_steps + on_policy_flags = broadcast_object_list(on_policy_flags, from_process=0) + + self._buffered_inputs = [None] * buffer_steps + self._buffered_on_policy_flags = on_policy_flags + self._buffered_text_logs = [None] * buffer_steps + + # Store off-policy slices directly + on_policy_indices = [] + for i, is_on_policy in enumerate(on_policy_flags): + if is_on_policy: + on_policy_indices.append(i) + else: + self._buffered_inputs[i] = slices[i] + + # Generate student completions for on-policy slices + if on_policy_indices: + self._generate_student_completions(slices, on_policy_indices) + + # Gather on-policy text logs once per optimizer step (all processes must participate) + if self.log_completions: + on_policy_prompts = [] + on_policy_completions = [] + for i in on_policy_indices: + if self._buffered_text_logs[i] is not None: + prompts, completions = self._buffered_text_logs[i] + on_policy_prompts.extend(prompts) + on_policy_completions.extend(completions) + self._textual_logs["prompt"].extend(gather_object(on_policy_prompts)) + self._textual_logs["completion"].extend(gather_object(on_policy_completions)) + + @profiling_decorator + def _generate_student_completions(self, slices: list[dict[str, torch.Tensor | Any]], on_policy_indices: list[int]): + """Generate completions from the student model for on-policy training.""" + if not self.use_vllm: + self._generate_with_model(slices, on_policy_indices) + return + + # Collect all prompts across on-policy slices, stripping left-padding so vLLM + # receives only real prompt token IDs (like GRPO trainer). + local_prompts = [] + local_slice_indices = [] + pad_token_id = self.processing_class.pad_token_id + for slice_idx in on_policy_indices: + prompt_mask = slices[slice_idx].get("prompt_attention_mask") + for i, prompt in enumerate(slices[slice_idx]["prompts"]): + if prompt_mask is not None: + prompt = prompt[prompt_mask[i].bool()] + elif pad_token_id is not None: + first_non_pad = (prompt != pad_token_id).nonzero(as_tuple=True)[0] + if len(first_non_pad) > 0: + prompt = prompt[first_non_pad[0] :] + local_prompts.append(prompt) + local_slice_indices.append(slice_idx) + + # Sync student weights to vLLM if needed + if ( + self.state.global_step != self._last_vllm_sync_step + and self.state.global_step % self.vllm_sync_frequency == 0 + ): + self.vllm_generation.sync_weights() + self._last_vllm_sync_step = self.state.global_step + + # Generate completions — pass token IDs directly, no text decoding + prompt_ids_list = [p.tolist() for p in local_prompts] + _, completion_ids, _, _ = self.vllm_generation.generate( + prompts=prompt_ids_list, images=None, num_generations=self.num_generations + ) + + # Process completions into the buffer + self._store_completions_in_buffer( + slices, on_policy_indices, local_slice_indices, local_prompts, completion_ids + ) + + def _generate_with_model(self, slices: list[dict[str, torch.Tensor | Any]], on_policy_indices: list[int]): + """Fallback generation using model.generate() (no vLLM).""" + with unwrap_model_for_generation( + self.model, self.accelerator, generation_kwargs=self.generation_kwargs + ) as unwrapped_model: + for slice_idx in on_policy_indices: + slice_inputs = slices[slice_idx] + generated_outputs = unwrapped_model.generate( + input_ids=slice_inputs["prompts"], + attention_mask=slice_inputs.get("prompt_attention_mask", None), + generation_config=self.generation_config, + return_dict_in_generate=True, + ) + generated_tokens = generated_outputs.sequences + batch_size = generated_tokens.size(0) + device = generated_tokens.device + pad_token_id = self.processing_class.pad_token_id + prompt_width = slice_inputs["prompts"].shape[1] + prompt_mask = slice_inputs.get("prompt_attention_mask") + if prompt_mask is not None: + prompt_token_lengths = prompt_mask.sum(dim=1) + else: + prompt_token_lengths = torch.full((batch_size,), prompt_width, dtype=torch.long, device=device) + completion_lengths = self._get_completion_lengths(generated_tokens, prompt_width) + new_attention_mask, new_labels = self._build_sequence_batch( + generated_tokens, prompt_width, prompt_token_lengths, completion_lengths + ) + + # Decode for logging + prompt_texts = [] + completion_texts = [] + for idx in range(batch_size): + prompt_tokens = slice_inputs["prompts"][idx] + if prompt_mask is not None: + prompt_tokens = prompt_tokens[prompt_mask[idx].bool()] + elif pad_token_id is not None: + prompt_tokens = prompt_tokens[prompt_tokens != pad_token_id] + prompt_texts.append( + self.processing_class.decode(prompt_tokens.tolist(), skip_special_tokens=False) + ) + length = prompt_width + completion_length = int(completion_lengths[idx].item()) + completion_texts.append( + self.processing_class.decode( + generated_tokens[idx, length : length + completion_length].tolist(), + skip_special_tokens=False, + ) + ) + + updated = dict(slice_inputs) + updated["input_ids"] = generated_tokens + updated["attention_mask"] = new_attention_mask + updated["labels"] = new_labels + + self._buffered_inputs[slice_idx] = updated + self._buffered_text_logs[slice_idx] = (prompt_texts, completion_texts) + + def _store_completions_in_buffer( + self, + slices: list[dict[str, torch.Tensor | Any]], + on_policy_indices: list[int], + local_slice_indices: list[int], + local_prompts: list[torch.Tensor], + completion_ids: list, + ): + """Process vLLM completions and store them in the buffer. + + Uses original prompt token IDs directly (no decode/re-encode roundtrip), following the same approach as + GRPOTrainer. + """ + device = self.accelerator.device + pad_token_id = self.processing_class.pad_token_id if self.processing_class.pad_token_id is not None else 0 + max_completion_length = self.generation_config.max_new_tokens + + # Group completions and prompt token IDs by slice + slice_completions = {idx: [] for idx in on_policy_indices} + slice_prompt_ids = {idx: [] for idx in on_policy_indices} + for i, slice_idx in enumerate(local_slice_indices): + slice_completions[slice_idx].append(completion_ids[i]) + slice_prompt_ids[slice_idx].append(local_prompts[i]) + + for slice_idx in on_policy_indices: + slice_inputs = slices[slice_idx] + prompt_id_tensors = slice_prompt_ids[slice_idx] + prompt_width = max(len(p) for p in prompt_id_tensors) + prompt_token_lengths = torch.tensor([len(p) for p in prompt_id_tensors], device=device, dtype=torch.long) + prompt_attention_mask = ( + torch.arange(prompt_width, device=device).unsqueeze(0) + >= (prompt_width - prompt_token_lengths).unsqueeze(1) + ).long() + + # Left-pad prompt token IDs to the longest prompt in this slice + prompt_ids = torch.stack( + [F.pad(p, (prompt_width - len(p), 0), value=pad_token_id) for p in prompt_id_tensors] + ).to(device) + + # Pad/truncate completions (right-pad to max_completion_length) + completion_tensors = [] + completion_ids_for_text = [] + completion_lengths = [] + for comp_ids in slice_completions[slice_idx]: + t = torch.tensor(comp_ids, device=device) + if len(t) > max_completion_length: + t = t[:max_completion_length] + completion_ids_for_text.append(t.tolist()) + completion_lengths.append(len(t)) + if len(t) < max_completion_length: + padding = torch.full((max_completion_length - len(t),), pad_token_id, device=device, dtype=t.dtype) + t = torch.cat([t, padding]) + completion_tensors.append(t) + + completion_ids_padded = torch.stack(completion_tensors) + new_input_ids = torch.cat([prompt_ids, completion_ids_padded], dim=1) + completion_lengths = torch.tensor(completion_lengths, device=device, dtype=torch.long) + new_attention_mask, new_labels = self._build_sequence_batch( + new_input_ids, prompt_width, prompt_token_lengths, completion_lengths + ) + + # Decode for logging only + prompt_texts = self.processing_class.batch_decode( + prompt_id_tensors, skip_special_tokens=False, clean_up_tokenization_spaces=False + ) + completion_texts = self.processing_class.batch_decode( + completion_ids_for_text, skip_special_tokens=False, clean_up_tokenization_spaces=False + ) + + updated = dict(slice_inputs) + updated["input_ids"] = new_input_ids + updated["attention_mask"] = new_attention_mask + updated["labels"] = new_labels + # Update prompts to match the new padding width so prompt_length is consistent + updated["prompts"] = prompt_ids + updated["prompt_attention_mask"] = prompt_attention_mask + + self._buffered_inputs[slice_idx] = updated + self._buffered_text_logs[slice_idx] = (prompt_texts, completion_texts) + + @staticmethod + def _build_sequence_batch( + new_input_ids: torch.Tensor, + prompt_width: int, + prompt_token_lengths: torch.Tensor, + completion_lengths: torch.Tensor, + ) -> tuple[torch.Tensor, torch.Tensor]: + """Build attention mask and labels from prompt/completion lengths.""" + prompt_token_lengths = prompt_token_lengths.to(device=new_input_ids.device, dtype=torch.long) + completion_lengths = completion_lengths.to(device=new_input_ids.device, dtype=torch.long) + positions = torch.arange(new_input_ids.shape[1], device=new_input_ids.device).unsqueeze(0) + prompt_mask = (positions < prompt_width) & (positions >= (prompt_width - prompt_token_lengths).unsqueeze(1)) + completion_mask = (positions >= prompt_width) & (positions < (prompt_width + completion_lengths).unsqueeze(1)) + new_attention_mask = (prompt_mask | completion_mask).long() + + new_labels = torch.full_like(new_input_ids, -100) + new_labels[completion_mask] = new_input_ids[completion_mask] + + return new_attention_mask, new_labels + + # ────────────────────────────────────────────────────────────────────── + # Loss computation + # ────────────────────────────────────────────────────────────────────── + + @staticmethod + def _reduce_divergence_loss(jsd, labels=None, reduction="batchmean", num_items_in_batch=None): + """Reduce a per-token divergence tensor using the trainer's label mask semantics. + + When `num_items_in_batch` is provided (as under gradient accumulation), the divergence is reduced as `sum / + num_items_in_batch`, matching the gradient-accumulation-correct behavior of HF's default cross-entropy. + Otherwise it falls back to the local `reduction` (default `batchmean`). See issue #4719. + """ + mask = None + if labels is not None: + mask = labels != -100 + jsd = jsd[mask] + + if num_items_in_batch is not None: + # Normalize by the global number of valid tokens for gradient-accumulation-correct loss. + jsd_sum = jsd.sum() + if isinstance(num_items_in_batch, torch.Tensor): + num_items_in_batch = num_items_in_batch.to(jsd_sum.device) + return jsd_sum / num_items_in_batch + if reduction == "batchmean": + # clamp_min(1) avoids 0/0 -> nan when a sample has no unmasked positions + # (e.g. completion fully truncated). jsd[mask] is empty -> jsd.sum() == 0, + # so 0/1 == 0 with a valid grad path. + denom = mask.sum().clamp_min(1) if labels is not None else max(jsd.size(0), 1) + return jsd.sum() / denom + elif reduction == "sum": + return jsd.sum() + elif reduction == "mean": + return jsd.mean() + else: + return jsd + + @staticmethod + def generalized_jsd_loss( + student_logits, + teacher_logits, + labels=None, + beta=0.5, + temperature=1.0, + reduction="batchmean", + top_k=0, + add_tail=True, + num_items_in_batch=None, + ): + """ + Compute the generalized Jensen-Shannon Divergence loss for knowledge distillation. + + Args: + student_logits: Tensor of shape (batch_size, sequence_length, vocab_size). + teacher_logits: Tensor of shape (batch_size, sequence_length, vocab_size). + labels: Tensor of shape (batch_size, sequence_length) with -100 for positions to ignore. + beta: Interpolation coefficient. 0.0 = forward KL, 1.0 = reverse KL. + temperature: Softmax temperature. + reduction: 'batchmean', 'sum', 'mean', or 'none'. + top_k: Number of top tokens to restrict the loss to. The support set depends on beta: + beta=0 (forward KL) uses teacher's top-k, beta=1 (reverse KL) uses student's top-k, 0 0 and student_logits.size(-1) > top_k: + neg_inf = torch.full((), float("-inf"), dtype=student_logits.dtype, device=student_logits.device) + student_log_probs_full = F.log_softmax(student_logits, dim=-1) + teacher_log_probs_full = F.log_softmax(teacher_logits, dim=-1) + + if beta == 0: + # Forward KL: teacher-selected support + _, support = teacher_logits.topk(top_k, dim=-1) + support_mask = torch.ones_like(support, dtype=torch.bool) + elif beta == 1: + # Reverse KL: student-selected support + _, support = student_logits.topk(top_k, dim=-1) + support_mask = torch.ones_like(support, dtype=torch.bool) + else: + # JSD: union of both supports (concatenate + deduplicate) + _, student_top = student_logits.topk(top_k, dim=-1) + _, teacher_top = teacher_logits.topk(top_k, dim=-1) + support = torch.cat([teacher_top, student_top], dim=-1) + support_mask = torch.ones(support.shape, dtype=torch.bool, device=support.device) + for i in range(1, support.shape[-1]): + prev_matches = support[..., i : i + 1] == support[..., :i] + prev_valid = support_mask[..., :i] + support_mask[..., i] &= ~(prev_matches & prev_valid).any(dim=-1) + support = torch.where(support_mask, support, torch.zeros_like(support)) + + student_support_logps = student_log_probs_full.gather(-1, support) + teacher_support_logps = teacher_log_probs_full.gather(-1, support) + + # Mask invalid (duplicate) positions with -inf + student_topk_logps = torch.where(support_mask, student_support_logps, neg_inf) + teacher_topk_logps = torch.where(support_mask, teacher_support_logps, neg_inf) + + if add_tail: + # Add tail bucket: append log(1 - sum(exp(top_k_logps))) to preserve + # the remaining probability mass outside the top-k. This prevents trivial + # zero loss when top_k is small (especially top_k=1). + base_support_mask = support_mask + student_log_probs, support_mask = _add_tail_bucket(student_topk_logps, base_support_mask) + teacher_log_probs, _ = _add_tail_bucket(teacher_topk_logps, base_support_mask) + else: + student_log_probs = student_topk_logps - torch.logsumexp(student_topk_logps, dim=-1, keepdim=True) + teacher_log_probs = teacher_topk_logps - torch.logsumexp(teacher_topk_logps, dim=-1, keepdim=True) + else: + student_log_probs = F.log_softmax(student_logits, dim=-1) + teacher_log_probs = F.log_softmax(teacher_logits, dim=-1) + + jsd = _jsd_divergence(student_log_probs, teacher_log_probs, beta, support_mask) + return DistillationTrainer._reduce_divergence_loss( + jsd, labels=labels, reduction=reduction, num_items_in_batch=num_items_in_batch + ) + + def _get_reverse_kl_top_1_tokens( + self, student_scores: torch.Tensor, completion_tokens: torch.Tensor + ) -> torch.Tensor: + """Return the reverse-KL top-1 token IDs for the mixed top-1 loss path. + + Args: + student_scores: Any (B, T, V) tensor whose argmax selects the student's top token + (logits or log-probs — both are order-preserving). + completion_tokens: (B, T) actual token IDs in the completion. + """ + if self.reverse_kl_top_1_mode == "argmax": + return student_scores.argmax(dim=-1) + return completion_tokens + + def _compute_sparse_top_1_divergence_loss( + self, + student_log_probs: torch.Tensor, + teacher_top1_token_ids: torch.Tensor, + teacher_top1_logprobs: torch.Tensor, + reverse_token_ids: torch.Tensor, + reverse_teacher_logprobs: torch.Tensor, + labels: torch.Tensor, + num_items_in_batch=None, + ) -> torch.Tensor: + """Compute exact generalized JSD/KL on top-1 support for the mixed beta>0 path.""" + neg_inf = torch.full((), float("-inf"), dtype=student_log_probs.dtype, device=student_log_probs.device) + + if self.beta == 1: + support = reverse_token_ids.unsqueeze(-1) + support_mask = torch.ones_like(support, dtype=torch.bool) + teacher_support_logprobs = reverse_teacher_logprobs.unsqueeze(-1) + else: + teacher_support = teacher_top1_token_ids.unsqueeze(-1) + reverse_support = reverse_token_ids.unsqueeze(-1) + support = torch.cat([teacher_support, reverse_support], dim=-1) + support_mask = torch.ones_like(support, dtype=torch.bool) + support_mask[..., 1] = support[..., 1] != support[..., 0] + teacher_support_logprobs = torch.stack([teacher_top1_logprobs, reverse_teacher_logprobs], dim=-1) + support = torch.where(support_mask, support, torch.zeros_like(support)) + + student_support_logprobs = student_log_probs.gather(-1, support) + student_support_logprobs = torch.where(support_mask, student_support_logprobs, neg_inf) + teacher_support_logprobs = torch.where(support_mask, teacher_support_logprobs, neg_inf) + + if self.loss_add_tail: + base_support_mask = support_mask + student_sparse_log_probs, support_mask = _add_tail_bucket(student_support_logprobs, base_support_mask) + teacher_sparse_log_probs, _ = _add_tail_bucket(teacher_support_logprobs, base_support_mask) + else: + student_sparse_log_probs = student_support_logprobs - torch.logsumexp( + student_support_logprobs, dim=-1, keepdim=True + ) + teacher_sparse_log_probs = teacher_support_logprobs - torch.logsumexp( + teacher_support_logprobs, dim=-1, keepdim=True + ) + + jsd = _jsd_divergence(student_sparse_log_probs, teacher_sparse_log_probs, self.beta, support_mask) + return self._reduce_divergence_loss( + jsd, labels=labels, reduction="batchmean", num_items_in_batch=num_items_in_batch + ) + + def _compute_local_sparse_top_1_divergence_loss( + self, + student_logits: torch.Tensor, + teacher_logits: torch.Tensor, + completion_tokens: torch.Tensor, + labels: torch.Tensor, + num_items_in_batch=None, + ) -> torch.Tensor: + """Compute the mixed top-1 loss for a local teacher using gathered full-logit probabilities.""" + student_log_probs = F.log_softmax(student_logits / self.temperature, dim=-1) + teacher_log_probs = F.log_softmax(teacher_logits / self.temperature, dim=-1) + + teacher_top1_token_ids = teacher_logits.argmax(dim=-1) + teacher_top1_logprobs = teacher_log_probs.gather(dim=-1, index=teacher_top1_token_ids.unsqueeze(-1)).squeeze( + -1 + ) + reverse_token_ids = self._get_reverse_kl_top_1_tokens(student_logits, completion_tokens) + reverse_teacher_logprobs = teacher_log_probs.gather(dim=-1, index=reverse_token_ids.unsqueeze(-1)).squeeze(-1) + + return self._compute_sparse_top_1_divergence_loss( + student_log_probs=student_log_probs, + teacher_top1_token_ids=teacher_top1_token_ids, + teacher_top1_logprobs=teacher_top1_logprobs, + reverse_token_ids=reverse_token_ids, + reverse_teacher_logprobs=reverse_teacher_logprobs, + labels=labels, + num_items_in_batch=num_items_in_batch, + ) + + def _get_teacher_logits(self, inputs: dict[str, torch.Tensor | Any]) -> torch.Tensor: + """Get teacher logits — dispatches between local model and external server.""" + if self.teacher_model is not None: + self.teacher_model.eval() + with torch.no_grad(): + return self.teacher_model( + input_ids=inputs["input_ids"], + attention_mask=inputs["attention_mask"], + ).logits + elif self.use_teacher_server: + raise NotImplementedError( + "Fetching full teacher logits with use_teacher_server=True is not supported. " + "Server-backed distillation only supports per-token logprobs via " + "`_get_teacher_token_logprobs_from_server`." + ) + else: + raise ValueError("No teacher model or teacher server configured.") + + def _get_teacher_token_logprobs_from_server( + self, + inputs: dict[str, torch.Tensor | Any], + aligned_prompt_length: int, + ) -> dict[str, torch.Tensor]: + """Fetch per-token teacher logprobs from an external vLLM server. + + Returns a dict with: + ``actual_logprobs`` – (batch, completion_length) teacher log-prob for the actual + token at each position (for reverse KL). + ``topk_logprobs`` – (batch, completion_length, K) teacher top-k sorted logprobs + (for forward KL). + ``topk_token_ids`` – (batch, completion_length, K) corresponding token IDs. + """ + import numpy as np + + input_ids = inputs["input_ids"] + batch_size = input_ids.shape[0] + sequences, prompt_lengths, completion_lengths = build_teacher_request_inputs( + input_ids, + inputs["attention_mask"], + prompt_attention_mask=inputs.get("prompt_attention_mask"), + labels=inputs.get("labels"), + ) + + # The pure forward server path can use the requested teacher top-k support. + # When beta > 0, config validation restricts the server-backed path to top-1. + requested_top_k = self.loss_top_k + result = self.teacher_client.get_sequence_logprobs( + sequences=sequences, + prompt_lengths=prompt_lengths, + top_logprobs=requested_top_k, + temperature=self.temperature, + ) + K = requested_top_k + + device = input_ids.device + labels = inputs.get("labels") + if labels is None: + raise ValueError("labels are required to align teacher-server logprobs with the student loss tensors.") + + # The student loss slices tensors in padded-sequence coordinates starting at `aligned_prompt_length`. + # Place each teacher completion into that same coordinate system by locating the first non-masked completion + # token in `labels`. This works for both left-padded off-policy batches and on-policy batches where + # completions are right-padded after a fixed-width prompt block. + completion_offsets = [] + label_mask = labels != -100 + for sample_mask, comp_len in zip(label_mask, completion_lengths, strict=True): + if comp_len == 0: + completion_offsets.append(0) + continue + completion_start = int(torch.nonzero(sample_mask, as_tuple=False)[0].item()) + completion_offsets.append(completion_start - aligned_prompt_length) + + # Size the output tensors to tightly fit the teacher logprobs. Using the full padded + # sequence length would include padding positions with -inf teacher logprobs, producing + # +inf in the forward pass and NaN gradients in the backward pass (0 * inf = NaN). + # Shorter samples in variable-length batches still need the -inf sentinel at the tail; + # downstream loss consumers (_compute_server_sparse_top_1_divergence_loss, + # _compute_server_forward_kl_loss) neutralise those positions before the divergence + # math runs. + completion_length = max( + (offset + len(lps) for offset, lps in zip(completion_offsets, result["logprobs"], strict=True)), + default=0, + ) + + # actual_logprobs: (B, T) — teacher logprob for the actual token + def _actual_to_tensor(key): + arr = np.full((batch_size, completion_length), float("-inf"), dtype=np.float32) + for i, (offset, seq_lps) in enumerate(zip(completion_offsets, result[key], strict=True)): + if seq_lps: + vals = np.array(seq_lps, dtype=np.float32) # (comp_len_i, 1) + arr[i, offset : offset + vals.shape[0]] = vals[:, 0] + return torch.from_numpy(arr).to(device) + + # topk: (B, T, K) + def _topk_to_tensor(key, k, np_dtype, fill): + arr = np.full((batch_size, completion_length, k), fill, dtype=np_dtype) + for i, (offset, seq_vals) in enumerate(zip(completion_offsets, result[key], strict=True)): + if seq_vals: + vals = np.array(seq_vals, dtype=np_dtype) # (comp_len_i, k) + arr[i, offset : offset + vals.shape[0], :] = vals + return torch.from_numpy(arr).to(device) + + return { + "actual_logprobs": _actual_to_tensor("actual_logprobs"), + "topk_logprobs": _topk_to_tensor("logprobs", K, np.float32, float("-inf")), + "topk_token_ids": _topk_to_tensor("logprob_token_ids", K, np.int64, 0), + } + + def _compute_server_sparse_top_1_divergence_loss( + self, + teacher_result: dict[str, torch.Tensor], + student_log_probs: torch.Tensor, + completion_tokens: torch.Tensor, + labels: torch.Tensor, + ) -> torch.Tensor: + """Compute exact sparse top-1 generalized JSD/KL from server-provided teacher logprobs. + + Args: + teacher_result: dict with ``actual_logprobs`` (B, T), ``topk_logprobs`` (B, T, K), + ``topk_token_ids`` (B, T, K). + student_log_probs: (B, T, V) student log-softmax over vocabulary. + completion_tokens: (B, T) actual token IDs in the completion. + labels: (B, T) with -100 for positions to ignore. + """ + topk_teacher_lps = teacher_result["topk_logprobs"] # (B, T, 1) + topk_token_ids = teacher_result["topk_token_ids"] # (B, T, 1) + actual_teacher_lps = teacher_result["actual_logprobs"] # (B, T) + required = labels != -100 + + missing_actual = required & ~torch.isfinite(actual_teacher_lps) + if missing_actual.any(): + missing_count = int(missing_actual.sum().item()) + total_required = int(required.sum().item()) + raise ValueError( + "Teacher server is missing actual-token logprobs for required reverse-KL positions: " + f"{missing_count}/{total_required}." + ) + if self.beta < 1: + teacher_top1_logprobs = topk_teacher_lps.squeeze(-1) + missing_top1 = required & ~torch.isfinite(teacher_top1_logprobs) + if missing_top1.any(): + missing_count = int(missing_top1.sum().item()) + total_required = int(required.sum().item()) + raise ValueError( + "Teacher server is missing top-1 logprobs for required forward-KL positions: " + f"{missing_count}/{total_required}." + ) + + # Replace -inf teacher logprobs at intra-batch padding (labels == -100) with 0 so + # reverse-KL's student_probs·(log_s - log_t) does not leak +inf into the backward pass. + pad_mask_2d = ~required + pad_mask_3d = pad_mask_2d.unsqueeze(-1) + topk_teacher_lps = torch.where(pad_mask_3d, 0.0, topk_teacher_lps) + actual_teacher_lps = torch.where(pad_mask_2d, 0.0, actual_teacher_lps) + + # Server path only supports "sampled" mode — config validation enforces this, but we guard + # explicitly so future relaxations of the config check don't silently change behaviour. + reverse_token_ids = self._get_reverse_kl_top_1_tokens(student_log_probs, completion_tokens) + # The server path normalizes locally (batchmean), not by num_items_in_batch: teacher logprobs may not cover + # every student completion token (the loss is summed over the trimmed teacher window), so the global token + # count would be the wrong denominator. Gradient-accumulation normalization for the server path is left as a + # follow-up. + return self._compute_sparse_top_1_divergence_loss( + student_log_probs=student_log_probs, + teacher_top1_token_ids=topk_token_ids.squeeze(-1), + teacher_top1_logprobs=topk_teacher_lps.squeeze(-1), + reverse_token_ids=reverse_token_ids, + reverse_teacher_logprobs=actual_teacher_lps, + labels=labels, + ) + + def _compute_server_forward_kl_loss( + self, + teacher_result: dict[str, torch.Tensor], + student_log_probs: torch.Tensor, + labels: torch.Tensor, + ) -> torch.Tensor: + """Compute sparse forward KL from server-provided teacher top-k logprobs (beta==0 path). + + Args: + teacher_result: dict with ``topk_logprobs`` (B, T, K) and ``topk_token_ids`` (B, T, K). + student_log_probs: (B, T, V) student log-softmax over vocabulary. + labels: (B, T) with -100 for positions to ignore. + """ + teacher_topk_logprobs = teacher_result["topk_logprobs"] + teacher_topk_token_ids = teacher_result["topk_token_ids"] + valid = teacher_topk_logprobs > float("-inf") + neg_inf = torch.full((), float("-inf"), dtype=student_log_probs.dtype, device=student_log_probs.device) + student_topk_logprobs = student_log_probs.gather(dim=-1, index=teacher_topk_token_ids) + student_topk_logprobs = torch.where(valid, student_topk_logprobs, neg_inf) + teacher_topk_logprobs = torch.where(valid, teacher_topk_logprobs, neg_inf) + + if self.loss_add_tail: + base_support_mask = valid + student_sparse_log_probs, support_mask = _add_tail_bucket(student_topk_logprobs, base_support_mask) + teacher_sparse_log_probs, _ = _add_tail_bucket(teacher_topk_logprobs, base_support_mask) + else: + support_mask = valid + student_sparse_log_probs = student_topk_logprobs - torch.logsumexp( + student_topk_logprobs, dim=-1, keepdim=True + ) + teacher_sparse_log_probs = teacher_topk_logprobs - torch.logsumexp( + teacher_topk_logprobs, dim=-1, keepdim=True + ) + + jsd = _jsd_divergence( + student_sparse_log_probs, + teacher_sparse_log_probs, + beta=0.0, + support_mask=support_mask, + ) + # See `_compute_server_sparse_top_1_divergence_loss`: the server path normalizes locally, not by + # num_items_in_batch, because the teacher window may not cover every student completion token. + return self._reduce_divergence_loss(jsd, labels=labels, reduction="batchmean") + + def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): + self._raise_if_local_teacher_tokenizer_mismatch() + + if self.use_liger_loss: + loss = self._compute_liger_loss(model, inputs, num_items_in_batch=num_items_in_batch) + return (loss, None) if return_outputs else loss + + # Student forward pass + student_outputs = model( + input_ids=inputs["input_ids"], + attention_mask=inputs["attention_mask"], + ) + prompt_length = self._compute_prompt_length(inputs) + labels = inputs["labels"][:, prompt_length:] + completion_tokens = inputs["input_ids"][:, prompt_length:] + + if self.use_teacher_server: + # Server path: token-level divergence using teacher logprobs. + # The server returns: + # actual_logprobs – (B, T) teacher log p(x_actual) (for reverse KL) + # topk_logprobs – (B, T, K) teacher top-k sorted logprobs (for forward KL) + # topk_token_ids – (B, T, K) corresponding token IDs + teacher_result = self._get_teacher_token_logprobs_from_server(inputs, prompt_length) + + student_logits = student_outputs.logits[:, prompt_length - 1 : -1, :] + student_log_probs = F.log_softmax(student_logits / self.temperature, dim=-1) + + comp_len = teacher_result["actual_logprobs"].shape[1] + completion_tokens = completion_tokens[:, :comp_len] + trimmed_labels = labels[:, :comp_len] + + if self.beta > 0: + loss = self._compute_server_sparse_top_1_divergence_loss( + teacher_result=teacher_result, + student_log_probs=student_log_probs[:, :comp_len, :], + completion_tokens=completion_tokens, + labels=trimmed_labels, + ) + else: + loss = self._compute_server_forward_kl_loss( + teacher_result=teacher_result, + student_log_probs=student_log_probs[:, :comp_len, :], + labels=trimmed_labels, + ) + else: + # Local teacher: exact full-vocabulary loss except for the shared mixed top-1 path. + teacher_logits = self._get_teacher_logits(inputs) + student_logits = student_outputs.logits[:, prompt_length - 1 : -1, :] + teacher_logits = teacher_logits[:, prompt_length - 1 : -1, :] + if self.beta > 0 and self.loss_top_k == 1: + loss = self._compute_local_sparse_top_1_divergence_loss( + student_logits=student_logits, + teacher_logits=teacher_logits, + completion_tokens=completion_tokens, + labels=labels, + num_items_in_batch=num_items_in_batch, + ) + else: + loss = self.generalized_jsd_loss( + student_logits=student_logits, + teacher_logits=teacher_logits, + labels=labels, + beta=self.beta, + temperature=self.temperature, + top_k=self.loss_top_k, + add_tail=self.loss_add_tail, + num_items_in_batch=num_items_in_batch, + ) + + return (loss, student_outputs) if return_outputs else loss + + def _liger_student_forward(self, student, inputs): + """Decoder-only forward used by the Liger JSD path (skips lm_head to save memory).""" + if hasattr(student, "get_decoder") and student.get_decoder() is not None: + decoder = student.get_decoder() + else: + decoder = getattr(student, getattr(student, "base_model_prefix", "model"), student) + return decoder( + input_ids=inputs["input_ids"], + attention_mask=inputs["attention_mask"], + use_cache=False, + ) + + def _compute_liger_loss(self, model, inputs, num_items_in_batch=None): + """Memory-efficient JSD using Liger kernel (operates on hidden states, not full logits).""" + # Route through the DDP/FSDP wrapper via _forward_redirection so that + # DDP.forward() is called and prepare_for_backward() fires correctly. + unwrapped_student = self.accelerator.unwrap_model(model) + student_outputs = self._forward_redirection( + model, unwrapped_student, self._liger_student_forward, unwrapped_student, inputs + ) + + self.teacher_model.eval() + unwrapped_teacher = self.accelerator.unwrap_model(self.teacher_model) + if hasattr(unwrapped_teacher, "get_decoder") and unwrapped_teacher.get_decoder() is not None: + base_teacher = unwrapped_teacher.get_decoder() + else: + base_teacher = getattr( + unwrapped_teacher, getattr(unwrapped_teacher, "base_model_prefix", "model"), unwrapped_teacher + ) + with torch.no_grad(): + teacher_outputs = base_teacher( + input_ids=inputs["input_ids"], + attention_mask=inputs["attention_mask"], + use_cache=False, + ) + + student_hidden = student_outputs.last_hidden_state[:, :-1] + teacher_hidden = teacher_outputs.last_hidden_state[:, :-1] + del student_outputs, teacher_outputs + + student_hidden = student_hidden.reshape(-1, student_hidden.shape[-1]) + teacher_hidden = teacher_hidden.reshape(-1, teacher_hidden.shape[-1]) + + labels_mask = inputs["labels"] != -100 + masked_input_ids = torch.where(labels_mask, inputs["input_ids"], torch.full_like(inputs["input_ids"], -100)) + true_labels = masked_input_ids[:, 1:].reshape(-1) + + student_head = unwrapped_student.get_output_embeddings() + teacher_head = unwrapped_teacher.get_output_embeddings() + + loss = self.liger_jsd_loss( + student_input=student_hidden, + student_weight=student_head.weight, + teacher_input=teacher_hidden, + teacher_weight=teacher_head.weight, + true_labels=true_labels, + student_bias=getattr(student_head, "bias", None), + teacher_bias=getattr(teacher_head, "bias", None), + ) + + # The Liger JSD loss normalizes by the local number of valid tokens. Under gradient accumulation we want + # the global normalization, so rescale by `num_valid_local / num_items_in_batch`. + if num_items_in_batch is not None: + num_valid_local = (true_labels != -100).sum().clamp_min(1) + if isinstance(num_items_in_batch, torch.Tensor): + num_items_in_batch = num_items_in_batch.to(loss.device) + loss = loss * num_valid_local / num_items_in_batch + + del student_hidden, teacher_hidden, true_labels + return loss + + def _get_liger_zero3_lm_head_gather_ctx(self, model: nn.Module): + """Context manager for gathering lm_head parameters under Liger + ZeRO-3.""" + if not self.use_liger_loss: + return nullcontext() + + deepspeed_plugin = self.accelerator.state.deepspeed_plugin + if deepspeed_plugin is None or deepspeed_plugin.zero_stage != 3: + return nullcontext() + + import deepspeed + + unwrapped_student = self.accelerator.unwrap_model(model) + unwrapped_teacher = self.accelerator.unwrap_model(self.teacher_model) + student_head = unwrapped_student.get_output_embeddings() + teacher_head = unwrapped_teacher.get_output_embeddings() + params = [student_head.weight, teacher_head.weight] + if student_head.bias is not None: + params.append(student_head.bias) + if teacher_head.bias is not None: + params.append(teacher_head.bias) + return deepspeed.zero.GatheredParameters(params, modifier_rank=None) + + # ────────────────────────────────────────────────────────────────────── + # Training step & Logging + # ────────────────────────────────────────────────────────────────────── + + @profiling_decorator + def training_step( + self, model: nn.Module, inputs: dict[str, torch.Tensor | Any], num_items_in_batch: int | None = None + ) -> torch.Tensor: + """Training step with on/off-policy loss tracking and completion stats.""" + buffer_steps = self.args.gradient_accumulation_steps + + with self._get_liger_zero3_lm_head_gather_ctx(model): + loss = super().training_step(model, inputs, num_items_in_batch) + + slice_idx = (self._buffer_step - 1) % buffer_steps + + # Determine if this slice is on-policy + is_on_policy = False + if self._buffered_on_policy_flags is not None and slice_idx < len(self._buffered_on_policy_flags): + is_on_policy = self._buffered_on_policy_flags[slice_idx] + + # Track completion length stats — read from buffered inputs (which reflect on-policy generation) + actual_inputs = self._buffered_inputs[slice_idx] if self._buffered_inputs is not None else inputs + labels = actual_inputs.get("labels") + if labels is not None: + completion_lengths = (labels != -100).sum(dim=1).float() + gathered_lengths = self.accelerator.gather(completion_lengths) + mode = "train" + prefix = "on_policy" if is_on_policy else "off_policy" + self._metrics[mode][f"completions/{prefix}_mean_length"].append(gathered_lengths.mean().item()) + self._metrics[mode][f"completions/{prefix}_max_length"].append(gathered_lengths.max().item()) + self._metrics[mode][f"completions/{prefix}_min_length"].append(gathered_lengths.min().item()) + + # Log fraction of completions that hit max_completion_length (truncated) + max_comp_len = getattr(self.generation_config, "max_new_tokens", None) + if is_on_policy and max_comp_len is not None: + truncated_frac = (gathered_lengths >= max_comp_len).float().mean().item() + self._metrics[mode]["completions/truncated_fraction"].append(truncated_frac) + + # Track loss per policy type + loss_scalar = float(loss.detach()) + step_equiv = 1.0 / self.args.gradient_accumulation_steps + if is_on_policy: + self._on_policy_loss_total += loss_scalar + self._on_policy_step_equiv += step_equiv + else: + self._off_policy_loss_total += loss_scalar + self._off_policy_step_equiv += step_equiv + + return loss + + def log(self, logs: dict[str, float], start_time: float | None = None) -> None: + mode = "train" if self.model.training else "eval" + metrics = {key: sum(val) / len(val) for key, val in self._metrics[mode].items()} + + if mode == "train": + # Aggregate on/off-policy losses across distributed processes + device = self.accelerator.device if hasattr(self.accelerator, "device") else torch.device("cpu") + vec = torch.tensor( + [ + self._on_policy_loss_total, + self._off_policy_loss_total, + self._on_policy_step_equiv, + self._off_policy_step_equiv, + ], + dtype=torch.float64, + device=device, + ) + + if ( + getattr(self.accelerator, "distributed_type", DistributedType.NO) != DistributedType.NO + and dist.is_available() + and dist.is_initialized() + ): + dist.all_reduce(vec, op=dist.ReduceOp.SUM) + + on_sum, off_sum, on_eq, off_eq = vec.tolist() + if on_eq > 0: + logs["on_policy_loss"] = round(on_sum / on_eq, 4) + if off_eq > 0: + logs["off_policy_loss"] = round(off_sum / off_eq, 4) + + self._on_policy_loss_total = self._off_policy_loss_total = 0.0 + self._on_policy_step_equiv = self._off_policy_step_equiv = 0.0 + + if mode == "eval": + metrics = {f"eval_{key}": val for key, val in metrics.items()} + + logs.update(metrics) + super().log(logs, start_time) + self._metrics[mode].clear() + + # Log completions to console, wandb, and trackio + should_log_completions = ( + self.log_completions + and self.state.global_step > 0 + and self.state.global_step % self.log_completions_steps == 0 + ) + + if should_log_completions and self.accelerator.is_main_process: + prompts = list(self._textual_logs["prompt"]) + completions = list(self._textual_logs["completion"]) + + if prompts: + _print_completions_sample(prompts, completions, self.state.global_step, self.num_completions_to_print) + + logging_backends = [] + if self.args.report_to and "wandb" in self.args.report_to and wandb.run is not None: + logging_backends.append(wandb) + if self.args.report_to and "trackio" in self.args.report_to: + logging_backends.append(trackio) + + if logging_backends: + import pandas as pd + + table_data = { + "step": [str(self.state.global_step)] * len(prompts), + "prompt": prompts, + "completion": completions, + } + df = pd.DataFrame(table_data) + if self.num_completions_to_print and len(df) > self.num_completions_to_print: + df = df.sample(n=self.num_completions_to_print, random_state=42) + + for logging_backend in logging_backends: + logging_backend.log({"completions": logging_backend.Table(dataframe=df)}) + + # Clear text logs on all processes after the logging interval + if should_log_completions: + self._textual_logs["prompt"].clear() + self._textual_logs["completion"].clear() diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/dppo/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/dppo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0ce3ffeae4fc9c790f3249ba48a958567c66d35f --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/dppo/__init__.py @@ -0,0 +1,17 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +from .dppo_config import DPPOConfig +from .dppo_trainer import DPPOTrainer diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/dppo/dppo_config.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/dppo/dppo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..92736aac144ad648aeb4b52973535744330963c6 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/dppo/dppo_config.py @@ -0,0 +1,115 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field +from typing import Literal + +from ...trainer.grpo_config import GRPOConfig + + +@dataclass +class DPPOConfig(GRPOConfig): + """ + Configuration class for DPPOTrainer. + + DPPO (Divergence Proximal Policy Optimization) replaces PPO/GRPO's heuristic ratio-clipping with a principled trust + region based on direct policy divergence estimates. + + Paper: "Rethinking the Trust Region in LLM Reinforcement Learning" (arXiv:2602.04879) + + Args: + divergence_type (`Literal["binary_tv", "binary_kl", "topk_tv", "topk_kl"]`, *optional*, defaults to `"binary_tv"`): + Divergence approximation used for the trust-region mask. Binary variants use only per-token log-probs; + top-K variants require storing top-K token IDs and log-probs during rollout generation plus full logits + during training. + + divergence_topk (`int`, *optional*, defaults to `20`): + K for top-K divergence approximations. Only used when `divergence_type` is `"topk_tv"` or `"topk_kl"`. + + clip_ratio_c (`float`, *optional*, defaults to `20.0`): + Upper bound on the importance-sampling ratio for stability. The IS ratio is clamped to [0, clip_ratio_c]. + + epsilon (`float`, inherited from GRPOConfig, default overridden to `0.15`): + Divergence threshold δ_low. Tokens whose divergence exceeds this when the policy moves in the + advantage-decreasing direction are masked. The paper recommends 0.15 for TV divergence and 0.05 for KL + divergence. + + epsilon_high (`float`, inherited from GRPOConfig, default overridden to `0.15`): + Divergence threshold δ_high. Tokens whose divergence exceeds this when the policy moves in the + advantage-increasing direction are masked. The paper recommends 0.15 for TV divergence and 0.05 for KL + divergence. + """ + + divergence_type: Literal["binary_tv", "binary_kl", "topk_tv", "topk_kl"] = field( + default="binary_tv", + metadata={ + "help": "Divergence approximation used for the trust-region mask. Binary variants use only per-token " + "log-probs; top-K variants require storing top-K token IDs and log-probs during rollout generation plus " + "full logits during training." + }, + ) + divergence_topk: int = field( + default=20, + metadata={ + "help": "K for top-K divergence approximations. Only used when `divergence_type` is `'topk_tv'` or " + "`'topk_kl'`." + }, + ) + clip_ratio_c: float = field( + default=20.0, + metadata={ + "help": "Upper bound on the importance-sampling ratio for stability. The IS ratio is clamped to " + "[0, clip_ratio_c]." + }, + ) + epsilon: float = field( + default=0.15, + metadata={ + "help": "Divergence threshold δ_low. Tokens whose divergence exceeds this when the policy moves in the " + "advantage-decreasing direction are masked. The paper recommends 0.15 for TV divergence and 0.05 for KL " + "divergence." + }, + ) + epsilon_high: float = field( + default=0.15, + metadata={ + "help": "Divergence threshold δ_high. Tokens whose divergence exceeds this when the policy moves in the " + "advantage-increasing direction are masked. The paper recommends 0.15 for TV divergence and 0.05 for KL " + "divergence." + }, + ) + + def __post_init__(self): + super().__post_init__() + + if self.divergence_type not in ("binary_tv", "binary_kl", "topk_tv", "topk_kl"): + raise ValueError( + f"divergence_type must be one of 'binary_tv', 'binary_kl', 'topk_tv', 'topk_kl', " + f"got {self.divergence_type!r}" + ) + + if self.divergence_topk < 1: + raise ValueError(f"divergence_topk must be >= 1, got {self.divergence_topk}") + + if self.clip_ratio_c <= 0: + raise ValueError(f"clip_ratio_c must be > 0, got {self.clip_ratio_c}") + + if self.loss_type != "dapo": + raise ValueError(f"loss_type {self.loss_type} is not supported for DPPO") + + if self.top_entropy_quantile != 1.0: + raise ValueError("top_entropy_quantile is not supported for DPPO") + + if self.off_policy_mask_threshold is not None: + raise ValueError("off_policy_mask_threshold is not supported for DPPO") diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/dppo/dppo_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/dppo/dppo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..f339383bc946398762d9d0dce42ec941e8b0dd38 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/dppo/dppo_trainer.py @@ -0,0 +1,1396 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import asyncio +import copy +import math +import textwrap +from collections.abc import Callable +from contextlib import nullcontext +from copy import copy as shallow_copy +from typing import Any + +import numpy as np +import torch +import transformers +from accelerate.utils import gather_object +from datasets import Dataset, IterableDataset +from packaging.version import Version +from torch.distributed.fsdp import FullyShardedDataParallel as FSDP +from transformers import ( + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + Trainer, + TrainerCallback, +) +from transformers.utils import is_peft_available + +from ...chat_template_utils import parse_response +from ...data_utils import ( + apply_chat_template, + is_conversational, + prepare_multimodal_messages, +) +from ...extras.profiling import profiling_context, profiling_decorator +from ...models import unwrap_model_for_generation +from ...models.utils import disable_gradient_checkpointing +from ...trainer.grpo_trainer import EnvironmentFactory, GRPOTrainer, RewardFunc, RolloutFunc +from ...trainer.utils import ( + entropy_from_logits, + nanstd, + pad, + selective_log_softmax, + use_adapter, +) +from .dppo_config import DPPOConfig + + +if is_peft_available(): + from peft import PeftConfig, PeftModel + +SAFETY_CLAMP_MAX = 20 + + +def _strip_padding(tensor: torch.Tensor, mask: torch.Tensor) -> list[list]: + """Remove padding from a batched tensor using a mask, returning a ragged list-of-lists.""" + return [row[m].tolist() for row, m in zip(tensor, mask.bool(), strict=True)] + + +class DPPOTrainer(GRPOTrainer): + """ + Trainer for Divergence Proximal Policy Optimization (DPPO). + + DPPO replaces PPO/GRPO's heuristic ratio-clipping with a principled trust region based on direct policy divergence + estimates. PPO-style clipping masks tokens based on probability ratio π/μ, which over-penalizes low-probability + tokens and under-penalizes high-probability tokens. In contrast, DPPO masks based on direct approximation of policy + divergence (e.g TV or KL) ensuring updates stay within a theoretically grounded trust region. + + + Four divergence approximations are supported: + - `binary_tv`: Absolute probability difference |π(a) - μ(a)| (simplest) + - `binary_kl`: Bernoulli KL divergence between old and new token probabilities + - `topk_tv`: Total variation over the top-K tokens of the distribution + - `topk_kl`: KL divergence over the top-K tokens of the distribution + + Args: + model (`str` or [`~transformers.PreTrainedModel`] or [`~peft.PeftModel`]): + Model to be trained. Can be either: + + - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a + path to a *directory* containing model weights saved using + [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded + using `.from_pretrained` (where `` is derived from the model + config) with the keyword arguments in `args.model_init_kwargs`. + - A [`~transformers.PreTrainedModel`] object. Only causal language models are supported. + - A [`~peft.PeftModel`] object. Only causal language models are supported. + reward_funcs (`RewardFunc | list[RewardFunc]`): + Reward functions to be used for computing the rewards. To compute the rewards, we call all the reward + functions with the prompts and completions and sum the rewards. Can be either: + + - A single reward function, such as: + - A string: The *model ID* of a pretrained model hosted inside a model repo on huggingface.co, or a + path to a *directory* containing model weights saved using + [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded + using [`~transformers.AutoModelForSequenceClassification.from_pretrained`] with `num_labels=1` and the + keyword arguments in `args.model_init_kwargs`. + - A [`~transformers.PreTrainedModel`] object: Only sequence classification models are supported. + - A custom reward function: The function is provided with the prompts and the generated completions, + plus any additional columns in the dataset. It should return a list of rewards. Custom reward + functions can be either synchronous or asynchronous and can also return `None` when the reward is + not applicable to those samples. This is useful for multi-task training where different reward + functions apply to different types of samples. When a reward function returns `None` for a sample, + that reward function is excluded from the reward calculation for that sample. For more details, see + [Using a custom reward + function](#using-a-custom-reward-function). + + The trainer's state is also passed to the reward function. The trainer's state is an instance of + [`~transformers.TrainerState`] and can be accessed by accessing the `trainer_state` argument to the + reward function's signature. + - A list of reward functions, where each item can independently be any of the above types. Mixing different + types within the list (e.g., a string model ID and a custom reward function) is allowed. + args ([`DPPOConfig`], *optional*): + Configuration for this trainer. If `None`, a default configuration is used. + train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]): + Dataset to use for training. It must include a column `"prompt"`. Any additional columns in the dataset is + ignored. The format of the samples can be either: + + - [Standard](dataset_formats#standard): Each sample contains plain text. + - [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role + and content). + eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Dataset | IterableDataset]`): + Dataset to use for evaluation. It must meet the same requirements as `train_dataset`. + processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.ProcessorMixin`], *optional*): + Processing class used to process the data. The padding side must be set to "left". If `None`, the + processing class is loaded from the model's name with [`~transformers.AutoProcessor.from_pretrained`]. A + padding token, `tokenizer.pad_token`, must be set. If the processing class has not set a padding token, + `tokenizer.eos_token` will be used as the default. + reward_processing_classes ([`~transformers.PreTrainedTokenizerBase`] or `list[PreTrainedTokenizerBase]`, *optional*): + Processing classes corresponding to the reward functions specified in `reward_funcs`. Can be either: + + - A single processing class: Used when `reward_funcs` contains only one reward function. + - A list of processing classes: Must match the order and length of the reward functions in `reward_funcs`. + If set to `None`, or if an element of the list corresponding to a [`~transformers.PreTrainedModel`] is + `None`, the tokenizer for the model is automatically loaded using + [`~transformers.AutoTokenizer.from_pretrained`]. For elements in `reward_funcs` that are custom reward + functions (not [`~transformers.PreTrainedModel`]), the corresponding entries in `reward_processing_classes` + are ignored. + callbacks (list of [`~transformers.TrainerCallback`], *optional*): + List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed + in [here](https://huggingface.co/docs/transformers/main_classes/callback). + + If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`] + method. + optimizers (`tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None]`, *optional*, defaults to `(None, None)`): + A tuple containing the optimizer and the scheduler to use. Will default to an instance of `AdamW` on your + model and a scheduler given by [`~transformers.get_linear_schedule_with_warmup`] controlled by `args`. + peft_config ([`~peft.PeftConfig`], *optional*): + PEFT configuration used to wrap the model. If `None`, the model is not wrapped. + tools (list of `Callable`, *optional*): + A list of callable tool functions (sync or async) that the model can invoke during generation. Each tool + should be a standard Python function with properly type-hinted arguments and return values, and a + Google-style docstring describing its purpose, arguments, and return value. For more details, see: + https://huggingface.co/docs/transformers/en/chat_extras#passing-tools. The model uses the function's name, + type hints, and docstring to determine how to call it. Ensure that the model's chat template supports tool + use and that it has been fine-tuned for tool calling. + rollout_func (`RolloutFunc`, *optional*): + Function to use for generating completions. It receives the list of prompts allocated to the current + process and the trainer instance. It must return a dict with `"prompt_ids"`, `"completion_ids"`, and + `"logprobs"` fields. Any other fields are forwarded to the reward functions. This feature is experimental + and may change or be removed at any time without prior notice. + environment_factory (`EnvironmentFactory`, *optional*): + A callable that creates and returns an environment instance. The environment class should define methods + that can be invoked as tools during generation. Each method should comply with the same requirements as the + `tools` described above. If `environment_factory` is provided, an instance of the environment is created + for each generation in the batch, allowing for parallel and independent interactions. The environment must + also implement a callable `reset` method that can be used to reset state between generations. The `reset` + method should return either `None` or a string: when it returns a string, that string is appended to the + last user message before generation. This feature is experimental and may change or be removed at any time + without prior notice. + """ + + _tag_names = ["trl", "dppo"] + _name = "DPPO" + _paper = { + "title": "Rethinking the Trust Region in LLM Reinforcement Learning", + "id": "2602.04879", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @article{qi2026rethinking, + title = {{Rethinking the Trust Region in LLM Reinforcement Learning}}, + author = {Qi, Penghui and Zhou, Xiangxin and Liu, Zichen and Pang, Tianyu and Du, Chao and Lin, Min and Lee, Wee Sun}, + journal = {arXiv preprint arXiv:2602.04879}, + year = {2026} + }"""), + } + + def __init__( + self, + model: "str | PreTrainedModel | PeftModel", + reward_funcs: RewardFunc | list[RewardFunc], + args: DPPOConfig | None = None, + train_dataset: Dataset | IterableDataset | None = None, + eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None, + processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None, + reward_processing_classes: PreTrainedTokenizerBase | list[PreTrainedTokenizerBase] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None), + peft_config: "PeftConfig | None" = None, + tools: list[Callable] | None = None, + rollout_func: RolloutFunc | None = None, + environment_factory: EnvironmentFactory | None = None, + ): + if args is None: + model_name = model if isinstance(model, str) else model.config._name_or_path + model_name = model_name.split("/")[-1] + args = DPPOConfig(f"{model_name}-DPPO") + + self.divergence_type = args.divergence_type + self.divergence_topk = args.divergence_topk + self.clip_ratio_c = args.clip_ratio_c + + super().__init__( + model=model, + reward_funcs=reward_funcs, + args=args, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + reward_processing_classes=reward_processing_classes, + callbacks=callbacks, + optimizers=optimizers, + peft_config=peft_config, + tools=tools, + rollout_func=rollout_func, + environment_factory=environment_factory, + ) + + if self.divergence_type in ["topk_tv", "topk_kl"] and self.use_vllm: + self.vllm_generation.logprobs = self.divergence_topk + + def _tokenize_prompts(self, prompts: list): + """Tokenize prompts and extract images/multimodal fields for generation.""" + if is_conversational({"prompt": prompts[0]}): + images = [] + has_images = False + for prompt in prompts: + prompt_images = [] + for message in prompt: + if isinstance(message["content"], list): + for part in message["content"]: + if part["type"] == "image": + prompt_images.append(part["image"]) + has_images = True + images.append(prompt_images if prompt_images else None) + images = images if has_images else None + + # Workaround for a bug in transformers 5.3.0 where some processors (e.g. Qwen2.5-VL) crash on + # batched unpadded input (transformers#44514). + # Fixed in transformers 5.4.0 (transformers#44563). + needs_padding_workaround = Version("5.3.0") <= Version(transformers.__version__) < Version("5.4.0") + tokenized = self.processing_class.apply_chat_template( + conversation=prompts, + tools=self.tools or None, # `or None`: Llama bug: it renders tool boilerplate for tools=[] + chat_template=self.chat_template, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + **({"padding": True} if needs_padding_workaround else {}), + **self.chat_template_kwargs, + ) + if needs_padding_workaround: + # Unpad input_ids: remove padding tokens using attention_mask to get per-sequence lists + prompt_ids = [ + [tok for tok, m in zip(ids, mask, strict=True) if m] + for ids, mask in zip(tokenized["input_ids"], tokenized["attention_mask"], strict=True) + ] + else: + prompt_ids = tokenized["input_ids"] + multimodal_fields = {k: v for k, v in tokenized.items() if k not in ("input_ids", "attention_mask")} + else: + prompt_ids = self.processing_class(text=prompts)["input_ids"] + images = None + multimodal_fields = {} + return prompt_ids, images, multimodal_fields + + def _generate_single_turn(self, prompt_ids, images, multimodal_fields): + """Generate completions, always extracting sampled token logprobs. + + Returns: + 5-tuple of (prompt_ids, completion_ids, logprobs, topk_logprobs, topk_token_ids). topk_logprobs and + topk_token_ids are None when divergence_type is not topk. + """ + device = self.accelerator.device + mode = "train" if self.model.training else "eval" + needs_topk = self.divergence_type in ["topk_tv", "topk_kl"] + K = self.divergence_topk + + if self.use_vllm: + if self.state.global_step != self._last_loaded_step: + with profiling_context(self, "sync_weights"): + self.vllm_generation.sync_weights() + self._last_loaded_step = self.state.global_step + + num_generations = self.num_generations if mode == "train" else self.num_generations_eval + prompt_ids, completion_ids, logprobs, logprob_token_ids = self.vllm_generation.generate( + prompts=prompt_ids, + images=images, + num_generations=num_generations, + profiler=profiling_context(self, "vLLM.generate"), + ) + + if needs_topk: + # vLLM returns up to K+1 entries sorted by rank (most probable first). + # The sampled token is always included but may be at any position. + # Per the paper, A'_t = TopK(μ, K) ∪ {a_t}. We keep exactly K slots: if the + # sampled token a_t is not in the top-K, it replaces the K-th ranked entry. + topk_logprobs = [] + topk_token_ids = [] + sampled_logprobs = [] + for seq_lps, seq_tids, seq_cids in zip(logprobs, logprob_token_ids, completion_ids, strict=True): + seq_topk_lps, seq_topk_tids, seq_sampled = [], [], [] + for step_lps, step_tids, sampled_tid in zip(seq_lps, seq_tids, seq_cids, strict=True): + idx = step_tids.index(sampled_tid) + seq_sampled.append(step_lps[idx]) + # Take top-K entries, then ensure sampled token is present + tk_lps = step_lps[:K] + tk_tids = step_tids[:K] + if sampled_tid not in tk_tids: + tk_lps[-1] = step_lps[idx] + tk_tids[-1] = sampled_tid + seq_topk_lps.append(tk_lps) + seq_topk_tids.append(tk_tids) + topk_logprobs.append(seq_topk_lps) + topk_token_ids.append(seq_topk_tids) + sampled_logprobs.append(seq_sampled) + else: + sampled_logprobs = [[step_lps[0] for step_lps in seq_lps] for seq_lps in logprobs] + topk_logprobs = None + topk_token_ids = None + + return prompt_ids, completion_ids, sampled_logprobs, topk_logprobs, topk_token_ids + else: + prompt_tensors = [torch.tensor(ids) for ids in prompt_ids] + padded_ids = pad(prompt_tensors, padding_value=self._tokenizer.pad_token_id, padding_side="left") + attention_mask = pad([torch.ones_like(t) for t in prompt_tensors], padding_value=0, padding_side="left") + generate_inputs = {"input_ids": padded_ids, "attention_mask": attention_mask} + for key, value in multimodal_fields.items(): + if isinstance(value, torch.Tensor): + generate_inputs[key] = value + elif isinstance(value, list) and value and isinstance(value[0], list): + generate_inputs[key] = pad([torch.tensor(x) for x in value], padding_value=0, padding_side="left") + else: + generate_inputs[key] = torch.tensor(np.array(value)) + generate_inputs = Trainer._prepare_inputs(self, generate_inputs) + + gen_config = shallow_copy(self.generation_config) + gen_config.output_logits = True + gen_config.return_dict_in_generate = True + + with ( + profiling_context(self, "transformers.generate"), + unwrap_model_for_generation( + self.model_wrapped, + self.accelerator, + gather_deepspeed3_params=self.args.ds3_gather_for_generation, + generation_kwargs=self.generation_kwargs, + ) as unwrapped_model, + torch.no_grad(), + FSDP.summon_full_params(self.model_wrapped, recurse=False) if self.is_fsdp_enabled else nullcontext(), + ): + gen_output = unwrapped_model.generate(**generate_inputs, generation_config=gen_config) + + prompt_ids_tensor, prompt_mask = generate_inputs["input_ids"], generate_inputs["attention_mask"] + prompt_length = prompt_ids_tensor.size(1) + completion_ids = gen_output.sequences[:, prompt_length:] + + sampled_chunks = [] + topk_logps_chunks = [] if needs_topk else None + topk_ids_chunks = [] if needs_topk else None + + for t, logits_t in enumerate(gen_output.logits): + # logits_t: (B, V) + logits_t = logits_t / self.temperature + + # exact sampled-token logprob without allocating (B, V) log_softmax output + logZ_t = torch.logsumexp(logits_t, dim=-1, keepdim=True) + sampled_ids_t = completion_ids[:, t : t + 1] + sampled_lp_t = logits_t.gather(-1, sampled_ids_t) - logZ_t + sampled_chunks.append(sampled_lp_t.cpu()) + + if needs_topk: + topk_logits_t, topk_ids_t = torch.topk(logits_t, k=K, dim=-1) # (B, K), (B, K) + topk_lp_t = topk_logits_t - logZ_t + + # Ensure sampled token is included in A'_t = TopK ∪ {a_t} + missing = ~(topk_ids_t == sampled_ids_t).any(dim=-1) + if missing.any(): + topk_ids_t = topk_ids_t.clone() + topk_lp_t = topk_lp_t.clone() + topk_ids_t[missing, -1] = sampled_ids_t[missing, 0] + topk_lp_t[missing, -1] = sampled_lp_t[missing, 0] + + topk_ids_chunks.append(topk_ids_t.cpu()) + topk_logps_chunks.append(topk_lp_t.cpu()) + + # Mask everything after the first EOS token + is_eos = completion_ids == self._tokenizer.eos_token_id + has_eos = is_eos.any(dim=1) + eos_idx = torch.full((is_eos.size(0),), is_eos.size(1), dtype=torch.long, device=device) + eos_idx[has_eos] = is_eos.int().argmax(dim=1)[has_eos] + sequence_indices = torch.arange(is_eos.size(1), device=device).expand(is_eos.size(0), -1) + completion_mask = (sequence_indices <= eos_idx.unsqueeze(1)).int() + prompt_mask_cpu = prompt_mask.bool().cpu() + completion_mask_cpu = completion_mask.bool().cpu() + + prompt_ids_out = _strip_padding(prompt_ids_tensor.cpu(), prompt_mask_cpu) + completion_ids_out = _strip_padding(completion_ids.cpu(), completion_mask_cpu) + logprobs_out = _strip_padding(torch.cat(sampled_chunks, dim=1), completion_mask_cpu) + if needs_topk: + topk_logprobs = _strip_padding(torch.stack(topk_logps_chunks, dim=1), completion_mask_cpu) + topk_token_ids = _strip_padding(torch.stack(topk_ids_chunks, dim=1), completion_mask_cpu) + else: + topk_logprobs = None + topk_token_ids = None + + return prompt_ids_out, completion_ids_out, logprobs_out, topk_logprobs, topk_token_ids + + def _tool_call_loop( + self, prompts, prompt_ids, completion_ids, completions, logprobs, topk_logprobs, topk_token_ids + ): + """Tool execution loop that also threads top-K logprob data alongside logprobs. + + Mirrors GRPOTrainer._tool_call_loop but additionally concatenates topk_logprobs and topk_token_ids the same way + logprobs is concatenated: real data for model-generated tokens, zero-padding for tool-result tokens. When topk + data is None (binary divergence), behaves identically to the parent. + """ + K = self.divergence_topk + has_topk = topk_logprobs is not None + + tool_calls = [completion[0].get("tool_calls") for completion in completions] + idxs_with_tool = [idx for idx, tool_call in enumerate(tool_calls) if tool_call] + tool_calls = [tool_calls[idx] for idx in idxs_with_tool] + tool_mask = [[1] * len(ids) for ids in completion_ids] + tool_call_count = 0 + tool_failure_count = 0 + iteration_num = 0 + while idxs_with_tool and iteration_num < self.max_tool_calling_iterations: + prompt_completion_tools = [prompts[i] for i in idxs_with_tool] + + for idx in range(len(idxs_with_tool)): + idx_with_tool = idxs_with_tool[idx] + tool_call_list = tool_calls[idx] + prompt_completion_tool = prompt_completion_tools[idx] + sync_tool_dict = self._sync_tool_dicts[idx_with_tool] + async_tool_dict = self._async_tool_dicts[idx_with_tool] + prompt_completion_tool.append(completions[idx_with_tool][-1]) + async_coros = [] + tool_call_results = [] + for tool_call in tool_call_list: + tool_call_count += 1 + if tool_call["type"] == "function": + function = tool_call["function"] + name = function["name"] + try: + if name in sync_tool_dict: + tool_call_results.append((name, sync_tool_dict[name](**function["arguments"]))) + elif name in async_tool_dict: + async_coros.append((name, async_tool_dict[name](**function["arguments"]))) + else: + raise ValueError(f"Tool {name} not found.") + except Exception as err: + tool_failure_count += 1 + tool_call_results.append((name, {"error": str(err)})) + else: + tool_failure_count += 1 + name = tool_call.get("name", "unknown") + tool_call_results.append((name, {"error": f"Unsupported tool call type: {tool_call['type']}"})) + + if async_coros: + + async def _run_async_tools(async_coros): + coros = [coro for _, coro in async_coros] + results = await asyncio.gather(*coros, return_exceptions=True) + return [(name, result) for (name, _), result in zip(async_coros, results, strict=False)] + + async_results = asyncio.run_coroutine_threadsafe( + _run_async_tools(async_coros), self.async_loop + ).result() + + for name, result in async_results: + if isinstance(result, Exception): + tool_failure_count += 1 + tool_call_results.append((name, {"error": str(result)})) + else: + tool_call_results.append((name, result)) + + for name, result in tool_call_results: + tool_message = {"role": "tool", "name": name, "content": str(result)} + prompt_completion_tool.append(tool_message) + completions[idx_with_tool].append(tool_message) + + # Tokenize and filter samples whose length exceeds max allowed length + pct_ids = self.processing_class.apply_chat_template( + prompt_completion_tools, + tools=self.tools or None, # `or None`: Llama bug: it renders tool boilerplate for tools=[] + chat_template=self.chat_template, + add_generation_prompt=True, + tokenize=True, + return_dict=False, + **self.chat_template_kwargs, + ) + if self.use_vllm and self.vllm_mode == "colocate": + max_model_len = self.vllm_generation.llm.llm_engine.model_config.max_model_len + elif not self.use_vllm: + max_model_len = self.model.config.max_position_embeddings + else: + raise NotImplementedError( + f"Unsupported mode detected: use_vllm={self.use_vllm}, vllm_mode={self.vllm_mode}" + ) + overlong = [len(pct) >= max_model_len for pct in pct_ids] + for idx in range(len(idxs_with_tool)): + idx_with_tool = idxs_with_tool[idx] + if overlong[idx]: + prompt_length = len(prompt_ids[idx_with_tool]) + ct = pct_ids[idx][prompt_length : prompt_length + self.max_completion_length] + completion_ids[idx_with_tool] = ct + tool_mask[idx_with_tool] += [1] * (len(ct) - len(tool_mask[idx_with_tool])) + if logprobs is not None: + logprobs[idx_with_tool] += [0.0] * (len(ct) - len(logprobs[idx_with_tool])) + if has_topk: + topk_logprobs[idx_with_tool] += [[0.0] * K] * (len(ct) - len(topk_logprobs[idx_with_tool])) + topk_token_ids[idx_with_tool] += [[0] * K] * (len(ct) - len(topk_token_ids[idx_with_tool])) + + idxs_with_tool = [idx for idx, o in zip(idxs_with_tool, overlong, strict=True) if not o] + prompt_completion_tools = [pct for pct, o in zip(prompt_completion_tools, overlong, strict=True) if not o] + if not idxs_with_tool: + break + + # Generate new completions after tool execution + pct_prompt_ids, pct_images, pct_multimodal_fields = self._tokenize_prompts(prompt_completion_tools) + ( + prompt_completion_tool_ids, + post_tool_ids, + post_tool_logprobs, + post_tool_topk_logprobs, + post_tool_topk_token_ids, + ) = self._generate_single_turn(pct_prompt_ids, pct_images, pct_multimodal_fields) + + # Sanity check: chat template must be prefix-preserving + for idx in range(len(idxs_with_tool)): + idx_with_tool = idxs_with_tool[idx] + pct = prompt_completion_tool_ids[idx] + if prompt_ids[idx_with_tool] != pct[: len(prompt_ids[idx_with_tool])]: + raise ValueError( + "The chat template is not prefix-preserving. Please update it to use a prefix-preserving " + "format." + ) + + # Truncate so that pct[len(prompt_ids[idx]):] + post_tool does not exceed max_completion_length + for idx in range(len(idxs_with_tool)): + idx_with_tool = idxs_with_tool[idx] + prompt_len = len(prompt_ids[idx_with_tool]) + completion_tool_ids = prompt_completion_tool_ids[idx][prompt_len:] + excess_length = len(completion_tool_ids) + len(post_tool_ids[idx]) - self.max_completion_length + if excess_length > 0: + post_tool_ids[idx] = post_tool_ids[idx][:-excess_length] + if logprobs is not None: + post_tool_logprobs[idx] = post_tool_logprobs[idx][:-excess_length] + if has_topk and post_tool_topk_logprobs is not None: + post_tool_topk_logprobs[idx] = post_tool_topk_logprobs[idx][:-excess_length] + post_tool_topk_token_ids[idx] = post_tool_topk_token_ids[idx][:-excess_length] + excess_length = len(completion_tool_ids) + len(post_tool_ids[idx]) - self.max_completion_length + if excess_length > 0: + prompt_completion_tool_ids[idx] = prompt_completion_tool_ids[idx][:-excess_length] + + # Update tool_mask and logprobs: tool result tokens get 0/0.0, post-tool model tokens get 1/real values + for idx in range(len(idxs_with_tool)): + idx_with_tool = idxs_with_tool[idx] + prompt_completion_tool_length = len(prompt_completion_tool_ids[idx]) + prompt_length = len(prompt_ids[idx_with_tool]) + completion_length = len(completion_ids[idx_with_tool]) + post_tool_length = len(post_tool_ids[idx]) + tool_length = prompt_completion_tool_length - prompt_length - completion_length + tool_mask[idx_with_tool] += [0] * tool_length + [1] * post_tool_length + if logprobs is not None: + logprobs[idx_with_tool] += [0.0] * tool_length + post_tool_logprobs[idx] + if has_topk: + topk_pad = [[0.0] * K] * tool_length + tid_pad = [[0] * K] * tool_length + post_topk_lp = post_tool_topk_logprobs[idx] if post_tool_topk_logprobs is not None else [] + post_topk_tid = post_tool_topk_token_ids[idx] if post_tool_topk_token_ids is not None else [] + topk_logprobs[idx_with_tool] += topk_pad + post_topk_lp + topk_token_ids[idx_with_tool] += tid_pad + post_topk_tid + + # Update completion_ids with the new completions (after tool execution) + for idx in range(len(idxs_with_tool)): + idx_with_tool = idxs_with_tool[idx] + prompt_length = len(prompt_ids[idx_with_tool]) + pct = prompt_completion_tool_ids[idx] + completion_ids[idx_with_tool] = pct[prompt_length:] + post_tool_ids[idx] + + # Decode post-tool completions + post_tool_completions = [parse_response(self._tokenizer, ids) if ids else {} for ids in post_tool_ids] + + for idx in range(len(idxs_with_tool)): + idx_with_tool = idxs_with_tool[idx] + if post_tool_completions[idx]: + completions[idx_with_tool].append(post_tool_completions[idx]) + + # Check for further tool calls + tool_calls = [completion.get("tool_calls") for completion in post_tool_completions] + idxs_with_tool = [idx for idx, tool_call in zip(idxs_with_tool, tool_calls, strict=True) if tool_call] + tool_calls = [tool_call for tool_call in tool_calls if tool_call] + iteration_num += 1 + + return ( + tool_mask, + completions, + completion_ids, + logprobs, + topk_logprobs, + topk_token_ids, + tool_call_count, + tool_failure_count, + ) + + def _generate(self, prompts: list): + """Generate completions, handling tool calls, and thread top-K logprob data through the full pipeline. + + Returns: + 9-tuple of (prompt_ids, completion_ids, tool_mask, completions, total_completion_tokens, logprobs, + topk_logprobs, topk_token_ids, extra_fields). + """ + device = self.accelerator.device + mode = "train" if self.model.training else "eval" + needs_topk = self.divergence_type in ["topk_tv", "topk_kl"] + + # Copy the prompts to avoid modifying the original list + prompts = copy.deepcopy(prompts) + + if self.rollout_func is not None: + # Keep vLLM weights in sync for custom rollouts that rely on vLLM utilities. + if self.use_vllm and self.state.global_step != self._last_loaded_step: + with profiling_context(self, "sync_weights"): + self.vllm_generation.sync_weights() + self._last_loaded_step = self.state.global_step + + # Pass prompts to rollout_func preserving structured messages. + # Chat templating must happen inside rollout_func, at the backend boundary, so that + # multimodal content (images, typed content blocks) is not lost before rollout logic runs. + output = self.rollout_func(prompts, self) + required_keys = {"prompt_ids", "completion_ids", "logprobs"} + missing_keys = required_keys - output.keys() + if missing_keys: + missing_keys_list = sorted(missing_keys) + raise ValueError(f"rollout_func must return keys {missing_keys_list} in its output dict.") + extra_fields = {k: v for k, v in output.items() if k not in required_keys} + prompt_ids = output["prompt_ids"] + completion_ids = output["completion_ids"] + logprobs = output["logprobs"] + topk_logprobs = extra_fields.pop("topk_logprobs", None) + topk_token_ids = extra_fields.pop("topk_token_ids", None) + if needs_topk and (topk_logprobs is None or topk_token_ids is None): + raise ValueError( + "rollout_func must return keys ['topk_logprobs', 'topk_token_ids'] when divergence_type is " + f"{self.divergence_type!r}." + ) + else: + prompt_ids, images, multimodal_fields = self._tokenize_prompts(prompts) + prompt_ids, completion_ids, logprobs, topk_logprobs, topk_token_ids = self._generate_single_turn( + prompt_ids, images, multimodal_fields + ) + extra_fields = {} + + # Decode completions. It's important to use `parse_response` when possible, because it handles tool calls. + if is_conversational({"prompt": prompts[0]}): + if ( + Version(transformers.__version__) >= Version("5.0.0") # parse_response added in v5 + and hasattr(self._tokenizer, "response_schema") # attribute not set by default for now + and self._tokenizer.response_schema is not None # only works if the tokenizer has a schema + ): + completions = [[parse_response(self._tokenizer, ids)] for ids in completion_ids] + else: + contents = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True) + completions = [[{"role": "assistant", "content": content}] for content in contents] + else: + completions = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True) + + # Extract tool calls from the completions and (possibly) execute them + if self.tools: + ( + tool_mask, + completions, + completion_ids, + logprobs, + topk_logprobs, + topk_token_ids, + tool_call_count, + tool_failure_count, + ) = self._tool_call_loop( + prompts, prompt_ids, completion_ids, completions, logprobs, topk_logprobs, topk_token_ids + ) + else: + tool_mask = extra_fields.pop("env_mask", None) + + # Get completion length per sequence, used for logging + prompt_lengths = torch.tensor([len(ids) for ids in prompt_ids], device=device) + if tool_mask is not None: + completion_lengths = torch.tensor([sum(mask) for mask in tool_mask], device=device) + else: + completion_lengths = torch.tensor([len(ids) for ids in completion_ids], device=device) + agg_prompt_lengths = self.accelerator.gather(prompt_lengths) + agg_completion_lengths = self.accelerator.gather(completion_lengths) + total_prompt_tokens = agg_prompt_lengths.sum() + total_completion_tokens = agg_completion_lengths.sum() + + if mode == "train": + self.state.num_input_tokens_seen += (total_prompt_tokens + total_completion_tokens).item() + self._metrics[mode]["num_tokens"] = [self.state.num_input_tokens_seen] + + self._metrics[mode]["completions/mean_length"].append(agg_completion_lengths.float().mean().item()) + self._metrics[mode]["completions/min_length"].append(agg_completion_lengths.float().min().item()) + self._metrics[mode]["completions/max_length"].append(agg_completion_lengths.float().max().item()) + + eos_and_pad = [self._tokenizer.eos_token_id, self._tokenizer.pad_token_id] + is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids], device=device) + agg_is_truncated = self.accelerator.gather(is_truncated) + self._metrics[mode]["completions/clipped_ratio"].append(agg_is_truncated.float().mean().item()) + term_completion_lengths = agg_completion_lengths[~agg_is_truncated] + if len(term_completion_lengths) == 0: + term_completion_lengths = torch.zeros(1, device=device) + self._metrics[mode]["completions/mean_terminated_length"].append(term_completion_lengths.float().mean().item()) + self._metrics[mode]["completions/min_terminated_length"].append(term_completion_lengths.float().min().item()) + self._metrics[mode]["completions/max_terminated_length"].append(term_completion_lengths.float().max().item()) + + if self.tools: + agg_tool_call_count = self.accelerator.gather(torch.tensor(tool_call_count, device=device)).sum() + tool_call_frequency = (agg_tool_call_count / len(agg_prompt_lengths)).item() + self._metrics[mode]["tools/call_frequency"].append(tool_call_frequency) + agg_tool_failure_count = self.accelerator.gather(torch.tensor(tool_failure_count, device=device)).sum() + failure_frequency = ( + (agg_tool_failure_count / agg_tool_call_count).item() if agg_tool_call_count > 0 else 0.0 + ) + self._metrics[mode]["tools/failure_frequency"].append(failure_frequency) + + return ( + prompt_ids, + completion_ids, + tool_mask, + completions, + total_completion_tokens, + logprobs, + topk_logprobs, + topk_token_ids, + extra_fields, + ) + + @profiling_decorator + def _get_per_token_logps_with_topk( + self, + model, + input_ids, + attention_mask, + logits_to_keep, + topk_token_ids, + batch_size=None, + compute_entropy=False, + pixel_values=None, + image_grid_thw=None, + num_images=None, + pixel_attention_mask=None, + image_sizes=None, + token_type_ids=None, + mm_token_type_ids=None, + ) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor]: + """Compute per-token log-probs, (optionally) entropies, and top-K log-probs in one forward pass. + + Evaluates the current policy's log-probs at the rollout's top-K token IDs from the same forward pass used for + per_token_logps, avoiding an extra model call. + + Args: + topk_token_ids: Rollout policy's top-K token IDs, shape (B, T, K). The current policy's + log-probs are evaluated at these positions. + + Returns: + Tuple of (per_token_logps, entropies, current_topk_logps). + """ + batch_size = batch_size or input_ids.size(0) + all_logps = [] + all_entropies = [] + all_topk_logps = [] + + for start in range(0, input_ids.size(0), batch_size): + end = start + batch_size + input_ids_batch = input_ids[start:end] + attention_mask_batch = attention_mask[start:end] + + model_inputs = {"input_ids": input_ids_batch, "attention_mask": attention_mask_batch} + if image_grid_thw is not None and pixel_values is not None: + rows_per_image = image_grid_thw.prod(dim=-1) + rows_per_sample = torch.split(rows_per_image, num_images) + rows_per_sample = torch.stack([s.sum() for s in rows_per_sample]) + cum_rows = torch.cat([torch.tensor([0], device=rows_per_sample.device), rows_per_sample.cumsum(0)]) + row_start, row_end = cum_rows[start].item(), cum_rows[end].item() + model_inputs["pixel_values"] = pixel_values[row_start:row_end] + cum_imgs = torch.tensor([0] + num_images).cumsum(0) + img_start, img_end = cum_imgs[start], cum_imgs[end] + model_inputs["image_grid_thw"] = image_grid_thw[img_start:img_end] + elif pixel_values is not None: + model_inputs["pixel_values"] = pixel_values[start:end] + if pixel_attention_mask is not None: + model_inputs["pixel_attention_mask"] = pixel_attention_mask[start:end] + if image_sizes is not None: + model_inputs["image_sizes"] = image_sizes[start:end] + if token_type_ids is not None: + model_inputs["token_type_ids"] = token_type_ids[start:end] + if mm_token_type_ids is not None: + model_inputs["mm_token_type_ids"] = mm_token_type_ids[start:end] + + if "logits_to_keep" in self.model_kwarg_keys: + model_inputs["logits_to_keep"] = logits_to_keep + 1 + + model_inputs["use_cache"] = False + + logits = model(**model_inputs).logits + logits = logits[:, :-1, :] + logits = logits[:, -logits_to_keep:, :] + logits = logits / self.temperature + + completion_ids = input_ids_batch[:, -logits_to_keep:] + logps = selective_log_softmax(logits, completion_ids) + all_logps.append(logps) + + if compute_entropy: + with torch.no_grad(): + entropies = entropy_from_logits(logits) + all_entropies.append(entropies) + + with torch.no_grad(): + topk_logps = selective_log_softmax(logits, topk_token_ids[start:end]) + all_topk_logps.append(topk_logps) + + logps = torch.cat(all_logps, dim=0) + entropies = torch.cat(all_entropies, dim=0) if compute_entropy else None + topk_logps = torch.cat(all_topk_logps, dim=0) + return logps, entropies, topk_logps + + def _generate_and_score_completions( + self, inputs: list[dict[str, torch.Tensor | Any]] + ) -> dict[str, torch.Tensor | Any]: + device = self.accelerator.device + mode = "train" if self.model.training else "eval" + + prompts = [x["prompt"] for x in inputs] + + if self.environments: + for prompt, environment, reset_kwargs in zip(prompts, self.environments, inputs, strict=True): + observation = environment.reset(**reset_kwargs) + if observation is None: + continue + prompt[-1]["content"] += observation + + if "images" in inputs[0]: + images = [example.get("images") for example in inputs] + elif "image" in inputs[0]: + images = [[example.get("image")] if example.get("image") is not None else None for example in inputs] + else: + images = None + # Transformers requires at least one image in the batch, otherwise it throws an error + if images is not None and all(img_list == [] for img_list in images): + images = None + + # If the prompts are conversational and the inputs contain images, we need to convert the prompts from + # [{"role": "user", "content": "What color is the sky?"}] to + # [{"role": "user", "content": [{"type": "image", "image": }, {"type": "text", "text": "What color is the sky?"}]}] + if images is not None: + if not is_conversational(inputs[0]): + raise ValueError( + "Multimodal training requires conversational prompts. It looks like the dataset contains " + "non-conversational inputs, likely because a chat template was applied before passing the dataset " + "to the trainer. Please provide the raw conversational prompts and let the trainer apply the chat " + "template internally." + ) + prompts = [ + prepare_multimodal_messages(prompt, images=image_list) + for prompt, image_list in zip(prompts, images, strict=True) + ] + + ( + prompt_ids_list, + completion_ids_list, + tool_mask_list, + completions, + num_items_in_batch, + sampling_per_token_logps_list, + topk_logprobs_list, + topk_token_ids_list, + extra_fields, + ) = self._generate(prompts) + + # Convert lists of token IDs to padded tensors + prompt_ids = [torch.tensor(ids) for ids in prompt_ids_list] + prompt_mask = [torch.ones_like(ids, dtype=torch.long) for ids in prompt_ids] + prompt_ids = pad( + prompt_ids, + padding_value=self._tokenizer.pad_token_id, + padding_side="left", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + prompt_mask = pad( + prompt_mask, padding_value=0, padding_side="left", pad_to_multiple_of=self.pad_to_multiple_of + ).to(device=device) + completion_ids = [torch.tensor(ids) for ids in completion_ids_list] + completion_mask = [torch.ones_like(ids, dtype=torch.long) for ids in completion_ids] + completion_ids = pad( + completion_ids, + padding_value=self._tokenizer.pad_token_id, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + completion_mask = pad( + completion_mask, padding_value=0, padding_side="right", pad_to_multiple_of=self.pad_to_multiple_of + ).to(device=device) + sampling_per_token_logps = [torch.tensor(logps) for logps in sampling_per_token_logps_list] + sampling_per_token_logps = pad( + sampling_per_token_logps, + padding_value=0.0, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + if tool_mask_list is not None: + tool_mask = [torch.tensor(mask) for mask in tool_mask_list] + tool_mask = pad( + tool_mask, padding_value=1, padding_side="right", pad_to_multiple_of=self.pad_to_multiple_of + ).to(device=device) + else: + tool_mask = None + if topk_logprobs_list is not None: + sampling_topk_logps = [torch.tensor(lp) for lp in topk_logprobs_list] + sampling_topk_logps = pad( + sampling_topk_logps, + padding_value=0.0, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + sampling_topk_token_ids = [torch.tensor(tid, dtype=torch.long) for tid in topk_token_ids_list] + sampling_topk_token_ids = pad( + sampling_topk_token_ids, + padding_value=0, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + else: + sampling_topk_logps = None + sampling_topk_token_ids = None + + # If mask_truncated_completions is enabled, zero out truncated completions for attention and loss masking + if self.mask_truncated_completions: + eos_and_pad = [self._tokenizer.eos_token_id, self._tokenizer.pad_token_id] + is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids_list], device=device) + # Mask completion_mask for attention masking + completion_mask = completion_mask * (~is_truncated).unsqueeze(1).int() + # Also mask tool_mask for consistency in multi-turn training + if tool_mask is not None: + tool_mask = tool_mask * (~is_truncated).unsqueeze(1).int() + + # Concatenate prompt_mask with completion_mask for logit computation + prompt_completion_ids = torch.cat([prompt_ids, completion_ids], dim=1) # (B, P+C) + attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) # (B, P+C) + + logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens + batch_size = self.args.per_device_train_batch_size if mode == "train" else self.args.per_device_eval_batch_size + + num_images = [len(img_list) for img_list in images] if images is not None else None + + # Get forward_kwargs for models with multimodal inputs + if images is not None: + prompts_text = [ + apply_chat_template( + {"prompt": prompt}, self.processing_class, tools=self.tools, **self.chat_template_kwargs + )["prompt"] + for prompt in prompts + ] + prompt_inputs = self.processing_class(images=images, text=prompts_text, padding=True, return_tensors="pt") + prompt_inputs = Trainer._prepare_inputs(self, prompt_inputs) + forward_kwargs = {k: v for k, v in prompt_inputs.items() if k not in ["input_ids", "attention_mask"]} + else: + forward_kwargs = {} + + # If token_type_ids are used, extend them with zeros for the completion part + if "token_type_ids" in forward_kwargs: + token_type_ids = forward_kwargs["token_type_ids"] + if self.pad_to_multiple_of is not None: + padding_size = prompt_ids.size(1) - token_type_ids.size(1) + if padding_size > 0: + token_type_ids = torch.cat( + [token_type_ids.new_zeros((token_type_ids.size(0), padding_size)), token_type_ids], dim=1 + ) + forward_kwargs["token_type_ids"] = torch.cat( + [token_type_ids, token_type_ids.new_zeros(completion_ids.shape)], dim=1 + ) + # If mm_token_type_ids are used, extend them with zeros for the completion part + if "mm_token_type_ids" in forward_kwargs: + mm_token_type_ids = forward_kwargs["mm_token_type_ids"] + if self.pad_to_multiple_of is not None: + padding_size = prompt_ids.size(1) - mm_token_type_ids.size(1) + if padding_size > 0: + mm_token_type_ids = torch.cat( + [mm_token_type_ids.new_zeros((mm_token_type_ids.size(0), padding_size)), mm_token_type_ids], + dim=1, + ) + forward_kwargs["mm_token_type_ids"] = torch.cat( + [mm_token_type_ids, mm_token_type_ids.new_zeros(completion_ids.shape)], dim=1 + ) + + # When gradient checkpointing is enabled with use_reentrant=True (non default), calling the model inside a + # torch.no_grad() block triggers a harmless PyTorch warning ("None of the inputs have requires_grad=True"). + # Temporarily disable checkpointing to avoid this warning during inference. + with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs): + # Compute the per-token log probabilities for the reference model + if self.beta != 0.0: + if self.ref_model is not None: + ref_per_token_logps, _ = self._get_per_token_logps_and_entropies( + self.ref_model, + prompt_completion_ids, + attention_mask, + logits_to_keep, + batch_size=batch_size, + num_images=num_images, + **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes + ) + else: + # When training a PEFT adapter, how we obtain the reference depends on the setup: + # - New adapter: disabling adapters yields the base model. + # - Re-training an existing adapter: an initial copy is loaded under the name "ref". + model = self.accelerator.unwrap_model(self.model) + with use_adapter(model, adapter_name="ref" if "ref" in model.peft_config else None): + ref_per_token_logps, _ = self._get_per_token_logps_and_entropies( + self.model, + prompt_completion_ids, + attention_mask, + logits_to_keep, + batch_size=batch_size, + num_images=num_images, + **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes + ) + else: + ref_per_token_logps = None + + # Decode + prompts_text = self.processing_class.batch_decode(prompt_ids, skip_special_tokens=True) + completions_text = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True) + + # Merge extra_fields from rollout_func into inputs for reward functions + if extra_fields: + for i, inp in enumerate(inputs): + for key, values in extra_fields.items(): + if isinstance(values, list) and i < len(values): + inp[key] = values[i] + elif not isinstance(values, list): + inp[key] = values + + # Calculate rewards for each reward function. rewards_per_func aggregates rewards across all processes. This is + # important because rewards will be normalized per group, and completions are distributed. We will later slice + # rewards_per_func to extract each process's subset. + rewards_per_func = self._calculate_rewards(inputs, prompts, completions, completion_ids_list) + num_generations = self.num_generations if mode == "train" else self.num_generations_eval + + if self.multi_objective_aggregation == "sum_then_normalize": + # Apply weights to each reward function's output and sum + rewards = (rewards_per_func * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1) + mean_grouped_rewards = rewards.view(-1, num_generations).mean(dim=1) + mean_grouped_rewards = mean_grouped_rewards.repeat_interleave(num_generations, dim=0) + if self.scale_rewards in ["group", "none"]: + # If self.scale_rewards = "none", we'll only use std_rewards to check for zero std for logging + if num_generations > 1: + std_rewards = rewards.view(-1, num_generations).std(dim=1) + std_rewards = std_rewards.repeat_interleave(num_generations, dim=0) + else: # doesn't occur during training, but could occur in eval when num_generations_eval=1 + std_rewards = torch.zeros_like(rewards) + elif self.scale_rewards == "batch": + # Compute global std + if rewards.numel() > 1: + std_rewards = rewards.std().expand_as(rewards) + else: # doesn't occur during training, but could occur in eval when num_generations_eval=batch_size=1 + std_rewards = torch.zeros_like(rewards) + else: + raise ValueError( + f"Invalid value for scale_rewards: {self.scale_rewards}. Must be one of 'batch', 'group', or 'none'." + ) + + advantages = rewards - mean_grouped_rewards + if self.scale_rewards != "none": + advantages = advantages / (std_rewards + 1e-4) + is_std_zero = torch.isclose(std_rewards, torch.zeros_like(std_rewards)) # for logging + + elif self.multi_objective_aggregation == "normalize_then_sum": + grouped = rewards_per_func.view(-1, num_generations, len(self.reward_funcs)) + mean_k = torch.nanmean(grouped, dim=1, keepdim=True) + std_k = nanstd(grouped, dim=1, keepdim=True) if num_generations > 1 else torch.zeros_like(mean_k) + reward_k = (grouped - mean_k) / (std_k + 1e-4) + reward_k = reward_k.view(-1, len(self.reward_funcs)) + rewards = (reward_k * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1) + std_rewards = rewards.std().expand_as(rewards) if rewards.numel() > 1 else torch.zeros_like(rewards) + advantages = (rewards - rewards.mean()) / (std_rewards + 1e-4) + is_std_zero = torch.isclose(std_rewards, torch.zeros_like(std_rewards)) # for logging + + else: + raise ValueError( + f"Invalid multi_objective_aggregation: {self.multi_objective_aggregation}. Must be " + "'sum_then_normalize' or 'normalize_then_sum'." + ) + + # Slice to keep only the local part of the data + process_slice = slice( + self.accelerator.process_index * len(prompts), + (self.accelerator.process_index + 1) * len(prompts), + ) + all_process_advantages = advantages.clone() # keep the aggregated advantages for logging + advantages = advantages[process_slice] + + # Calculate mean reward per function, but only for samples where the function was applied (non-NaN values) + for i, reward_func_name in enumerate(self.reward_func_names): + mean_rewards = torch.nanmean(rewards_per_func[:, i]).item() + self._metrics[mode][f"rewards/{reward_func_name}/mean"].append(mean_rewards) + std_func_rewards = nanstd(rewards_per_func[:, i]).item() + self._metrics[mode][f"rewards/{reward_func_name}/std"].append(std_func_rewards) + rewards = (rewards_per_func * self.reward_weights.to(rewards_per_func.device).unsqueeze(0)).nansum(dim=1) + self._metrics[mode]["reward"].append(rewards.mean().item()) + self._metrics[mode]["reward_std"].append(rewards.std().item()) + self._metrics[mode]["frac_reward_zero_std"].append(is_std_zero.float().mean().item()) + + # Log prompt and completion texts + self._logs["prompt"].extend(gather_object(prompts_text)) + self._logs["completion"].extend(gather_object(completions_text)) + for i, name in enumerate(self.reward_func_names): + self._logs["rewards"][name].extend(rewards_per_func[:, i].tolist()) + self._logs["advantages"].extend(all_process_advantages.tolist()) + + # Flush user-logged extra columns (from log_extra), gathering across processes. + # Keys must be sorted so that all ranks call gather_object in the same order, otherwise values + # get mis-attributed across columns (dict insertion order may differ between processes). + for column in sorted(self._pending_extra_logs): + self._logs["extra"][column].extend(gather_object(self._pending_extra_logs[column])) + self._pending_extra_logs.clear() + + # Flush user-logged metrics (from log_metric), averaging across processes. + # Keys must be sorted so that all ranks call accelerator.gather in the same order, otherwise values + # get mis-attributed across metrics (dict insertion order may differ between processes). + for name in sorted(self._pending_metrics): + values = self._pending_metrics[name] + local_mean = sum(values) / len(values) + global_mean = self.accelerator.gather(torch.tensor(local_mean, device=device)).mean().item() + self._metrics[mode][name].append(global_mean) + self._pending_metrics.clear() + + if images is not None: + self._logs["images"].extend(gather_object(images)) + + output = { + "prompt_ids": prompt_ids, + "prompt_mask": prompt_mask, + "completion_ids": completion_ids, + "completion_mask": completion_mask, + "advantages": advantages, + "num_items_in_batch": num_items_in_batch, + "sampling_per_token_logps": sampling_per_token_logps, + } + if ref_per_token_logps is not None: + output["ref_per_token_logps"] = ref_per_token_logps + if "pixel_values" in forward_kwargs: + output["pixel_values"] = forward_kwargs["pixel_values"] + if "image_grid_thw" in forward_kwargs: + output["image_grid_thw"] = forward_kwargs["image_grid_thw"] + if "pixel_attention_mask" in forward_kwargs: + output["pixel_attention_mask"] = forward_kwargs["pixel_attention_mask"] + if "image_sizes" in forward_kwargs: + output["image_sizes"] = forward_kwargs["image_sizes"] + if "token_type_ids" in forward_kwargs: + output["token_type_ids"] = forward_kwargs["token_type_ids"] + if "mm_token_type_ids" in forward_kwargs: + output["mm_token_type_ids"] = forward_kwargs["mm_token_type_ids"] + if images is not None: + output["num_images"] = num_images + if tool_mask is not None: + output["tool_mask"] = tool_mask + if sampling_topk_logps is not None: + output["sampling_topk_logps"] = sampling_topk_logps + if sampling_topk_token_ids is not None: + output["sampling_topk_token_ids"] = sampling_topk_token_ids + return output + + @torch.no_grad() + def _compute_divergence_mask( + self, + per_token_logps, + sampling_per_token_logps, + advantages, + completion_mask, + current_topk_logps=None, + sampling_topk_logps=None, + ): + """ + Compute a per-token trust-region mask based on the configured divergence type. Tokens where the policy has + diverged too far from the sampling distribution (in a direction that would increase the loss) are masked out. + + Args: + per_token_logps (`torch.Tensor`): + Log-probabilities of the current policy at the sampled tokens, shape `(B, T)`. + sampling_per_token_logps (`torch.Tensor`): + Log-probabilities of the sampling (rollout) policy at the sampled tokens, shape `(B, T)`. + advantages (`torch.Tensor`): + Per-token or per-sequence advantage estimates, broadcastable to `(B, T)`. + completion_mask (`torch.Tensor`): + Binary mask of shape `(B, T)` where `1` indicates valid completion tokens and `0` padding. + current_topk_logps (`torch.Tensor` or `None`): + Log-probabilities of the current policy at the rollout's top-K token IDs, shape `(B, T, K)`. Required + when `divergence_type` is `"topk_tv"` or `"topk_kl"`. + sampling_topk_logps (`torch.Tensor` or `None`): + Log-probabilities of the sampling policy at the rollout's top-K token IDs, shape `(B, T, K)`. Required + when `divergence_type` is `"topk_tv"` or `"topk_kl"`. + + Returns: + `torch.Tensor`: + Float mask of shape `(B, T)` where `1.0` indicates tokens to keep and `0.0` tokens to mask out. + """ + prob = torch.exp(per_token_logps) + sampling_prob = torch.exp(sampling_per_token_logps) + + delta_low = self.epsilon_low + delta_high = self.epsilon_high + + if self.divergence_type == "binary_tv": + # TV = |π - μ| + divergence = (prob - sampling_prob).abs() + # Mask tokens where divergence > threshold AND policy moves away from trust region + invalid_pos = (divergence > delta_high) & (prob > sampling_prob) + invalid_neg = (divergence > delta_low) & (prob < sampling_prob) + mask = torch.where(advantages > 0, ~invalid_pos, ~invalid_neg) + + elif self.divergence_type == "binary_kl": + # Bernoulli KL: D = μ log(μ/π) + (1-μ) log((1-μ)/(1-π)) + kl = sampling_prob * (sampling_per_token_logps - per_token_logps) + (1 - sampling_prob) * ( + torch.log1p(-sampling_prob.clamp(max=1 - 1e-7)) - torch.log1p(-prob.clamp(max=1 - 1e-7)) + ) + + invalid_pos = (kl > delta_high) & (prob > sampling_prob) + invalid_neg = (kl > delta_low) & (prob < sampling_prob) + mask = torch.where(advantages > 0, ~invalid_pos, ~invalid_neg) + + elif self.divergence_type in ("topk_tv", "topk_kl"): + current_topk_probs = torch.exp(current_topk_logps.float()) + rollout_topk_probs = torch.exp(sampling_topk_logps.float()) + + # Aggregate remaining probability mass outside top-K into a single rest bucket. + rollout_rest = (1.0 - rollout_topk_probs.sum(dim=-1)).clamp(min=1e-12) + current_rest = (1.0 - current_topk_probs.sum(dim=-1)).clamp(min=1e-12) + + if self.divergence_type == "topk_tv": + topk_tv = (current_topk_probs - rollout_topk_probs).abs().sum(dim=-1) + rest_tv = (current_rest - rollout_rest).abs() + divergence = (topk_tv + rest_tv) / 2.0 + else: + topk_kl = (rollout_topk_probs * (sampling_topk_logps - current_topk_logps)).sum(dim=-1) + rest_kl = rollout_rest * (rollout_rest.log() - current_rest.log()) + divergence = topk_kl + rest_kl + + invalid_pos = (divergence > delta_high) & (prob > sampling_prob) + invalid_neg = (divergence > delta_low) & (prob < sampling_prob) + mask = torch.where(advantages > 0, ~invalid_pos, ~invalid_neg) + + else: + raise ValueError(f"Unknown divergence_type: {self.divergence_type}") + + return mask.float() * completion_mask + + def _compute_loss(self, model, inputs): + # Compute per-token log probabilities for the model + prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"] + completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"] + input_ids = torch.cat([prompt_ids, completion_ids], dim=1) + attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) + logits_to_keep = completion_ids.size(1) + mask = completion_mask if "tool_mask" not in inputs else completion_mask * inputs["tool_mask"] + + forward_kwargs = { + "pixel_values": inputs.get("pixel_values"), + "image_grid_thw": inputs.get("image_grid_thw"), + "num_images": inputs.get("num_images"), + "pixel_attention_mask": inputs.get("pixel_attention_mask"), + "image_sizes": inputs.get("image_sizes"), + "token_type_ids": inputs.get("token_type_ids"), + "mm_token_type_ids": inputs.get("mm_token_type_ids"), + } + + sampling_topk_token_ids = inputs.get("sampling_topk_token_ids") + if self.divergence_type.startswith("topk_") and sampling_topk_token_ids is not None: + per_token_logps, entropies, current_topk_logps = self._get_per_token_logps_with_topk( + model, + input_ids, + attention_mask, + logits_to_keep, + topk_token_ids=sampling_topk_token_ids, + compute_entropy=True, + **forward_kwargs, + ) + else: + per_token_logps, entropies = self._get_per_token_logps_and_entropies( + model, + input_ids, + attention_mask, + logits_to_keep, + compute_entropy=True, + **forward_kwargs, + ) + current_topk_logps = None + + sampling_per_token_logps = inputs["sampling_per_token_logps"] + sampling_topk_logps = inputs.get("sampling_topk_logps") + + advantages = inputs["advantages"] + if advantages.dim() == 1: + advantages = advantages.unsqueeze(1) + + # DPPO: compute IS ratio (clamped, detached) and divergence mask + log_ratio = per_token_logps - sampling_per_token_logps + ratio = torch.exp(log_ratio.clamp(max=math.log(self.clip_ratio_c))).detach() + divergence_mask = self._compute_divergence_mask( + per_token_logps, + sampling_per_token_logps, + advantages, + mask, + current_topk_logps=current_topk_logps, + sampling_topk_logps=sampling_topk_logps, + ) + + # DPPO loss: -advantages * ratio * mask * log_prob + per_token_loss = -advantages * ratio * divergence_mask * per_token_logps + + # KL divergence with reference model + if self.beta != 0.0: + ref_per_token_logps = inputs["ref_per_token_logps"] + per_token_kl = ( + torch.exp(ref_per_token_logps - per_token_logps) - (ref_per_token_logps - per_token_logps) - 1 + ) + per_token_loss = per_token_loss + self.beta * per_token_kl + + mode = "train" if self.model.training else "eval" + normalizer = inputs["num_items_in_batch"] / self.accelerator.num_processes + loss = (per_token_loss * mask).sum() / normalizer + + # Log metrics + completion_token_count = mask.sum().clamp(min=1.0) + + def masked_batch_mean(x): + if x.shape[1] == 1: + return x.mean() + return (x * mask).sum() / completion_token_count + + if self.beta != 0.0: + mean_kl = masked_batch_mean(per_token_kl) + self._metrics[mode]["kl"].append(self.accelerator.gather(mean_kl).nanmean().item()) + + mean_entropy = masked_batch_mean(entropies) + self._metrics[mode]["entropy"].append(self.accelerator.gather(mean_entropy).nanmean().item()) + + prob_diff = (torch.exp(per_token_logps) - torch.exp(sampling_per_token_logps)).abs() + self._metrics[mode]["prob_diff/mean"].append( + self.accelerator.gather(masked_batch_mean(prob_diff)).nanmean().item() + ) + per_seq_max = prob_diff.masked_fill(mask == 0, float("-inf")).max(dim=1).values + per_seq_min = prob_diff.masked_fill(mask == 0, float("inf")).min(dim=1).values + self._metrics[mode]["prob_diff/max"].append(self.accelerator.gather(per_seq_max).max().item()) + self._metrics[mode]["prob_diff/min"].append(self.accelerator.gather(per_seq_min).min().item()) + + self._metrics[mode]["advantages/mean"].append(advantages.mean().item()) + self._metrics[mode]["advantages/std"].append(advantages.std().item()) + + # Log divergence mask statistics (analogous to clip_ratio in GRPO) + is_masked = (divergence_mask == 0) & (mask > 0) + is_masked_pos = is_masked & (advantages > 0) + is_masked_neg = is_masked & (advantages < 0) + + mask_ratio_pos = masked_batch_mean(is_masked_pos.float()) + mask_ratio_neg = masked_batch_mean(is_masked_neg.float()) + mask_ratio = masked_batch_mean(is_masked.float()) + + gathered_mask_ratio_neg = self.accelerator.gather(mask_ratio_neg) + self._metrics[mode]["mask_ratio/negative_adv_mean"].append(gathered_mask_ratio_neg.nanmean().item()) + gathered_mask_ratio_pos = self.accelerator.gather(mask_ratio_pos) + self._metrics[mode]["mask_ratio/positive_adv_mean"].append(gathered_mask_ratio_pos.nanmean().item()) + gathered_mask_ratio = self.accelerator.gather(mask_ratio) + self._metrics[mode]["mask_ratio/overall_mean"].append(gathered_mask_ratio.nanmean().item()) + + return loss diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gfpo/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gfpo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f91462a911daaff39038ef4cb53f18ffc845bea8 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gfpo/__init__.py @@ -0,0 +1,16 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .gfpo_config import GFPOConfig +from .gfpo_trainer import GFPOTrainer diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gfpo/gfpo_config.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gfpo/gfpo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..ae529987306eadc276115e425f4509e6dd7f1e1c --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gfpo/gfpo_config.py @@ -0,0 +1,35 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field + +from ...trainer.grpo_config import GRPOConfig as _GRPOConfig + + +@dataclass +class GFPOConfig(_GRPOConfig): + num_remains_in_group: int | None = field( + default=None, + metadata={ + "help": "number inputs remains after group filter function, `'num_remains_in_group'` must be >=2 if given." + }, + ) + + def __post_init__(self): + super().__post_init__() + + if self.num_remains_in_group is not None and self.num_remains_in_group >= self.num_generations: + raise ValueError( + f"Number remains in Group {self.num_remains_in_group} must be less than num_generations : {self.num_generations}." + ) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gfpo/gfpo_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gfpo/gfpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..b36001d3f03681e5d3cef72ff5d222f87d8a327c --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gfpo/gfpo_trainer.py @@ -0,0 +1,464 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging +from collections.abc import Callable +from typing import Any + +import torch +from accelerate.utils import gather_object + +from ...data_utils import apply_chat_template, is_conversational, prepare_multimodal_messages +from ...models.utils import disable_gradient_checkpointing +from ...trainer.grpo_trainer import GRPOTrainer as _GRPOTrainer +from ...trainer.utils import nanmax, nanmin, nanstd, pad + + +logger = logging.getLogger(__name__) + +GroupFilterFunc = Callable[[list[list[Any]], list[list[Any]]], list[list[float]]] + + +class GFPOTrainer(_GRPOTrainer): + def __init__( + self, + model, + reward_funcs, + args=None, + train_dataset=None, + eval_dataset=None, + processing_class=None, + reward_processing_classes=None, + group_filter_func=None, + callbacks=None, + optimizers=(None, None), + peft_config=None, + ): + super().__init__( + model=model, + reward_funcs=reward_funcs, + args=args, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + reward_processing_classes=reward_processing_classes, + callbacks=callbacks, + optimizers=optimizers, + peft_config=peft_config, + ) + self.group_filter_func = group_filter_func + self.num_remains_in_group = args.num_remains_in_group + if self.group_filter_func is None and self.num_remains_in_group is not None: + raise ValueError( + f"Group filter function must not be None when num_remains_in_group ({self.num_remains_in_group}) is given." + ) + if self.group_filter_func is not None and self.num_remains_in_group is None: + logger.warning("Group filter function is not activated since num_remains_in_group is not set") + + def _generate_and_score_completions(self, inputs): + device = self.accelerator.device + mode = "train" if self.model.training else "eval" + + prompts = [x["prompt"] for x in inputs] + + if "images" in inputs[0]: + images = [example.get("images") for example in inputs] + elif "image" in inputs[0]: + images = [[example.get("image")] if example.get("image") is not None else None for example in inputs] + else: + images = None + # Transformers requires at least one image in the batch, otherwise it throws an error + if images is not None and all(img_list == [] for img_list in images): + images = None + + # If the prompts are conversational and the inputs contain images, we need to convert the prompts from + # [{"role": "user", "content": "What color is the sky?"}] to + # [{"role": "user", "content": [{"type": "image", "image": }, {"type": "text", "text": "What color is the sky?"}]}] + if images is not None: + if not is_conversational(inputs[0]): + raise ValueError( + "Multimodal training requires conversational prompts. It looks like the dataset contains " + "non-conversational inputs, likely because a chat template was applied before passing the dataset " + "to the trainer. Please provide the raw conversational prompts and let the trainer apply the chat " + "template internally." + ) + prompts = [ + prepare_multimodal_messages(prompt, images=image_list) + for prompt, image_list in zip(prompts, images, strict=True) + ] + + dataset_images = images # preserve dataset images before _generate may overwrite + ( + prompt_ids_list, + completion_ids_list, + tool_mask_list, + completions, + num_items_in_batch, + sampling_per_token_logps_list, + extra_fields, + images, + tool_images, + ) = self._generate(prompts) + if images is None: + images = dataset_images # restore dataset images (rollout_func path returns None) + + # Convert lists of token IDs to padded tensors + prompt_ids = [torch.tensor(ids) for ids in prompt_ids_list] + prompt_mask = [torch.ones_like(ids, dtype=torch.long) for ids in prompt_ids] + prompt_ids = pad( + prompt_ids, + padding_value=self._tokenizer.pad_token_id, + padding_side="left", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + prompt_mask = pad( + prompt_mask, + padding_value=0, + padding_side="left", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + completion_ids = [torch.tensor(ids) for ids in completion_ids_list] + completion_mask = [torch.ones_like(ids, dtype=torch.long) for ids in completion_ids] + completion_ids = pad( + completion_ids, + padding_value=self._tokenizer.pad_token_id, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + completion_mask = pad( + completion_mask, + padding_value=0, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + if sampling_per_token_logps_list is not None: + sampling_per_token_logps = [torch.tensor(logps) for logps in sampling_per_token_logps_list] + sampling_per_token_logps = pad( + sampling_per_token_logps, + padding_value=0.0, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + else: + sampling_per_token_logps = None + + # If mask_truncated_completions is enabled, zero out truncated completions in completion_mask + if self.mask_truncated_completions: + eos_and_pad = [self._tokenizer.eos_token_id, self._tokenizer.pad_token_id] + is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids_list], device=device) + completion_mask = completion_mask * (~is_truncated).unsqueeze(1).int() + + # Concatenate prompt_mask with completion_mask for logit computation + prompt_completion_ids = torch.cat([prompt_ids, completion_ids], dim=1) # (B, P+C) + attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) # (B, P+C) + + logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens + batch_size = self.args.per_device_train_batch_size if mode == "train" else self.args.per_device_eval_batch_size + + num_images = [len(img_list) if img_list else 0 for img_list in images] if images is not None else None + + # Get forward_kwargs for models with multimodal inputs + if images is not None: + prompts_text = [ + apply_chat_template({"prompt": prompt}, self.processing_class)["prompt"] for prompt in prompts + ] + prompt_inputs = self.processing_class(images=images, text=prompts_text, padding=True, return_tensors="pt") + prompt_inputs = super()._prepare_inputs(prompt_inputs) + forward_kwargs = {k: v for k, v in prompt_inputs.items() if k not in ["input_ids", "attention_mask"]} + else: + forward_kwargs = {} + + # If token_type_ids are used, extend them with zeros for the completion part + if "token_type_ids" in forward_kwargs: + token_type_ids = forward_kwargs["token_type_ids"] + if self.pad_to_multiple_of is not None: + # Needed only with pad_to_multiple_of: otherwise prompt_ids and token_type_ids must have equal len + padding_size = prompt_ids.size(1) - token_type_ids.size(1) + if padding_size > 0: + token_type_ids = torch.cat( + [token_type_ids.new_zeros((token_type_ids.size(0), padding_size)), token_type_ids], dim=1 + ) + forward_kwargs["token_type_ids"] = torch.cat( + [token_type_ids, token_type_ids.new_zeros(completion_ids.shape)], dim=1 + ) + # If mm_token_type_ids are used, extend them with zeros for the completion part + if "mm_token_type_ids" in forward_kwargs: + mm_token_type_ids = forward_kwargs["mm_token_type_ids"] + if self.pad_to_multiple_of is not None: + # Needed only with pad_to_multiple_of: otherwise prompt_ids and mm_token_type_ids must have equal len + padding_size = prompt_ids.size(1) - mm_token_type_ids.size(1) + if padding_size > 0: + mm_token_type_ids = torch.cat( + [mm_token_type_ids.new_zeros((mm_token_type_ids.size(0), padding_size)), mm_token_type_ids], + dim=1, + ) + forward_kwargs["mm_token_type_ids"] = torch.cat( + [mm_token_type_ids, mm_token_type_ids.new_zeros(completion_ids.shape)], dim=1 + ) + + # When gradient checkpointing is enabled with use_reentrant=True (non default), calling the model inside a + # torch.no_grad() block triggers a harmless PyTorch warning ("None of the inputs have requires_grad=True"). + # Temporarily disable checkpointing to avoid this warning during inference. + with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs): + # If the generation and optimization steps are misaligned—i.e., if generation does not occur at the end of + # a full optimizer step (when gradient_accumulation_steps is not a multiple of generate_every)—then the + # samples may come from an earlier version of the model. In that case, we need to track old_per_token_logps + # for importance sampling. If the steps are aligned, importance sampling isn't necessary and we set + # old_per_token_logps to None. + # When using vLLM, we always compute old_per_token_logps for importance sampling, it was shown that the + # distribution mismatch between vLLM and the training model can be large and harm the training. + generate_every = self.args.steps_per_generation * self.num_iterations # generation frequency + if self.args.gradient_accumulation_steps % generate_every != 0 or ( + self.use_vllm and self.vllm_importance_sampling_correction + ): + old_per_token_logps, _ = self._get_per_token_logps_and_entropies( + self.model, + prompt_completion_ids, + attention_mask, + logits_to_keep, + batch_size, + num_images=num_images, + **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes + ) + else: + old_per_token_logps = None + + # Compute the importance sampling ratio when using vLLM, to correct for potential distribution mismatch + if self.use_vllm and self.vllm_importance_sampling_correction: + importance_sampling_ratio = torch.exp(old_per_token_logps - sampling_per_token_logps) + importance_sampling_ratio = torch.clamp( + importance_sampling_ratio, + min=self.vllm_importance_sampling_clip_min, + max=self.vllm_importance_sampling_clip_max, + ) + + # Compute the per-token log probabilities for the reference model + if self.beta != 0.0: + if self.ref_model is not None: + ref_per_token_logps, _ = self._get_per_token_logps_and_entropies( + self.ref_model, + prompt_completion_ids, + attention_mask, + logits_to_keep, + batch_size=batch_size, + num_images=num_images, + **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes + ) + else: + with self.accelerator.unwrap_model(self.model).disable_adapter(): + ref_per_token_logps, _ = self._get_per_token_logps_and_entropies( + self.model, + prompt_completion_ids, + attention_mask, + logits_to_keep, + batch_size=batch_size, + num_images=num_images, + **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes + ) + else: + ref_per_token_logps = None + + # Decode + prompts_text = self.processing_class.batch_decode(prompt_ids, skip_special_tokens=True) + completions_text = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True) + if is_conversational(inputs[0]): + completions = [] + for prompt, completion in zip(prompts, completions_text, strict=True): + bootstrap = prompt.pop()["content"] if prompt[-1]["role"] == "assistant" else "" + if isinstance(bootstrap, list): # for VLM, the format might be [{"type": "text", "text": "..."}] + assert len(bootstrap) == 1 and bootstrap[0]["type"] == "text" + bootstrap = bootstrap[0]["text"] + completions.append([{"role": "assistant", "content": bootstrap + completion}]) + else: + completions = completions_text + + # Calculate rewards for each reward function. rewards_per_func aggregates rewards across all processes. This is + # important because rewards will be normalized per group, and completions are distributed. We will later slice + # rewards_per_func to extract each process's subset. + rewards_per_func = self._calculate_rewards(inputs, prompts, completions, completion_ids_list) + + # Apply weights to each reward function's output and sum + rewards = (rewards_per_func * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1) + + num_in_group = self.num_generations + num_inputs_in_device = len(prompts) + + if self.num_remains_in_group is not None and mode == "train": + num_in_group = self.num_remains_in_group + + all_completions = gather_object(completions) + + group_filter_scores = self.group_filter_func( + group_completions=[ + all_completions[i : i + 1 * self.num_generations] + for i in range(len(all_completions) // self.num_generations) + ], + group_rewards=rewards.view(-1, self.num_generations).tolist(), + ) + group_filter_scores = torch.tensor(group_filter_scores, device=device) + + _, group_local_indices = torch.topk(group_filter_scores, self.num_remains_in_group, dim=-1) + group_row_offsets = torch.arange(0, len(all_completions), self.num_generations, device=device).unsqueeze(1) + group_global_indices = group_row_offsets + group_local_indices + group_global_indices = group_global_indices.flatten() + + rewards = rewards[group_global_indices] + rewards_per_func = rewards_per_func[group_global_indices, :] + + num_inputs_in_device = int(len(prompts) / self.num_generations * self.num_remains_in_group) + + # Compute grouped-wise rewards + mean_grouped_rewards = rewards.view(-1, num_in_group).mean(dim=1) + + # Normalize the rewards to compute the advantages + mean_grouped_rewards = mean_grouped_rewards.repeat_interleave(num_in_group, dim=0) + advantages = rewards - mean_grouped_rewards + + if self.scale_rewards in ["group", "none"]: + # If self.scale_rewards = "none", we'll still log group level std + std_rewards = rewards.view(-1, num_in_group).std(dim=1) + std_rewards = std_rewards.repeat_interleave(num_in_group, dim=0) + elif self.scale_rewards == "batch": + # Compute global std + std_rewards = rewards.std().expand_as(rewards) + else: + raise ValueError( + f"Invalid value for scale_rewards: {self.scale_rewards}. Must be one of 'batch', 'group', or 'none'." + ) + + is_std_zero = torch.isclose(std_rewards, torch.zeros_like(std_rewards)) + if self.scale_rewards != "none": + advantages = advantages / (std_rewards + 1e-4) + + # Slice to keep only the local part of the data + process_slice = slice( + self.accelerator.process_index * num_inputs_in_device, + (self.accelerator.process_index + 1) * num_inputs_in_device, + ) + all_process_advantages = advantages.clone() # keep the aggregated advantages for logging + advantages = advantages[process_slice] + + if self.num_remains_in_group is not None and mode == "train": + local_input_indices_to_keep = group_global_indices[process_slice] - self.accelerator.process_index * len( + prompts + ) # step is length of prompts + + prompt_ids = prompt_ids[local_input_indices_to_keep] + prompt_mask = prompt_mask[local_input_indices_to_keep] + completion_ids = completion_ids[local_input_indices_to_keep] + completion_mask = completion_mask[local_input_indices_to_keep] + attention_mask = attention_mask[local_input_indices_to_keep] + completion_lengths = completion_mask.sum(1) + agg_completion_lengths = self.accelerator.gather(completion_lengths) + num_items_in_batch = agg_completion_lengths.sum() + + if sampling_per_token_logps is not None: + sampling_per_token_logps = sampling_per_token_logps[local_input_indices_to_keep] + if old_per_token_logps is not None: + old_per_token_logps = old_per_token_logps[local_input_indices_to_keep] + if ref_per_token_logps is not None: + ref_per_token_logps = ref_per_token_logps[local_input_indices_to_keep] + if self.use_vllm and self.vllm_importance_sampling_correction: + importance_sampling_ratio = importance_sampling_ratio[local_input_indices_to_keep] + + # Calculate mean reward per function, but only for samples where the function was applied (non-NaN values) + for i, reward_func_name in enumerate(self.reward_func_names): + mean_rewards = torch.nanmean(rewards_per_func[:, i]).item() + self._metrics[mode][f"rewards/{reward_func_name}/mean"].append(mean_rewards) + std_func_rewards = nanstd(rewards_per_func[:, i]).item() + self._metrics[mode][f"rewards/{reward_func_name}/std"].append(std_func_rewards) + rewards = (rewards_per_func * self.reward_weights.to(rewards_per_func.device).unsqueeze(0)).nansum(dim=1) + self._metrics[mode]["reward"].append(rewards.mean().item()) + self._metrics[mode]["reward_std"].append(rewards.std().item()) + self._metrics[mode]["frac_reward_zero_std"].append(is_std_zero.float().mean().item()) + + # Log prompt and completion texts + all_prompts_text = gather_object(prompts_text) + all_completions_text = gather_object(completions_text) + all_images = gather_object(images) if images is not None else None + if self.num_remains_in_group is not None and mode == "train": + group_global_indices_list = group_global_indices.tolist() + all_prompts_text = [all_prompts_text[i] for i in group_global_indices_list] + all_completions_text = [all_completions_text[i] for i in group_global_indices_list] + if images is not None: + all_images = [all_images[i] for i in group_global_indices_list] + + self._logs["prompt"].extend(all_prompts_text) + self._logs["completion"].extend(all_completions_text) + for i, name in enumerate(self.reward_func_names): + self._logs["rewards"][name].extend(rewards_per_func[:, i].tolist()) + self._logs["advantages"].extend(all_process_advantages.tolist()) + + if images is not None: + self._logs["images"].extend(all_images) + + if self.use_vllm and self.vllm_importance_sampling_correction: + delta = torch.abs(old_per_token_logps - sampling_per_token_logps) + delta = delta[completion_mask.bool()] + mean_delta = torch.mean(delta) if delta.numel() > 0 else torch.tensor(0.0, device=device) + max_delta = torch.max(delta) if delta.numel() > 0 else torch.tensor(0.0, device=device) + self._metrics[mode]["sampling/sampling_logp_difference/mean"].append( + self.accelerator.gather(mean_delta).mean().item() + ) + self._metrics[mode]["sampling/sampling_logp_difference/max"].append( + self.accelerator.gather(max_delta).max().item() + ) + + flat_is_ratio = importance_sampling_ratio[completion_mask.bool()] + min_importance_sampling_ratio = ( + torch.min(flat_is_ratio) if flat_is_ratio.numel() > 0 else torch.tensor(0.0, device=device) + ) + mean_importance_sampling_ratio = ( + torch.mean(flat_is_ratio) if flat_is_ratio.numel() > 0 else torch.tensor(0.0, device=device) + ) + max_importance_sampling_ratio = ( + torch.max(flat_is_ratio) if flat_is_ratio.numel() > 0 else torch.tensor(0.0, device=device) + ) + self._metrics[mode]["sampling/importance_sampling_ratio/min"].append( + nanmin(self.accelerator.gather(min_importance_sampling_ratio)).item() + ) + self._metrics[mode]["sampling/importance_sampling_ratio/mean"].append( + self.accelerator.gather(mean_importance_sampling_ratio).nanmean().item() + ) + self._metrics[mode]["sampling/importance_sampling_ratio/max"].append( + nanmax(self.accelerator.gather(max_importance_sampling_ratio)).item() + ) + + output = { + "prompt_ids": prompt_ids, + "prompt_mask": prompt_mask, + "completion_ids": completion_ids, + "completion_mask": completion_mask, + "advantages": advantages, + "num_items_in_batch": num_items_in_batch, + } + if old_per_token_logps is not None: + output["old_per_token_logps"] = old_per_token_logps + if self.use_vllm and self.vllm_importance_sampling_correction: + output["importance_sampling_ratio"] = importance_sampling_ratio + if ref_per_token_logps is not None: + output["ref_per_token_logps"] = ref_per_token_logps + if "pixel_values" in forward_kwargs: + output["pixel_values"] = forward_kwargs["pixel_values"] + if "image_grid_thw" in forward_kwargs: + output["image_grid_thw"] = forward_kwargs["image_grid_thw"] + if "pixel_attention_mask" in forward_kwargs: + output["pixel_attention_mask"] = forward_kwargs["pixel_attention_mask"] + if "image_sizes" in forward_kwargs: + output["image_sizes"] = forward_kwargs["image_sizes"] + if "token_type_ids" in forward_kwargs: + output["token_type_ids"] = forward_kwargs["token_type_ids"] + if images is not None: + output["num_images"] = num_images + return output diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gkd/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gkd/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d49fe68a623fbca5fdc6cd4581464ac65d892fa9 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gkd/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .gkd_config import GKDConfig +from .gkd_trainer import GKDTrainer + + +__all__ = ["GKDConfig", "GKDTrainer"] diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gkd/gkd_config.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gkd/gkd_config.py new file mode 100644 index 0000000000000000000000000000000000000000..4ea10761c45228f10c8acb42ce7cb48eba5eede8 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gkd/gkd_config.py @@ -0,0 +1,110 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field +from typing import Any + +from ...trainer.sft_config import SFTConfig + + +@dataclass +class GKDConfig(SFTConfig): + """ + Configuration class for [`experimental.gkd.GKDTrainer`]. + + This class includes only the parameters that are specific to GKD training. For a full list of training arguments, + please refer to the [`~transformers.TrainingArguments`] and [`SFTConfig`] documentation. + + Args: + temperature (`float`, *optional*, defaults to `0.9`): + Temperature for sampling. The higher the temperature, the more random the completions. + lmbda (`float`, *optional*, defaults to `0.5`): + Lambda parameter that controls the student data fraction (i.e., the proportion of on-policy + student-generated outputs). + beta (`float`, *optional*, defaults to `0.5`): + Interpolation coefficient between `0.0` and `1.0` of the Generalized Jensen-Shannon Divergence loss. When + beta is `0.0`, the loss is the KL divergence. When beta is `1.0`, the loss is the Inverse KL Divergence. + max_new_tokens (`int`, *optional*, defaults to `128`): + Maximum number of tokens to generate per completion. + teacher_model_name_or_path (`str`, *optional*): + Model name or path of the teacher model. If `None`, the teacher model will be the same as the model being + trained. + teacher_model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the teacher model + from a string. + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the model. + seq_kd (`bool`, *optional*, defaults to `False`): + Seq_kd parameter that controls whether to perform Sequence-Level KD (can be viewed as supervised FT on + teacher-generated output). + """ + + _VALID_DICT_FIELDS = SFTConfig._VALID_DICT_FIELDS + ["teacher_model_init_kwargs"] + + temperature: float = field( + default=0.9, + metadata={"help": "Temperature for sampling. The higher the temperature, the more random the completions."}, + ) + lmbda: float = field( + default=0.5, + metadata={ + "help": "Lambda parameter that controls the student data fraction (i.e., the proportion of on-policy " + "student-generated outputs)." + }, + ) + beta: float = field( + default=0.5, + metadata={ + "help": "Interpolation coefficient between `0.0` and `1.0` of the Generalized Jensen-Shannon Divergence " + "loss. When beta is `0.0`, the loss is the KL divergence. When beta is `1.0`, the loss is the Inverse KL " + "Divergence." + }, + ) + max_new_tokens: int = field( + default=128, + metadata={"help": "Maximum number of tokens to generate per completion."}, + ) + teacher_model_name_or_path: str | None = field( + default=None, + metadata={ + "help": "Model name or path of the teacher model. If `None`, the teacher model will be the same as the " + "model being trained." + }, + ) + teacher_model_init_kwargs: dict[str, Any] | str | None = field( + default=None, + metadata={ + "help": "Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the " + "teacher model from a string." + }, + ) + disable_dropout: bool = field( + default=True, + metadata={"help": "Whether to disable dropouts in `model`."}, + ) + seq_kd: bool = field( + default=False, + metadata={ + "help": "Seq_kd parameter that controls whether to perform Sequence-Level KD (can be viewed as supervised " + "FT on teacher-generated output)." + }, + ) + + def __post_init__(self): + super().__post_init__() + # check lmbda and beta are in the range [0, 1] + if self.lmbda < 0.0 or self.lmbda > 1.0: + raise ValueError("lmbda must be in the range [0.0, 1.0].") + if self.beta < 0.0 or self.beta > 1.0: + raise ValueError("beta must be in the range [0.0, 1.0].") diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gkd/gkd_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gkd/gkd_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..1c942bae19404f7257b251a34ef5e98dc8972878 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gkd/gkd_trainer.py @@ -0,0 +1,504 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import random +import textwrap +from collections.abc import Callable +from typing import Any + +import torch +import torch.nn as nn +import torch.nn.functional as F +from datasets import Dataset +from transformers import ( + AutoModelForCausalLM, + BaseImageProcessor, + DataCollator, + FeatureExtractionMixin, + GenerationConfig, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, +) +from transformers.trainer_utils import EvalPrediction +from transformers.utils import ModelOutput, is_liger_kernel_available, is_peft_available + +from ...models import prepare_deepspeed +from ...models.utils import _ForwardRedirection, unwrap_model_for_generation +from ...trainer.sft_trainer import SFTTrainer +from ...trainer.utils import disable_dropout_in_model +from ..utils import DataCollatorForChatML, empty_cache +from .gkd_config import GKDConfig + + +if is_peft_available(): + from peft import PeftConfig + +if is_liger_kernel_available(): + from liger_kernel.chunked_loss import LigerFusedLinearJSDLoss + + +class GKDTrainer(SFTTrainer): + """Trainer for Generalized Knowledge Distillation (GKD) of language models. + + For details on GKD, see the paper: [On-Policy Distillation of Language Models: Learning from Self-Generated + Mistakes](https://huggingface.co/papers/2306.13649). + + Args: + model ([`~transformers.PreTrainedModel`] or `torch.nn.Module` or `str`, *optional*): + Model to be trained, or the string identifier of the model to be instantiated from a pretrained model. + teacher_model ([`~transformers.PreTrainedModel`] or `torch.nn.Module` or `str`, *optional*): + Teacher model for knowledge distillation, or the string identifier of the model to be instantiated from a + pretrained model. + args ([`experimental.gkd.GKDConfig`], *optional*): + Training arguments. + data_collator ([`~transformers.DataCollator`], *optional*): + Data collator to batch samples from the dataset. It defaults to a + [`experimental.utils.DataCollatorForChatML`] using the `processing_class`. + train_dataset ([`~datasets.Dataset`], *optional*): + Dataset for training. + eval_dataset ([`~datasets.Dataset`] or `dict` of [`~datasets.Dataset`], *optional*): + Dataset for evaluation. + processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*): + Class to process the data. + compute_metrics (`Callable`, *optional*): + Function to compute metrics at evaluation. Must take in an [`~transformers.EvalPrediction`] and return a + dictionary string to float. + callbacks (`list` of [`~transformers.TrainerCallback`], *optional*): + Callbacks to use during training. + optimizers (`tuple` of `torch.optim.Optimizer` and `torch.optim.lr_scheduler.LambdaLR`, *optional*, defaults to `(None, None)`): + Tuple containing the optimizer and the learning rate scheduler to use for training. + preprocess_logits_for_metrics (`Callable`, *optional*): + Function to preprocess the logits before computing the metrics. Must take in the `logits` and `labels` and + return the logits to be used for metrics computation. + peft_config ([`~peft.PeftConfig`], *optional*): + PEFT configuration to use PEFT for training. If `None`, PEFT is not used. If provided, the `model` will be + wrapped with the specified PEFT adapter. + formatting_func (`Callable`, *optional*): + Function to format the dataset. Must take in an example and return an example. + """ + + _tag_names = ["trl", "gkd"] + _name = "GKD" + _paper = { + "title": "On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes", + "id": "2306.13649", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @inproceedings{agarwal2024on-policy, + title = {{On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes}}, + author = {Rishabh Agarwal and Nino Vieillard and Yongchao Zhou and Piotr Stanczyk and Sabela Ramos Garea and Matthieu Geist and Olivier Bachem}, + year = 2024, + booktitle = {The Twelfth International Conference on Learning Representations, {ICLR} 2024, Vienna, Austria, May 7-11, 2024}, + publisher = {OpenReview.net}, + url = {https://openreview.net/forum?id=3zKtaqxLhW}, + }"""), + } + + def __init__( + self, + model: PreTrainedModel | nn.Module | str | None = None, + teacher_model: PreTrainedModel | nn.Module | str = None, + args: GKDConfig | None = None, + data_collator: DataCollator | None = None, # type: ignore + train_dataset: Dataset | None = None, + eval_dataset: Dataset | dict[str, Dataset] | None = None, + processing_class: PreTrainedTokenizerBase + | BaseImageProcessor + | FeatureExtractionMixin + | ProcessorMixin + | None = None, + compute_metrics: Callable[[EvalPrediction], dict] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None, + peft_config: "PeftConfig | None" = None, + formatting_func: Callable | None = None, + ): + # Ensure Trainer does not drop non-signature columns used by the collator (e.g., "prompts") + args.remove_unused_columns = False + # Respect a user-provided data_collator; otherwise, provide a ChatML collator that + if data_collator is None: + data_collator = DataCollatorForChatML(tokenizer=processing_class, max_length=args.max_length) + + # Ensure SFTTrainer does not pre-process the dataset when using a ChatML collator, + # so that raw conversational fields (e.g., "messages") remain available to the collator. + if args.dataset_kwargs is None: + args.dataset_kwargs = {"skip_prepare_dataset": True} + else: + args.dataset_kwargs["skip_prepare_dataset"] = True + + # Liger fused GKD loss (JSD) + self.use_liger_gkd_loss = False + if args.use_liger_kernel: + # Match the non-Liger path: pure JSD (no hard CE component) and no temperature + # scaling, since `generalized_jsd_loss` is called without a `temperature` argument. + self.liger_jsd_loss = LigerFusedLinearJSDLoss( + beta=args.beta, + ignore_index=-100, + compiled=False, + weight_hard_loss=0.0, + weight_soft_loss=1.0, + ) + self.use_liger_gkd_loss = True + self._forward_redirection = _ForwardRedirection() + + super().__init__( + model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + peft_config=peft_config, + formatting_func=formatting_func, + ) + + if args.teacher_model_init_kwargs is None: + teacher_model_init_kwargs = {} + elif not isinstance(teacher_model, str): + raise ValueError( + "You passed teacher_model_init_kwargs to the GKDConfig, but your teacher_model is already instantiated." + ) + else: + teacher_model_init_kwargs = args.teacher_model_init_kwargs + teacher_model_init_kwargs["dtype"] = ( + teacher_model_init_kwargs["dtype"] + if teacher_model_init_kwargs["dtype"] in ["auto", None] + else getattr(torch, teacher_model_init_kwargs["dtype"]) + ) + + if isinstance(teacher_model, str): + teacher_model = AutoModelForCausalLM.from_pretrained(teacher_model, **teacher_model_init_kwargs) + + # Disable dropout in the model + if args.disable_dropout: + disable_dropout_in_model(self.model) + + if self.is_deepspeed_enabled: + self.teacher_model = prepare_deepspeed(teacher_model, self.accelerator) + else: + self.teacher_model = self.accelerator.prepare_model(teacher_model, evaluation_mode=True) + + self.lmbda = args.lmbda + self.beta = args.beta + self.temperature = args.temperature + self.seq_kd = args.seq_kd + + generation_kwargs = { + "max_new_tokens": args.max_new_tokens, + "temperature": args.temperature, + "do_sample": True, + "top_k": 0, + "use_cache": False if args.gradient_checkpointing else True, + "pad_token_id": self.processing_class.pad_token_id, + } + self.generation_config = GenerationConfig(**generation_kwargs) + # Keep training-specific generation kwargs to overwrite model's original generation config + self.generation_kwargs = generation_kwargs + # Set custom EOS tokens if they are specified by the model's generation + # config. This is important for models with the Llama 3 chat template, + # which use special tokens <|eot_id|> and <|eom_id|> to mark the end of + # turns or messages. + if ( + hasattr(self.model.generation_config, "eos_token_id") + and self.model.generation_config.eos_token_id is not None + ): + self.generation_config.eos_token_id = self.model.generation_config.eos_token_id + + @staticmethod + def generalized_jsd_loss( + student_logits, + teacher_logits, + labels=None, + beta=0.5, + temperature=1.0, + reduction="batchmean", + num_items_in_batch=None, + ): + """ + Compute the generalized Jensen-Shannon Divergence loss for knowledge distillation using F.kl_div. See Eq. (1) + of https://huggingface.co/papers/2306.13649 for the definition. + + Args: + student_logits: + Tensor of shape (batch_size, sequence_length, vocab_size) + teacher_logits: + Tensor of shape (batch_size, sequence_length, vocab_size) + labels: + Tensor of shape (batch_size, sequence_length) with -100 for padding tokens to ignore when computing + loss + beta: + Interpolation coefficient between 0 and 1 (default: 0.5) + temperature: + Softmax temperature (default: 1.0) + reduction: + Specifies the reduction to apply to the output (default: 'batchmean') + + Returns: + loss: Scalar tensor with the generalized JSD loss + """ + + # Apply temperature scaling + student_logits = student_logits / temperature + teacher_logits = teacher_logits / temperature + + # Compute log probabilities for student and probabilities for teacher + student_log_probs = F.log_softmax(student_logits, dim=-1) + teacher_log_probs = F.log_softmax(teacher_logits, dim=-1) + + if beta == 0: + jsd = F.kl_div(student_log_probs, teacher_log_probs, reduction="none", log_target=True) + elif beta == 1: + jsd = F.kl_div(teacher_log_probs, student_log_probs, reduction="none", log_target=True) + else: + # Compute the log of the mixture distribution + # log(a + b) = log(exp(log(a)) + exp(log(b))) -> for mixture + beta = torch.tensor(beta, dtype=student_log_probs.dtype, device=student_log_probs.device) + mixture_log_probs = torch.logsumexp( + torch.stack([student_log_probs + torch.log1p(-beta), teacher_log_probs + torch.log(beta)]), + dim=0, + ) + + # Compute KL divergences using F.kl_div + # PyTorch differs from the standard mathematical definition, so the order of the probability distributions is swapped compared to that defined in the paper. + kl_teacher = F.kl_div(mixture_log_probs, teacher_log_probs, reduction="none", log_target=True) + kl_student = F.kl_div(mixture_log_probs, student_log_probs, reduction="none", log_target=True) + + # Compute the Generalized Jensen-Shannon Divergence + jsd = beta * kl_teacher + (1 - beta) * kl_student + + # Masking + if labels is not None: + mask = labels != -100 + jsd = jsd[mask] + + # Apply reduction + if num_items_in_batch is not None: + # Normalize by the global number of valid tokens for gradient-accumulation-correct loss (see issue #4719). + jsd_sum = jsd.sum() + if isinstance(num_items_in_batch, torch.Tensor): + num_items_in_batch = num_items_in_batch.to(jsd_sum.device) + return jsd_sum / num_items_in_batch + if reduction == "batchmean": + # clamp_min(1) avoids 0/0 -> nan when a sample has no unmasked positions + # (e.g. completion fully truncated). jsd[mask] is empty -> jsd.sum() == 0, + # so 0/1 == 0 with a valid grad path. + denom = mask.sum().clamp_min(1) if labels is not None else max(jsd.size(0), 1) + return jsd.sum() / denom + elif reduction == "sum": + return jsd.sum() + elif reduction == "mean": + return jsd.mean() + else: + return jsd + + def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): + if self.use_liger_gkd_loss: + # Forward only through the base models (avoid lm_head to save memory). + # Route through the DDP/FSDP wrapper via _forward_redirection so that + # DDP.forward() is called and prepare_for_backward() fires correctly. + unwrapped_student = self.accelerator.unwrap_model(model) + student_outputs = self._forward_redirection( + model, unwrapped_student, self._liger_student_forward, unwrapped_student, inputs + ) + + self.teacher_model.eval() + unwrapped_teacher = self.accelerator.unwrap_model(self.teacher_model) + if hasattr(unwrapped_teacher, "get_decoder") and unwrapped_teacher.get_decoder() is not None: + base_teacher = unwrapped_teacher.get_decoder() + else: + base_teacher = getattr( + unwrapped_teacher, getattr(unwrapped_teacher, "base_model_prefix", "model"), unwrapped_teacher + ) + with torch.no_grad(): + teacher_outputs = base_teacher( + input_ids=inputs["input_ids"], + attention_mask=inputs["attention_mask"], + use_cache=False, + ) + + # hidden states (shifted) + student_hidden = student_outputs.last_hidden_state[:, :-1] + teacher_hidden = teacher_outputs.last_hidden_state[:, :-1] + + # Release teacher outputs; keep student_outputs for return_outputs + del teacher_outputs + + # labels mask and labels (shifted) + labels_mask = inputs["labels"] != -100 + masked_input_ids = torch.where( + labels_mask, inputs["input_ids"], torch.full_like(inputs["input_ids"], -100) + ) + true_labels = masked_input_ids[:, 1:].contiguous() + + # Release intermediate tensors + del labels_mask, masked_input_ids + + # heads + student_head = unwrapped_student.get_output_embeddings() + teacher_head = unwrapped_teacher.get_output_embeddings() + + # liger fused jsd loss + loss = self.liger_jsd_loss( + student_input=student_hidden, + student_weight=student_head.weight, + teacher_input=teacher_hidden, + teacher_weight=teacher_head.weight, + true_labels=true_labels, + student_bias=getattr(student_head, "bias", None), + teacher_bias=getattr(teacher_head, "bias", None), + ) + + # The Liger JSD loss normalizes by the local number of valid tokens. Under gradient accumulation we want + # the global normalization, so rescale by `num_valid_local / num_items_in_batch`. + if num_items_in_batch is not None: + num_valid_local = (true_labels != -100).sum().clamp_min(1) + if isinstance(num_items_in_batch, torch.Tensor): + num_items_in_batch = num_items_in_batch.to(loss.device) + loss = loss * num_valid_local / num_items_in_batch + + # Release hidden states after loss computation + del student_hidden, teacher_hidden, true_labels + empty_cache() + if return_outputs: + return (loss, ModelOutput(logits=None, last_hidden_state=student_outputs.last_hidden_state)) + else: + return loss + else: + # compute student output + student_outputs = model( + input_ids=inputs["input_ids"], + attention_mask=inputs["attention_mask"], + ) + + # compute teacher output in eval mode + self.teacher_model.eval() + with torch.no_grad(): + teacher_outputs = self.teacher_model( + input_ids=inputs["input_ids"], + attention_mask=inputs["attention_mask"], + ) + + # Standard causal shift: logits at position i predict the token at i + 1. The `labels != -100` mask + # inside `generalized_jsd_loss` already excludes prompt (and padding) positions, so we do not slice by + # prompt length. Slicing by `inputs["prompts"].shape[1]` (the batch-max prompt width) would drop real + # completion tokens for samples whose prompt is shorter than the batch maximum, since `labels` is padded + # to the full-sequence width independently of `prompts`. + shifted_student_logits = student_outputs.logits[:, :-1, :] + shifted_teacher_logits = teacher_outputs.logits[:, :-1, :] + shifted_labels = inputs["labels"][:, 1:] + + # compute loss + loss = self.generalized_jsd_loss( + student_logits=shifted_student_logits, + teacher_logits=shifted_teacher_logits, + labels=shifted_labels, + beta=self.beta, + num_items_in_batch=num_items_in_batch, + ) + + # empty cache + empty_cache() + + # Return loss + return (loss, student_outputs) if return_outputs else loss + + def _liger_student_forward(self, student, inputs): + """Decoder-only forward used by the Liger JSD path (skips lm_head to save memory).""" + if hasattr(student, "get_decoder") and student.get_decoder() is not None: + decoder = student.get_decoder() + else: + decoder = getattr(student, getattr(student, "base_model_prefix", "model"), student) + return decoder( + input_ids=inputs["input_ids"], + attention_mask=inputs["attention_mask"], + use_cache=False, + ) + + @staticmethod + def generate_on_policy_outputs(model, inputs, generation_config, pad_token_id=None): + # Generate output with respect to the prompt-only + generated_outputs = model.generate( + input_ids=inputs["prompts"], + attention_mask=inputs.get("prompt_attention_mask", None), + generation_config=generation_config, + return_dict_in_generate=True, + ) + + # Get the generated token IDs + generated_tokens = generated_outputs.sequences + # Calculate new attention mask + new_attention_mask = torch.ones_like(generated_tokens) + new_labels = generated_tokens.clone() + + # If there's pad_token_id, set attention mask to 0 for padding tokens + if pad_token_id is not None: + new_labels[new_labels == pad_token_id] = -100 + new_attention_mask[generated_tokens == pad_token_id] = 0 + + # Mask the prompt so only the generated completion contributes to the loss. `generate` echoes + # the prompt back as the first `prompt_length` columns, so masking them with -100 matches the + # collator convention (`labels[:len(prompt)] = -100`) that `compute_loss` relies on. + prompt_length = inputs["prompts"].shape[1] + new_labels[:, :prompt_length] = -100 + + return generated_tokens, new_attention_mask, new_labels + + def training_step( + self, model: nn.Module, inputs: dict[str, torch.Tensor | Any], num_items_in_batch: int | None = None + ) -> torch.Tensor: + """ + Perform a training step for the Generalized Knowledge Distillation (GKD) model. + + This method implements the on-policy learning approach described in the GKD paper. With probability + `self.lmbda`, it generates new responses using the student model, which are then used for training instead of + the original inputs. + """ + if random.random() <= self.lmbda: + with ( + unwrap_model_for_generation( + model, + self.accelerator, + generation_kwargs=self.generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762 + ) as unwrapped_model + ): + new_input_ids, new_attention_mask, new_labels = self.generate_on_policy_outputs( + unwrapped_model, inputs, self.generation_config, self.processing_class.pad_token_id + ) + inputs["input_ids"] = new_input_ids + inputs["attention_mask"] = new_attention_mask + inputs["labels"] = new_labels + elif self.seq_kd: + with ( + unwrap_model_for_generation( + self.teacher_model, + self.accelerator, + generation_kwargs=self.generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762 + ) as unwrapped_model + ): + new_input_ids, new_attention_mask, new_labels = self.generate_on_policy_outputs( + unwrapped_model, inputs, self.generation_config, self.processing_class.pad_token_id + ) + inputs["input_ids"] = new_input_ids + inputs["attention_mask"] = new_attention_mask + inputs["labels"] = new_labels + + loss = super().training_step(model, inputs, num_items_in_batch) + return loss diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gold/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gold/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9c2a8c1149130a77081ed794d02c7d7629d265bb --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gold/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .gold_config import GOLDConfig +from .gold_trainer import GOLDTrainer + + +__all__ = ["GOLDConfig", "GOLDTrainer"] diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gold/gold.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gold/gold.py new file mode 100644 index 0000000000000000000000000000000000000000..4b457acaee39ff4566f05b57102946c69efc89e1 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gold/gold.py @@ -0,0 +1,155 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# /// script +# dependencies = [ +# "trl @ git+https://github.com/huggingface/trl.git", +# "peft", +# "trackio", +# ] +# /// + +# docstyle-ignore +""" +# Full training: +python trl/experimental/gold/gold.py \ + --model_name_or_path meta-llama/Llama-3.2-1B-Instruct \ + --teacher_model_name_or_path Qwen/Qwen2-1.5B-Instruct \ + --dataset_name trl-lib/chatbot_arena_completions \ + --learning_rate 2e-5 \ + --per_device_train_batch_size 4 \ + --gradient_accumulation_steps 8 \ + --output_dir gold-model \ + --num_train_epochs 1 \ + --push_to_hub + +# LoRA: +python trl/experimental/gold/gold.py \ + --model_name_or_path meta-llama/Llama-3.2-1B-Instruct \ + --teacher_model_name_or_path Qwen/Qwen2-1.5B-Instruct \ + --dataset_name trl-lib/chatbot_arena_completions \ + --learning_rate 2e-4 \ + --per_device_train_batch_size 4 \ + --gradient_accumulation_steps 8 \ + --output_dir gold-model \ + --num_train_epochs 1 \ + --push_to_hub \ + --use_peft \ + --lora_r 64 \ + --lora_alpha 16 +""" + +import logging + +from datasets import load_dataset +from transformers import AutoTokenizer, GenerationConfig + +from trl import ( + LogCompletionsCallback, + ModelConfig, + ScriptArguments, + TrlParser, + get_kbit_device_map, + get_peft_config, + get_quantization_config, +) +from trl.experimental.gold.gold_config import GOLDConfig +from trl.experimental.gold.gold_trainer import GOLDTrainer + + +logger = logging.getLogger(__name__) + + +if __name__ == "__main__": + parser = TrlParser((ScriptArguments, GOLDConfig, ModelConfig)) + script_args, training_args, model_args = parser.parse_args_and_config() + + ################ + # Model & Tokenizer + ################ + quantization_config = get_quantization_config(model_args) + model_kwargs = dict( + revision=model_args.model_revision, + trust_remote_code=model_args.trust_remote_code, + attn_implementation=model_args.attn_implementation, + dtype=model_args.dtype, + use_cache=False if training_args.gradient_checkpointing else True, + device_map=get_kbit_device_map() if quantization_config is not None else None, + quantization_config=quantization_config, + ) + training_args.model_init_kwargs = model_kwargs + + if training_args.teacher_tokenizer_name_or_path is None and training_args.use_uld_loss: + training_args.teacher_tokenizer_name_or_path = training_args.teacher_model_name_or_path + teacher_model_kwargs = dict( + revision=training_args.teacher_model_revision, + trust_remote_code=model_args.trust_remote_code, + attn_implementation=model_args.attn_implementation, + dtype=model_args.dtype, + use_cache=True, + device_map=get_kbit_device_map() if quantization_config is not None else None, + quantization_config=quantization_config, + ) + if training_args.teacher_model_init_kwargs is not None: + teacher_model_kwargs.update(training_args.teacher_model_init_kwargs) + training_args.teacher_model_init_kwargs = teacher_model_kwargs + + tokenizer = AutoTokenizer.from_pretrained( + model_args.model_name_or_path, + revision=model_args.model_revision, + trust_remote_code=model_args.trust_remote_code, + ) + if tokenizer.pad_token is None: + tokenizer.pad_token = tokenizer.eos_token + + ################ + # Dataset + ################ + dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config) + + ################ + # Training + ################ + eval_dataset = None + if training_args.eval_strategy != "no": + if script_args.dataset_test_split in dataset: + eval_dataset = dataset[script_args.dataset_test_split] + elif "validation" in dataset: + eval_dataset = dataset["validation"] + elif "dev" in dataset: + eval_dataset = dataset["dev"] + + trainer = GOLDTrainer( + model=model_args.model_name_or_path, + teacher_model=training_args.teacher_model_name_or_path, + args=training_args, + train_dataset=dataset[script_args.dataset_train_split], + eval_dataset=eval_dataset, + processing_class=tokenizer, + peft_config=get_peft_config(model_args), + ) + + if training_args.eval_strategy != "no": + generation_config = GenerationConfig( + max_new_tokens=training_args.max_completion_length, do_sample=True, temperature=training_args.temperature + ) + completions_callback = LogCompletionsCallback(trainer, generation_config, num_prompts=8) + trainer.add_callback(completions_callback) + + trainer.train() + + # Save and push to hub + trainer.save_model(training_args.output_dir) + if training_args.push_to_hub: + trainer.push_to_hub(dataset_name=script_args.dataset_name) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gold/gold_config.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gold/gold_config.py new file mode 100644 index 0000000000000000000000000000000000000000..54d235ae4734075999deb0425a225fc8258555f4 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gold/gold_config.py @@ -0,0 +1,503 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from dataclasses import dataclass, field +from typing import Any + +from ...trainer.sft_config import SFTConfig + + +@dataclass +class GOLDConfig(SFTConfig): + # docstyle-ignore + r""" + Configuration class for [`GOLDTrainer`]. + + This class includes only the parameters that are specific to GOLD training. For a full list of training arguments, + please refer to the [`~transformers.TrainingArguments`] and [`SFTConfig`] documentation. + + Args: + > Parameters that control generation and the training loop + + temperature (`float`, *optional*, defaults to `0.9`): + Temperature for sampling. The higher the temperature, the more random the completions. + top_p (`float`, *optional*, defaults to `0.95`): + If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to + `top_p` or higher are kept for generation. + top_k (`int`, *optional*, defaults to `0`): + Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, top-k-filtering is + disabled and all tokens are considered. + lmbda (`float`, *optional*, defaults to `0.5`): + Lambda parameter that controls the student data fraction (i.e., the proportion of on-policy + student-generated outputs). + beta (`float`, *optional*, defaults to `0.5`): + Interpolation coefficient between `0.0` and `1.0` of the Generalized Jensen-Shannon Divergence loss. When + beta is `0.0`, the loss is the KL divergence. When beta is `1.0`, the loss is the Inverse KL Divergence. + max_completion_length (`int`, *optional*, defaults to `128`): + Maximum number of tokens to generate per completion. + teacher_model_name_or_path (`str`, *optional*): + Model name or path of the teacher model. If `None`, the teacher model will be the same as the model being + trained. + teacher_model_revision (`str` or `None`, *optional*, defaults to `None`): + Model revision of the teacher model (e.g., branch name, tag, or commit hash). If `None`, the default + revision is used. + teacher_model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the teacher model + from a string. + teacher_tokenizer_name_or_path (`str`, *optional*): + Tokenizer name or path for the teacher model. If None when using ULD loss, will use the same tokenizer as + the student model (not recommended for cross-tokenizer distillation). + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the model. + seq_kd (`bool`, *optional*, defaults to `False`): + Seq_kd parameter that controls whether to perform Sequence-Level KD (can be viewed as supervised FT on + teacher-generated output). + num_generations (`int`, *optional*, defaults to `1`): + Number of generations per prompt. Each prompt is repeated this many times in the generation batch. + generation_batch_size (`int` or `None`, *optional*, defaults to `None`): + Number of unique prompts per worker per optimizer step. If `None`, it is computed from + `(per_device_train_batch_size * gradient_accumulation_steps) // num_generations`. + > Parameters that control the ULD loss + + use_uld_loss (`bool`, *optional*, defaults to `False`): + Whether to use Universal Logit Distillation (ULD) loss instead of Generalized Jensen-Shannon Divergence + loss. + use_extended_uld (`bool`, *optional*, defaults to `True`): + Whether to enable extended ULD alignment that uses tokenizers to align and merge token probabilities + across student and teacher tokenizations. When `True`, the trainer will compute token mappings and merge + probabilities for split tokens; when `False`, ULD will use simple positional truncation like in the + original ULD paper. + uld_use_hybrid_loss (`bool`, *optional*, defaults to `False`): + Whether to use a hybrid loss that combines ULD loss and JSD loss. When `True`, the final loss is a + combination of JSD for known token mappings and ULD for unknown token mappings. + uld_hybrid_matched_weight (`float` or `None`, *optional*): + Weight for the matched token loss component when using hybrid ULD + JSD loss. This weight scales the JSD + loss computed over tokens that have a direct mapping between student and teacher tokenizations. If `None`, + uses adaptive weighting based on vocabulary overlap. Must be set together with + `uld_hybrid_unmatched_weight` (both `None` or both `float`). + uld_hybrid_unmatched_weight (`float` or `None`, *optional*): + Weight for the unmatched token loss component when using hybrid ULD + JSD loss. This weight scales the ULD + loss computed over tokens that do not have a direct mapping between student and teacher tokenizations. If + `None`, uses adaptive weighting based on vocabulary overlap. Must be set together with + `uld_hybrid_matched_weight` (both `None` or both `float`). + uld_crossentropy_weight (`float`, *optional*, defaults to `0.0`): + Weight for the cross-entropy loss component in ULD loss. If 0, only ULD distillation loss is used. + uld_distillation_weight (`float`, *optional*, defaults to `1.0`): + Weight for the distillation loss component in ULD loss. + uld_student_temperature (`float`, *optional*, defaults to `1.0`): + Temperature for student logits in ULD loss computation. + uld_teacher_temperature (`float`, *optional*, defaults to `1.0`): + Temperature for teacher logits in ULD loss computation. + uld_skip_student_eos (`bool`, *optional*, defaults to `True`): + Whether to skip EOS token for student in ULD loss computation. + uld_skip_teacher_eos (`bool`, *optional*, defaults to `True`): + Whether to skip EOS token for teacher in ULD loss computation. + > Parameters that control vLLM integration + + use_vllm (`bool`, *optional*, defaults to `False`): + Whether to use vLLM for generating completions from the student model. Requires `vllm` to be installed. + vllm_mode (`str`, *optional*, defaults to `"colocate"`): + Mode for student vLLM integration. Either `"server"` (connect to a running TRL vLLM server) or `"colocate"` + (run vLLM in the same process). + vllm_server_host (`str`, *optional*, defaults to `"0.0.0.0"`): + Host of the vLLM server for the student model (if `vllm_mode="server"`). + vllm_server_port (`int`, *optional*, defaults to `8001`): + Port of the vLLM server for the student model (if `vllm_mode="server"`). + vllm_server_timeout (`float`, *optional*, defaults to `240.0`): + Timeout for connecting to the student vLLM server (if `vllm_mode="server"`). + vllm_gpu_memory_utilization (`float`, *optional*, defaults to `0.9`): + GPU memory utilization for the colocated student vLLM engine (if `vllm_mode="colocate"`). It is recommended + to set this to a low value if the student and teacher models share the same GPU. + vllm_tensor_parallel_size (`int`, *optional*, defaults to `1`): + Tensor parallel size for the colocated student vLLM engine (if `vllm_mode="colocate"`). + vllm_structured_outputs_regex (`str`, *optional*): + Regex for vLLM structured outputs for the student model. + vllm_server_base_url (`str`, *optional*): + Base URL for the vLLM server (e.g., `"http://localhost:8001"`). If provided, `vllm_server_host` and + `vllm_server_port` are ignored. + vllm_group_port (`int`, *optional*, defaults to `51216`): + Port for the vLLM weight-update group (NCCL communicator). Unless the port is occupied, there is no need to + change it. + vllm_max_model_length (`int`, *optional*): + Maximum model sequence length for the colocated vLLM engine when `vllm_mode="colocate"`. Defaults to the + model's maximum context length. + vllm_model_impl (`str`, *optional*, defaults to `"vllm"`): + Model implementation backend to use in vLLM. Use `"vllm"` (default) or `"transformers"`. + vllm_sync_frequency (`int`, *optional*, defaults to `1`): + Frequency (in training steps) to synchronize student model weights to vLLM engine. Set to 1 to sync after + every step. + vllm_enable_sleep_mode (`bool`, *optional*, defaults to `False`): + Enable vLLM sleep mode to offload student weights/cache during the optimizer step. Keeps GPU memory usage + low, but waking the engine adds host–device transfer latency. + + > Parameters that control 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`. + log_completions_steps (`int`, *optional*, defaults to `100`): + Number of steps between logging (prompt, completion) pairs. Only used if `log_completions` is set to + `True`. + num_completions_to_print (`int` or `None`, *optional*): + Number of completions to print with `rich`. If `None`, all completions are logged. + wandb_log_unique_prompts (`bool`, *optional*, defaults to `True`): + Whether to log the unique prompts to wandb. This will create a new run for each unique prompt. + callbacks (`list[str]`, *optional*, defaults to `[]`): + The callbacks to run during training. + + > [!NOTE] + > These parameters have default values different from [`~transformers.TrainingArguments`]: + > - `learning_rate`: Defaults to `1e-7` instead of `5e-5`. + """ + + _VALID_DICT_FIELDS = SFTConfig._VALID_DICT_FIELDS + ["teacher_model_init_kwargs"] + + # Parameters whose default values are overridden from TrainingArguments + learning_rate: float = field( + default=1e-7, + metadata={"help": "The initial learning rate for AdamW."}, + ) + + # GOLD-specific parameters + temperature: float = field( + default=0.9, + metadata={"help": "Temperature for sampling. The higher the temperature, the more random the completions."}, + ) + top_p: float = field( + default=0.95, + metadata={ + "help": "If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to " + "`top_p` or higher are kept for generation." + }, + ) + top_k: int = field( + default=0, + metadata={ + "help": "Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, " + "top-k-filtering is disabled and all tokens are considered." + }, + ) + lmbda: float = field( + default=0.5, + metadata={ + "help": "Lambda parameter that controls the student data fraction (i.e., the proportion of on-policy " + "student-generated outputs)." + }, + ) + beta: float = field( + default=0.5, + metadata={ + "help": "Interpolation coefficient between `0.0` and `1.0` of the Generalized Jensen-Shannon Divergence " + "loss. When beta is `0.0`, the loss is the KL divergence. When beta is `1.0`, the loss is the Inverse KL " + "Divergence." + }, + ) + max_completion_length: int = field( + default=128, + metadata={"help": "Maximum number of tokens to generate per completion."}, + ) + teacher_model_name_or_path: str | None = field( + default=None, + metadata={ + "help": "Model name or path of the teacher model. If `None`, the teacher model will be the same as the " + "model being trained." + }, + ) + teacher_model_revision: str | None = field( + default=None, + metadata={ + "help": "Model revision of the teacher model (e.g., branch name, tag, or commit hash). If `None`, the " + "default revision is used." + }, + ) + teacher_model_init_kwargs: dict[str, Any] | str | None = field( + default=None, + metadata={ + "help": "Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the " + "teacher model from a string." + }, + ) + teacher_tokenizer_name_or_path: str | None = field( + default=None, + metadata={ + "help": "Tokenizer name or path for the teacher model. If None when using ULD loss, will use the same " + "tokenizer as the student model (not recommended for cross-tokenizer distillation)." + }, + ) + disable_dropout: bool = field( + default=True, + metadata={"help": "Whether to disable dropouts in `model`."}, + ) + seq_kd: bool = field( + default=False, + metadata={ + "help": "Seq_kd parameter that controls whether to perform Sequence-Level KD (can be viewed as supervised " + "FT on teacher-generated output)." + }, + ) + num_generations: int = field( + default=1, + metadata={ + "help": "Number of generations per prompt. Increasing this will decrease the number of unique prompts per optimization step." + }, + ) + generation_batch_size: int | None = field( + default=None, + metadata={ + "help": "Number of unique prompts per worker per optimizer step. " + "If None, computed from (per_device_train_batch_size * gradient_accumulation_steps) // num_generations." + }, + ) + + # ULD Loss parameters + use_uld_loss: bool = field( + default=False, + metadata={ + "help": "Whether to use Universal Logit Distillation (ULD) loss instead of Generalized Jensen-Shannon Divergence loss." + }, + ) + use_extended_uld: bool = field( + default=True, + metadata={ + "help": ( + "Whether to enable extended ULD alignment that uses tokenizers to align and merge token " + "probabilities across student and teacher tokenizations. When True, the trainer will compute " + "token mappings and merge probabilities for split tokens; when False, ULD will use simple " + "positional truncation like in the original ULD paper." + ) + }, + ) + uld_use_hybrid_loss: bool = field( + default=False, + metadata={ + "help": ( + "Whether to use a hybrid loss that combines ULD loss and JSD loss. When True, the final loss is a " + "a combination of JSD for known token mappings and ULD for unknown token mappings." + ) + }, + ) + uld_hybrid_matched_weight: float | None = field( + default=None, + metadata={ + "help": ( + "Weight for the matched token loss component when using hybrid ULD + JSD loss. This weight scales " + "the JSD loss computed over tokens that have a direct mapping between student and teacher " + "tokenizations. If None, uses adaptive weighting based on vocabulary overlap. Must be set together " + "with uld_hybrid_unmatched_weight (both None or both float)." + ) + }, + ) + uld_hybrid_unmatched_weight: float | None = field( + default=None, + metadata={ + "help": ( + "Weight for the unmatched token loss component when using hybrid ULD + JSD loss. This weight scales " + "the ULD loss computed over tokens that do not have a direct mapping between student and teacher " + "tokenizations. If None, uses adaptive weighting based on vocabulary overlap. Must be set together " + "with uld_hybrid_matched_weight (both None or both float)." + ) + }, + ) + uld_crossentropy_weight: float = field( + default=0.0, + metadata={"help": "Weight for the cross-entropy loss component in ULD loss."}, + ) + uld_distillation_weight: float = field( + default=1.0, + metadata={"help": "Weight for the distillation loss component in ULD loss."}, + ) + uld_student_temperature: float = field( + default=1.0, + metadata={"help": "Temperature for student logits in ULD loss computation."}, + ) + uld_teacher_temperature: float = field( + default=1.0, + metadata={"help": "Temperature for teacher logits in ULD loss computation."}, + ) + + uld_skip_student_eos: bool = field( + default=True, + metadata={"help": "Whether to skip EOS token for student in ULD loss computation."}, + ) + uld_skip_teacher_eos: bool = field( + default=True, + metadata={"help": "Whether to skip EOS token for teacher in ULD loss computation."}, + ) + + # vLLM parameters + use_vllm: bool = field( + default=False, + metadata={"help": "Whether to use vLLM for generating completions. Requires `vllm` to be installed."}, + ) + vllm_mode: str = field( + default="colocate", + metadata={ + "help": 'Mode for vLLM integration. Either "server" (connect to a running TRL vLLM server) or "colocate" (run vLLM in the same process).' + }, + ) + vllm_server_base_url: str | None = field( + default=None, + metadata={ + "help": 'Base URL for the vLLM server (e.g., "http://localhost:8001"). If provided, vllm_server_host and vllm_server_port are ignored.' + }, + ) + vllm_server_host: str = field( + default="0.0.0.0", + metadata={"help": 'Host of the vLLM server when `vllm_mode="server"`.'}, + ) + vllm_server_port: int = field( + default=8001, + metadata={"help": 'Port of the vLLM server when `vllm_mode="server"`.'}, + ) + vllm_server_timeout: float = field( + default=240.0, + metadata={"help": 'Timeout (in seconds) for connecting to the vLLM server when `vllm_mode="server"`.'}, + ) + vllm_group_port: int = field( + default=51216, + metadata={"help": "Port for the vLLM weight-update group (NCCL communicator)."}, + ) + vllm_gpu_memory_utilization: float = field( + default=0.9, + metadata={ + "help": 'GPU memory utilization for the colocated vLLM engine when `vllm_mode="colocate"`. Lower values reduce contention when sharing a device with the student/teacher models.' + }, + ) + vllm_tensor_parallel_size: int = field( + default=1, + metadata={"help": 'Tensor parallel size for the colocated vLLM engine when `vllm_mode="colocate"`.'}, + ) + vllm_max_model_length: int | None = field( + default=None, + metadata={ + "help": 'Maximum model sequence length for the colocated vLLM engine when `vllm_mode="colocate"`. Defaults to the model\'s maximum context length.' + }, + ) + vllm_model_impl: str = field( + default="vllm", + metadata={"help": 'Model implementation backend to use in vLLM. Use "vllm" (default) or "transformers".'}, + ) + vllm_structured_outputs_regex: str | None = field( + default=None, + metadata={"help": "Regex pattern used for vLLM structured outputs (optional)."}, + ) + vllm_sync_frequency: int = field( + default=1, + metadata={ + "help": "Frequency (in training steps) to synchronize model weights to the vLLM engine. Set to 1 to sync after every step." + }, + ) + vllm_enable_sleep_mode: bool = field( + default=False, + metadata={ + "help": "Enable vLLM sleep mode to offload student weights/cache during the optimizer step. Keeps GPU " + "memory usage low, but waking the engine adds host–device transfer latency." + }, + ) + # Parameters that control the logging + log_completions: bool = field( + default=False, + metadata={ + "help": "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`." + }, + ) + log_completions_steps: int = field( + default=100, + metadata={ + "help": "Number of steps between logging (prompt, completion) pairs. Only used if `log_completions` is " + "set to `True`." + }, + ) + num_completions_to_print: int | None = field( + default=None, + metadata={"help": "Number of completions to print with `rich`. If `None`, all completions are logged."}, + ) + wandb_log_unique_prompts: bool = field( + default=True, + metadata={ + "help": ("Whether to log the unique prompts to wandb. This will create a new run for each unique prompt.") + }, + ) + callbacks: list[str] = field( + default_factory=lambda: [], + metadata={"help": "The callbacks to run during training."}, + ) + + def __post_init__(self): + super().__post_init__() + + # check lmbda and beta are in the range [0, 1] + if self.lmbda < 0.0 or self.lmbda > 1.0: + raise ValueError("lmbda must be in the range [0.0, 1.0].") + if self.beta < 0.0 or self.beta > 1.0: + raise ValueError("beta must be in the range [0.0, 1.0].") + + # Validate that max_length is sufficient for max_completion_length + if self.max_length is not None and self.max_completion_length >= self.max_length: + raise ValueError( + f"max_completion_length ({self.max_completion_length}) must be smaller than max_length ({self.max_length}) " + f"to leave room for the prompt. Consider increasing max_length or reducing max_completion_length." + ) + + if self.num_generations < 1: + raise ValueError(f"num_generations must be at least 1, got {self.num_generations}.") + local_sequence_batch_size = self.per_device_train_batch_size * self.gradient_accumulation_steps + if self.generation_batch_size is None: + self.generation_batch_size = local_sequence_batch_size // self.num_generations + if self.generation_batch_size < 1: + raise ValueError( + f"generation_batch_size must be at least 1. Got generation_batch_size={self.generation_batch_size}." + ) + if self.generation_batch_size * self.num_generations != local_sequence_batch_size: + raise ValueError( + "generation_batch_size and num_generations must exactly partition the local optimizer-step batch. " + "Expected generation_batch_size * num_generations == per_device_train_batch_size * " + f"gradient_accumulation_steps, got {self.generation_batch_size} * {self.num_generations} != " + f"{self.per_device_train_batch_size} * {self.gradient_accumulation_steps}." + ) + if self.num_generations > 1 and self.lmbda < 1.0: + warnings.warn( + f"num_generations={self.num_generations} with lmbda={self.lmbda} means off-policy batches include " + f"{self.num_generations} copies of each sample; consider lmbda=1.0 when num_generations > 1.", + UserWarning, + stacklevel=2, + ) + + # Validate ULD parameters + if self.use_uld_loss: + if self.uld_crossentropy_weight < 0.0: + raise ValueError("uld_crossentropy_weight must be non-negative.") + if self.uld_distillation_weight < 0.0: + raise ValueError("uld_distillation_weight must be non-negative.") + if self.uld_student_temperature <= 0.0: + raise ValueError("uld_student_temperature must be positive.") + if self.uld_teacher_temperature <= 0.0: + raise ValueError("uld_teacher_temperature must be positive.") + + # Validate hybrid loss weights - both must be None or both must be set + if self.uld_use_hybrid_loss: + if (self.uld_hybrid_matched_weight is None) != (self.uld_hybrid_unmatched_weight is None): + raise ValueError( + "uld_hybrid_matched_weight and uld_hybrid_unmatched_weight must both be None (for adaptive " + "weighting) or both be set to numeric values. Got uld_hybrid_matched_weight=" + f"{self.uld_hybrid_matched_weight} and uld_hybrid_unmatched_weight=" + f"{self.uld_hybrid_unmatched_weight}." + ) + if self.uld_hybrid_matched_weight is not None: + if self.uld_hybrid_matched_weight < 0.0: + raise ValueError("uld_hybrid_matched_weight must be non-negative.") + if self.uld_hybrid_unmatched_weight < 0.0: + raise ValueError("uld_hybrid_unmatched_weight must be non-negative.") diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gold/gold_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gold/gold_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..487bf8ead97c78da5a3eade1f906d3d63dbedb9c --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gold/gold_trainer.py @@ -0,0 +1,2040 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import random +import textwrap +from collections import defaultdict, deque +from collections.abc import Callable +from contextlib import nullcontext +from functools import partial +from itertools import takewhile +from typing import Any, Optional + +import torch +import torch.distributed as dist +import torch.nn as nn +import torch.nn.functional as F +from accelerate import PartialState +from accelerate.utils import DistributedType, broadcast_object_list, gather_object +from datasets import Dataset, IterableDataset +from torch.utils.data import DataLoader +from transformers import AutoTokenizer, TrainerCallback +from transformers.data.data_collator import DataCollator +from transformers.feature_extraction_utils import FeatureExtractionMixin +from transformers.generation.configuration_utils import GenerationConfig +from transformers.image_processing_utils import BaseImageProcessor +from transformers.integrations.integration_utils import is_wandb_available +from transformers.modeling_utils import PreTrainedModel +from transformers.processing_utils import ProcessorMixin +from transformers.tokenization_utils_base import PreTrainedTokenizerBase +from transformers.trainer_utils import EvalPrediction, seed_worker +from transformers.utils import is_datasets_available, is_liger_kernel_available, is_peft_available, is_rich_available + +from ...data_utils import is_conversational, maybe_convert_to_chatml, pack_dataset +from ...extras.profiling import profiling_decorator +from ...generation.vllm_generation import VLLMGeneration +from ...import_utils import is_vllm_available +from ...models import prepare_deepspeed +from ...models.utils import _ForwardRedirection, unwrap_model_for_generation +from ...trainer.sft_trainer import SFTTrainer +from ...trainer.utils import ( + RepeatSampler, + create_model_from_path, + disable_dropout_in_model, + pad, + split_tensor_dict, +) +from ..utils import ( + DataCollatorForChatML, + empty_cache, + encode_with_byte_offsets, + pad_byte_offsets, + piece_byte_len, +) +from .gold_config import GOLDConfig + + +if is_peft_available(): + from peft import PeftConfig + +if is_wandb_available(): + import wandb + + +if is_liger_kernel_available(): + from liger_kernel.chunked_loss import LigerFusedLinearJSDLoss + +if is_rich_available(): + from rich.console import Console + from rich.panel import Panel + from rich.table import Table + from rich.text import Text + + +def print_prompt_completions_sample_uld( + prompts: list[str], + completions: list[str], + step: int, + num_samples: int = None, +) -> None: + """ + Print out a sample of model completions to the console. + + This function creates a nicely formatted table showing prompt-completion pairs, useful for monitoring model outputs + during training. It requires the `rich` library to be installed. + + Args: + prompts (`list[str]`): + List of prompts. + completions (`list[str]`): + List of completions corresponding to the prompts. + step (`int`): + Current training step number, used in the output title. + num_samples (`int` or `None`, *optional*, defaults to `None`): + Number of random samples to display. If `None` (default), all items will be displayed. + + Example: + ```python + >>> from trl.experimental.gold.gold_trainer import print_prompt_completions_sample_uld + + >>> prompts = ["The sky is", "The sun is"] + >>> completions = [" blue.", " in the sky."] + >>> print_prompt_completions_sample_uld(prompts, completions, 42) + ╭─────────── Step 42 ───────────╮ + │ ┏━━━━━━━━━━━━┳━━━━━━━━━━━━━━┓ │ + │ ┃ Prompt ┃ Completion ┃ │ + │ ┡━━━━━━━━━━━━╇━━━━━━━━━━━━━━┩ │ + │ │ The sky is │ blue. │ │ + │ ├────────────┼──────────────┤ │ + │ │ The sun is │ in the sky. │ │ + │ └────────────┴──────────────┘ │ + ╰───────────────────────────────╯ + ``` + """ + if not is_rich_available(): + raise ImportError( + "The function `print_prompt_completions_sample_uld` requires the `rich` library. Please install it with " + "`pip install rich`." + ) + console = Console() + table = Table(show_header=True, header_style="bold white", expand=True) + + # Add columns + table.add_column("Prompt", style="bright_yellow") + table.add_column("Completion", style="bright_green") + + # Some basic input validation + if num_samples is not None: + if num_samples >= len(prompts): + num_samples = None + elif num_samples <= 0: + return + + # Subsample data if num_samples is specified + if num_samples is not None: + indices = random.sample(range(len(prompts)), num_samples) + prompts = [prompts[i] for i in indices] + completions = [completions[i] for i in indices] + + for i in range(len(prompts)): + table.add_row(Text(prompts[i]), Text(completions[i])) + table.add_section() # Adds a separator between rows + + panel = Panel(table, expand=False, title=f"Step {step}", border_style="bold white") + console.print(panel) + + +def build_teacher_inputs_from_texts( + tokenizer: PreTrainedTokenizerBase, + prompt_texts: list[str], + completion_texts: list[str], +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Tokenize teacher prompts/completions and produce tensors ready for GOLD loss. + + Returns ``(input_ids, labels, attention_mask, byte_offsets)``. ``byte_offsets`` is a ``[batch, seq, 2]`` tensor of + UTF-8 byte ``(start, end)`` for each token: prompt and padding positions are filled with ``(0, 0)``; completion + tokens carry offsets relative to the corresponding ``completion_text``; the appended EOS gets ``(content_len, + content_len)``. Byte offsets are derived from the fast tokenizer's char offsets via ``encode_with_byte_offsets``. + """ + + pad_token_id = tokenizer.pad_token_id + eos_token_id = tokenizer.eos_token_id + backend = tokenizer.backend_tokenizer + + prompt_token_ids = tokenizer(prompt_texts, add_special_tokens=True)["input_ids"] + completion_encs = encode_with_byte_offsets(backend, completion_texts, add_special_tokens=False) + + sequences: list[torch.Tensor] = [] + attention_masks: list[torch.Tensor] = [] + labels_list: list[torch.Tensor] = [] + offsets_list: list[list[tuple[int, int]]] = [] + + for prompt_ids, (enc_ids, enc_offs), completion_text in zip( + prompt_token_ids, completion_encs, completion_texts, strict=True + ): + # Remove trailing EOS from prompt so completions can extend cleanly + if eos_token_id is not None and prompt_ids and prompt_ids[-1] == eos_token_id: + prompt_ids = prompt_ids[:-1] + + completion_ids = list(enc_ids) + completion_offs = list(enc_offs) + content_len = len(completion_text.encode("utf-8")) + + sequence = list(prompt_ids) + completion_ids + offsets = [(0, 0)] * len(prompt_ids) + completion_offs + if eos_token_id is not None: + sequence.append(eos_token_id) + offsets.append((content_len, content_len)) + + seq_tensor = torch.tensor(sequence, dtype=torch.long) + sequences.append(seq_tensor) + attention_masks.append(torch.ones_like(seq_tensor)) + offsets_list.append(offsets) + + labels = seq_tensor.clone() + labels[: len(prompt_ids)] = -100 + if pad_token_id is not None: + labels[labels == pad_token_id] = -100 + labels_list.append(labels) + + teacher_input_ids = pad( + sequences, + padding_side="right", + padding_value=pad_token_id if pad_token_id is not None else 0, + ) + teacher_attention_mask = pad(attention_masks, padding_side="right", padding_value=0).bool() + teacher_labels = pad(labels_list, padding_side="right", padding_value=-100) + + if eos_token_id is not None: + for row in range(teacher_attention_mask.size(0)): + valid = ( + teacher_input_ids[row] != pad_token_id + if pad_token_id is not None + else teacher_attention_mask[row].bool() + ) + if valid.any(): + last_idx = valid.nonzero(as_tuple=True)[0][-1] + teacher_attention_mask[row, last_idx + 1 :] = False + + target_len = teacher_input_ids.size(1) + teacher_byte_offsets = torch.stack( + [pad_byte_offsets(offs, target_len, padding_side="right") for offs in offsets_list], + dim=0, + ) + + return teacher_input_ids, teacher_labels, teacher_attention_mask, teacher_byte_offsets + + +class ULDLoss(nn.Module): + """ + Universal Logit Distillation Loss. + """ + + def __init__(self, config: GOLDConfig, student_tokenizer=None, teacher_tokenizer=None, device=None): + super().__init__() + self.device = device + self.crossentropy_weight = config.uld_crossentropy_weight + self.distillation_weight = config.uld_distillation_weight + self.student_temperature = config.uld_student_temperature + self.teacher_temperature = config.uld_teacher_temperature + self.skip_student_eos = config.uld_skip_student_eos + self.skip_teacher_eos = config.uld_skip_teacher_eos + self.use_extended_uld = config.use_extended_uld + self.ignore_index = -100 + + # Add tokenizers for enhanced alignment + self.student_tokenizer = student_tokenizer + self.teacher_tokenizer = teacher_tokenizer + + # Hybrid ULD configuration + self.use_hybrid_loss = getattr(config, "uld_use_hybrid_loss", False) + self.hybrid_matched_weight = getattr(config, "uld_hybrid_matched_weight", None) + self.hybrid_unmatched_weight = getattr(config, "uld_hybrid_unmatched_weight", None) + self.beta = getattr(config, "beta", 1.0) # For JSD loss in hybrid matched tokens + + # Initialize vocabulary mapping for hybrid loss + self._vocab_mapping = None + self._teacher_matched_ids = None + self._student_matched_ids = None + if self.use_hybrid_loss and student_tokenizer is not None and teacher_tokenizer is not None: + self._initialize_vocabulary_mapping() + + def __call__( + self, + student_logits, + teacher_logits, + student_labels, + teacher_labels, + student_input_ids, + teacher_input_ids, + student_byte_offsets=None, + teacher_byte_offsets=None, + ): + """ + Compute ULD loss with GKD trainer interface. + + Args: + student_logits: Student model logits [batch_size, seq_len, vocab_size] + teacher_logits: Teacher model logits [batch_size, seq_len, vocab_size] + student_labels: Student target labels [batch_size, seq_len] + teacher_labels: Teacher target labels [batch_size, seq_len] + student_input_ids: Student input token IDs [batch_size, seq_len] + teacher_input_ids: Teacher input token IDs [batch_size, seq_len] + student_byte_offsets: Per-token UTF-8 byte offsets ``[batch, seq, 2]`` + from the data collator (relative to the rendered chat-template message). Required. + teacher_byte_offsets: Per-sample list of completion-relative byte + offsets (one list per batch item) from ``build_teacher_inputs_from_texts``. Required. + + Returns: + Total loss (cross-entropy + distillation) + """ + # Compute cross-entropy loss for student + if self.crossentropy_weight > 0: + shift_logits = student_logits[..., :-1, :].contiguous() + shift_labels = student_labels[..., 1:].contiguous() + loss_fct = nn.CrossEntropyLoss(ignore_index=self.ignore_index) + crossentropy_loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1)) + crossentropy_loss = self.crossentropy_weight * crossentropy_loss + else: + crossentropy_loss = 0.0 + + # Compute distillation loss using ULD approximation + distillation_loss = self._compute_distillation_loss( + student_logits, + teacher_logits, + student_labels, + teacher_labels, + student_input_ids, + teacher_input_ids, + student_byte_offsets=student_byte_offsets, + teacher_byte_offsets=teacher_byte_offsets, + ) + + return crossentropy_loss + distillation_loss + + def _initialize_vocabulary_mapping(self): + """Initialize vocabulary mapping for hybrid ULD loss.""" + # Computing vocabulary mapping for hybrid ULD + + student_vocab = self.student_tokenizer.get_vocab() + teacher_vocab = self.teacher_tokenizer.get_vocab() + + # Create reverse mapping for student + student_token_to_id = dict(student_vocab.items()) + + vocab_mapping = {} + teacher_matched_ids = set() + student_matched_ids = set() + + for token_str, teacher_id in teacher_vocab.items(): + if token_str in student_token_to_id: + student_id = student_token_to_id[token_str] + vocab_mapping[teacher_id] = student_id + teacher_matched_ids.add(teacher_id) + student_matched_ids.add(student_id) + + self._vocab_mapping = vocab_mapping + self._teacher_matched_ids = teacher_matched_ids + self._student_matched_ids = student_matched_ids + + max_matched_teacher_id = max(self._vocab_mapping.keys()) + self.mapping_tensor = torch.full((max_matched_teacher_id + 1,), -1, dtype=torch.long) # -1 for unmapped ids + for k, v in self._vocab_mapping.items(): + self.mapping_tensor[k] = v + if self.device is not None: + self.mapping_tensor = self.mapping_tensor.to(self.device) + + def _compute_distillation_loss( + self, + student_logits, + teacher_logits, + student_labels, + teacher_labels, + student_input_ids, + teacher_input_ids, + student_byte_offsets=None, + teacher_byte_offsets=None, + ): + """ + Compute the Universal Logit Distillation loss with token mapping. + + This version uses actual input_ids for accurate token mapping and multiplies probabilities for split tokens. + Both student_input_ids and teacher_input_ids are required for optimal alignment. + """ + # Get answer regions (same as original) + student_answer_index, student_answer_size = self._get_start_and_size_answers(student_labels) + teacher_answer_index, teacher_answer_size = self._get_start_and_size_answers(teacher_labels) + + if self.skip_student_eos: + student_answer_size = [size - 1 for size in student_answer_size] + if self.skip_teacher_eos: + teacher_answer_size = [size - 1 for size in teacher_answer_size] + + # Handle edge case where all answer sizes are 0 + if ( + not student_answer_size + or not teacher_answer_size + or max(max(student_answer_size), max(teacher_answer_size)) <= 0 + ): + return torch.zeros(1, device=student_logits.device, requires_grad=True) * student_logits.sum() * 1e-8 + + batch_size = student_logits.size(0) + distillation_losses = [] + + for i in range(batch_size): + # Get answer regions for this batch item + student_start = student_answer_index[i] + student_size = student_answer_size[i] + teacher_start = teacher_answer_index[i] + teacher_size = teacher_answer_size[i] + + if student_size <= 0 or teacher_size <= 0: + loss_i = student_logits[i].sum() * 0.0 + distillation_losses.append(loss_i) + continue + + # Extract answer logits + student_answer_logits = student_logits[i, student_start : student_start + student_size] + teacher_answer_logits = teacher_logits[i, teacher_start : teacher_start + teacher_size] + + # Convert to probabilities + student_probs = F.softmax(student_answer_logits / self.student_temperature, dim=-1) + teacher_probs = F.softmax(teacher_answer_logits / self.teacher_temperature, dim=-1) + + # Pass actual input_ids so split-token groups can multiply conditional probabilities. + student_token_ids = student_input_ids[i, student_start : student_start + student_size].tolist() + teacher_token_ids = teacher_input_ids[i, teacher_start : teacher_start + teacher_size].tolist() + + if self.use_extended_uld: + if student_byte_offsets is None or teacher_byte_offsets is None: + raise ValueError("Byte offsets are required when `use_extended_uld=True`.") + + # Both sides are completion-relative, so plain slicing gives a shared byte coordinate system. + s_answer = student_byte_offsets[i, student_start : student_start + student_size].tolist() + t_answer = teacher_byte_offsets[i, teacher_start : teacher_start + teacher_size].tolist() + student_groups, teacher_groups = self._align_by_byte_offsets(s_answer, t_answer) + # Drop degenerate pairs where either side is empty — e.g. teacher's trailing zero-width EOS at + # ``(content_len, content_len)`` paired with an empty student group merges to a zero distribution + # and inflates the loss (only reachable when ``skip_teacher_eos=False``). + paired = [(sg, tg) for sg, tg in zip(student_groups, teacher_groups, strict=False) if sg and tg] + student_groups = [sg for sg, _ in paired] + teacher_groups = [tg for _, tg in paired] + student_aligned = self._merge_probabilities_with_alignment_groups( + student_probs, student_groups, student_token_ids + ) + teacher_aligned = self._merge_probabilities_with_alignment_groups( + teacher_probs, teacher_groups, teacher_token_ids + ) + else: + min_length = min(len(student_token_ids), len(teacher_token_ids)) + student_aligned = student_probs[:min_length, :] + teacher_aligned = teacher_probs[:min_length, :] + + # Apply ULD loss computation + if self.use_hybrid_loss and self._vocab_mapping is not None: + # Use hybrid approach: direct comparison for matched tokens, sorting for unmatched + aligned_loss = self._compute_hybrid_uld_loss(student_aligned, teacher_aligned) + else: + # Original approach: sort all probabilities + student_sorted = student_aligned.sort(dim=-1, descending=True).values + teacher_sorted = teacher_aligned.sort(dim=-1, descending=True).values + + # Pad vocabularies to same size + student_vocab_size = student_sorted.size(-1) + teacher_vocab_size = teacher_sorted.size(-1) + max_vocab_size = max(student_vocab_size, teacher_vocab_size) + + if student_vocab_size < max_vocab_size: + student_sorted = F.pad(student_sorted, (0, max_vocab_size - student_vocab_size)) + if teacher_vocab_size < max_vocab_size: + teacher_sorted = F.pad(teacher_sorted, (0, max_vocab_size - teacher_vocab_size)) + + # Compute L1 distance (ULD approach) + aligned_loss = F.l1_loss(student_sorted, teacher_sorted, reduction="sum") + aligned_loss /= student_aligned.size(0) # Normalize by sequence length + distillation_losses.append(aligned_loss) + + distillation_loss = torch.stack(distillation_losses).mean() + return self.distillation_weight * distillation_loss + + @staticmethod + def _align_by_byte_offsets(s_offsets, t_offsets): + """ + Walk both byte-offset arrays, advancing the side whose current token ends earlier. A group closes when both + sides reach the same byte boundary — the points where the two tokenizers agree on a split. + """ + s_groups, t_groups = [], [] + s_start = t_start = s = t = 0 + n_s, n_t = len(s_offsets), len(t_offsets) + while s < n_s and t < n_t: + s_end, t_end = s_offsets[s][1], t_offsets[t][1] + if s_end < t_end: + s += 1 + elif s_end > t_end: + t += 1 + else: + s += 1 + t += 1 + s_groups.append(list(range(s_start, s))) + t_groups.append(list(range(t_start, t))) + s_start, t_start = s, t + if s < n_s or t < n_t: + s_groups.append(list(range(s_start, n_s))) + t_groups.append(list(range(t_start, n_t))) + return s_groups, t_groups + + def _merge_probabilities_with_alignment_groups(self, probs, alignment_groups, token_ids=None): + """ + Merge probabilities based on alignment groups with corrected conditional probability handling. + + For a group merging tokens at positions [i, i+1, ..., i+k], we compute: + P_merged(y | x) = P(y | x) × P(token_{i+1} | token_i, x) × ... × P(token_{i+k} | ..., x) + + Where: + - P(y | x) is the marginal probability distribution over all vocabulary tokens at position i + - token_{i+1}, ..., token_{i+k} are the ACTUAL tokens that were generated + - The conditional probabilities P(token_j | ..., x) are extracted as SCALARS + - y ranges over all vocabulary tokens at position i + + This ensures the probability of the actual generated sequence is correct (by the chain rule), while introducing + a known bias for counterfactual tokens (since we don't have P(token_{i+k} | y, x) for y != token_i). The merged + distribution is unnormalized but preserves correct relative probabilities. + + Args: + probs: Probability tensor [seq_len, vocab_size] + alignment_groups: List of alignment groups (each group is a list of positions to merge) + token_ids: Actual token IDs that were generated [seq_len]. REQUIRED when any group has + len(group) > 1. If None when multi-token groups exist, raises ValueError. + + Returns: + Merged probability tensor [num_groups, vocab_size] + + Raises: + ValueError: If token_ids is None when merging multi-token groups + """ + if not alignment_groups: + return probs + + # Create aligned tensor + vocab_size = probs.size(-1) + target_len = len(alignment_groups) + aligned_probs = torch.zeros(target_len, vocab_size, device=probs.device, dtype=probs.dtype) + eps = 1e-8 + + # Process each alignment group + for group_idx, group in enumerate(alignment_groups): + # Handle probability merging + if len(group) > 1: + # Multiple tokens map to this group - merge using corrected conditional probability approach + if token_ids is None: + raise ValueError( + "token_ids must be provided when merging multi-token groups. " + "This is required for mathematically correct probability merging." + ) + + # Start with the marginal distribution at the first position + first_pos = group[0] + marginal_probs = probs[first_pos] # P(y | x₀) for all y + + # For each subsequent token in the group, extract the SCALAR conditional probability + # of the actual token that was generated, and multiply + conditional_prob_product = 1.0 + for idx in group[1:]: + # Get the actual token ID that was generated at this position + actual_token_id = token_ids[idx] + # Extract its probability (scalar) + token_prob = probs[idx, actual_token_id].clamp_min(eps) + conditional_prob_product *= token_prob + + # Merge: multiply the scalar conditional prob product with the entire marginal distribution + # This gives: P(y | x_0) × P(token_1 | token_0, x) × ... × P(token_k | ..., x) + # Note: This is unnormalized, but preserves the correct joint probability for the actual sequence + merged_probs = marginal_probs * conditional_prob_product + aligned_probs[group_idx] = merged_probs + + elif len(group) == 1: + aligned_probs[group_idx] = probs[group[0]] + else: + # No tokens map to this group + aligned_probs[group_idx] = torch.zeros_like(probs[0]) + + return aligned_probs + + def _compute_hybrid_uld_loss(self, student_aligned, teacher_aligned): + """ + Compute hybrid ULD loss on aligned probability distributions. This method: + 1. Directly compares probabilities for tokens with matching vocabulary entries + 2. Uses sorting approach only for tokens with different vocabulary entries + + Args: + student_aligned: Aligned student probabilities [seq_len, student_vocab_size] + teacher_aligned: Aligned teacher probabilities [seq_len, teacher_vocab_size] + Returns: + Combined hybrid loss + """ + device = student_aligned.device + # seq_len = student_aligned.size(0) # Unused variable + student_vocab_size = student_aligned.size(-1) + teacher_vocab_size = teacher_aligned.size(-1) + + # Convert sets to sorted tensors for indexing + if self._teacher_matched_ids: + teacher_matched_indices = torch.tensor(sorted(self._teacher_matched_ids), dtype=torch.long, device=device) + student_matched_indices = self.mapping_tensor[teacher_matched_indices] + else: + teacher_matched_indices = torch.tensor([], dtype=torch.long, device=device) + student_matched_indices = torch.tensor([], dtype=torch.long, device=device) + + # Create masks for unmatched tokens + teacher_matched_mask = torch.zeros(teacher_vocab_size, dtype=torch.bool, device=device) + student_matched_mask = torch.zeros(student_vocab_size, dtype=torch.bool, device=device) + + if len(teacher_matched_indices) > 0: + teacher_matched_mask[teacher_matched_indices] = True + student_matched_mask[student_matched_indices] = True + + # 1. JSD loss for matched vocabulary tokens (direct semantic correspondence) + matched_loss = torch.tensor(0.0, device=device) + matched_token_count = 0 + if len(teacher_matched_indices) > 0: + # Extract probabilities for matched tokens + teacher_matched_probs = teacher_aligned[:, teacher_matched_indices] # [seq_len, num_matched] + student_matched_probs = student_aligned[:, student_matched_indices] # [seq_len, num_matched] + matched_token_count = teacher_matched_probs.size(-1) + + # Use JSD loss for semantically aligned tokens + # Convert probabilities back to logits for JSD computation + + # Apply generalized JSD loss to matched tokens + matched_loss = self._compute_jsd_loss_for_matched_tokens(student_matched_probs, teacher_matched_probs) + + # 2. Sorted comparison loss for unmatched vocabulary tokens + teacher_unmatched_mask = ~teacher_matched_mask + student_unmatched_mask = ~student_matched_mask + + teacher_unmatched_probs = teacher_aligned[:, teacher_unmatched_mask] # [seq_len, num_teacher_unmatched] + student_unmatched_probs = student_aligned[:, student_unmatched_mask] # [seq_len, num_student_unmatched] + + unmatched_loss = torch.tensor(0.0, device=device) + if teacher_unmatched_probs.size(-1) > 0 and student_unmatched_probs.size(-1) > 0: + # Sort unmatched probabilities + teacher_unmatched_sorted = teacher_unmatched_probs.sort(dim=-1, descending=True).values + student_unmatched_sorted = student_unmatched_probs.sort(dim=-1, descending=True).values + + # Pad to same size if needed + teacher_unmatched_size = teacher_unmatched_sorted.size(-1) + student_unmatched_size = student_unmatched_sorted.size(-1) + max_unmatched_size = max(teacher_unmatched_size, student_unmatched_size) + + if teacher_unmatched_size < max_unmatched_size: + teacher_unmatched_sorted = F.pad( + teacher_unmatched_sorted, (0, max_unmatched_size - teacher_unmatched_size) + ) + if student_unmatched_size < max_unmatched_size: + student_unmatched_sorted = F.pad( + student_unmatched_sorted, (0, max_unmatched_size - student_unmatched_size) + ) + + # L1 loss on sorted unmatched tokens + unmatched_loss = F.l1_loss(student_unmatched_sorted, teacher_unmatched_sorted, reduction="sum") + unmatched_loss /= student_aligned.size(0) # Normalize by sequence length + + # 3. Combine losses with weights + if self.hybrid_matched_weight is None: + # Use adaptive weighting based on vocabulary overlap + hybrid_matched_weight = matched_token_count / max(1, teacher_vocab_size) + hybrid_unmatched_weight = 1.0 - hybrid_matched_weight + else: + # Use fixed weights provided in config + hybrid_matched_weight = self.hybrid_matched_weight + hybrid_unmatched_weight = self.hybrid_unmatched_weight + + total_loss = hybrid_matched_weight * matched_loss + hybrid_unmatched_weight * unmatched_loss + + # Store matched/unmatched components for logging + self.last_matched_loss = matched_loss + self.last_unmatched_loss = unmatched_loss + + return total_loss + + def _compute_jsd_loss_for_matched_tokens(self, student_logits, teacher_logits): + """ + Compute JSD loss for matched vocabulary tokens. + + Args: + student_logits: Student logits for matched tokens [seq_len, num_matched] + teacher_logits: Teacher logits for matched tokens [seq_len, num_matched] + Returns: + JSD loss for matched tokens + """ + # Reshape to [batch_size * seq_len, vocab_size] format expected by generalized_jsd_loss + batch_seq_len, num_matched = student_logits.shape + + student_logits_reshaped = student_logits.view(-1, num_matched) + teacher_logits_reshaped = teacher_logits.view(-1, num_matched) + + # Use the GOLD generalized JSD loss implementation that accepts probability inputs + jsd_loss = GOLDTrainer.generalized_jsd_loss( + student_logits_reshaped, + teacher_logits_reshaped, + labels=None, # No masking needed for matched tokens + beta=self.beta, # Standard JSD beta + temperature=1.0, # Already applied in main computation + reduction="batchmean", + logits_are_probs=True, + ) + + return jsd_loss + + def _get_start_and_size_answers(self, answer_tensors): + answers_index = [] + answers_size = [] + + for answer in answer_tensors: + answer_mask = answer.ne(self.ignore_index) + if not answer_mask.any(): + answers_index.append(0) + answers_size.append(0) + continue + + valid_indices = answer_mask.nonzero(as_tuple=True)[0] + answers_index.append(int(valid_indices[0].item())) + answers_size.append(int(answer_mask.sum().item())) + return answers_index, answers_size + + +class GOLDTrainer(SFTTrainer): + _tag_names = ["trl", "gold"] + _name = "GOLD" + _paper = { + "title": "Unlocking On-Policy Distillation for Any Model Family", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @misc{patino2025unlocking, + title = {{Unlocking On-Policy Distillation for Any Model Family}}, + author = {Carlos Miguel Patiño and Kashif Rasul and Quentin Gallouédec and Ben Burtenshaw and Sergio Paniego and Vaibhav Srivastav and Thibaud Frere and Ed Beeching and Lewis Tunstall and Leandro von Werra and Thomas Wolf}, + year = 2025, + url = {https://huggingface.co/spaces/HuggingFaceH4/general-on-policy-logit-distillation}, + }"""), + } + + def __init__( + self, + model: PreTrainedModel | nn.Module | str | None = None, + teacher_model: PreTrainedModel | nn.Module | str = None, + args: GOLDConfig | None = None, + data_collator: DataCollator | None = None, # type: ignore + train_dataset: Dataset | None = None, + eval_dataset: Dataset | dict[str, Dataset] | None = None, + processing_class: PreTrainedTokenizerBase + | BaseImageProcessor + | FeatureExtractionMixin + | ProcessorMixin + | None = None, + compute_metrics: Callable[[EvalPrediction], dict] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None, + peft_config: Optional["PeftConfig"] = None, + ): + self.model_name_or_path = model if isinstance(model, str) else model.config._name_or_path + self.model_revision = (args.model_init_kwargs or {}).get("revision") + + # Respect a user-provided data_collator; otherwise, provide a ChatML collator that + if data_collator is None: + data_collator = DataCollatorForChatML(tokenizer=processing_class, max_length=args.max_length) + + # Liger fused GKD loss (JSD) + self.use_liger_gkd_loss = False + if args.use_liger_kernel: + self.liger_jsd_loss = LigerFusedLinearJSDLoss( + beta=args.beta, + ignore_index=-100, + temperature=args.temperature, + compiled=False, + weight_hard_loss=0.0, + weight_soft_loss=1.0, + ) + self.use_liger_gkd_loss = True + self._forward_redirection = _ForwardRedirection() + + if args.teacher_model_init_kwargs is None: + teacher_model_init_kwargs = {} + elif not isinstance(teacher_model, str): + raise ValueError( + "You passed teacher_model_init_kwargs to the GOLDConfig, but your teacher_model is already instantiated." + ) + else: + teacher_model_init_kwargs = args.teacher_model_init_kwargs + teacher_model_init_kwargs["dtype"] = ( + teacher_model_init_kwargs["dtype"] + if teacher_model_init_kwargs["dtype"] in ["auto", None] + else getattr(torch, teacher_model_init_kwargs["dtype"]) + ) + + if args.use_uld_loss and args.teacher_tokenizer_name_or_path is None: + if isinstance(teacher_model, str): + args.teacher_tokenizer_name_or_path = teacher_model + else: + raise ValueError( + "`teacher_tokenizer_name_or_path` must be set when using ULD loss with a pre-instantiated teacher model." + ) + + if isinstance(teacher_model, str): + init_kwargs = dict(teacher_model_init_kwargs) + if args.teacher_model_revision is not None: + init_kwargs.setdefault("revision", args.teacher_model_revision) + teacher_model = create_model_from_path(teacher_model, **init_kwargs) + self.use_uld_loss = args.use_uld_loss + self.teacher_tokenizer = None + if args.use_uld_loss and args.teacher_tokenizer_name_or_path is not None: + self.teacher_tokenizer = AutoTokenizer.from_pretrained(args.teacher_tokenizer_name_or_path) + if not hasattr(self.teacher_tokenizer, "pad_token") or self.teacher_tokenizer.pad_token is None: + self.teacher_tokenizer.pad_token = self.teacher_tokenizer.eos_token + + # Hybrid ULD loss configuration is handled in ULDLoss class + + super().__init__( + model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + peft_config=peft_config, + ) + + if args.disable_dropout: + disable_dropout_in_model(self.model) + if not args.use_uld_loss: + teacher_model.resize_token_embeddings(self.model.config.get_text_config().vocab_size) + + if self.is_deepspeed_enabled: + self.teacher_model = prepare_deepspeed(teacher_model, self.accelerator) + else: + self.teacher_model = self.accelerator.prepare_model(teacher_model, evaluation_mode=True) + + self.lmbda = args.lmbda + self.beta = args.beta + self.temperature = args.temperature + self.top_p = args.top_p + self.seq_kd = args.seq_kd + self.num_generations = args.num_generations + + # Track per-step loss statistics for on/off-policy batches (used in logging) + self._on_policy_loss_total = 0.0 + self._off_policy_loss_total = 0.0 + self._on_policy_step_equiv = 0.0 + self._off_policy_step_equiv = 0.0 + + # Buffering for rollouts across gradient accumulation steps + self._buffered_inputs = None + self._buffered_on_policy = None + self._buffered_text_logs = None + self._step = 0 + + # Hybrid ULD matched/unmatched accumulators (logged every step when ULD hybrid is used) + self._matched_sum = 0.0 + self._unmatched_sum = 0.0 + self._matched_step_eq = 0.0 + self._unmatched_step_eq = 0.0 + + self.uld_loss_fn = None + if self.use_uld_loss: + self.uld_loss_fn = ULDLoss( + config=args, + student_tokenizer=processing_class, + teacher_tokenizer=self.teacher_tokenizer, + device=self.accelerator.device, + ) + + generation_kwargs = { + "max_new_tokens": args.max_completion_length, + "temperature": args.temperature, + "top_p": args.top_p, + "do_sample": True, + "top_k": args.top_k, + "pad_token_id": self.processing_class.pad_token_id, + } + self.generation_config = GenerationConfig(**generation_kwargs) + # Keep training-specific generation kwargs to overwrite model's original generation config + self.generation_kwargs = generation_kwargs + if ( + hasattr(self.model.generation_config, "eos_token_id") + and self.model.generation_config.eos_token_id is not None + ): + self.generation_config.eos_token_id = self.model.generation_config.eos_token_id + + # Initialize the metrics + self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)} + self._total_train_tokens = 0 + self.log_completions = args.log_completions + self.log_completion_steps = args.log_completions_steps + self.wandb_log_unique_prompts = args.wandb_log_unique_prompts + self.num_completions_to_print = args.num_completions_to_print + # maxlen is set to the total number of forward passes per step. This value of `maxlen` ensures we log only the + # final optimization step. + maxlen = self.accelerator.num_processes * args.per_device_train_batch_size * args.gradient_accumulation_steps + self._textual_logs = { + "prompt": deque(maxlen=maxlen), + "completion": deque(maxlen=maxlen), + "rewards": defaultdict(lambda: deque(maxlen=maxlen)), + "advantages": deque(maxlen=maxlen), + } + + self.use_vllm = args.use_vllm + if self.use_vllm: + if not is_vllm_available(): + raise ImportError( + "vLLM is not available and use_vllm is set to True. Please install vLLM with " + "`pip install vllm` to use it." + ) + self.vllm_generation = VLLMGeneration( + model=self.model, + accelerator=self.accelerator, + processing_class=self.processing_class, + mode=args.vllm_mode, + structured_outputs_regex=args.vllm_structured_outputs_regex, + server_base_url=args.vllm_server_base_url, + server_host=args.vllm_server_host, + server_port=args.vllm_server_port, + group_port=args.vllm_group_port, + server_timeout=args.vllm_server_timeout, + tensor_parallel_size=args.vllm_tensor_parallel_size, + gpu_memory_utilization=args.vllm_gpu_memory_utilization, + max_model_length=args.vllm_max_model_length or args.max_length, + max_num_seqs=args.per_device_train_batch_size * args.gradient_accumulation_steps, + enable_sleep_mode=args.vllm_enable_sleep_mode, + model_impl=args.vllm_model_impl, + repetition_penalty=getattr(args, "repetition_penalty", 1.0), + temperature=args.temperature, + top_p=args.top_p, + top_k=args.top_k, + min_p=getattr(args, "min_p", 0.0), + max_completion_length=args.max_completion_length, + logprobs=None, + ) + self.vllm_sync_frequency = args.vllm_sync_frequency + self._last_vllm_sync_step = -self.vllm_sync_frequency + + def _set_signature_columns_if_needed(self): + super()._set_signature_columns_if_needed() + required_columns = [ + "prompts", + "prompt_attention_mask", + "messages", + "chat_template_kwargs", + "tools", + "original_prompt_text", + "original_completion_text", + "byte_offsets", + "completion_mask", + ] + if self._signature_columns is None: + self._signature_columns = required_columns + else: + for column in required_columns: + if column not in self._signature_columns: + self._signature_columns.append(column) + + def _get_train_sampler(self, dataset=None): + if dataset is None: + dataset = self.train_dataset + return RepeatSampler( + data_source=dataset, + mini_repeat_count=self.num_generations, + batch_size=self.args.generation_batch_size * self.accelerator.num_processes, + repeat_count=self.args.gradient_accumulation_steps, + shuffle=True, + seed=self.args.seed, + ) + + def get_train_dataloader(self): + """ + Override Trainer.get_train_dataloader to load one generation batch per optimizer window. + + The dataloader yields local batches of size `per_device_train_batch_size * gradient_accumulation_steps`. The + `RepeatSampler` (with `repeat_count=gradient_accumulation_steps`) ensures each generation batch is sampled + `gradient_accumulation_steps` times so Trainer's loop iterates the correct number of times. Only the first + batch in each window triggers `_fill_buffer`; the rest are ignored by `_prepare_inputs`. + """ + if self.train_dataset is None: + raise ValueError("Trainer: training requires a train_dataset.") + + train_dataset = self.train_dataset + data_collator = self.data_collator + if is_datasets_available() and isinstance(train_dataset, Dataset): + train_dataset = self._remove_unused_columns(train_dataset, description="training") + else: + data_collator = self._get_collator_with_removed_columns(data_collator, description="training") + + dataloader_params = { + "batch_size": self._train_batch_size * self.args.gradient_accumulation_steps, + "collate_fn": data_collator, + "num_workers": self.args.dataloader_num_workers, + "pin_memory": self.args.dataloader_pin_memory, + "persistent_workers": self.args.dataloader_persistent_workers, + } + + if not isinstance(train_dataset, torch.utils.data.IterableDataset): + dataloader_params["sampler"] = self._get_train_sampler() + dataloader_params["drop_last"] = self.args.dataloader_drop_last + dataloader_params["worker_init_fn"] = partial( + seed_worker, + num_workers=self.args.dataloader_num_workers, + rank=self.args.process_index, + ) + if self.args.dataloader_num_workers > 0: + dataloader_params["prefetch_factor"] = self.args.dataloader_prefetch_factor + + return self.accelerator.prepare(DataLoader(train_dataset, **dataloader_params)) + + @profiling_decorator + def _prepare_inputs(self, generation_batch: dict[str, torch.Tensor | Any]) -> dict[str, torch.Tensor | Any]: + if not self.model.training: + return generation_batch + + buffer_steps = self.args.gradient_accumulation_steps + if self._step % buffer_steps == 0 or self._buffered_inputs is None: + self._fill_buffer(generation_batch, buffer_steps) + + slice_idx = self._step % buffer_steps + inputs = self._buffered_inputs[slice_idx] + self._step += 1 + return inputs + + @staticmethod + def _build_sequence_batch( + new_input_ids: torch.Tensor, + prompt_lengths: torch.Tensor, + pad_token_id: int | None, + attention_mask: torch.Tensor | None = None, + ) -> tuple[torch.Tensor, torch.Tensor]: + """Build attention mask and labels from full sequences and prompt lengths.""" + prompt_lengths = prompt_lengths.to(device=new_input_ids.device, dtype=torch.long) + positions = torch.arange(new_input_ids.shape[1], device=new_input_ids.device).unsqueeze(0) + completion_mask = positions >= prompt_lengths.unsqueeze(1) + + if attention_mask is not None: + new_attention_mask = attention_mask.to(device=new_input_ids.device, dtype=new_input_ids.dtype) + else: + new_attention_mask = torch.ones_like(new_input_ids) + if pad_token_id is not None: + new_attention_mask[new_input_ids == pad_token_id] = 0 + + new_labels = torch.full_like(new_input_ids, -100) + new_labels[completion_mask & new_attention_mask.bool()] = new_input_ids[ + completion_mask & new_attention_mask.bool() + ] + if attention_mask is None and pad_token_id is not None: + new_labels[new_input_ids == pad_token_id] = -100 + + return new_attention_mask, new_labels + + def _maybe_add_completion_byte_offsets(self, updated_slice: dict[str, torch.Tensor | Any]) -> None: + """Attach completion-relative byte offsets to on-policy ULD batches. + + Derived from the sampled ids via ``piece_byte_len`` (no decode→re-encode round-trip). + """ + if not ( + self.use_uld_loss + and self.teacher_tokenizer is not None + and self.uld_loss_fn is not None + and self.uld_loss_fn.use_extended_uld + ): + return + + new_input_ids = updated_slice["input_ids"] + new_labels = updated_slice["labels"] + seq_len = new_input_ids.shape[1] + + rows: list[list[tuple[int, int]]] = [] + for row_ids, row_labels in zip(new_input_ids.cpu().tolist(), new_labels.cpu().tolist(), strict=True): + offs: list[tuple[int, int]] = [(0, 0)] * seq_len + cumulative = 0 + for pos, (tid, label) in enumerate(zip(row_ids, row_labels, strict=True)): + if label == -100: + continue + nb = piece_byte_len(self.processing_class.convert_ids_to_tokens([tid])[0]) + offs[pos] = (cumulative, cumulative + nb) + cumulative += nb + rows.append(offs) + updated_slice["byte_offsets"] = torch.tensor(rows, dtype=torch.long, device=new_input_ids.device) + + @profiling_decorator + def _fill_buffer(self, generation_batch: dict[str, torch.Tensor | Any], buffer_steps: int): + slices = split_tensor_dict(generation_batch, buffer_steps) + + if self.accelerator.is_main_process: + on_policy_flags = [random.random() <= self.lmbda for _ in range(buffer_steps)] + else: + on_policy_flags = [False] * buffer_steps + + on_policy_flags = broadcast_object_list(on_policy_flags, from_process=0) + on_policy_indices = [i for i, flag in enumerate(on_policy_flags) if flag] + + self._buffered_inputs = [None] * buffer_steps + self._buffered_on_policy = on_policy_flags + self._buffered_text_logs = [None] * buffer_steps + + for i, flag in enumerate(on_policy_flags): + if not flag: + slice_inputs = slices[i] + + if ( + self.use_uld_loss + and self.teacher_tokenizer is not None + and ("original_prompt_text" not in slice_inputs or "original_completion_text" not in slice_inputs) + ): + raise ValueError( + "Off-policy batch missing 'original_prompt_text' or 'original_completion_text' fields. " + "Use the default DataCollatorForChatML (or a collator that emits these fields) so the " + "teacher tokenizer has source text to align against." + ) + if ( + self.use_uld_loss + and self.teacher_tokenizer is not None + and self.uld_loss_fn.use_extended_uld + and "byte_offsets" not in slice_inputs + ): + raise ValueError( + "Off-policy batch missing `byte_offsets`. Use the default DataCollatorForChatML or set " + "`use_extended_uld=False`." + ) + + self._buffered_inputs[i] = slice_inputs + + if on_policy_indices: + self._generate_on_policy_for_slices(slices, on_policy_indices) + + @profiling_decorator + def _generate_on_policy_for_slices( + self, slices: list[dict[str, torch.Tensor | Any]], on_policy_indices: list[int] + ): + prompt_ids_list = [] + local_slice_indices = [] + for slice_idx in on_policy_indices: + slice_inputs = slices[slice_idx] + prompt_attention_mask = slice_inputs.get("prompt_attention_mask") + for prompt_idx, prompt in enumerate(slice_inputs["prompts"]): + if prompt_attention_mask is not None: + prompt = prompt[prompt_attention_mask[prompt_idx].bool()] + prompt_ids_list.append(prompt.tolist()) + local_slice_indices.append(slice_idx) + + prompts_text = self.processing_class.batch_decode( + prompt_ids_list, + skip_special_tokens=False, + ) + + if not self.use_vllm: + self._generate_non_vllm_for_slices(slices, on_policy_indices) + return + + if ( + self.state.global_step != self._last_vllm_sync_step + and self.state.global_step >= self._last_vllm_sync_step + self.vllm_sync_frequency + ): + self.vllm_generation.sync_weights() + self._last_vllm_sync_step = self.state.global_step + + _, completion_ids, _, _ = self.vllm_generation.generate( + prompts=prompt_ids_list, + images=None, + num_generations=self.num_generations, + ) + + self._process_completions_to_buffer( + slices, + on_policy_indices, + local_slice_indices, + completion_ids, + prompt_ids_list, + prompts_text, + self.generation_config.max_new_tokens, + ) + + def _generate_non_vllm_for_slices(self, slices: list[dict[str, torch.Tensor | Any]], on_policy_indices: list[int]): + """Fallback generation without vLLM (uses model.generate per slice).""" + with unwrap_model_for_generation( + self.model, + self.accelerator, + generation_kwargs=self.generation_kwargs, + ) as unwrapped_model: + for slice_idx in on_policy_indices: + slice_inputs = slices[slice_idx] + result = self.generate_on_policy_outputs( + unwrapped_model, + slice_inputs, + self.generation_config, + self.processing_class.pad_token_id, + ) + new_input_ids, new_attention_mask, new_labels, prompt_texts, completion_texts = result + + updated_slice = dict(slice_inputs) + updated_slice["input_ids"] = new_input_ids + updated_slice["attention_mask"] = new_attention_mask + updated_slice["labels"] = new_labels + updated_slice["original_prompt_text"] = prompt_texts + updated_slice["original_completion_text"] = completion_texts + self._maybe_add_completion_byte_offsets(updated_slice) + + self._buffered_inputs[slice_idx] = updated_slice + self._buffered_text_logs[slice_idx] = (prompt_texts, completion_texts) + + def _process_completions_to_buffer( + self, + slices: list[dict[str, torch.Tensor | Any]], + on_policy_indices: list[int], + local_slice_indices: list[int], + completion_ids: list, + prompt_ids_list: list[list[int]], + prompts_text: list[str], + max_completion_length: int, + ): + """ + Process vLLM completions and update buffered inputs for on-policy slices. + """ + device = self.accelerator.device + pad_token_id = self.processing_class.pad_token_id if self.processing_class.pad_token_id is not None else 0 + + slice_completions = {idx: [] for idx in on_policy_indices} + slice_prompt_ids = {idx: [] for idx in on_policy_indices} + slice_prompts = {idx: [] for idx in on_policy_indices} + + for i, slice_idx in enumerate(local_slice_indices): + slice_completions[slice_idx].append(completion_ids[i]) + slice_prompt_ids[slice_idx].append(prompt_ids_list[i]) + slice_prompts[slice_idx].append(prompts_text[i]) + + for slice_idx in on_policy_indices: + slice_inputs = slices[slice_idx] + completion_ids_for_slice = slice_completions[slice_idx] + prompt_ids_for_slice = slice_prompt_ids[slice_idx] + prompt_txts = slice_prompts[slice_idx] + + prompt_max_length = max(1, self.args.max_length - max_completion_length) if self.args.max_length else None + truncated_prompt_ids = [] + prompt_attention_masks = [] + truncation_side = getattr(self.processing_class, "truncation_side", "right") + for prompt_ids in prompt_ids_for_slice: + if prompt_max_length and len(prompt_ids) > prompt_max_length: + if truncation_side == "left": + prompt_ids = prompt_ids[-prompt_max_length:] + else: + prompt_ids = prompt_ids[:prompt_max_length] + prompt_tensor = torch.tensor(prompt_ids, device=device, dtype=torch.long) + truncated_prompt_ids.append(prompt_tensor) + prompt_attention_masks.append(torch.ones(len(prompt_ids), device=device, dtype=torch.long)) + + prompt_ids = pad(truncated_prompt_ids, padding_side="left", padding_value=pad_token_id) + prompt_attention_mask = pad(prompt_attention_masks, padding_side="left", padding_value=0) + + # Decode the truncated prompt so the teacher conditions on the same context the student saw. + # `clean_up_tokenization_spaces=False` matches the completion decode below so byte counts stay aligned. + prompt_txts_with_special = self.processing_class.batch_decode( + [ids.tolist() for ids in truncated_prompt_ids], + skip_special_tokens=False, + clean_up_tokenization_spaces=False, + ) + + completion_ids_tensors = [torch.tensor(ids, device=device) for ids in completion_ids_for_slice] + completion_ids_for_text: list[list[int]] = [] + padded_completion_ids_list = [] + completion_attention_masks = [] + for completion_tensor in completion_ids_tensors: + if len(completion_tensor) > max_completion_length: + truncated_completion_tensor = completion_tensor[:max_completion_length] + padded_completion_ids_list.append(truncated_completion_tensor) + completion_ids_for_text.append(truncated_completion_tensor.tolist()) + completion_attention_masks.append( + torch.ones(len(truncated_completion_tensor), device=device, dtype=torch.long) + ) + elif len(completion_tensor) < max_completion_length: + padding_needed = max_completion_length - len(completion_tensor) + padded_tensor = torch.cat( + [ + completion_tensor, + torch.full( + (padding_needed,), + pad_token_id, + device=device, + dtype=completion_tensor.dtype, + ), + ] + ) + padded_completion_ids_list.append(padded_tensor) + completion_ids_for_text.append(completion_tensor.tolist()) + completion_attention_masks.append( + torch.cat( + [ + torch.ones(len(completion_tensor), device=device, dtype=torch.long), + torch.zeros(padding_needed, device=device, dtype=torch.long), + ] + ) + ) + else: + padded_completion_ids_list.append(completion_tensor) + completion_ids_for_text.append(completion_tensor.tolist()) + completion_attention_masks.append( + torch.ones(len(completion_tensor), device=device, dtype=torch.long) + ) + + completion_ids_padded = torch.stack(padded_completion_ids_list) + completion_attention_mask = torch.stack(completion_attention_masks) + + new_input_ids = torch.cat([prompt_ids, completion_ids_padded], dim=1) + new_attention_mask = torch.cat([prompt_attention_mask, completion_attention_mask], dim=1) + prompt_lengths = torch.full((prompt_ids.shape[0],), prompt_ids.shape[1], device=device) + new_attention_mask, new_labels = self._build_sequence_batch( + new_input_ids, + prompt_lengths, + pad_token_id, + attention_mask=new_attention_mask, + ) + + completion_texts = self.processing_class.batch_decode( + completion_ids_for_text, + skip_special_tokens=False, + clean_up_tokenization_spaces=False, + ) + + updated_slice = dict(slice_inputs) + updated_slice["input_ids"] = new_input_ids + updated_slice["attention_mask"] = new_attention_mask + updated_slice["labels"] = new_labels + updated_slice["original_prompt_text"] = prompt_txts_with_special + updated_slice["original_completion_text"] = completion_texts + self._maybe_add_completion_byte_offsets(updated_slice) + + self._buffered_inputs[slice_idx] = updated_slice + self._buffered_text_logs[slice_idx] = (prompt_txts, completion_texts) + + def _prepare_dataset( + self, + dataset: Dataset | IterableDataset, + processing_class: PreTrainedTokenizerBase | BaseImageProcessor | FeatureExtractionMixin | ProcessorMixin, + args, + packing: bool, + formatting_func: Callable[[dict], str] | None, + dataset_name: str, + ) -> Dataset | IterableDataset: + """Preserve original text fields for ULD when needed.""" + column_names = list(next(iter(dataset)).keys()) + is_processed = "input_ids" in column_names + + if packing and self.use_uld_loss and self.teacher_tokenizer is not None: + raise ValueError( + "Packing is not supported with cross-tokenizer ULD because byte-offset alignment is defined per " + "prompt/completion example." + ) + + if not is_processed or (self.use_uld_loss and self.teacher_tokenizer is not None): + return self._prepare_dataset_with_original_text( + dataset, processing_class, args, packing, formatting_func, dataset_name + ) + + return super()._prepare_dataset(dataset, processing_class, args, packing, formatting_func, dataset_name) + + def _prepare_dataset_with_original_text( + self, + dataset: Dataset | IterableDataset, + processing_class: PreTrainedTokenizerBase | BaseImageProcessor | FeatureExtractionMixin | ProcessorMixin, + args, + packing: bool, + formatting_func: Callable[[dict], str] | None, + dataset_name: str, + ) -> Dataset | IterableDataset: + """ + Prepare dataset while preserving original text for cross-tokenizer distillation. + """ + # Build the kwargs for the `map` function + map_kwargs = {} + if isinstance(dataset, Dataset): # IterableDataset does not support num_proc + map_kwargs["num_proc"] = args.dataset_num_proc + + with PartialState().main_process_first(): + # Apply the formatting function if any + if formatting_func is not None: + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Applying formatting function to {dataset_name} dataset" + + def _func(example): + return {"text": formatting_func(example)} + + dataset = dataset.map(_func, batched=False, **map_kwargs) + + # Convert the dataset to ChatML if needed + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Converting {dataset_name} dataset to ChatML" + column_names = next(iter(dataset)).keys() + dataset = dataset.map( + maybe_convert_to_chatml, + remove_columns="conversations" if "conversations" in column_names else None, + **map_kwargs, + ) + + # Add EOS token if needed: non-conversational only + first_example = next(iter(dataset)) + if not is_conversational(first_example): + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Adding EOS to {dataset_name} dataset" + + def add_eos(example, eos_token): + if "text" in example and not example["text"].endswith(eos_token): # language modeling case + example["text"] = example["text"] + eos_token + elif "completion" in example and not example["completion"].endswith(eos_token): + example["completion"] = example["completion"] + eos_token + return example + + dataset = dataset.map( + add_eos, + fn_kwargs={"eos_token": processing_class.eos_token}, + remove_columns="messages" if "messages" in column_names else None, # renamed to "text" + **map_kwargs, + ) + + # Tokenize the dataset while preserving original text + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Tokenizing {dataset_name} dataset (preserving original text)" + + def tokenize_with_original_text(example, processing_class, dataset_text_field, max_length): + """Emit input_ids, attention_mask, byte_offsets, completion_mask, and the original prompt/completion + text. Byte offsets and input_ids come from a single ``encode_with_byte_offsets`` call.""" + backend = processing_class.backend_tokenizer + result = {} + + if "prompt" in example: # prompt-completion case + if is_conversational(example): + prompt_text = processing_class.apply_chat_template( + example["prompt"], + add_generation_prompt=True, + tokenize=False, + **example.get("chat_template_kwargs", {}), + ) + full_text = processing_class.apply_chat_template( + example["prompt"] + example["completion"], + tokenize=False, + **example.get("chat_template_kwargs", {}), + ) + prompt_text = "".join( + x for x, _ in takewhile(lambda x: x[0] == x[1], zip(prompt_text, full_text, strict=False)) + ) + completion_text = full_text[len(prompt_text) :] + else: + prompt_text = example["prompt"] + completion_text = example["completion"] + full_text = prompt_text + completion_text + result["original_prompt_text"] = prompt_text + result["original_completion_text"] = completion_text + elif is_conversational(example): + messages = example["messages"] + assistant_indices = [idx for idx, msg in enumerate(messages) if msg["role"] == "assistant"] + if assistant_indices: + completion_idx = assistant_indices[-1] + prompt_messages = messages[:completion_idx] + full_messages = messages[: completion_idx + 1] + if prompt_messages: + prompt_text = processing_class.apply_chat_template( + prompt_messages, + add_generation_prompt=True, + tokenize=False, + **example.get("chat_template_kwargs", {}), + ) + else: + prompt_text = "" + full_text = processing_class.apply_chat_template( + full_messages, + add_generation_prompt=False, + tokenize=False, + **example.get("chat_template_kwargs", {}), + ) + prompt_text = "".join( + x for x, _ in takewhile(lambda x: x[0] == x[1], zip(prompt_text, full_text, strict=False)) + ) + completion_text = full_text[len(prompt_text) :] + result["original_prompt_text"] = prompt_text + result["original_completion_text"] = completion_text + else: + full_text = processing_class.apply_chat_template( + messages, tokenize=False, **example.get("chat_template_kwargs", {}) + ) + prompt_text = "" + result["original_prompt_text"] = "" + result["original_completion_text"] = full_text + else: + text = example.get(dataset_text_field, example.get("text", "")) + prompt_text = "" + full_text = text + result["original_prompt_text"] = "" + result["original_completion_text"] = text + + # Single backend call: ids and char-derived byte offsets from the same encoding, + # so input_ids[i] is described by full_offs[i] without any boundary slop. + [(input_ids, full_offs)] = encode_with_byte_offsets(backend, [full_text], add_special_tokens=False) + prompt_byte_len = len(prompt_text.encode("utf-8")) + completion_start = next( + (idx for idx, (s, _) in enumerate(full_offs) if s >= prompt_byte_len), + len(input_ids), + ) + # Completion-relative: prompt positions zeroed, completion offsets shifted to + # the assistant content's first byte (matches build_teacher_inputs_from_texts). + byte_offsets = [(0, 0)] * completion_start + [ + (s - prompt_byte_len, e - prompt_byte_len) for s, e in full_offs[completion_start:] + ] + + # Keep the last `max_length` tokens (the completion end). `completion_mask` tracks the + # boundary so it survives truncation without re-tokenizing the prompt. + if max_length is not None and len(input_ids) > max_length: + drop = len(input_ids) - max_length + input_ids = input_ids[drop:] + byte_offsets = byte_offsets[drop:] + completion_start = max(0, completion_start - drop) + # If truncation ate into the completion, rebase the kept completion offsets so they're + # relative to the new (truncated) `original_completion_text` the teacher will re-encode. + if completion_start < len(byte_offsets): + base = byte_offsets[completion_start][0] + if base > 0: + byte_offsets = byte_offsets[:completion_start] + [ + (s - base, e - base) for s, e in byte_offsets[completion_start:] + ] + # Resync the strings the teacher will re-encode with the ids the student kept. + decode = partial( + processing_class.decode, skip_special_tokens=False, clean_up_tokenization_spaces=False + ) + result["original_prompt_text"] = decode(input_ids[:completion_start]) + result["original_completion_text"] = decode(input_ids[completion_start:]) + + result["input_ids"] = input_ids + result["attention_mask"] = [1] * len(input_ids) + result["byte_offsets"] = byte_offsets + result["completion_mask"] = [0] * completion_start + [1] * (len(input_ids) - completion_start) + return result + + dataset = dataset.map( + tokenize_with_original_text, + fn_kwargs={ + "processing_class": processing_class, + "dataset_text_field": args.dataset_text_field, + "max_length": args.max_length, + }, + **map_kwargs, + ) + + # Pack if requested. Truncation already happened in `tokenize_with_original_text`, keeping + # the completion end — so the generic front-truncating `truncate_dataset` is intentionally + # not applied here (it would drop the completion). + if packing: + if args.max_length is None: + raise ValueError("When packing is enabled, `max_length` can't be `None`.") + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Packing {dataset_name} dataset" + + columns_to_keep = ["input_ids", "original_prompt_text", "original_completion_text"] + existing_columns = set(dataset.column_names) + columns_to_select = [col for col in columns_to_keep if col in existing_columns] + + dataset = dataset.select_columns(columns_to_select) + dataset = pack_dataset(dataset, args.max_length, args.packing_strategy, map_kwargs) + + if args.use_liger_kernel: + required_columns = { + "input_ids", + "attention_mask", + "position_ids", + "completion_mask", + "messages", + "original_prompt_text", + "original_completion_text", + "byte_offsets", + } + dataset = dataset.select_columns(required_columns.intersection(dataset.column_names)) + + return dataset + + @staticmethod + def generalized_jsd_loss( + student_logits, + teacher_logits, + labels=None, + beta=0.5, + temperature=1.0, + reduction="batchmean", + logits_are_probs=False, + num_items_in_batch=None, + ): + """ + Compute the generalized Jensen-Shannon Divergence loss for knowledge distillation using F.kl_div. See Eq. (1) + of https://huggingface.co/papers/2306.13649 for the definition. + + Args: + student_logits: + Tensor of shape (batch_size, sequence_length, vocab_size) + teacher_logits: + Tensor of shape (batch_size, sequence_length, vocab_size) + labels: + Tensor of shape (batch_size, sequence_length) with -100 for padding tokens to ignore when computing + loss + beta: + Interpolation coefficient between 0 and 1 (default: 0.5) + temperature: + Softmax temperature (default: 1.0) + reduction: + Specifies the reduction to apply to the output (default: 'batchmean') + + Returns: + loss: Scalar tensor with the generalized JSD loss + """ + + if logits_are_probs: + student_log_probs = torch.log(student_logits.clamp_min(1e-8)) + teacher_log_probs = torch.log(teacher_logits.clamp_min(1e-8)) + else: + # Apply temperature scaling to logits before computing probabilities + student_logits = student_logits / temperature + teacher_logits = teacher_logits / temperature + # Compute log probabilities for student and probabilities for teacher + student_log_probs = F.log_softmax(student_logits, dim=-1) + teacher_log_probs = F.log_softmax(teacher_logits, dim=-1) + + if beta == 0: + jsd = F.kl_div(student_log_probs, teacher_log_probs, reduction="none", log_target=True) + elif beta == 1: + jsd = F.kl_div(teacher_log_probs, student_log_probs, reduction="none", log_target=True) + else: + # Compute the log of the mixture distribution + # log(a + b) = log(exp(log(a)) + exp(log(b))) -> for mixture + beta = torch.tensor(beta, dtype=student_log_probs.dtype, device=student_log_probs.device) + mixture_log_probs = torch.logsumexp( + torch.stack([student_log_probs + torch.log1p(-beta), teacher_log_probs + torch.log(beta)]), + dim=0, + ) + + # Compute KL divergences using F.kl_div + # PyTorch differs from the standard mathematical definition, so the order of the probability distributions is swapped compared to that defined in the paper. + kl_teacher = F.kl_div(mixture_log_probs, teacher_log_probs, reduction="none", log_target=True) + kl_student = F.kl_div(mixture_log_probs, student_log_probs, reduction="none", log_target=True) + + # Compute the Generalized Jensen-Shannon Divergence + jsd = beta * kl_teacher + (1 - beta) * kl_student + + # Masking + if labels is not None: + mask = labels != -100 + jsd = jsd[mask] + + # Apply reduction + if num_items_in_batch is not None: + # Normalize by the global number of valid tokens for gradient-accumulation-correct loss (see issue #4719). + jsd_sum = jsd.sum() + if isinstance(num_items_in_batch, torch.Tensor): + num_items_in_batch = num_items_in_batch.to(jsd_sum.device) + return jsd_sum / num_items_in_batch + if reduction == "batchmean": + # clamp_min(1) avoids 0/0 -> nan when a sample has no unmasked positions + # (e.g. completion fully truncated). jsd[mask] is empty -> jsd.sum() == 0, + # so 0/1 == 0 with a valid grad path. + denom = mask.sum().clamp_min(1) if labels is not None else max(jsd.size(0), 1) + return jsd.sum() / denom + elif reduction == "sum": + return jsd.sum() + elif reduction == "mean": + return jsd.mean() + else: + return jsd + + def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): + if self.use_uld_loss and self.teacher_tokenizer is not None: + # Both DataCollatorForChatML and the on-policy generation path attach these + # fields, so cross-tokenizer ULD never has to round-trip through batch_decode. + prompt_texts = inputs["original_prompt_text"] + completion_texts = inputs["original_completion_text"] + + ( + teacher_input_ids, + teacher_labels, + teacher_attention_mask, + teacher_completion_byte_offsets, + ) = build_teacher_inputs_from_texts(self.teacher_tokenizer, prompt_texts, completion_texts) + + teacher_input_ids = teacher_input_ids.to(self.accelerator.device) + teacher_labels = teacher_labels.to(self.accelerator.device) + teacher_attention_mask = teacher_attention_mask.to(self.accelerator.device) + + outputs_student = model( + input_ids=inputs["input_ids"], + attention_mask=inputs["attention_mask"], + use_cache=False, + ) + + self.teacher_model.eval() + with torch.no_grad(): + outputs_teacher = self.teacher_model( + input_ids=teacher_input_ids, + attention_mask=teacher_attention_mask, + ) + else: + if self.use_liger_gkd_loss: + # Forward only through the base models (avoid lm_head to save memory). + # Route through the DDP/FSDP wrapper via _forward_redirection so that + # DDP.forward() is called and prepare_for_backward() fires correctly. + unwrapped_student = self.accelerator.unwrap_model(model) + student_outputs = self._forward_redirection( + model, unwrapped_student, self._liger_student_forward, unwrapped_student, inputs + ) + + self.teacher_model.eval() + unwrapped_teacher = self.accelerator.unwrap_model(self.teacher_model) + if hasattr(unwrapped_teacher, "get_decoder") and unwrapped_teacher.get_decoder() is not None: + base_teacher = unwrapped_teacher.get_decoder() + else: + base_teacher = getattr( + unwrapped_teacher, getattr(unwrapped_teacher, "base_model_prefix", "model"), unwrapped_teacher + ) + with torch.no_grad(): + teacher_outputs = base_teacher( + input_ids=inputs["input_ids"], + attention_mask=inputs["attention_mask"], + use_cache=False, + ) + + student_hidden = student_outputs.last_hidden_state[:, :-1] + teacher_hidden = teacher_outputs.last_hidden_state[:, :-1] + + del student_outputs, teacher_outputs + + student_hidden = student_hidden.reshape(-1, student_hidden.shape[-1]) + teacher_hidden = teacher_hidden.reshape(-1, teacher_hidden.shape[-1]) + + labels_mask = inputs["labels"] != -100 + masked_input_ids = torch.where( + labels_mask, inputs["input_ids"], torch.full_like(inputs["input_ids"], -100) + ) + true_labels = masked_input_ids[:, 1:].reshape(-1) + + student_head = unwrapped_student.get_output_embeddings() + teacher_head = unwrapped_teacher.get_output_embeddings() + + loss = self.liger_jsd_loss( + student_input=student_hidden, + student_weight=student_head.weight, + teacher_input=teacher_hidden, + teacher_weight=teacher_head.weight, + true_labels=true_labels, + student_bias=getattr(student_head, "bias", None), + teacher_bias=getattr(teacher_head, "bias", None), + ) + + # The Liger JSD loss normalizes by the local number of valid tokens. Under gradient accumulation we + # want the global normalization, so rescale by `num_valid_local / num_items_in_batch`. + if num_items_in_batch is not None: + num_valid_local = (true_labels != -100).sum().clamp_min(1) + if isinstance(num_items_in_batch, torch.Tensor): + num_items_in_batch = num_items_in_batch.to(loss.device) + loss = loss * num_valid_local / num_items_in_batch + + del student_hidden, teacher_hidden, true_labels + else: + outputs_student = model( + input_ids=inputs["input_ids"], + attention_mask=inputs["attention_mask"], + ) + + self.teacher_model.eval() + with torch.no_grad(): + outputs_teacher = self.teacher_model( + input_ids=inputs["input_ids"], + attention_mask=inputs["attention_mask"], + ) + + # Standard causal shift: logits at position i predict the token at i + 1. The `labels != -100` mask + # inside `generalized_jsd_loss` already excludes prompt (and padding) positions, so we do not slice by + # prompt length. Slicing by `inputs["prompts"].shape[1]` (the batch-max prompt width) would drop real + # completion tokens for samples whose prompt is shorter than the batch maximum, since `labels` is + # padded to the full-sequence width independently of `prompts`. + shifted_student_logits = outputs_student.logits[:, :-1, :] + shifted_teacher_logits = outputs_teacher.logits[:, :-1, :] + shifted_labels = inputs["labels"][:, 1:] + loss = self.generalized_jsd_loss( + student_logits=shifted_student_logits, + teacher_logits=shifted_teacher_logits, + labels=shifted_labels, + beta=self.beta, + temperature=self.temperature, + num_items_in_batch=num_items_in_batch, + ) + + if self.use_uld_loss and self.teacher_tokenizer is not None: + student_labels = inputs["labels"].clone() + if self.processing_class.pad_token_id is not None: + student_labels[student_labels == self.processing_class.pad_token_id] = -100 + if self.teacher_tokenizer.pad_token_id is not None: + teacher_labels[teacher_labels == self.teacher_tokenizer.pad_token_id] = -100 + + student_byte_offsets = inputs.get("byte_offsets") + if self.uld_loss_fn.use_extended_uld and student_byte_offsets is None: + raise ValueError("Input batches must include `byte_offsets` when `use_extended_uld=True`.") + + loss = self.uld_loss_fn( + student_logits=outputs_student.logits, + teacher_logits=outputs_teacher.logits, + student_labels=student_labels, + teacher_labels=teacher_labels, + student_input_ids=inputs["input_ids"], + teacher_input_ids=teacher_input_ids, + student_byte_offsets=student_byte_offsets, + teacher_byte_offsets=teacher_completion_byte_offsets, + ) + + if hasattr(self.uld_loss_fn, "last_matched_loss") and hasattr(self.uld_loss_fn, "last_unmatched_loss"): + ga = max(1, int(self.args.gradient_accumulation_steps)) + step_eq = 1.0 / ga + matched_val = ( + self.uld_loss_fn.last_matched_loss.item() + if self.uld_loss_fn.last_matched_loss is not None + else 0.0 + ) + unmatched_val = ( + self.uld_loss_fn.last_unmatched_loss.item() + if self.uld_loss_fn.last_unmatched_loss is not None + else 0.0 + ) + + self._matched_sum += matched_val + self._unmatched_sum += unmatched_val + self._matched_step_eq += step_eq + self._unmatched_step_eq += step_eq + + empty_cache() + + return (loss, outputs_student) if return_outputs else loss + + def generate_on_policy_outputs(self, model, inputs, generation_config, pad_token_id=None): + # Generate output with respect to the prompt only + generated_outputs = model.generate( + input_ids=inputs["prompts"], + attention_mask=inputs.get("prompt_attention_mask", None), + generation_config=generation_config, + return_dict_in_generate=True, + ) + # Get the generated token IDs + generated_tokens = generated_outputs.sequences + + batch_size = generated_tokens.size(0) + device = generated_tokens.device + + prompt_mask = inputs.get("prompt_attention_mask") + pad_token_id = pad_token_id if pad_token_id is not None else self.processing_class.pad_token_id + + # model.generate() returns full sequences (prompt + completion), so completions start + # after the full padded prompt width. + prompt_lengths = torch.full((batch_size,), inputs["prompts"].shape[1], dtype=torch.long, device=device) + + new_input_ids = generated_tokens + new_attention_mask, new_labels = self._build_sequence_batch(new_input_ids, prompt_lengths, pad_token_id) + + prompt_texts = [] + completion_texts = [] + for idx in range(batch_size): + length = int(prompt_lengths[idx].item()) + prompt_tokens = inputs["prompts"][idx] + if prompt_mask is not None: + prompt_tokens = prompt_tokens[prompt_mask[idx].bool()] + elif pad_token_id is not None: + prompt_tokens = prompt_tokens[prompt_tokens != pad_token_id] + prompt_texts.append( + self.processing_class.decode( + prompt_tokens.tolist(), + skip_special_tokens=False, + clean_up_tokenization_spaces=False, + ) + ) + completion_tokens = new_input_ids[idx, length:] + completion_tokens = completion_tokens[new_labels[idx, length:] != -100] + completion_texts.append( + self.processing_class.decode( + completion_tokens.tolist(), + skip_special_tokens=False, + clean_up_tokenization_spaces=False, + ) + ) + + return new_input_ids, new_attention_mask, new_labels, prompt_texts, completion_texts + + def _liger_student_forward(self, student, inputs): + """Decoder-only forward used by the Liger JSD path (skips lm_head to save memory).""" + if hasattr(student, "get_decoder") and student.get_decoder() is not None: + decoder = student.get_decoder() + else: + decoder = getattr(student, getattr(student, "base_model_prefix", "model"), student) + return decoder( + input_ids=inputs["input_ids"], + attention_mask=inputs["attention_mask"], + use_cache=False, + ) + + def _get_liger_zero3_lm_head_gather_ctx(self, model: nn.Module): + if not self.use_liger_gkd_loss: + return nullcontext() + + deepspeed_plugin = self.accelerator.state.deepspeed_plugin + if deepspeed_plugin is None or deepspeed_plugin.zero_stage != 3: + return nullcontext() + + import deepspeed + + unwrapped_student = self.accelerator.unwrap_model(model) + unwrapped_teacher = self.accelerator.unwrap_model(self.teacher_model) + student_head = unwrapped_student.get_output_embeddings() + teacher_head = unwrapped_teacher.get_output_embeddings() + params = [student_head.weight, teacher_head.weight] + if student_head.bias is not None: + params.append(student_head.bias) + if teacher_head.bias is not None: + params.append(teacher_head.bias) + return deepspeed.zero.GatheredParameters(params, modifier_rank=None) + + @profiling_decorator + def training_step( + self, model: nn.Module, inputs: dict[str, torch.Tensor | Any], num_items_in_batch: int | None = None + ) -> torch.Tensor: + """ + Perform a training step for the General Online Logit Distillation (GOLD) model. + + This method implements the on-policy learning approach described in the GOLD blog post. With probability + `self.lmbda`, it generates new responses using the student model, which are then used for training instead of + the offline original inputs. + """ + buffer_steps = self.args.gradient_accumulation_steps + + # Keep lm_head gathered across forward+backward for Liger + ZeRO-3. + with self._get_liger_zero3_lm_head_gather_ctx(model): + loss = super().training_step(model, inputs, num_items_in_batch) + + slice_idx = (self._step - 1) % buffer_steps + + on_policy = False + if self._buffered_on_policy is not None and slice_idx < len(self._buffered_on_policy): + on_policy = self._buffered_on_policy[slice_idx] + + if on_policy and self._buffered_text_logs is not None and self._buffered_text_logs[slice_idx] is not None: + prompt_texts, completion_texts = self._buffered_text_logs[slice_idx] + self._textual_logs["prompt"].extend(gather_object(prompt_texts)) + self._textual_logs["completion"].extend(gather_object(completion_texts)) + + loss_scalar = float(loss.detach()) + step_equiv = 1.0 / self.args.gradient_accumulation_steps + + if on_policy: + self._on_policy_loss_total += loss_scalar + self._on_policy_step_equiv += step_equiv + else: + self._off_policy_loss_total += loss_scalar + self._off_policy_step_equiv += step_equiv + return loss + + def log(self, logs: dict[str, float], start_time: float | None = None) -> None: + mode = "train" if self.model.training else "eval" + metrics = {key: sum(val) / len(val) for key, val in self._metrics[mode].items()} # average the metrics + + if mode == "train": + device = self.accelerator.device if hasattr(self.accelerator, "device") else torch.device("cpu") + vec = torch.tensor( + [ + self._on_policy_loss_total, + self._off_policy_loss_total, + self._on_policy_step_equiv, + self._off_policy_step_equiv, + self._matched_sum, + self._unmatched_sum, + self._matched_step_eq, + self._unmatched_step_eq, + ], + dtype=torch.float64, + device=device, + ) + + if ( + getattr(self.accelerator, "distributed_type", DistributedType.NO) != DistributedType.NO + and dist.is_available() + and dist.is_initialized() + ): + dist.all_reduce(vec, op=dist.ReduceOp.SUM) + + ( + on_sum, + off_sum, + on_eq, + off_eq, + matched_sum, + unmatched_sum, + matched_eq, + unmatched_eq, + ) = vec.tolist() + + if on_eq > 0: + logs["on_policy_loss"] = round(on_sum / on_eq, 4) + if off_eq > 0: + logs["off_policy_loss"] = round(off_sum / off_eq, 4) + + if matched_eq > 0: + logs["matched_loss"] = round(matched_sum / matched_eq, 4) + if unmatched_eq > 0: + logs["unmatched_loss"] = round(unmatched_sum / unmatched_eq, 4) + + self._on_policy_loss_total = self._off_policy_loss_total = 0.0 + self._on_policy_step_equiv = self._off_policy_step_equiv = 0.0 + self._matched_sum = self._unmatched_sum = 0.0 + self._matched_step_eq = self._unmatched_step_eq = 0.0 + + # This method can be called both in training and evaluation. When called in evaluation, the keys in `logs` + # start with "eval_". We need to add the prefix "eval_" to the keys in `metrics` to match the format. + if mode == "eval": + metrics = {f"eval_{key}": val for key, val in metrics.items()} + + logs.update(metrics) + super().log(logs, start_time) + self._metrics[mode].clear() + + if ( + self.accelerator.is_main_process + and self.log_completions + and ((self.state.global_step % self.log_completion_steps) == 0) + ): + if is_rich_available(): + print_prompt_completions_sample_uld( + self._textual_logs["prompt"], + self._textual_logs["completion"], + self.state.global_step, + self.num_completions_to_print, + ) + + if self.args.report_to and "wandb" in self.args.report_to and wandb.run is not None: + import pandas as pd + + table = { + "step": [self.state.global_step] * len(self._textual_logs["prompt"]), + "prompt": self._textual_logs["prompt"], + "completion": self._textual_logs["completion"], + } + df = pd.DataFrame(table) + if self.wandb_log_unique_prompts: + df = df.drop_duplicates(subset=["prompt"]) + if self.num_completions_to_print and len(df) > 0: + df = df.sample(n=self.num_completions_to_print, random_state=42) + wandb.log({"completions": wandb.Table(dataframe=df)}) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/grpo_with_replay_buffer/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/grpo_with_replay_buffer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..708ea62d6740e6ca43c7de21bb716abce1e7c284 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/grpo_with_replay_buffer/__init__.py @@ -0,0 +1,16 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .grpo_with_replay_buffer_config import GRPOWithReplayBufferConfig +from .grpo_with_replay_buffer_trainer import GRPOWithReplayBufferTrainer, ReplayBuffer diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/grpo_with_replay_buffer/grpo_with_replay_buffer_config.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/grpo_with_replay_buffer/grpo_with_replay_buffer_config.py new file mode 100644 index 0000000000000000000000000000000000000000..9955af51dcf2264c905452e7bb578f3041a60b5c --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/grpo_with_replay_buffer/grpo_with_replay_buffer_config.py @@ -0,0 +1,34 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field + +from ...trainer.grpo_config import GRPOConfig + + +@dataclass +class GRPOWithReplayBufferConfig(GRPOConfig): + """ + New Parameters: + replay_buffer_size (`int`, *optional*, defaults to `64`): + A cache that stores the rollouts with the highest advantage scores and variance per group. If a new + group has 0 variance, it is replaced with a group sampled from the replay buffer. + """ + + replay_buffer_size: int = field( + default=64, + metadata={ + "help": "A cache that stores the rollouts with the highest advantage scores and variance per group. If a new group has 0 variance, it is replaced with a group sampled from the replay buffer." + }, + ) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/grpo_with_replay_buffer/grpo_with_replay_buffer_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/grpo_with_replay_buffer/grpo_with_replay_buffer_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..8dc3b3ce20550aba0f4c68ae84ba79cb6543e653 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/grpo_with_replay_buffer/grpo_with_replay_buffer_trainer.py @@ -0,0 +1,797 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import heapq +from typing import Any + +import torch +from accelerate.utils import gather_object + +from ...data_utils import apply_chat_template, is_conversational, prepare_multimodal_messages +from ...models.utils import disable_gradient_checkpointing +from ...trainer.grpo_trainer import GRPOTrainer +from ...trainer.utils import nanmax, nanmin, nanstd, pad +from .grpo_with_replay_buffer_config import GRPOWithReplayBufferConfig + + +class ReplayBuffer: + """ + A simple replay buffer to store and sample previously seen rollouts. + """ + + def __init__(self, max_size: int): + self.max_size = max_size + self.heap = [] # Min-heap of (score, data) tuples + + def add(self, scores: list[float], data: list[dict]): + for score, datum in zip(scores, data, strict=True): + if len(self.heap) < self.max_size: + heapq.heappush(self.heap, (score, datum)) + else: + # Only add if score is better than worst (minimum) item + if score > self.heap[0][0]: + heapq.heapreplace(self.heap, (score, datum)) + + def sample(self, num_samples: int) -> list[dict[str, torch.Tensor]]: + if not self.heap: + return None + + # Sample by normalized scores + scores = torch.tensor([item[0] for item in self.heap], dtype=torch.float32) + probabilities = scores / scores.sum() + replacement = False + if num_samples > len(self.heap): + replacement = True + chosen_indices = torch.multinomial(probabilities, num_samples, replacement=replacement).tolist() + return [self.heap[i][1] for i in chosen_indices] + + +class GRPOWithReplayBufferTrainer(GRPOTrainer): + def __init__(self, args: GRPOWithReplayBufferConfig | None = None, **kwargs): + super().__init__(args=args, **kwargs) + self.replay_buffer = ReplayBuffer(args.replay_buffer_size) if args.replay_buffer_size > 0 else None + + def _generate_and_score_completions( + self, inputs: list[dict[str, torch.Tensor | Any]] + ) -> dict[str, torch.Tensor | Any]: + device = self.accelerator.device + mode = "train" if self.model.training else "eval" + + prompts = [x["prompt"] for x in inputs] + + if "images" in inputs[0]: + images = [example.get("images") for example in inputs] + elif "image" in inputs[0]: + images = [[example.get("image")] if example.get("image") is not None else None for example in inputs] + else: + images = None + # Transformers requires at least one image in the batch, otherwise it throws an error + if images is not None and all(img_list == [] for img_list in images): + images = None + + # If the prompts are conversational and the inputs contain images, we need to convert the prompts from + # [{"role": "user", "content": "What color is the sky?"}] to + # [{"role": "user", "content": [{"type": "image", "image": }, {"type": "text", "text": "What color is the sky?"}]}] + if images is not None: + if not is_conversational(inputs[0]): + raise ValueError( + "Multimodal training requires conversational prompts. It looks like the dataset contains " + "non-conversational inputs, likely because a chat template was applied before passing the dataset " + "to the trainer. Please provide the raw conversational prompts and let the trainer apply the chat " + "template internally." + ) + prompts = [ + prepare_multimodal_messages(prompt, images=image_list) + for prompt, image_list in zip(prompts, images, strict=True) + ] + + dataset_images = images # preserve dataset images before _generate may overwrite + ( + prompt_ids_list, + completion_ids_list, + tool_mask_list, + completions, + num_items_in_batch, + sampling_per_token_logps_list, + extra_fields, + images, + tool_images, + ) = self._generate(prompts) + if images is None: + images = dataset_images # restore dataset images (rollout_func path returns None) + + # Convert lists of token IDs to padded tensors + prompt_ids = [torch.tensor(ids) for ids in prompt_ids_list] + prompt_mask = [torch.ones_like(ids, dtype=torch.long) for ids in prompt_ids] + prompt_ids = pad( + prompt_ids, + padding_value=self._tokenizer.pad_token_id, + padding_side="left", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + prompt_mask = pad( + prompt_mask, + padding_value=0, + padding_side="left", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + completion_ids = [torch.tensor(ids) for ids in completion_ids_list] + completion_mask = [torch.ones_like(ids, dtype=torch.long) for ids in completion_ids] + completion_ids = pad( + completion_ids, + padding_value=self._tokenizer.pad_token_id, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + completion_mask = pad( + completion_mask, + padding_value=0, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + if sampling_per_token_logps_list is not None: + sampling_per_token_logps = [torch.tensor(logps) for logps in sampling_per_token_logps_list] + sampling_per_token_logps = pad( + sampling_per_token_logps, + padding_value=0.0, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + else: + sampling_per_token_logps = None + if self.tools: + tool_mask = [torch.tensor(mask) for mask in tool_mask_list] + tool_mask = pad( + tool_mask, + padding_value=1, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) # 0 for tool result tokens, 1 elsewhere + + # If mask_truncated_completions is enabled, zero out truncated completions in completion_mask + if self.mask_truncated_completions: + eos_and_pad = [self._tokenizer.eos_token_id, self._tokenizer.pad_token_id] + is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids_list], device=device) + completion_mask = completion_mask * (~is_truncated).unsqueeze(1).int() + + # Concatenate prompt_mask with completion_mask for logit computation + prompt_completion_ids = torch.cat([prompt_ids, completion_ids], dim=1) # (B, P+C) + attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) # (B, P+C) + + logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens + batch_size = self.args.per_device_train_batch_size if mode == "train" else self.args.per_device_eval_batch_size + + num_images = [len(img_list) if img_list else 0 for img_list in images] if images is not None else None + + # Get forward_kwargs for models with multimodal inputs + if images is not None: + prompts_text = [ + apply_chat_template( + {"prompt": prompt}, self.processing_class, tools=self.tools, **self.chat_template_kwargs + )["prompt"] + for prompt in prompts + ] + prompt_inputs = self.processing_class(images=images, text=prompts_text, padding=True, return_tensors="pt") + prompt_inputs = super()._prepare_inputs(prompt_inputs) + forward_kwargs = {k: v for k, v in prompt_inputs.items() if k not in ["input_ids", "attention_mask"]} + else: + forward_kwargs = {} + + # If token_type_ids are used, extend them with zeros for the completion part + if "token_type_ids" in forward_kwargs: + token_type_ids = forward_kwargs["token_type_ids"] + if self.pad_to_multiple_of is not None: + # Needed only with pad_to_multiple_of: otherwise prompt_ids and token_type_ids must have equal len + padding_size = prompt_ids.size(1) - token_type_ids.size(1) + if padding_size > 0: + token_type_ids = torch.cat( + [token_type_ids.new_zeros((token_type_ids.size(0), padding_size)), token_type_ids], dim=1 + ) + forward_kwargs["token_type_ids"] = torch.cat( + [token_type_ids, token_type_ids.new_zeros(completion_ids.shape)], dim=1 + ) + # If mm_token_type_ids are used, extend them with zeros for the completion part + if "mm_token_type_ids" in forward_kwargs: + mm_token_type_ids = forward_kwargs["mm_token_type_ids"] + if self.pad_to_multiple_of is not None: + # Needed only with pad_to_multiple_of: otherwise prompt_ids and mm_token_type_ids must have equal len + padding_size = prompt_ids.size(1) - mm_token_type_ids.size(1) + if padding_size > 0: + mm_token_type_ids = torch.cat( + [mm_token_type_ids.new_zeros((mm_token_type_ids.size(0), padding_size)), mm_token_type_ids], + dim=1, + ) + forward_kwargs["mm_token_type_ids"] = torch.cat( + [mm_token_type_ids, mm_token_type_ids.new_zeros(completion_ids.shape)], dim=1 + ) + + # When gradient checkpointing is enabled with use_reentrant=True (non default), calling the model inside a + # torch.no_grad() block triggers a harmless PyTorch warning ("None of the inputs have requires_grad=True"). + # Temporarily disable checkpointing to avoid this warning during inference. + with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs): + # If the generation and optimization steps are misaligned—i.e., if generation does not occur at the end of + # a full optimizer step (when gradient_accumulation_steps is not a multiple of generate_every)—then the + # samples may come from an earlier version of the model. In that case, we need to track old_per_token_logps + # for importance sampling. If the steps are aligned, importance sampling isn't necessary and we set + # old_per_token_logps to None. + # When using vLLM, we always compute old_per_token_logps for importance sampling, it was shown that the + # distribution mismatch between vLLM and the training model can be large and harm the training. + generate_every = self.args.steps_per_generation * self.num_iterations # generation frequency + if self.args.gradient_accumulation_steps % generate_every != 0 or ( + self.use_vllm and self.vllm_importance_sampling_correction + ): + old_per_token_logps, _ = self._get_per_token_logps_and_entropies( + self.model, + prompt_completion_ids, + attention_mask, + logits_to_keep, + batch_size, + num_images=num_images, + **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes + ) + else: + old_per_token_logps = None + + # Compute the importance sampling ratio when using vLLM, to correct for potential distribution mismatch + if self.use_vllm and self.vllm_importance_sampling_correction: + importance_sampling_ratio = torch.exp(old_per_token_logps - sampling_per_token_logps) + importance_sampling_ratio = torch.clamp( + importance_sampling_ratio, + min=self.vllm_importance_sampling_clip_min, + max=self.vllm_importance_sampling_clip_max, + ) + + # Compute the per-token log probabilities for the reference model + if self.beta != 0.0: + if self.ref_model is not None: + ref_per_token_logps, _ = self._get_per_token_logps_and_entropies( + self.ref_model, + prompt_completion_ids, + attention_mask, + logits_to_keep, + batch_size=batch_size, + num_images=num_images, + **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes + ) + else: + with self.accelerator.unwrap_model(self.model).disable_adapter(): + ref_per_token_logps, _ = self._get_per_token_logps_and_entropies( + self.model, + prompt_completion_ids, + attention_mask, + logits_to_keep, + batch_size=batch_size, + num_images=num_images, + **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes + ) + else: + ref_per_token_logps = None + + # Decode + prompts_text = self.processing_class.batch_decode(prompt_ids, skip_special_tokens=True) + completions_text = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True) + + # Merge extra_fields from rollout_func into inputs for reward functions + if extra_fields: + for i, inp in enumerate(inputs): + for key, values in extra_fields.items(): + if isinstance(values, list) and i < len(values): + inp[key] = values[i] + elif not isinstance(values, list): + inp[key] = values + + # Calculate rewards for each reward function. rewards_per_func aggregates rewards across all processes. This is + # important because rewards will be normalized per group, and completions are distributed. We will later slice + # rewards_per_func to extract each process's subset. + rewards_per_func = self._calculate_rewards(inputs, prompts, completions, completion_ids_list) + + # Apply weights to each reward function's output and sum + rewards = (rewards_per_func * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1) + + # Compute grouped-wise rewards + mean_grouped_rewards = rewards.view(-1, self.num_generations).mean(dim=1) + + # Normalize the rewards to compute the advantages + mean_grouped_rewards = mean_grouped_rewards.repeat_interleave(self.num_generations, dim=0) + advantages = rewards - mean_grouped_rewards + + grouped_std_rewards = rewards.view(-1, self.num_generations).std(dim=1) + grouped_std_rewards = grouped_std_rewards.repeat_interleave(self.num_generations, dim=0) + + if self.scale_rewards in ["group", "none"]: + # If self.scale_rewards = "none", we'll still log group level std + std_rewards = grouped_std_rewards.clone() + elif self.scale_rewards == "batch": + # Compute global std + std_rewards = rewards.std().expand_as(rewards) + else: + raise ValueError( + f"Invalid value for scale_rewards: {self.scale_rewards}. Must be one of 'batch', 'group', or 'none'." + ) + + is_std_zero = torch.isclose(std_rewards, torch.zeros_like(std_rewards)) + if self.scale_rewards != "none": + advantages = advantages / (std_rewards + 1e-4) + + # Slice to keep only the local part of the data + process_slice = slice( + self.accelerator.process_index * len(prompts), + (self.accelerator.process_index + 1) * len(prompts), + ) + all_process_advantages = advantages.clone() # keep the aggregated advantages for logging + advantages = advantages[process_slice] + grouped_std_rewards = grouped_std_rewards[process_slice] + + # Calculate mean reward per function, but only for samples where the function was applied (non-NaN values) + for i, reward_func_name in enumerate(self.reward_func_names): + mean_rewards = torch.nanmean(rewards_per_func[:, i]).item() + self._metrics[mode][f"rewards/{reward_func_name}/mean"].append(mean_rewards) + std_func_rewards = nanstd(rewards_per_func[:, i]).item() + self._metrics[mode][f"rewards/{reward_func_name}/std"].append(std_func_rewards) + rewards = (rewards_per_func * self.reward_weights.to(rewards_per_func.device).unsqueeze(0)).nansum(dim=1) + self._metrics[mode]["reward"].append(rewards.mean().item()) + self._metrics[mode]["reward_std"].append(rewards.std().item()) + self._metrics[mode]["frac_reward_zero_std"].append(is_std_zero.float().mean().item()) + + # Log prompt and completion texts + self._logs["prompt"].extend(gather_object(prompts_text)) + self._logs["completion"].extend(gather_object(completions_text)) + for i, name in enumerate(self.reward_func_names): + self._logs["rewards"][name].extend(rewards_per_func[:, i].tolist()) + self._logs["advantages"].extend(all_process_advantages.tolist()) + + if images is not None: + self._logs["images"].extend(gather_object(images)) + + if self.use_vllm and self.vllm_importance_sampling_correction: + delta = torch.abs(old_per_token_logps - sampling_per_token_logps) + mask = completion_mask.bool() if not self.tools else (completion_mask * tool_mask).bool() + delta = delta[mask] + mean_delta = torch.mean(delta) if delta.numel() > 0 else torch.tensor(0.0, device=device) + max_delta = torch.max(delta) if delta.numel() > 0 else torch.tensor(0.0, device=device) + self._metrics[mode]["sampling/sampling_logp_difference/mean"].append( + self.accelerator.gather(mean_delta).mean().item() + ) + self._metrics[mode]["sampling/sampling_logp_difference/max"].append( + self.accelerator.gather(max_delta).max().item() + ) + + flat_is_ratio = importance_sampling_ratio[mask] + min_importance_sampling_ratio = ( + torch.min(flat_is_ratio) if flat_is_ratio.numel() > 0 else torch.tensor(0.0, device=device) + ) + mean_importance_sampling_ratio = ( + torch.mean(flat_is_ratio) if flat_is_ratio.numel() > 0 else torch.tensor(0.0, device=device) + ) + max_importance_sampling_ratio = ( + torch.max(flat_is_ratio) if flat_is_ratio.numel() > 0 else torch.tensor(0.0, device=device) + ) + self._metrics[mode]["sampling/importance_sampling_ratio/min"].append( + nanmin(self.accelerator.gather(min_importance_sampling_ratio)).item() + ) + self._metrics[mode]["sampling/importance_sampling_ratio/mean"].append( + self.accelerator.gather(mean_importance_sampling_ratio).nanmean().item() + ) + self._metrics[mode]["sampling/importance_sampling_ratio/max"].append( + nanmax(self.accelerator.gather(max_importance_sampling_ratio)).item() + ) + outputs_after_sampling_buffer = self.update_with_replay_buffer( + advantages, + grouped_std_rewards, + prompt_ids, + prompt_mask, + completion_ids, + completion_mask, + forward_kwargs, + num_items_in_batch, + old_per_token_logps, + ref_per_token_logps, + importance_sampling_ratio if self.use_vllm and self.vllm_importance_sampling_correction else None, + ) + if outputs_after_sampling_buffer is not None: + return outputs_after_sampling_buffer + else: + output = { + "prompt_ids": prompt_ids, + "prompt_mask": prompt_mask, + "completion_ids": completion_ids, + "completion_mask": completion_mask, + "advantages": advantages, + "num_items_in_batch": num_items_in_batch, + } + if old_per_token_logps is not None: + output["old_per_token_logps"] = old_per_token_logps + if self.use_vllm and self.vllm_importance_sampling_correction: + output["importance_sampling_ratio"] = importance_sampling_ratio + if ref_per_token_logps is not None: + output["ref_per_token_logps"] = ref_per_token_logps + if "pixel_values" in forward_kwargs: + output["pixel_values"] = forward_kwargs["pixel_values"] + if "image_grid_thw" in forward_kwargs: + output["image_grid_thw"] = forward_kwargs["image_grid_thw"] + if "pixel_attention_mask" in forward_kwargs: + output["pixel_attention_mask"] = forward_kwargs["pixel_attention_mask"] + if "image_sizes" in forward_kwargs: + output["image_sizes"] = forward_kwargs["image_sizes"] + if "token_type_ids" in forward_kwargs: + output["token_type_ids"] = forward_kwargs["token_type_ids"] + if images is not None: + output["num_images"] = num_images + if self.tools: + output["tool_mask"] = tool_mask + return output + + def slice_group_data( + self, data: torch.Tensor, mask: torch.Tensor, group_idx: int + ) -> tuple[torch.Tensor, torch.Tensor]: + """ + Slices the input data and mask tensors for a specific group index. Also trims the sequence length to the + maximum length in the group based on the mask. + + Args: + data: Tensor of shape (num_groups * num_generations, seq_length) + mask: Tensor of shape (num_groups * num_generations, seq_length) + group_idx: Index of the group to slice + Returns: + Tuple of (sliced_data, sliced_mask) for the specified group, with sequence length trimmed to the maximum + length in the group. + """ + start_idx = group_idx * self.num_generations + end_idx = (group_idx + 1) * self.num_generations + group_data = data[start_idx:end_idx] + group_mask = mask[start_idx:end_idx] + group_max_len = group_mask.sum(dim=1).max().item() + return group_data[:, :group_max_len], group_mask[:, :group_max_len] + + def update_replay_buffer( + self, + groups_with_variance: torch.Tensor, + group_advantages: torch.Tensor, + group_std_rewards: torch.Tensor, + prompt_ids: torch.Tensor, + prompt_mask: torch.Tensor, + completion_ids: torch.Tensor, + completion_mask: torch.Tensor, + forward_kwargs: dict, + optional_vision_fields: list[str] = None, + old_per_token_logps: torch.Tensor | None = None, + ref_per_token_logps: torch.Tensor | None = None, + importance_sampling_ratio: float | None = None, + ) -> None: + """ + Update the replay buffer with groups that have reward variance (std > 0). + + Args: + groups_with_variance: Boolean tensor indicating which groups have reward variance + group_advantages: Tensor of shape (num_groups, num_generations) containing advantage values + group_std_rewards: Tensor of shape (num_groups, num_generations) containing std of rewards per group + prompt_ids: Tensor containing prompt token IDs + prompt_mask: Tensor containing prompt attention masks + completion_ids: Tensor containing completion token IDs + completion_mask: Tensor containing completion attention masks + forward_kwargs: Dictionary containing additional prompt inputs (vision data, etc.) + optional_vision_fields: List of optional vision-related fields to include if present in forward_kwargs + old_per_token_logps: Optional tensor of old per-token log probabilities + ref_per_token_logps: Optional tensor of reference per-token log probabilities + importance_sampling_ratio: Optional importance sampling correction ratio + """ + # Prepare buffered outputs for groups with variance + buffered_outputs = [] + for _, group_idx in enumerate(groups_with_variance.nonzero(as_tuple=True)[0].unique().tolist()): + group_prompt_ids, group_prompt_mask = self.slice_group_data(prompt_ids, prompt_mask, group_idx) + group_completion_ids, group_completion_mask = self.slice_group_data( + completion_ids, completion_mask, group_idx + ) + + # Store unpadded data in the buffer + buffered_output = { + "prompt_ids": group_prompt_ids, + "completion_ids": group_completion_ids, + "advantages": group_advantages[group_idx].tolist(), + "prompt_mask": group_prompt_mask, + "completion_mask": group_completion_mask, + } + + # Add optional fields if they exist + optional_fields = { + "old_per_token_logps": old_per_token_logps if old_per_token_logps is not None else None, + "ref_per_token_logps": ref_per_token_logps if ref_per_token_logps is not None else None, + } + + for field_name, field_data in optional_fields.items(): + if field_data is not None: + buffered_output[field_name] = self.slice_group_data(field_data, completion_mask, group_idx)[0] + + # Add importance sampling if needed + if self.use_vllm and self.vllm_importance_sampling_correction: + buffered_output["importance_sampling_ratio"] = importance_sampling_ratio + + if optional_vision_fields: + # Add vision-related fields if they exist + for field_name in optional_vision_fields: + if field_name in forward_kwargs: + buffered_output[field_name] = self.slice_group_data( + forward_kwargs[field_name], prompt_mask, group_idx + )[0] + + buffered_outputs.append(buffered_output) + + if groups_with_variance.any(): + # Calculate replay buffer scores for groups with variance + replay_buffer_scores = (group_advantages.abs() * group_std_rewards).sum(dim=-1)[groups_with_variance] + # Add all groups to replay buffer at once (batch operation) + self.replay_buffer.add(replay_buffer_scores.tolist(), buffered_outputs) + + def sample_from_replay_buffer( + self, num_samples: int, optional_vision_fields: list[str] = None, optional_tensor_fields: list[str] = None + ) -> list[dict]: + """ + Sample groups from the replay buffer. + + Args: + num_samples: Number of samples to draw from the replay buffer + optional_vision_fields: List of optional vision-related fields to include if present in sampled data + optional_tensor_fields: List of optional tensor fields to include if present in sampled data + Returns: + List of sampled data dictionaries from the replay buffer + """ + sampled = self.replay_buffer.sample(num_samples=num_samples) + + # Extract and concatenate sampled data + sampled_data = { + "prompt_ids": [], + "prompt_mask": [], + "completion_ids": [], + "completion_mask": [], + "advantages": [], + } + + all_optional_fields = (optional_tensor_fields or []) + (optional_vision_fields or []) + # Initialize containers for optional fields if they exist in sampled data + for field in all_optional_fields: + if sampled and field in sampled[0]: + sampled_data[field] = [] + + # Extract data from each sampled item + for item in sampled: + # Handle core fields + for key in ["prompt_ids", "prompt_mask", "completion_ids", "completion_mask"]: + sampled_data[key].append(item[key]) + + # Handle advantages (list, not tensor) + sampled_data["advantages"].append(item["advantages"]) + + # Handle optional fields + for field in all_optional_fields: + if field in item: + sampled_data[field].append(item[field]) + + return sampled_data + + def update_with_replay_buffer( + self, + group_advantages: torch.Tensor, + group_std_rewards: torch.Tensor, + prompt_ids: torch.Tensor, + prompt_mask: torch.Tensor, + completion_ids: torch.Tensor, + completion_mask: torch.Tensor, + forward_kwargs: dict, + num_items_in_batch: int, + old_per_token_logps: torch.Tensor | None = None, + ref_per_token_logps: torch.Tensor | None = None, + importance_sampling_ratio: float | None = None, + ) -> None: + """ + Update current batch data with samples from replay buffer. + + Groups with reward variance (std > 0) are added to the replay buffer and then replaced with samples from the + buffer to improve training stability. + + Args: + group_advantages: Tensor of shape (num_groups, num_generations) containing advantage values + group_std_rewards: Tensor of shape (num_groups, num_generations) containing std of rewards per group + prompt_ids: Tensor containing prompt token IDs + prompt_mask: Tensor containing prompt attention masks + completion_ids: Tensor containing completion token IDs + completion_mask: Tensor containing completion attention masks + forward_kwargs: Dictionary containing additional prompt inputs (vision data, etc.) + num_items_in_batch: Number of items in the current batch + old_per_token_logps: Optional tensor of old per-token log probabilities + ref_per_token_logps: Optional tensor of reference per-token log probabilities + importance_sampling_ratio: Optional importance sampling correction ratio + """ + if self.replay_buffer.max_size <= 0: + return + + # Groups to consider for adding to the replay buffer + groups_with_variance = group_std_rewards.max(dim=0).values > 0 + # Groups to replace from the replay buffer + groups_without_variance = ~groups_with_variance + + # Track which optional fields are present in sampled data + optional_tensor_fields = ["old_per_token_logps", "ref_per_token_logps"] + vision_fields = ["pixel_values", "image_grid_thw", "pixel_attention_mask", "image_sizes"] + + self.update_replay_buffer( + groups_with_variance, + group_advantages, + group_std_rewards, + prompt_ids, + prompt_mask, + completion_ids, + completion_mask, + forward_kwargs, + vision_fields, + old_per_token_logps, + ref_per_token_logps, + importance_sampling_ratio, + ) + + # Sample from replay buffer to replace groups with variance + num_groups_to_replace = groups_without_variance.sum().item() + if not num_groups_to_replace: + return + + sampled_data = self.sample_from_replay_buffer( + num_samples=num_groups_to_replace, + optional_vision_fields=vision_fields, + optional_tensor_fields=optional_tensor_fields, + ) + + # Pad sampled data if they are shorter than the current batch sequences + # Or pad the current batch if sampled are longer + current_batch_prompt_seq_len = prompt_ids.size(1) + current_batch_completion_seq_len = completion_ids.size(1) + + groups_to_replace_idxs = groups_with_variance.logical_not().nonzero(as_tuple=True)[0].unique().tolist() + + # Determine target (max) sequence lengths once + sampled_prompt_lengths = [t.size(1) for t in sampled_data["prompt_ids"]] + sampled_completion_lengths = [t.size(1) for t in sampled_data["completion_ids"]] + target_prompt_len = max([current_batch_prompt_seq_len] + sampled_prompt_lengths) + target_completion_len = max([current_batch_completion_seq_len] + sampled_completion_lengths) + + # If any sampled prompt is longer, pad the whole batch prompt tensors once (left padding) + if target_prompt_len > current_batch_prompt_seq_len: + prompt_ids = pad( + list(prompt_ids.unbind(0)), + padding_value=self._tokenizer.pad_token_id, + pad_to_multiple_of=target_prompt_len, + padding_side="left", + ) + prompt_mask = pad( + list(prompt_mask.unbind(0)), padding_value=0, pad_to_multiple_of=target_prompt_len, padding_side="left" + ) + # If any sampled completion is longer, pad the whole batch completion tensors once (right padding) + if target_completion_len > current_batch_completion_seq_len: + completion_ids = pad( + list(completion_ids.unbind(0)), + padding_value=self._tokenizer.pad_token_id, + pad_to_multiple_of=target_completion_len, + padding_side="right", + ) + completion_mask = pad( + list(completion_mask.unbind(0)), + padding_value=0, + pad_to_multiple_of=target_completion_len, + padding_side="right", + ) + if old_per_token_logps is not None: + old_per_token_logps = pad( + list(old_per_token_logps.unbind(0)), + padding_value=0.0, + pad_to_multiple_of=target_completion_len, + padding_side="right", + ) + if ref_per_token_logps is not None: + ref_per_token_logps = pad( + list(ref_per_token_logps.unbind(0)), + padding_value=0.0, + pad_to_multiple_of=target_completion_len, + padding_side="right", + ) + + # Replace per-group data, padding only sampled groups that are shorter than the target + for i, group_idx in enumerate(groups_to_replace_idxs): + start_idx = group_idx * self.num_generations + end_idx = (group_idx + 1) * self.num_generations + idx_range = slice(start_idx, end_idx) + + # Pad sampled prompt to target length if needed + if sampled_data["prompt_ids"][i].size(1) < target_prompt_len: + sampled_data["prompt_ids"][i] = pad( + sampled_data["prompt_ids"][i], + padding_value=self._tokenizer.pad_token_id, + pad_to_multiple_of=target_prompt_len, + padding_side="left", + ) + sampled_data["prompt_mask"][i] = pad( + sampled_data["prompt_mask"][i], + padding_value=0, + pad_to_multiple_of=target_prompt_len, + padding_side="left", + ) + + # Pad sampled completion to target length if needed + if sampled_data["completion_ids"][i].size(1) < target_completion_len: + sampled_data["completion_ids"][i] = pad( + sampled_data["completion_ids"][i], + padding_value=self._tokenizer.pad_token_id, + pad_to_multiple_of=target_completion_len, + padding_side="right", + ) + sampled_data["completion_mask"][i] = pad( + sampled_data["completion_mask"][i], + padding_value=0, + pad_to_multiple_of=target_completion_len, + padding_side="right", + ) + if "old_per_token_logps" in sampled_data: + sampled_data["old_per_token_logps"][i] = pad( + sampled_data["old_per_token_logps"][i], + padding_value=0.0, + pad_to_multiple_of=target_completion_len, + padding_side="right", + ) + if "ref_per_token_logps" in sampled_data: + sampled_data["ref_per_token_logps"][i] = pad( + sampled_data["ref_per_token_logps"][i], + padding_value=0.0, + pad_to_multiple_of=target_completion_len, + padding_side="right", + ) + + # Assign (replace) group slice + prompt_ids[idx_range] = sampled_data["prompt_ids"][i] + prompt_mask[idx_range] = sampled_data["prompt_mask"][i] + completion_ids[idx_range] = sampled_data["completion_ids"][i] + completion_mask[idx_range] = sampled_data["completion_mask"][i] + group_advantages[group_idx] = sampled_data["advantages"][i] + + if "old_per_token_logps" in sampled_data: + old_per_token_logps[idx_range] = sampled_data["old_per_token_logps"][i] + if "ref_per_token_logps" in sampled_data: + ref_per_token_logps[idx_range] = sampled_data["ref_per_token_logps"][i] + + for field in vision_fields: + if field in sampled_data and field in forward_kwargs: + forward_kwargs[field][idx_range] = sampled_data[field][i] + + # Prepare final outputs after sampling and replacement + outputs_after_sampling_buffer = { + "prompt_ids": prompt_ids, + "prompt_mask": prompt_mask, + "completion_ids": completion_ids, + "completion_mask": completion_mask, + "advantages": group_advantages, + } + + # Replace optional tensor fields if they exist + for field in optional_tensor_fields: + if field in sampled_data: + outputs_after_sampling_buffer[field] = ( + old_per_token_logps if field == "old_per_token_logps" else ref_per_token_logps + ) + + # Replace vision fields if they exist + for field in vision_fields: + if field in sampled_data and field in forward_kwargs: + outputs_after_sampling_buffer[field] = forward_kwargs[field] + + outputs_after_sampling_buffer["num_items_in_batch"] = num_items_in_batch + if self.use_vllm and self.vllm_importance_sampling_correction: + outputs_after_sampling_buffer["importance_sampling_ratio"] = importance_sampling_ratio + + return outputs_after_sampling_buffer diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gspo_token/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gspo_token/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4c9814fddca65cfe8d5ccabccc9d646141e19364 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gspo_token/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .grpo_trainer import GRPOTrainer diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gspo_token/grpo_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gspo_token/grpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..0522058bc6eeda33779b6182130478545d1ff9b6 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/gspo_token/grpo_trainer.py @@ -0,0 +1,157 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch + +from ...trainer.grpo_trainer import GRPOTrainer as _GRPOTrainer +from ...trainer.utils import nanmax, nanmin + + +class GRPOTrainer(_GRPOTrainer): + def _compute_loss(self, model, inputs): + # Compute the per-token log probabilities for the model + prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"] + completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"] + input_ids = torch.cat([prompt_ids, completion_ids], dim=1) + attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) + logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens + + # Compute the per_token_logps and the entropy at each position in the completion + per_token_logps, entropies = self._get_per_token_logps_and_entropies( + model, + input_ids, + attention_mask, + logits_to_keep, + compute_entropy=True, + pixel_values=inputs.get("pixel_values"), + image_grid_thw=inputs.get("image_grid_thw"), + num_images=inputs.get("num_images"), + pixel_attention_mask=inputs.get("pixel_attention_mask"), + image_sizes=inputs.get("image_sizes"), + token_type_ids=inputs.get("token_type_ids"), + ) + + if self.top_entropy_quantile < 1.0: + entropy_mask = self.get_high_entropy_mask(entropies, completion_mask, 1 - self.top_entropy_quantile) + else: + entropy_mask = None + + # Compute the KL divergence between the model and the reference model + if self.beta != 0.0: + ref_per_token_logps = inputs["ref_per_token_logps"] + per_token_kl = ( + torch.exp(ref_per_token_logps - per_token_logps) - (ref_per_token_logps - per_token_logps) - 1 + ) + + # Compute the loss + advantages = inputs["advantages"] + # When num_iterations == 1 and steps_per_generation <= gradient_accumulation_steps, + # old_per_token_logps == per_token_logps. In this case we can skip its computation + # (see _generate_and_score_completions) and instead use per_token_logps.detach(). + # The exception is when using vLLM, where we always compute old_per_token_logps + # for importance sampling + old_per_token_logps = inputs.get("old_per_token_logps") + old_per_token_logps = per_token_logps.detach() if old_per_token_logps is None else old_per_token_logps + + log_ratio = per_token_logps - old_per_token_logps + if self.importance_sampling_level == "token": + log_importance_weights = log_ratio + elif self.importance_sampling_level == "sequence": + log_importance_weights = (log_ratio * completion_mask).sum(-1) / completion_mask.sum(-1).clamp(min=1.0) + log_importance_weights = log_importance_weights.unsqueeze(-1) + elif self.importance_sampling_level == "sequence_token": + # GSPO-token: sg[si(θ)] * πθ(yi,t)/sg[πθ(yi,t)] + seq_level_log_weight = (log_ratio * completion_mask).sum(-1) / completion_mask.sum(-1).clamp(min=1.0) + seq_level_log_weight = seq_level_log_weight.detach().unsqueeze(-1) # Stop gradient + log_importance_weights = per_token_logps - per_token_logps.detach() + seq_level_log_weight + else: + raise ValueError( + f"Unknown importance sampling level: {self.importance_sampling_level}. Possible values are 'token' " + "and 'sequence'." + ) + # From here, log_importance_weights (and all subsequent tensors, coef_1, coef_2, etc.) shape depends on + # importance_sampling_level: "token" level: (B, T); "sequence" level: (B, 1) + + coef_1 = torch.exp(log_importance_weights) + coef_2 = torch.clamp(coef_1, 1 - self.epsilon_low, 1 + self.epsilon_high) + + # Two-sided clipping + if self.args.delta is not None: + coef_1 = torch.clamp(coef_1, max=self.args.delta) + + per_token_loss1 = coef_1 * advantages.unsqueeze(1) + per_token_loss2 = coef_2 * advantages.unsqueeze(1) + per_token_loss = -torch.min(per_token_loss1, per_token_loss2) + if entropy_mask is not None: + per_token_loss = per_token_loss * entropy_mask + + if self.use_vllm and self.vllm_importance_sampling_correction: + per_token_loss = per_token_loss * inputs["importance_sampling_ratio"] + + if self.beta != 0.0: + per_token_loss = per_token_loss + self.beta * per_token_kl + + mode = "train" if self.model.training else "eval" + if self.loss_type == "grpo": + loss = ((per_token_loss * completion_mask).sum(-1) / completion_mask.sum(-1).clamp(min=1.0)).mean() + normalizer = self.current_gradient_accumulation_steps if mode == "train" else 1.0 # no accum in eval + loss = loss / normalizer + elif self.loss_type == "bnpo": + loss = (per_token_loss * completion_mask).sum() / completion_mask.sum().clamp(min=1.0) + normalizer = self.current_gradient_accumulation_steps if mode == "train" else 1.0 # no accum in eval + loss = loss / normalizer + elif self.loss_type == "dr_grpo": + loss = (per_token_loss * completion_mask).sum() / (per_token_loss.size(0) * self.max_completion_length) + normalizer = self.current_gradient_accumulation_steps if mode == "train" else 1.0 # no accum in eval + loss = loss / normalizer + elif self.loss_type == "dapo": + normalizer = inputs["num_items_in_batch"] / self.accelerator.num_processes + loss = (per_token_loss * completion_mask).sum() / normalizer + else: + raise ValueError(f"Unknown loss type: {self.loss_type}") + + # Log the metrics + completion_token_count = completion_mask.sum().clamp(min=1.0) + + def masked_batch_mean(x): + if x.shape[1] == 1: # when importance_sampling_level == "sequence" + return x.mean() + else: + return (x * completion_mask).sum() / completion_token_count + + if self.beta != 0.0: + mean_kl = masked_batch_mean(per_token_kl) + self._metrics[mode]["kl"].append(self.accelerator.gather(mean_kl).nanmean().item()) + + mean_entropy = masked_batch_mean(entropies) + self._metrics[mode]["entropy"].append(self.accelerator.gather(mean_entropy).nanmean().item()) + + # Compute the clipped probability ratios + is_low_clipped = (coef_1 < 1 - self.epsilon_low) & (advantages.unsqueeze(1) < 0) + is_high_clipped = (coef_1 > 1 + self.epsilon_high) & (advantages.unsqueeze(1) > 0) + is_region_clipped = is_low_clipped | is_high_clipped + + low_clip = masked_batch_mean(is_low_clipped.float()) + high_clip = masked_batch_mean(is_high_clipped.float()) + clip_ratio = masked_batch_mean(is_region_clipped.float()) + + gathered_low_clip = self.accelerator.gather(low_clip) + self._metrics[mode]["clip_ratio/low_mean"].append(gathered_low_clip.nanmean().item()) + self._metrics[mode]["clip_ratio/low_min"].append(nanmin(gathered_low_clip).item()) + gathered_high_clip = self.accelerator.gather(high_clip) + self._metrics[mode]["clip_ratio/high_mean"].append(gathered_high_clip.nanmean().item()) + self._metrics[mode]["clip_ratio/high_max"].append(nanmax(gathered_high_clip).item()) + gathered_clip_ratio = self.accelerator.gather(clip_ratio) + self._metrics[mode]["clip_ratio/region_mean"].append(gathered_clip_ratio.nanmean().item()) + return loss diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/kto/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/kto/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d7c21e2316bff7d621faa06622584271ee176d0e --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/kto/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .kto_config import KTOConfig +from .kto_trainer import KTOTrainer + + +__all__ = ["KTOConfig", "KTOTrainer"] diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/kto/kto_config.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/kto/kto_config.py new file mode 100644 index 0000000000000000000000000000000000000000..230cd6000a8ee1e8f07425d1c3da9a022504fe62 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/kto/kto_config.py @@ -0,0 +1,182 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field +from typing import Any + +from ...trainer.base_config import _BaseConfig + + +@dataclass +class KTOConfig(_BaseConfig): + # docstyle-ignore + r""" + Configuration class for the [`experimental.kto.KTOTrainer`]. + + This class includes only the parameters that are specific to KTO 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 + + model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments for [`~transformers.AutoModelForCausalLM.from_pretrained`], used when the `model` + argument of the [`KTOTrainer`] is provided as a string. + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the model and reference model. + + > Parameters that control the data preprocessing + + dataset_num_proc (`int`, *optional*): + Number of processes to use for processing the dataset. + max_length (`int` or `None`, *optional*, defaults to `1024`): + Maximum length of the tokenized sequence. Sequences longer than `max_length` are truncated from the left. + If `None`, no truncation is applied. + precompute_ref_log_probs (`bool`, *optional*, defaults to `False`): + Whether to precompute the reference model log probabilities for the entire training dataset before + training. This allows to save memory during training, as the reference model does not need to be kept in + memory. + precompute_ref_batch_size (`int`, *optional*): + Batch size to use when precomputing reference model log probabilities. This can be set higher than the + training batch size to speed up preprocessing. If `None`, defaults to `per_device_train_batch_size` for + training and `per_device_eval_batch_size` for evaluation. + + > Parameters that control the training + + loss_type (`str`, *optional*, defaults to `"kto"`): + Type of loss to use. Possible values are: + + - `"kto"`: KTO loss from the [KTO](https://huggingface.co/papers/2402.01306) paper. + - `"apo_zero_unpaired"`: Unpaired variant of APO-zero loss from the + [APO](https://huggingface.co/papers/2408.06266) paper. + + beta (`float`, *optional*, defaults to `0.1`): + Parameter controlling the deviation from the reference model. Higher β means less deviation from the + reference model. + desirable_weight (`float`, *optional*, defaults to `1.0`): + Desirable losses are weighed by this factor to counter unequal number of desirable and undesirable pairs. + undesirable_weight (`float`, *optional*, defaults to `1.0`): + Undesirable losses are weighed by this factor to counter unequal number of desirable and undesirable pairs. + activation_offloading (`bool`, *optional*, defaults to `False`): + Whether to offload the activations to the CPU. + > [!NOTE] + > These parameters have default values different from [`~transformers.TrainingArguments`]: + > - `logging_steps`: Defaults to `10` instead of `500`. + > - `gradient_checkpointing`: Defaults to `True` instead of `False`. + > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`. + > - `learning_rate`: Defaults to `1e-6` instead of `5e-5`. + > - `train_sampling_strategy`: Defaults to `"sequential"` instead of `"random"`. Loss types + > that estimate the KL divergence term (all except `"apo_zero_unpaired"`) require sequential + > sampling because the KL completion for each example is precomputed against its neighbors in + > a fixed-order batch; any other strategy breaks that pairing. + """ + + _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"] + + # Parameters whose default values are overridden from TrainingArguments + learning_rate: float = field( + default=1e-6, + metadata={"help": "The initial learning rate for AdamW."}, + ) + train_sampling_strategy: str = field( + default="sequential", + metadata={ + "help": "Sampler to use for the training dataloader. Loss types that estimate the KL divergence term " + "(all except `'apo_zero_unpaired'`) require `'sequential'` because the KL completion for each example is " + "precomputed against its neighbors in a fixed-order batch; any other strategy breaks that pairing. " + "Possible values are `'random'`, `'sequential'`, and `'group_by_length'`.", + "choices": ["random", "sequential", "group_by_length"], + }, + ) + + # Parameters that control the model + model_init_kwargs: dict[str, Any] | str | None = field( + default=None, + metadata={ + "help": "Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `model` argument of " + "the `KTOTrainer` is provided as a string." + }, + ) + disable_dropout: bool = field( + default=True, + metadata={"help": "Whether to disable dropout in the model and reference model."}, + ) + + # Parameters that control the data preprocessing + dataset_num_proc: int | None = field( + default=None, + metadata={"help": "Number of processes to use for processing the dataset."}, + ) + max_length: int | None = field( + default=1024, + metadata={ + "help": "Maximum length of the tokenized sequence. Sequences longer than `max_length` are truncated from " + "the left. If `None`, no truncation is applied." + }, + ) + precompute_ref_log_probs: bool = field( + default=False, + metadata={ + "help": "Whether to precompute the reference model log probabilities for the entire training dataset " + "before training. This allows to save memory during training, as the reference model does not need to be " + "kept in memory." + }, + ) + precompute_ref_batch_size: int | None = field( + default=None, + metadata={ + "help": "Batch size to use when precomputing reference model log probabilities. This can be set higher " + "than the training batch size to speed up preprocessing. If `None`, defaults to " + "`per_device_train_batch_size` for training and `per_device_eval_batch_size` for evaluation." + }, + ) + + # Parameters that control the training + loss_type: str = field( + default="kto", + metadata={ + "help": "Type of loss to use.", + "choices": ["kto", "apo_zero_unpaired"], + }, + ) + beta: float = field( + default=0.1, + metadata={ + "help": "Parameter controlling the deviation from the reference model. Higher β means less deviation from " + "the reference model." + }, + ) + desirable_weight: float = field( + default=1.0, + metadata={ + "help": "Desirable losses are weighed by this factor to counter unequal number of desirable and " + "undesirable pairs.", + }, + ) + undesirable_weight: float = field( + default=1.0, + metadata={ + "help": "Undesirable losses are weighed by this factor to counter unequal number of desirable and " + "undesirable pairs.", + }, + ) + activation_offloading: bool = field( + default=False, + metadata={"help": "Whether to offload the activations to the CPU."}, + ) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/kto/kto_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/kto/kto_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..00d6df2530bc1f4f297970324fe43c6239302cc3 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/kto/kto_trainer.py @@ -0,0 +1,1428 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import contextlib +import os +import textwrap +from collections import defaultdict +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import torch +import transformers +from accelerate import PartialState, logging +from accelerate.utils import is_peft_model, tqdm +from datasets import Dataset, IterableDataset, IterableDatasetDict, concatenate_datasets +from datasets.fingerprint import Hasher +from packaging.version import Version +from torch.nn import functional as F +from torch.utils.data import DataLoader, SequentialSampler +from transformers import ( + AutoProcessor, + DataCollator, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, +) +from transformers.data.data_collator import DataCollatorMixin +from transformers.trainer_utils import EvalLoopOutput, has_length +from transformers.utils import is_peft_available + +from ...data_utils import ( + apply_chat_template, + extract_prompt, + is_conversational, + prepare_multimodal_messages, + unpair_preference_dataset, +) +from ...import_utils import is_liger_kernel_available +from ...models import get_act_offloading_ctx_manager +from ...models.utils import disable_gradient_checkpointing, prepare_deepspeed, prepare_fsdp +from ...trainer.base_trainer import _BaseTrainer +from ...trainer.utils import ( + create_model_from_path, + disable_dropout_in_model, + flush_left, + get_config_model_id, + hash_module, + pad, + selective_log_softmax, + use_adapter, +) +from .kto_config import KTOConfig + + +if is_liger_kernel_available(): + from liger_kernel.chunked_loss import LigerFusedLinearKTOLoss + +if is_peft_available(): + from peft import PeftConfig, PeftModel, get_peft_model + + +logger = logging.get_logger(__name__) + +RUNNING_NAME = "running.pt" + + +def get_dataset_column_names(dataset: Dataset | IterableDataset) -> list[str]: + return list(next(iter(dataset)).keys()) if dataset.column_names is None else dataset.column_names + + +def _get_kl_completion_ids(batch: dict[str, list[Any]]) -> dict[str, list[Any]]: + """ + Creates mismatched pairs of prompts and completions for the KL dataset by adding a +1 offset to the order of + completions. For best results, the mismatched outputs y' used to estimate the KL term for a batch should be the + same set as the matched outputs y used to estimate the rewards in that batch, just paired with different x. + """ + batch["completion_ids"] = [batch["completion_ids"][-1]] + batch["completion_ids"][:-1] + return batch + + +@dataclass +class DataCollatorForUnpairedPreference(DataCollatorMixin): + """ + Data collator for unpaired preference data. Assembles completions from raw token IDs and pads sequences to the + maximum length of the batch. + + Each example is expected to contain `"prompt_ids"`, `"completion_ids"` (and optionally `"KL_completion_ids"`) keys. + The collator returns a dictionary with the following keys for each prefix (`"completion"` and, if present, + `"KL_completion"`): + - `"{prefix}_input_ids"`: full prompt + completion token IDs, padded to the batch maximum length. + - `"{prefix}_attention_mask"`: attention mask, padded with 0s. + - `"{prefix}_mask"`: binary mask where 1 marks completion tokens and 0 marks prompt or padding tokens. + + Args: + pad_token_id (`int`): + Token ID to use for padding `input_ids` sequences. + max_length (`int`, *optional*): + Maximum sequence length after assembly. Sequences longer than `max_length` are truncated from the end. + pad_to_multiple_of (`int`, *optional*): + If set, the sequences will be padded to a multiple of this value. + return_tensors (`str`, *optional*, defaults to `"pt"`): + The tensor type to return. Currently, only `"pt"` (PyTorch tensors) is supported. + """ + + pad_token_id: int + max_length: int | None = None + pad_to_multiple_of: int | None = None + return_tensors: str = "pt" + + def torch_call(self, examples: list[dict[str, Any]]) -> dict[str, Any]: + batch = {} + for prefix, ids_key in [("completion", "completion_ids"), ("KL_completion", "KL_completion_ids")]: + if ids_key not in examples[0]: + continue + + full_ids_list = [] + completion_mask_list = [] + for ex in examples: + prompt_ids = ex["prompt_ids"] + answer_ids = ex[ids_key] + full_ids = prompt_ids + answer_ids + completion_mask = [0] * len(prompt_ids) + [1] * len(answer_ids) + if self.max_length is not None: + full_ids = full_ids[: self.max_length] + completion_mask = completion_mask[: self.max_length] + full_ids_list.append(full_ids) + completion_mask_list.append(completion_mask) + + batch[f"{prefix}_input_ids"] = pad( + [torch.tensor(ids, dtype=torch.int64) for ids in full_ids_list], + padding_value=self.pad_token_id, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ) + batch[f"{prefix}_attention_mask"] = pad( + [torch.ones(len(ids), dtype=torch.int64) for ids in full_ids_list], + padding_value=0, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ) + batch[f"{prefix}_mask"] = pad( + [torch.tensor(m, dtype=torch.int64) for m in completion_mask_list], + padding_value=0, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ) + + if "ref_logps" in examples[0]: + batch["ref_logps"] = torch.tensor([ex["ref_logps"] for ex in examples]) + if "ref_KL_logps" in examples[0]: + batch["ref_KL_logps"] = torch.tensor([ex["ref_KL_logps"] for ex in examples]) + batch["label"] = [ex["label"] for ex in examples] + return batch + + +@dataclass +class DataCollatorForVisionUnpairedPreference(DataCollatorMixin): + """ + Data collator for vision unpaired preference data. Performs tokenization and image processing on-the-fly. + + Unlike the text-only [`DataCollatorForUnpairedPreference`], this collator does not expect pre-tokenized inputs. + Instead, it takes raw examples with `"prompt"`, `"completion"`, and `"images"` (or `"image"`) keys and processes + them at collation time. When `calculate_kl` is `True`, the collator also produces KL sequences by cycling + completions within the batch — the same mismatching strategy as the text-only path, but done here rather than as a + dataset pre-processing step. + + Each input example should contain at least: + - A `"prompt"` key with either a plain text string or a list of message dicts. + - A `"completion"` key with a plain text string or a list of message dicts. + - An `"images"` key holding a list of images, or an `"image"` key holding a single image. + - A `"label"` key (`bool`) indicating whether the completion is desirable. + + The collator outputs: + - `"completion_input_ids"`, `"completion_attention_mask"`, `"completion_mask"`: full prompt+completion sequence. + - `"pixel_values"` and any additional processor outputs (e.g., `"image_grid_thw"`). + - `"label"`: list of booleans. + - When `calculate_kl=True`: `"KL_completion_input_ids"`, `"KL_completion_attention_mask"`, `"KL_completion_mask"` + for the cycled KL sequences. + + Args: + processor ([`~transformers.ProcessorMixin`]): + The processor used to tokenize text and process images. + max_length (`int`, *optional*): + Maximum sequence length. Sequences longer than `max_length` are truncated. + calculate_kl (`bool`, *optional*, defaults to `True`): + Whether to produce KL sequences by cycling completions within the batch. + return_tensors (`str`, *optional*, defaults to `"pt"`): + The tensor type to return. Only `"pt"` is supported. + """ + + processor: ProcessorMixin + max_length: int | None = None + calculate_kl: bool = True + return_tensors: str = "pt" + + def torch_call(self, examples: list[dict[str, Any]]) -> dict[str, Any]: + if "image" in examples[0]: + for example in examples: + example["images"] = [example.pop("image")] + images = [example["images"] for example in examples] + # Transformers requires at least one image in the batch, otherwise it throws an error + if all(img_list == [] for img_list in images): + images = None + if is_conversational(examples[0]): # conversational case + for example in examples: + example["prompt"] = prepare_multimodal_messages(example["prompt"], images=example["images"]) + example["completion"] = prepare_multimodal_messages(example["completion"]) + examples = [apply_chat_template(example, self.processor) for example in examples] + + prompts = [example["prompt"] for example in examples] + completions = [example["completion"] for example in examples] + + processed_prompts = self.processor( + images=images, + text=prompts, + padding=True, + padding_side="left", + return_tensors=self.return_tensors, + add_special_tokens=False, # to avoid adding the BOS twice, see https://huggingface.co/blog/qgallouedec/gotchas-in-tokenizer-behavior#7-chat-template-and-tokenization-dont-compose-due-to-special-tokens + ) + processed_completions = self.processor( + text=completions, + padding=True, + padding_side="right", + return_tensors=self.return_tensors, + add_special_tokens=False, # to avoid adding the BOS twice, see https://huggingface.co/blog/qgallouedec/gotchas-in-tokenizer-behavior#7-chat-template-and-tokenization-dont-compose-due-to-special-tokens + ) + + # Concatenate prompts and completions + prompt_ids, prompt_mask = processed_prompts["input_ids"], processed_prompts["attention_mask"] + completion_ids, completion_mask = processed_completions["input_ids"], processed_completions["attention_mask"] + input_ids = torch.cat((prompt_ids, completion_ids), dim=1) + attention_mask = torch.cat((prompt_mask, completion_mask), dim=1) + completion_mask = torch.cat((torch.zeros_like(prompt_mask), completion_mask), dim=1) + + has_tti = "token_type_ids" in processed_prompts + has_mm_tti = "mm_token_type_ids" in processed_prompts + + if has_tti: # special case for Gemma + prompt_token_type_ids = processed_prompts["token_type_ids"] + completion_token_type_ids = processed_completions["token_type_ids"] + token_type_ids = torch.cat((prompt_token_type_ids, completion_token_type_ids), dim=1) + if has_mm_tti: # special case for Qwen2.5-VL + prompt_mm_token_type_ids = processed_prompts["mm_token_type_ids"] + completion_mm_token_type_ids = processed_completions.get( + "mm_token_type_ids", torch.zeros_like(completion_ids) + ) + mm_token_type_ids = torch.cat((prompt_mm_token_type_ids, completion_mm_token_type_ids), dim=1) + + # Flush left to reduce padding + if has_tti and has_mm_tti: + attention_mask, input_ids, completion_mask, token_type_ids, mm_token_type_ids = flush_left( + attention_mask, input_ids, completion_mask, token_type_ids, mm_token_type_ids + ) + elif has_tti: + attention_mask, input_ids, completion_mask, token_type_ids = flush_left( + attention_mask, input_ids, completion_mask, token_type_ids + ) + elif has_mm_tti: + attention_mask, input_ids, completion_mask, mm_token_type_ids = flush_left( + attention_mask, input_ids, completion_mask, mm_token_type_ids + ) + else: + attention_mask, input_ids, completion_mask = flush_left(attention_mask, input_ids, completion_mask) + + # Truncate if necessary + if self.max_length is not None: + input_ids = input_ids[:, : self.max_length] + attention_mask = attention_mask[:, : self.max_length] + completion_mask = completion_mask[:, : self.max_length] + if has_tti: + token_type_ids = token_type_ids[:, : self.max_length] + if has_mm_tti: + mm_token_type_ids = mm_token_type_ids[:, : self.max_length] + + # Build the output dictionary + output = processed_prompts # we take processed_prompts because it contains the images + output.pop("input_ids", None) + output.pop("attention_mask", None) + output["completion_input_ids"] = input_ids + output["completion_attention_mask"] = attention_mask + output["completion_mask"] = completion_mask + if has_tti: + output["token_type_ids"] = token_type_ids + if has_mm_tti: + output["mm_token_type_ids"] = mm_token_type_ids + + if self.calculate_kl: + # Cycle completions by +1 within the batch to create mismatched KL pairs — same strategy as + # _get_kl_completion_ids in the text-only path, but done here to keep the VLM dataset fully raw. + kl_completions = completions[-1:] + completions[:-1] + processed_kl = self.processor( + text=kl_completions, + padding=True, + padding_side="right", + return_tensors=self.return_tensors, + add_special_tokens=False, # to avoid adding the BOS twice, see https://huggingface.co/blog/qgallouedec/gotchas-in-tokenizer-behavior#7-chat-template-and-tokenization-dont-compose-due-to-special-tokens + ) + kl_ids = processed_kl["input_ids"] + kl_mask = processed_kl["attention_mask"] + + kl_input_ids = torch.cat((prompt_ids, kl_ids), dim=1) + kl_attention_mask = torch.cat((prompt_mask, kl_mask), dim=1) + kl_completion_mask = torch.cat((torch.zeros_like(prompt_mask), kl_mask), dim=1) + + # Build KL token-type tensors using the original (pre-flush) prompt tensors + if has_tti: + kl_completion_token_type_ids = processed_kl.get("token_type_ids", torch.zeros_like(kl_ids)) + kl_token_type_ids = torch.cat((prompt_token_type_ids, kl_completion_token_type_ids), dim=1) + if has_mm_tti: + kl_completion_mm_token_type_ids = processed_kl.get("mm_token_type_ids", torch.zeros_like(kl_ids)) + kl_mm_token_type_ids = torch.cat((prompt_mm_token_type_ids, kl_completion_mm_token_type_ids), dim=1) + + if has_tti and has_mm_tti: + kl_attention_mask, kl_input_ids, kl_completion_mask, kl_token_type_ids, kl_mm_token_type_ids = ( + flush_left( + kl_attention_mask, kl_input_ids, kl_completion_mask, kl_token_type_ids, kl_mm_token_type_ids + ) + ) + elif has_tti: + kl_attention_mask, kl_input_ids, kl_completion_mask, kl_token_type_ids = flush_left( + kl_attention_mask, kl_input_ids, kl_completion_mask, kl_token_type_ids + ) + elif has_mm_tti: + kl_attention_mask, kl_input_ids, kl_completion_mask, kl_mm_token_type_ids = flush_left( + kl_attention_mask, kl_input_ids, kl_completion_mask, kl_mm_token_type_ids + ) + else: + kl_attention_mask, kl_input_ids, kl_completion_mask = flush_left( + kl_attention_mask, kl_input_ids, kl_completion_mask + ) + + # Truncate if necessary + if self.max_length is not None: + kl_input_ids = kl_input_ids[:, : self.max_length] + kl_attention_mask = kl_attention_mask[:, : self.max_length] + kl_completion_mask = kl_completion_mask[:, : self.max_length] + if has_tti: + kl_token_type_ids = kl_token_type_ids[:, : self.max_length] + if has_mm_tti: + kl_mm_token_type_ids = kl_mm_token_type_ids[:, : self.max_length] + + output["KL_completion_input_ids"] = kl_input_ids + output["KL_completion_attention_mask"] = kl_attention_mask + output["KL_completion_mask"] = kl_completion_mask + if has_tti: + output["KL_completion_token_type_ids"] = kl_token_type_ids + if has_mm_tti: + output["KL_completion_mm_token_type_ids"] = kl_mm_token_type_ids + + output["label"] = [ex["label"] for ex in examples] + return output + + +class KTOTrainer(_BaseTrainer): + """ + Initialize KTOTrainer. + + Args: + model (`str` or [`~transformers.PreTrainedModel`] or [`~peft.PeftModel`]): + Model to be trained. Can be either: + + - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a + path to a *directory* containing model weights saved using + [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded + using `.from_pretrained` (where `` is derived from the model + config) with the keyword arguments in `args.model_init_kwargs`. + - A [`~transformers.PreTrainedModel`] object. Only causal language models are supported. + - A [`~peft.PeftModel`] object. Only causal language models are supported. + ref_model ([`~transformers.PreTrainedModel`], *optional*): + Reference model used to compute the reference log probabilities. + + - If provided, this model is used directly as the reference policy. + - If `None`, the trainer will automatically use the initial policy corresponding to `model`, i.e. the model + state before KTO training starts. + args ([`experimental.kto.KTOConfig`], *optional*): + Configuration for this trainer. If `None`, a default configuration is used. + train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]): + The dataset to use for training. + eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Dataset | IterableDataset]`): + The dataset to use for evaluation. + processing_class ([`~transformers.PreTrainedTokenizerBase`] or [`~transformers.ProcessorMixin`], *optional*): + Processing class used to process the data. The padding side must be set to "left". If `None`, the + processing class is loaded from the model's name with [`~transformers.AutoProcessor.from_pretrained`]. A + padding token, `tokenizer.pad_token`, must be set. If the processing class has not set a padding token, + `tokenizer.eos_token` will be used as the default. + data_collator ([`~transformers.DataCollator`], *optional*): + The data collator to use for training. If None is specified, the default data collator + ([`~experimental.kto.kto_trainer.DataCollatorForUnpairedPreference`]) will be used which will pad the + sequences to the maximum length of the sequences in the batch. + callbacks (`list[transformers.TrainerCallback]`): + The callbacks to use for training. + optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`): + The optimizer and scheduler to use for training. + peft_config ([`~peft.PeftConfig`], *optional*): + PEFT configuration used to wrap the model. If `None`, the model is not wrapped. + compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*): + The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to + metric values. + """ + + _tag_names = ["trl", "kto"] + _name = "KTO" + _paper = { + "title": "KTO: Model Alignment as Prospect Theoretic Optimization", + "id": "2402.01306", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @article{ethayarajh2024kto, + title = {{KTO: Model Alignment as Prospect Theoretic Optimization}}, + author = {Kawin Ethayarajh and Winnie Xu and Niklas Muennighoff and Dan Jurafsky and Douwe Kiela}, + year = 2024, + eprint = {arXiv:2402.01306}, + }"""), + } + + def __init__( + self, + model: "str | PreTrainedModel | PeftModel", + ref_model: PreTrainedModel | None = None, + args: KTOConfig | None = None, + train_dataset: Dataset | IterableDataset | None = None, + eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None, + processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None, + data_collator: DataCollator | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + peft_config: "PeftConfig | None" = None, + compute_metrics: Callable[[EvalLoopOutput], dict] | None = None, + ): + # Args + if args is None: + model_name = model if isinstance(model, str) else get_config_model_id(model.config) + model_name = model_name.split("/")[-1] + args = KTOConfig(f"{model_name}-KTO") + + if train_dataset is None: + raise ValueError("`train_dataset` is required") + elif isinstance(train_dataset, IterableDataset): + # IterableDataset requires dispatch_batches=False because Accelerate's dispatch mode may try to concatenate + # batches from multiple processes, leading to mismatch errors. + if args.accelerator_config.dispatch_batches is True: + logger.warning( + "You are using an `IterableDataset` for training with `dispatch_batches=True`. `dispatch_batches` " + "is forced to `False` when using an `IterableDataset`. To remove this warning, unset " + "`dispatch_batches` in `KTOConfig` or set it to `False`." + ) + args.accelerator_config.dispatch_batches = False + + # Model + if isinstance(model, str): + model_init_kwargs = args.model_init_kwargs or {} + # Distributed training requires device_map=None ("auto" fails) + if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + model_init_kwargs["device_map"] = None + model = create_model_from_path(model, **model_init_kwargs) + else: + if args.model_init_kwargs is not None: + logger.warning( + "You passed `model_init_kwargs` to the KTOConfig, but your model is already instantiated. " + "The `model_init_kwargs` will be ignored." + ) + if ref_model is model: + raise ValueError( + "`model` and `ref_model` cannot be the same object. In most cases you should omit `ref_model` and " + "we'll initialize it to a copy of `model` for you." + ) + + # Processing class + if processing_class is None: + processing_class = AutoProcessor.from_pretrained(get_config_model_id(model.config)) + if isinstance(processing_class, ProcessorMixin): + self._tokenizer = processing_class.tokenizer + self._is_vlm = True + elif isinstance(processing_class, PreTrainedTokenizerBase): + self._tokenizer = processing_class + self._is_vlm = False + else: + raise TypeError("The `processing_class` must be either a `PreTrainedTokenizerBase` or a `ProcessorMixin`") + if self._tokenizer.pad_token is None: + self._tokenizer.pad_token = self._tokenizer.eos_token + + # PEFT + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + if is_peft_model(model): + raise ValueError( + "You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first merge " + "and unload the existing adapter, save the resulting base model, and then pass that base model along " + "with the new `peft_config` to the trainer." + ) + # Create PEFT model + model = get_peft_model(model, peft_config) + + elif is_peft_model(model) and ref_model is None: + # If the model is a PEFT model with a pretrained adapter, we need to create a "ref" adapter that is a copy + # of the "default" adapter, so that we can use it as the reference model during KTO training. + model.add_adapter("ref", model.peft_config["default"]) + for name, param in model.named_parameters(): + if ".default." in name: + ref_name = name.replace(".default.", ".ref.") + ref_param = model.get_parameter(ref_name) + ref_param.data.copy_(param.data) + + # When using gradient checkpointing with PEFT, we need to enable input gradients. transformers.Trainer normally + # handles this, but a bug currently prevents it; see https://github.com/huggingface/transformers/issues/42489 + if is_peft_model(model) and args.gradient_checkpointing: + model.enable_input_require_grads() + + # When using QLoRA, the PEFT adapter weights are converted to bf16 to follow the recommendations from the + # original paper (see https://huggingface.co/papers/2305.14314, paragraph 3). Normally, this can be done by + # passing `autocast_adapter_dtype=False` to `get_peft_model`, but this option is not yet supported for + # quantized models. See: https://github.com/huggingface/peft/issues/2889 + # Non-quantized models do not have the `is_loaded_in_{8,4}bit` attributes, whereas quantized models do + if getattr(model, "is_loaded_in_4bit", False) or getattr(model, "is_loaded_in_8bit", False): + for param in model.parameters(): + if param.requires_grad: + param.data = param.data.to(torch.bfloat16) + + # Vision dataset detection + dataset_sample = next(iter(train_dataset)) + self._is_vision_dataset = "image" in dataset_sample or "images" in dataset_sample + if self._is_vision_dataset and not self._is_vlm: + raise ValueError( + "The dataset appears to be vision-related (contains 'image' or 'images' keys), but the provided " + "model does not seem to be a vision-language model. Please check your model and dataset." + ) + if self._is_vision_dataset and args.precompute_ref_log_probs: + raise ValueError( + "`precompute_ref_log_probs=True` is not supported for vision datasets. For vision-language " + "models, all data processing is performed on the fly rather than upfront. " + "Set `precompute_ref_log_probs=False`." + ) + if self._is_vision_dataset and ("chosen" in dataset_sample or "rejected" in dataset_sample): + raise ValueError( + "Vision datasets must be in unpaired format with `completion` and `label` columns. " + "Paired format (`chosen`/`rejected`) is not supported for vision datasets because " + "iterating over the full dataset to unpair it would be too expensive for large image " + "collections. Unpair your dataset first: `dataset = unpair_preference_dataset(dataset)`." + ) + + # Data collator + calculate_kl = args.loss_type not in ["apo_zero_unpaired"] + if data_collator is None and not self._is_vision_dataset: + data_collator = DataCollatorForUnpairedPreference( + pad_token_id=self._tokenizer.pad_token_id, + max_length=args.max_length, + ) + elif data_collator is None and self._is_vision_dataset: + data_collator = DataCollatorForVisionUnpairedPreference( + processor=processing_class, + max_length=args.max_length, + calculate_kl=calculate_kl, + ) + + # Training arguments + self.beta = args.beta + self.precompute_ref_logps = args.precompute_ref_log_probs + self.loss_type = args.loss_type + self.desirable_weight = args.desirable_weight + self.undesirable_weight = args.undesirable_weight + self.aux_loss_enabled = getattr(model.config, "output_router_logits", False) + self.aux_loss_coef = getattr(model.config, "router_aux_loss_coef", 0.0) + self.calculate_KL = calculate_kl + if self.calculate_KL and args.train_sampling_strategy != "sequential": + raise ValueError( + f"Loss type `'{args.loss_type}'` estimates the KL divergence term and requires " + f"`train_sampling_strategy='sequential'` because the KL completion for each example is precomputed " + f"against its neighbors in a fixed-order batch; any other strategy breaks that pairing. " + f"Got `train_sampling_strategy='{args.train_sampling_strategy}'`." + ) + if self.calculate_KL and args.per_device_train_batch_size <= 1: + raise ValueError( + "Actual (not effective) batch size must be > 1. KTO will not work properly because the KL term will be equivalent to the implied reward." + ) + if self.aux_loss_enabled and self.aux_loss_coef == 0.0: + logger.warning( + "You set `output_router_logits` to `True` in the model config, but `router_aux_loss_coef` is set to " + "`0.0`, meaning the auxiliary loss will not be used. Either set `router_aux_loss_coef` to a value " + "greater than `0.0`, or set `output_router_logits` to `False` if you don't want to use the auxiliary " + "loss.", + ) + + # Dataset + # Skip dataset preparation for VLMs: tokenization and image processing happen on-the-fly in the collator. + if not self._is_vision_dataset: + train_dataset = self._prepare_dataset(train_dataset, processing_class, args, "train") + if eval_dataset is not None: + if isinstance(eval_dataset, dict): + eval_dataset = { + key: self._prepare_dataset(dataset, processing_class, args, key) + for key, dataset in eval_dataset.items() + } + else: + eval_dataset = self._prepare_dataset(eval_dataset, processing_class, args, "eval") + + # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was + # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream + # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we + # default to the recommended non-reentrant behavior here, while preserving any user-provided value. + if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"): + args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {} + args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False) + + super().__init__( + model=model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + ) + + # Initialize activation offloading context + if self.args.activation_offloading: + self.maybe_activation_offload_context = get_act_offloading_ctx_manager(model=self.model) + else: + self.maybe_activation_offload_context = contextlib.nullcontext() + + # Reference model + if ref_model is None: + if is_peft_model(self.model) or args.precompute_ref_log_probs: + # If PEFT is used, the reference model is not needed since the adapter can be disabled to revert to the + # initial model. If precompute_ref_log_probs is True, the reference model does not need to be kept in + # memory during training. + self.ref_model = None + else: + ref_model_init_kwargs = args.model_init_kwargs or {} + # Distributed training requires device_map=None ("auto" fails) + if self.args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + ref_model_init_kwargs["device_map"] = None + ref_model_path = get_config_model_id(self.model.config) + self.ref_model = create_model_from_path(ref_model_path, **ref_model_init_kwargs) + else: + self.ref_model = ref_model + + # Disable dropout in the model and reference model + if args.disable_dropout: + disable_dropout_in_model(model) + if self.ref_model is not None: + disable_dropout_in_model(self.ref_model) + + # Initialize the metrics + self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)} + + # Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the + # model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set + # self.model_accepts_loss_kwargs to False to enable scaling. + self.model_accepts_loss_kwargs = False + + # Add tags to the model + self.model.add_model_tags(self._tag_names) + + if self.ref_model is not None: + if self.is_deepspeed_enabled: + self.ref_model = prepare_deepspeed(self.ref_model, self.accelerator) + elif self.is_fsdp_enabled: + self.ref_model = prepare_fsdp(self.ref_model, self.accelerator) + else: + self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True) + + self.use_liger_kernel = args.use_liger_kernel + # Import Liger kernel if enabled + if self.use_liger_kernel: + if not is_liger_kernel_available(): + raise ImportError( + "You set `use_liger_kernel=True` but the liger kernel is not available. " + "Please install liger-kernel first: `pip install liger-kernel`" + ) + if self.loss_type in ["apo_zero_unpaired"]: + raise ValueError( + "You cannot set `loss_type='apo_zero_unpaired'` with liger-kernel." + "Only KTO loss is supported with liger-kernel." + ) + if self.precompute_ref_logps: + raise ValueError( + "You cannot use `precompute_ref_log_probs=True` with liger kernel. Please set " + "`precompute_ref_log_probs=False`." + ) + if is_peft_model(self.model): + raise ValueError( + "You cannot use `use_liger_kernel=True` with Peft models. Please set `use_liger_kernel=False`." + ) + self.liger_loss_fn = LigerFusedLinearKTOLoss(beta=self.beta, use_ref_model=(self.ref_model is not None)) + + if self.precompute_ref_logps: + if isinstance(self.train_dataset, IterableDataset) or isinstance( + self.eval_dataset, (IterableDataset, IterableDatasetDict) + ): + raise ValueError( + "`precompute_ref_log_probs=True` is not supported with IterableDataset. Please use a map-style " + "Dataset or set `precompute_ref_log_probs=False`." + ) + self.train_dataset = self._precompute_ref_logps( + self.train_dataset, + "train", + self.args.precompute_ref_batch_size or self.args.per_device_train_batch_size, + ) + if self.eval_dataset is not None: + if isinstance(self.eval_dataset, dict): + self.eval_dataset = { + name: self._precompute_ref_logps( + dataset, name, self.args.precompute_ref_batch_size or self.args.per_device_eval_batch_size + ) + for name, dataset in self.eval_dataset.items() + } + else: + self.eval_dataset = self._precompute_ref_logps( + self.eval_dataset, + "eval", + self.args.precompute_ref_batch_size or self.args.per_device_eval_batch_size, + ) + + def _tokenize( + self, + processing_class: PreTrainedTokenizerBase | ProcessorMixin, + input: str | list, + **kwargs, + ) -> dict[str, list]: + """Tokenize a single example for dataset preprocessing. + + Dispatches to `apply_chat_template` for conversational input (list of message dicts) and to `__call__` for + non-conversational input (str). + + Args: + processing_class ([`~transformers.PreTrainedTokenizerBase`] or [`~transformers.ProcessorMixin`]): + The tokenizer or processor to use. + input (`str` or `list`): + A string for non-conversational input, or a list of message dicts for conversational input. + **kwargs: + Forwarded to `apply_chat_template` (e.g. `add_generation_prompt`, `return_assistant_tokens_mask`). + + Returns: + `dict` with at least an `"input_ids"` key mapping to a flat `list[int]`. + """ + if isinstance(input, list): # conversational: list of message dicts + if self._is_vlm: + input = prepare_multimodal_messages(input) + result = processing_class.apply_chat_template(input, tokenize=True, return_dict=True, **kwargs) + else: # non-conversational: plain text string + result = processing_class(text=input) + # VLMs emit a batch dimension even for single examples; unwrap it + if self._is_vlm: + return {k: v[0] for k, v in result.items()} + return result + + def _get_kl_dataset( + self, + dataset: Dataset | IterableDataset, + dataset_name: str, + args: KTOConfig, + ) -> Dataset | IterableDataset: + """ + Creates the KL dataset by creating mismatched (prompt, completion) pairs for KL divergence estimation. + + Args: + dataset (`Dataset` or `IterableDataset`): + Tokenized dataset with `prompt_ids` and `completion_ids` columns. + dataset_name (`str`): + Name used in progress bar descriptions. + args ([`KTOConfig`]): + Training arguments providing `per_device_train_batch_size` and `dataset_num_proc`. + + Returns: + `Dataset` or `IterableDataset` with a single `KL_completion_ids` column. + """ + map_kwargs = {} + if isinstance(dataset, Dataset): # IterableDataset does not support num_proc or desc + map_kwargs["num_proc"] = args.dataset_num_proc + map_kwargs["desc"] = f"Extracting KL {dataset_name} dataset" + kl_dataset = dataset.map( + _get_kl_completion_ids, batched=True, batch_size=args.per_device_train_batch_size, **map_kwargs + ) + + def rename_kl_fn(example): + return {"KL_completion_ids": example["completion_ids"]} + + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Assembling KL {dataset_name} dataset" + column_names = get_dataset_column_names(dataset) + kl_dataset = kl_dataset.map( + rename_kl_fn, + remove_columns=[c for c in get_dataset_column_names(kl_dataset) if c in column_names], + **map_kwargs, + ) + return kl_dataset + + def _prepare_dataset( + self, + dataset: Dataset | IterableDataset, + processing_class: PreTrainedTokenizerBase | ProcessorMixin, + args: KTOConfig | None, + dataset_name: str, + ) -> Dataset | IterableDataset: + # Build the kwargs for the `map` function + map_kwargs = {} + if isinstance(dataset, Dataset): # IterableDataset does not support num_proc + map_kwargs["num_proc"] = args.dataset_num_proc + + # Compute that only on the main process for faster data processing. + # see: https://github.com/huggingface/trl/pull/1255 + with PartialState().main_process_first(): + # Extract the prompt if needed + first_example = next(iter(dataset)) + if "prompt" not in first_example: + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Extracting prompt from {dataset_name} dataset" + dataset = dataset.map(extract_prompt, **map_kwargs) + + # Unpair the dataset if needed + first_example = next(iter(dataset)) + if "chosen" in first_example and "rejected" in first_example: + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Unpairing {dataset_name} dataset" + dataset = unpair_preference_dataset(dataset, **map_kwargs) + + # Add EOS token if needed: non-conversational only + first_example = next(iter(dataset)) + if not is_conversational(first_example): + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Adding EOS to {dataset_name} dataset" + + def add_eos(example, eos_token): + if not example["completion"].endswith(eos_token): + example["completion"] = example["completion"] + eos_token + return example + + dataset = dataset.map(add_eos, fn_kwargs={"eos_token": self._tokenizer.eos_token}, **map_kwargs) + + # Tokenize dataset + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Tokenizing {dataset_name} dataset" + + def tokenize_fn(example, processing_class): + if is_conversational(example): + chat_template_kwargs = example.get("chat_template_kwargs", {}) + prompt_ids = self._tokenize( + processing_class, + example["prompt"], + add_generation_prompt=True, + **chat_template_kwargs, + )["input_ids"] + prompt_completion_ids = self._tokenize( + processing_class, + example["prompt"] + example["completion"], + **chat_template_kwargs, + )["input_ids"] + else: + prompt_ids = self._tokenize(processing_class, example["prompt"])["input_ids"] + prompt_completion_ids = self._tokenize( + processing_class, example["prompt"] + example["completion"] + )["input_ids"] + + if not prompt_completion_ids[: len(prompt_ids)] == prompt_ids: + logger.warning( + "Mismatch between tokenized prompt and the start of tokenized prompt+completion. " + "This may be due to unexpected tokenizer behavior, whitespace issues, or special " + "token handling. Verify that the tokenizer is processing text consistently." + ) + + return { + "prompt_ids": prompt_ids, + "completion_ids": prompt_completion_ids[len(prompt_ids) :], + } + + dataset = dataset.map(tokenize_fn, fn_kwargs={"processing_class": processing_class}, **map_kwargs) + + # Get KL datasets if needed + if self.calculate_KL: + # create pairs for estimating the KL term by flipping the matched pairs in each batch of size total_batch_size + # i.e., (x_1, y_1), ..., (x_n, y_n) --> (x_1, y_n), ..., (x_n, y_1) = (x'_1, y'_1), ..., (x'_n, y'_n) + kl_dataset = self._get_kl_dataset(dataset, dataset_name, args) + dataset = concatenate_datasets([dataset, kl_dataset], axis=1) + + # Calculate dataset desirability balance + if dataset_name == "train" and isinstance(dataset, Dataset): # IterableDataset does not support len + num_desirable = max(sum(dataset["label"]), 1) + num_undesirable = max(len(dataset["label"]) - num_desirable, 1) # "label" is binary + + if num_desirable != num_undesirable: + # The lower and upper bounds come from Eq. (8) of https://huggingface.co/papers/2402.01306 + des_weight_lower_bound = round((num_undesirable * self.undesirable_weight / num_desirable) * 1, 2) + des_weight_upper_bound = round( + (num_undesirable * self.undesirable_weight / num_desirable) * 1.33, 2 + ) + und_weight_lower_bound = round((num_desirable * self.desirable_weight / num_undesirable) / 1.33, 2) + und_weight_upper_bound = round((num_desirable * self.desirable_weight / num_undesirable) / 1, 2) + + des_weight_in_range = des_weight_lower_bound <= self.desirable_weight <= des_weight_upper_bound + und_weight_in_range = und_weight_lower_bound <= self.undesirable_weight <= und_weight_upper_bound + + if not (des_weight_in_range or und_weight_in_range): + logger.warning( + "You have different amounts of desirable/positive and undesirable/negative examples but the " + "weights on the desirable and undesirable losses don't seem to be in an ideal range. Based " + f"on your data, we recommend EITHER " + f"desirable_weight in [{des_weight_lower_bound}, {des_weight_upper_bound}] or " + f"undesirable_weight in [{und_weight_lower_bound}, {und_weight_upper_bound}] (but NOT BOTH). " + "See the documentation on how to optimally set these weights.", + ) + return dataset + + def _set_signature_columns_if_needed(self): + # If `self.args.remove_unused_columns` is True, non-signature columns are removed. + # By default, this method sets `self._signature_columns` to the model's expected inputs (usually, "input_ids" + # and "attention_mask"). + if self._signature_columns is None: + if self._is_vision_dataset: + self._signature_columns = [ + "prompt", + "completion", + "image", + "images", + "label", + "chat_template_kwargs", + ] + else: + self._signature_columns = [ + "prompt_ids", + "completion_ids", + "KL_completion_ids", + "label", + "ref_logps", + "ref_KL_logps", + ] + + def _precompute_ref_logps(self, dataset: Dataset, name: str, batch_size: int) -> Dataset: + model_hash = hash_module(self.ref_model or self.model) + fingerprint = Hasher.hash((dataset._fingerprint, model_hash, self.calculate_KL)) + cache_file = dataset._get_cache_file_path(fingerprint) + if os.path.exists(cache_file): + return concatenate_datasets([dataset, Dataset.from_file(cache_file)], axis=1) + + dataloader = DataLoader( + dataset, + batch_size=batch_size, + collate_fn=self.data_collator, + num_workers=self.args.dataloader_num_workers, + pin_memory=self.args.dataloader_pin_memory, + shuffle=False, + ) + data_loader = self.accelerator.prepare(dataloader) + ref_logps = [] + ref_KL_logps = [] + for padded_batch in tqdm(iterable=data_loader, desc=f"Computing reference log probs for {name} dataset"): + ref_logp, ref_KL_logp = self.compute_ref_log_probs(padded_batch) + if self.calculate_KL: + ref_logp, ref_KL_logp = self.accelerator.gather_for_metrics((ref_logp, ref_KL_logp)) + ref_KL_logps.append(ref_KL_logp.cpu()) + else: + ref_logp = self.accelerator.gather_for_metrics(ref_logp) + ref_logps.append(ref_logp.cpu()) + + ref_logps = torch.cat(ref_logps) + if self.calculate_KL: + ref_KL_logps = torch.cat(ref_KL_logps) + + if self.accelerator.is_main_process: + + def add_ref_logps(batch, indices): + result = {"ref_logps": ref_logps[indices]} + if self.calculate_KL: + result.update({"ref_KL_logps": ref_KL_logps[indices]}) + return result + + dataset.map( + add_ref_logps, + with_indices=True, + batched=True, + remove_columns=dataset.column_names, + new_fingerprint=fingerprint, + desc=f"Caching reference log probs for {name} dataset", + ) + self.accelerator.wait_for_everyone() + + return concatenate_datasets([dataset, Dataset.from_file(cache_file)], axis=1) + + def compute_ref_log_probs(self, inputs): + """Computes reference log probabilities for a single padded batch.""" + with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs): + if self.ref_model is None: + if is_peft_model(self.model): + model = self.accelerator.unwrap_model(self.model) + with use_adapter(model, adapter_name="ref" if "ref" in model.peft_config else None): + completion_logits = self.model( + inputs["completion_input_ids"], + attention_mask=inputs["completion_attention_mask"], + ).logits + + if self.calculate_KL: + KL_logits = self.model( + inputs["KL_completion_input_ids"], + attention_mask=inputs["KL_completion_attention_mask"], + ).logits + else: + completion_logits = self.model( + inputs["completion_input_ids"], + attention_mask=inputs["completion_attention_mask"], + ).logits + + if self.calculate_KL: + KL_logits = self.model( + inputs["KL_completion_input_ids"], + attention_mask=inputs["KL_completion_attention_mask"], + ).logits + else: + completion_logits = self.ref_model( + inputs["completion_input_ids"], attention_mask=inputs["completion_attention_mask"] + ).logits + + if self.calculate_KL: + KL_logits = self.ref_model( + inputs["KL_completion_input_ids"], + attention_mask=inputs["KL_completion_attention_mask"], + ).logits + + shift_logits = completion_logits[:, :-1, :].contiguous() + per_token_logps = selective_log_softmax(shift_logits, inputs["completion_input_ids"][:, 1:].contiguous()) + per_token_logps[inputs["completion_mask"][:, 1:] == 0] = 0.0 + completion_logps = per_token_logps.sum(-1) + + if self.calculate_KL: + shift_KL_logits = KL_logits[:, :-1, :].contiguous() + KL_per_token_logps = selective_log_softmax( + shift_KL_logits, inputs["KL_completion_input_ids"][:, 1:].contiguous() + ) + KL_per_token_logps[inputs["KL_completion_mask"][:, 1:] == 0] = 0.0 + KL_logps = KL_per_token_logps.sum(-1) + else: + KL_logps = None + + return completion_logps, KL_logps + + def _compute_kl_logps(self, model, batch): + """Compute KL log probabilities for a given batch.""" + KL_logps = None + if self.calculate_KL: + _non_model_keys = { + "completion_input_ids", + "completion_attention_mask", + "completion_mask", + "KL_completion_mask", + "KL_completion_token_type_ids", + "KL_completion_mm_token_type_ids", + "label", + "ref_logps", + "ref_KL_logps", + } + KL_model_kwargs = {k: v for k, v in batch.items() if k not in _non_model_keys} + KL_model_kwargs["input_ids"] = KL_model_kwargs.pop("KL_completion_input_ids") + KL_model_kwargs["attention_mask"] = KL_model_kwargs.pop("KL_completion_attention_mask") + # KL sequences have different widths from the main completion after flush_left; override token-type + # tensors with the KL-specific ones the collator built for exactly this purpose. + if "KL_completion_token_type_ids" in batch: + KL_model_kwargs["token_type_ids"] = batch["KL_completion_token_type_ids"] + if "KL_completion_mm_token_type_ids" in batch: + KL_model_kwargs["mm_token_type_ids"] = batch["KL_completion_mm_token_type_ids"] + + with torch.no_grad(): + KL_logits = model(**KL_model_kwargs).logits + + shift_KL_logits = KL_logits[:, :-1, :].contiguous() + KL_per_token_logps = selective_log_softmax( + shift_KL_logits, batch["KL_completion_input_ids"][:, 1:].contiguous() + ) + KL_per_token_logps[batch["KL_completion_mask"][:, 1:] == 0] = 0.0 + KL_logps = KL_per_token_logps.sum(-1) + return KL_logps + + def _compute_loss_liger(self, model, inputs, return_outputs): + if return_outputs: + raise RuntimeError( + "return_outputs=True is not supported with the Liger KTO loss. The Liger loss computes the loss " + "without materializing logits, so outputs cannot be returned." + ) + mode = "train" if self.model.training else "eval" + batch = {k: (v.to(self.accelerator.device) if isinstance(v, torch.Tensor) else v) for k, v in inputs.items()} + + labels = torch.tensor(batch["label"]) + num_chosen = labels.sum().to(self.accelerator.device) + num_rejected = (len(labels) - num_chosen).to(self.accelerator.device) + + policy_KL_logps = self._compute_kl_logps(model, batch) + ref_KL_logps = self._compute_kl_logps(self.ref_model, batch) + if self.calculate_KL: + kl = (policy_KL_logps - ref_KL_logps).mean().detach() + kl = self.accelerator.gather_for_metrics(kl).mean().clamp(min=0) + else: + kl = torch.zeros(1).to(self.accelerator.device) + + _non_model_keys = { + "completion_mask", + "KL_completion_input_ids", + "KL_completion_attention_mask", + "KL_completion_mask", + "KL_completion_token_type_ids", + "KL_completion_mm_token_type_ids", + "label", + "ref_logps", + "ref_KL_logps", + } + model_kwargs = {k: v for k, v in batch.items() if k not in _non_model_keys} + model_kwargs["input_ids"] = model_kwargs.pop("completion_input_ids") + model_kwargs["attention_mask"] = model_kwargs.pop("completion_attention_mask") + model_kwargs["use_cache"] = False + if self.aux_loss_enabled: + model_kwargs["output_router_logits"] = True + + # `base_model` gives the inner module (skipping `lm_head`) — text decoder for LMs, multimodal wrapper for + # VLMs (so vision-token injection runs before the text decoder). `get_decoder()` won't do: on VLMs it + # returns just the text stack and feeds image-placeholder IDs through it. + # Pre-5.0 transformers VLMs set `base_model_prefix = ""` so `base_model is self` (re-runs `lm_head`). + # Fall back to `.model` there. + if self._is_vlm and Version(transformers.__version__) < Version("5.0.0"): + backbone, ref_backbone = model.model, self.ref_model.model + else: + backbone, ref_backbone = model.base_model, self.ref_model.base_model + + outputs = backbone(**model_kwargs) + + # reference model + with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs): + ref_outputs = ref_backbone(**{k: v for k, v in model_kwargs.items() if k != "output_router_logits"}) + lm_head = model.get_output_embeddings() + ref_lm_head = self.ref_model.get_output_embeddings() + + shift_completion_mask = batch["completion_mask"][:, 1:].contiguous() + target = batch["completion_input_ids"][:, 1:].clone() + target[shift_completion_mask == 0] = -100 + + ( + loss, + ( + chosen_logps_sum, + rejected_logps_sum, + chosen_logits_sum, + rejected_logits_sum, + chosen_rewards_sum, + rejected_rewards_sum, + ), + ) = self.liger_loss_fn( + _input=outputs.last_hidden_state[:, :-1], + lin_weight=lm_head.weight, + target=target, + bias=lm_head.bias if hasattr(lm_head, "bias") else None, + preference_labels=torch.tensor(batch["label"], dtype=torch.bool).to(self.accelerator.device), + ref_input=ref_outputs.last_hidden_state[:, :-1], + ref_weight=ref_lm_head.weight, + ref_bias=ref_lm_head.bias if hasattr(lm_head, "bias") else None, + kl=kl, + ) + if self.aux_loss_enabled: + loss += self.aux_loss_coef * outputs.aux_loss + + self._metrics[mode]["kl"].append(kl.item()) + + all_num_chosen = self.accelerator.gather_for_metrics(num_chosen).sum().item() + all_num_rejected = self.accelerator.gather_for_metrics(num_rejected).sum().item() + + if all_num_chosen > 0: + self._metrics[mode]["rewards/chosen"].append( + self.accelerator.gather_for_metrics(chosen_rewards_sum.nansum()).nansum().item() / all_num_chosen + ) + self._metrics[mode]["logps/chosen"].append( + self.accelerator.gather_for_metrics(chosen_logps_sum.nansum()).nansum().item() / all_num_chosen + ) + self._metrics[mode]["logits/chosen"].append( + self.accelerator.gather_for_metrics(chosen_logits_sum.nansum()).nansum().item() / all_num_chosen + ) + + if all_num_rejected > 0: + self._metrics[mode]["rewards/rejected"].append( + self.accelerator.gather_for_metrics(rejected_rewards_sum.nansum()).nansum().item() / all_num_rejected + ) + self._metrics[mode]["logps/rejected"].append( + self.accelerator.gather_for_metrics(rejected_logps_sum.nansum()).nansum().item() / all_num_rejected + ) + self._metrics[mode]["logits/rejected"].append( + self.accelerator.gather_for_metrics(rejected_logits_sum.nansum()).nansum().item() / all_num_rejected + ) + + return loss + + def _compute_loss(self, model, inputs, return_outputs): + """Compute the KTO loss and other metrics for the given batch of inputs for train or test.""" + mode = "train" if self.model.training else "eval" + batch = {k: (v.to(self.accelerator.device) if isinstance(v, torch.Tensor) else v) for k, v in inputs.items()} + + labels = torch.tensor(batch["label"]) + num_chosen = labels.sum().to(self.accelerator.device) + num_rejected = (len(labels) - num_chosen).to(self.accelerator.device) + + policy_KL_logps = self._compute_kl_logps(model, batch) + + _non_model_keys = { + "completion_mask", + "KL_completion_input_ids", + "KL_completion_attention_mask", + "KL_completion_mask", + "KL_completion_token_type_ids", + "KL_completion_mm_token_type_ids", + "label", + "ref_logps", + "ref_KL_logps", + } + model_kwargs = {k: v for k, v in batch.items() if k not in _non_model_keys} + model_kwargs["input_ids"] = model_kwargs.pop("completion_input_ids") + model_kwargs["attention_mask"] = model_kwargs.pop("completion_attention_mask") + if self.aux_loss_enabled: + model_kwargs["output_router_logits"] = True + + outputs = model(**model_kwargs) + if self.aux_loss_enabled: + aux_loss = outputs.aux_loss + + shift_logits = outputs.logits[:, :-1, :].contiguous() + per_token_logps = selective_log_softmax(shift_logits, batch["completion_input_ids"][:, 1:].contiguous()) + per_token_logps[batch["completion_mask"][:, 1:] == 0] = 0.0 + completion_logps = per_token_logps.sum(-1) + + if completion_logps.shape[0] != len(batch["label"]): + raise ValueError( + "There is a mismatch between the number of examples in this batch and the number of " + "examples for which an output sequence was predicted." + ) + + device = outputs.logits.device + bool_labels = torch.as_tensor(batch["label"], dtype=torch.bool, device=device) + chosen_idx = torch.nonzero(bool_labels, as_tuple=False).view(-1) + rejected_idx = torch.nonzero(~bool_labels, as_tuple=False).view(-1) + + policy_chosen_logps = completion_logps.index_select(0, chosen_idx) + policy_rejected_logps = completion_logps.index_select(0, rejected_idx) + policy_chosen_logits = outputs.logits.index_select(0, chosen_idx) + policy_rejected_logits = outputs.logits.index_select(0, rejected_idx) + + if self.precompute_ref_logps: + ref_chosen_logps = batch["ref_logps"].index_select(0, chosen_idx) + ref_rejected_logps = batch["ref_logps"].index_select(0, rejected_idx) + if self.calculate_KL: + ref_KL_logps = batch["ref_KL_logps"] + else: + ref_KL_logps = None + else: + ref_model_kwargs = {k: v for k, v in model_kwargs.items() if k != "output_router_logits"} + with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs): + if is_peft_model(self.model) and self.ref_model is None: + ref_model_unwrapped = self.accelerator.unwrap_model(self.model) + with use_adapter( + ref_model_unwrapped, adapter_name="ref" if "ref" in ref_model_unwrapped.peft_config else None + ): + ref_KL_logps = self._compute_kl_logps(self.model, batch) + ref_outputs = self.model(**ref_model_kwargs) + else: + ref_KL_logps = self._compute_kl_logps(self.ref_model, batch) + ref_outputs = self.ref_model(**ref_model_kwargs) + ref_shift_logits = ref_outputs.logits[:, :-1, :].contiguous() + ref_per_token_logps = selective_log_softmax( + ref_shift_logits, batch["completion_input_ids"][:, 1:].contiguous() + ) + ref_per_token_logps[batch["completion_mask"][:, 1:] == 0] = 0.0 + ref_completion_logps = ref_per_token_logps.sum(-1) + ref_chosen_logps = ref_completion_logps.index_select(0, chosen_idx) + ref_rejected_logps = ref_completion_logps.index_select(0, rejected_idx) + + if self.calculate_KL: + kl = (policy_KL_logps - ref_KL_logps).mean().detach() + kl = self.accelerator.gather_for_metrics(kl).mean().clamp(min=0) + else: + kl = torch.zeros(1).to(policy_chosen_logps.device) + # Chosen losses + if policy_chosen_logps.shape[0] != 0 or ref_chosen_logps.shape[0] != 0: + chosen_logratios = policy_chosen_logps - ref_chosen_logps + + if self.loss_type == "kto": + # Eqn (7) of the KTO paper (https://huggingface.co/papers/2402.01306) + chosen_losses = 1 - F.sigmoid(self.beta * (chosen_logratios - kl)) + elif self.loss_type == "apo_zero_unpaired": + # Unpaired variant of Eqn (7) of the APO paper (https://huggingface.co/papers/2408.06266) + # Use this loss when you believe the chosen outputs are better than your model's default output + chosen_losses = 1 - F.sigmoid(self.beta * chosen_logratios) + + chosen_rewards = self.beta * chosen_logratios.detach() + + else: + # lists can't be empty -- if they are, then accelerate.gather will hang + chosen_losses = torch.Tensor([]).to(self.accelerator.device) + chosen_rewards = torch.Tensor([]).to(self.accelerator.device) + # Rejected losses + if policy_rejected_logps.shape[0] != 0 or ref_rejected_logps.shape[0] != 0: + rejected_logratios = policy_rejected_logps - ref_rejected_logps + + if self.loss_type == "kto": + rejected_losses = 1 - F.sigmoid(self.beta * (kl - rejected_logratios)) + elif self.loss_type == "apo_zero_unpaired": + rejected_losses = F.sigmoid(self.beta * rejected_logratios) + + rejected_rewards = self.beta * rejected_logratios.detach() + else: + # lists can't be empty -- if they are, then accelerate.gather will hang + rejected_losses = torch.Tensor([]).to(self.accelerator.device) + rejected_rewards = torch.Tensor([]).to(self.accelerator.device) + losses = torch.cat( + (self.desirable_weight * chosen_losses, self.undesirable_weight * rejected_losses), + 0, + ) + + self._metrics[mode]["kl"].append(kl.item()) + + all_num_chosen = self.accelerator.gather_for_metrics(num_chosen).sum().item() + all_num_rejected = self.accelerator.gather_for_metrics(num_rejected).sum().item() + + if all_num_chosen > 0: + self._metrics[mode]["rewards/chosen"].append( + self.accelerator.gather_for_metrics(chosen_rewards.nansum()).nansum().item() / all_num_chosen + ) + self._metrics[mode]["logps/chosen"].append( + self.accelerator.gather_for_metrics(policy_chosen_logps.nansum()).nansum().item() / all_num_chosen + ) + self._metrics[mode]["logits/chosen"].append( + self.accelerator.gather_for_metrics(policy_chosen_logits.nansum()).nansum().item() / all_num_chosen + ) + + if all_num_rejected > 0: + self._metrics[mode]["rewards/rejected"].append( + self.accelerator.gather_for_metrics(rejected_rewards.nansum()).nansum().item() / all_num_rejected + ) + self._metrics[mode]["logps/rejected"].append( + self.accelerator.gather_for_metrics(policy_rejected_logps.nansum()).nansum().item() / all_num_rejected + ) + self._metrics[mode]["logits/rejected"].append( + self.accelerator.gather_for_metrics(policy_rejected_logits.nansum()).nansum().item() / all_num_rejected + ) + + loss = losses.nanmean() + if self.aux_loss_enabled: + loss += self.aux_loss_coef * aux_loss + + return (loss, outputs) if return_outputs else loss + + def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): + try: + if self.use_liger_kernel: + return self._compute_loss_liger(model, inputs, return_outputs) + return self._compute_loss(model, inputs, return_outputs) + except ValueError as e: + if "Image features and image tokens do not match" in str(e) and self.args.max_length is not None: + raise ValueError( + f"The current `max_length` ({self.args.max_length}) is too short and causes image placeholder " + f"tokens in `input_ids` to be truncated, while the corresponding image features remain intact. " + f"Please increase `max_length` or set it to `None` to disable truncation." + ) from e + raise + + def _get_train_sampler(self, train_dataset: Dataset | None = None) -> torch.utils.data.Sampler | None: + if self.calculate_KL and Version(transformers.__version__) < Version("5.2.0"): + if train_dataset is None: + train_dataset = self.train_dataset + if train_dataset is None or not has_length(train_dataset): + return None + return SequentialSampler(train_dataset) + return super()._get_train_sampler(train_dataset) + + # During eval, Trainer calls prediction_step. If no labels are present in the inputs, it only runs forward and + # returns logits. We override prediction_step to force compute_loss, because this trainer doesn't involve labels. + def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys=None): + inputs = self._prepare_inputs(inputs) + with torch.no_grad(), self.compute_loss_context_manager(): + if prediction_loss_only: + loss = self.compute_loss(model, inputs, return_outputs=False) # logits aren't materialized with liger + logits, labels = None, None + else: + loss, outputs = self.compute_loss(model, inputs, return_outputs=True) + logits, labels = outputs.logits, inputs["completion_input_ids"] + return loss, logits, labels + + # Override training step to add activation offloading context. + def training_step(self, *args, **kwargs): + with self.maybe_activation_offload_context: + return super().training_step(*args, **kwargs) + + def log(self, logs: dict[str, float], start_time: float | None = None) -> None: + mode = "train" if self.model.training else "eval" + metrics = {key: sum(val) / len(val) for key, val in self._metrics[mode].items()} # average the metrics + if "rewards/chosen" in metrics and "rewards/rejected" in metrics: + metrics["rewards/margins"] = metrics["rewards/chosen"] - metrics["rewards/rejected"] + # This method can be called both in training and evaluation. When called in evaluation, the keys in `logs` + # start with "eval_". We need to add the prefix "eval_" to the keys in `metrics` to match the format. + if mode == "eval": + metrics = {f"eval_{key}": val for key, val in metrics.items()} + logs.update(metrics) + super().log(logs, start_time) + self._metrics[mode].clear() + + # Ensure the model card is saved along with the checkpoint + def _save_checkpoint(self, model, trial): + if self.args.hub_model_id is None: + model_name = Path(self.args.output_dir).name + else: + model_name = self.args.hub_model_id.split("/")[-1] + self.create_model_card(model_name=model_name) + super()._save_checkpoint(model, trial) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/merge_model_callback.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/merge_model_callback.py new file mode 100644 index 0000000000000000000000000000000000000000..2f8478759204105aa02eea715b884c755bfc9757 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/merge_model_callback.py @@ -0,0 +1,352 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging +import os + +import torch +from huggingface_hub import HfApi +from transformers import TrainerCallback + +from ..import_utils import is_mergekit_available +from ..trainer.utils import get_config_model_id + + +if is_mergekit_available(): + from mergekit.config import MergeConfiguration + from mergekit.merge import MergeOptions, run_merge + + +# Logger for module-level logging +logger = logging.getLogger(__name__) + + +def upload_model_to_hf(folder_path: str, repo_id: str): + api = HfApi() + # Create the repository if it doesn't exist + repo = api.create_repo(repo_id, repo_type="model") + + # Upload the folder to the specified repository + api.upload_folder( + folder_path=folder_path, + repo_id=repo.repo_id, + repo_type=repo.repo_type, + ) + + +class MergeConfig: + r""" + Configuration class for merging two models using `mergekit`. + + This class provides a structured way to configure and generate merge configurations for various merge methods, such + as `linear`, `ties`, `dare_ties`, and `slerp`. + + Args: + method (`str`, *optional*, defaults to `"linear"`): + Merge method to use. Supported methods include: + + - `"linear"`: Linearly combines two models with specified weights. + - `"ties"`: Combines two models using the TIES method with density parameters. + - `"dare_ties"`: A variant of TIES for domain adaptation. + - `"slerp"`: Combines models using spherical linear interpolation. + + Note: + + For more details about the merge methods and how they are implemented, see the [MergeKit GitHub + repository](https://github.com/arcee-ai/mergekit?tab=readme-ov-file#merge-methods). + + Attributes: + method (`str`): The merge method to use. + policy_model_path (`str` or `None`): Path to the policy model. + target_model_path (`str` or `None`): Path to the target model. + policy_model_weight (`float`): Weight for the policy model (for `linear` and `ties` methods). + target_model_weight (`float`): Weight for the target model (for `linear` and `ties` methods). + policy_model_density (`list[float]`): Density parameters for the policy model (for `ties` and `dare_ties`). + target_model_density (`list[float]`): Density parameters for the target model (for `ties` and `dare_ties`). + normalize (`float` or `None`): Normalization factor for the TIES method. + t_values (`float` or `None`): Interpolation factor for the SLERP method. + dtype (`str`): Data type to use for merging, e.g., `"float16"`. + """ + + def __init__(self, method: str = "linear"): + if not is_mergekit_available(): + raise ImportError("MergeConfig requires the `mergekit` extra. To install, run `pip install mergekit`.") + self.method = method + self.policy_model_path = None + self.target_model_path = None + + # Initialize relevant parameters based on the method + if method == "linear": + self.policy_model_weight = 0.5 + self.target_model_weight = 0.5 + self.dtype = "float16" + elif method == "ties": + self.policy_model_weight = 1.0 + self.policy_model_density = [1.0, 0.7, 0.1] + self.target_model_weight = 1.0 + self.target_model_density = [1.0] + self.normalize = 1.0 + self.dtype = "float16" + elif method == "dare_ties": + self.policy_model_weight = 1.0 + self.policy_model_density = [1.0, 0.7, 0.1] + self.target_model_weight = 1.0 + self.target_model_density = [1.0] + self.normalize = 1.0 + self.dtype = "float16" + elif method == "slerp": + self.t_values = 0.5 + self.dtype = "float16" + else: + raise ValueError(f"Unsupported merge method: {method}") + + def create_merge_config_linear(self) -> "MergeConfiguration": + """ + Creates a merge configuration for a linear merge of two models with specified weights. + """ + # Create the merge configuration dictionary + merge_config_dict = { + "dtype": self.dtype, + "merge_method": "linear", + "models": [ + {"model": self.policy_model_path, "parameters": {"weight": self.policy_model_weight}}, + {"model": self.target_model_path, "parameters": {"weight": self.target_model_weight}}, + ], + } + + # Create the MergeConfiguration from the dictionary + merge_config = MergeConfiguration.model_validate(merge_config_dict) + + return merge_config + + def create_merge_config_ties(self) -> "MergeConfiguration": + """ + Creates a merge configuration for a TIES merge of two models, with specified weights and densities. + """ + # Create the TIES merge configuration dictionary + merge_config_dict = { + "merge_method": "ties", + "slices": None, # Optional slices if needed + "models": [ + { + "model": { + "model": {"path": self.target_model_path, "revision": None}, + "lora": None, + "override_architecture": None, + }, + "parameters": {"density": self.target_model_density, "weight": self.target_model_weight}, + }, + { + "model": { + "model": {"path": self.policy_model_path, "revision": None}, + "lora": None, + "override_architecture": None, + }, + "parameters": {"density": self.policy_model_density, "weight": self.policy_model_weight}, + }, + ], + "parameters": {"normalize": self.normalize}, + "base_model": { + "model": {"path": self.policy_model_path, "revision": None}, + "lora": None, + "override_architecture": None, + }, + "dtype": self.dtype, + "tokenizer_source": None, + "tokenizer": None, + "chat_template": None, + "out_dtype": None, + } + + # Create the MergeConfiguration from the dictionary + merge_config = MergeConfiguration.model_validate(merge_config_dict) + + return merge_config + + def create_merge_config_dare_ties(self) -> "MergeConfiguration": + """ + Creates a merge configuration for a DARE TIES merge of two models, with specified weights and densities. + """ + # Create the DARE TIES merge configuration dictionary + merge_config_dict = { + "merge_method": "dare_ties", + "slices": None, # Optional slices if needed + "models": [ + { + "model": { + "model": {"path": self.target_model_path, "revision": None}, + "lora": None, + "override_architecture": None, + }, + "parameters": {"density": self.target_model_density, "weight": self.target_model_weight}, + }, + { + "model": { + "model": {"path": self.policy_model_path, "revision": None}, + "lora": None, + "override_architecture": None, + }, + "parameters": {"density": self.policy_model_density, "weight": self.policy_model_weight}, + }, + ], + "parameters": {"normalize": self.normalize}, + "base_model": { + "model": {"path": self.policy_model_path, "revision": None}, + "lora": None, + "override_architecture": None, + }, + "dtype": self.dtype, + "tokenizer_source": None, + "tokenizer": None, + "chat_template": None, + "out_dtype": None, + } + + # Create the MergeConfiguration from the dictionary + merge_config = MergeConfiguration.model_validate(merge_config_dict) + + return merge_config + + def create_merge_config_slerp(self) -> "MergeConfiguration": + """ + Creates a merge configuration for a SLERP merge of a model with a base model. + """ + + # Create the SLERP merge configuration dictionary + merge_config_dict = { + "merge_method": "slerp", + "slices": None, # Optional slices if needed + "models": [ + { + "model": { + "model": {"path": self.target_model_path, "revision": None}, + "lora": None, + "override_architecture": None, + }, + "parameters": None, # No specific parameters for SLERP model + } + ], + "parameters": { + "t": self.t_values # Set the t values for SLERP + }, + "base_model": { + "model": {"path": self.policy_model_path, "revision": None}, + "lora": None, + "override_architecture": None, + }, + "dtype": self.dtype, + "tokenizer_source": None, + "tokenizer": None, + "chat_template": None, + "out_dtype": None, + } + + # Create the MergeConfiguration from the dictionary + merge_config = MergeConfiguration.model_validate(merge_config_dict) + + return merge_config + + def create(self) -> "MergeConfiguration": + if self.method == "linear": + return self.create_merge_config_linear() + elif self.method == "ties": + return self.create_merge_config_ties() + elif self.method == "dare_ties": + return self.create_merge_config_dare_ties() + elif self.method == "slerp": + return self.create_merge_config_slerp() + + +def merge_models(config: "MergeConfiguration", out_path: str): + """ + Merge two models using mergekit + + Args: + config (`MergeConfiguration`): The merge configuration. + out_path (`str`): The output path for the merged model. + """ + if not is_mergekit_available(): + raise ImportError("merge_models requires the `mergekit` extra. To install, run `pip install mergekit`.") + run_merge( + config, + out_path=out_path, + options=MergeOptions( + device="auto", + cuda=torch.cuda.is_available(), + copy_tokenizer=True, + lazy_unpickle=False, + low_cpu_memory=False, + ), + ) + + +class MergeModelCallback(TrainerCallback): + r""" + A [`~transformers.TrainerCallback`] that merges the policy model (the model being trained) with another model based + on a merge configuration. + + Args: + merge_config ([`experimental.merge_model_callback.MergeConfig`], *optional*): + Configuration used for the merging process. If not provided, the default + [`~experimental.merge_model_callback.MergeConfig`] is used. + merge_at_every_checkpoint (`bool`, *optional*, defaults to `False`): + Whether to merge the model at every checkpoint. + push_to_hub (`bool`, *optional*, defaults to `False`): + Whether to push the merged model to the Hub after merging. + + Example: + + ```python + from trl.experimental.merge_model_callback import MergeConfig, MergeModelCallback + + config = MergeConfig() + merge_callback = MergeModelCallback(config) + trainer = DPOTrainer(..., callbacks=[merge_callback]) + ``` + """ + + def __init__( + self, + merge_config: "MergeConfig | None" = None, + merge_at_every_checkpoint: bool = False, + push_to_hub: bool = False, + ): + if not is_mergekit_available(): + raise ImportError( + "MergeModelCallback requires the `mergekit` extra. To install, run `pip install mergekit`." + ) + self.merge_config = merge_config or MergeConfig() + self.merge_at_every_checkpoint = merge_at_every_checkpoint + self.push_to_hub = push_to_hub + + def _merge_and_maybe_push(self, output_dir, global_step, model): + checkpoint_path = os.path.join(output_dir, f"checkpoint-{global_step}") + self.merge_config.policy_model_path = checkpoint_path + if self.merge_config.target_model_path is None: + self.merge_config.target_model_path = get_config_model_id(model.config) + merge_path = os.path.join(checkpoint_path, "merged") + + merge_models(self.merge_config.create(), merge_path) + + if self.push_to_hub: + repo_name = f"{output_dir}_checkpoint-{global_step}_merged" + upload_model_to_hf(merge_path, repo_name) + + def on_save(self, args, state, control, model=None, **kwargs): + if self.merge_at_every_checkpoint: + self._merge_and_maybe_push(args.output_dir, state.global_step, model) + + def on_train_end(self, args, state, control, model=None, **kwargs): + if not self.merge_at_every_checkpoint: + self._merge_and_maybe_push(args.output_dir, state.global_step, model) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/minillm/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/minillm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..07bc38f0ef9973010a3eed3c9adf4ef5137ec6b1 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/minillm/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .minillm_config import MiniLLMConfig +from .minillm_trainer import MiniLLMTrainer + + +__all__ = ["MiniLLMConfig", "MiniLLMTrainer"] diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/minillm/minillm_config.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/minillm/minillm_config.py new file mode 100644 index 0000000000000000000000000000000000000000..678868aabb8aa78a50eb53282ca390364674b82d --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/minillm/minillm_config.py @@ -0,0 +1,137 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field +from typing import Any + +from ...trainer.base_config import _BaseConfig +from ...trainer.grpo_config import GRPOConfig + + +@dataclass +class MiniLLMConfig(GRPOConfig): + """ + Configuration class for [`MiniLLMTrainer`]. + + This class includes only the parameters that are specific to MiniLLM training. For a full list of training + arguments, please refer to the [`~transformers.TrainingArguments`] and [`GRPOConfig`] documentation. + + Args: + teacher_model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the teacher model + from a string. + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the model. + rkl_advantage (`bool`, *optional*, defaults to `True`): + Whether to add the reverse KL advantage to the reward advantage. + single_step_decomposition (`bool`, *optional*, defaults to `True`): + Whether to use single-step decomposition for the KL divergence computation. + kd_temperature (`float`, *optional*, defaults to `1.0`): + Temperature for knowledge distillation. Higher temperatures produce softer probability distributions over + classes. + gamma (`float`, *optional*, defaults to `0.0`): + Discount factor for future rewards in reinforcement learning. + length_normalization (`bool`, *optional*, defaults to `True`): + Whether to apply length normalization to the rewards. + """ + + _VALID_DICT_FIELDS = GRPOConfig._VALID_DICT_FIELDS + ["teacher_model_init_kwargs"] + + teacher_model_init_kwargs: dict[str, Any] | str | None = field( + default=None, + metadata={ + "help": "Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the " + "teacher model from a string." + }, + ) + disable_dropout: bool = field( + default=True, + metadata={"help": "Whether to disable dropouts in `model`."}, + ) + rkl_advantage: bool = field( + default=True, + metadata={"help": "Whether to add the reverse KL advantage to the reward advantage."}, + ) + single_step_decomposition: bool = field( + default=True, + metadata={"help": "Whether to use single-step decomposition for the KL divergence computation."}, + ) + kd_temperature: float = field( + default=1.0, + metadata={ + "help": "Temperature for knowledge distillation. Higher temperatures produce softer probability " + "distributions over classes." + }, + ) + gamma: float = field( + default=0.0, + metadata={"help": "Discount factor for future rewards in reinforcement learning."}, + ) + length_normalization: bool = field( + default=True, + metadata={"help": "Whether to apply length normalization to the rewards."}, + ) + + def __post_init__(self): + # We do not use the post_init of GRPOConfig because: + # 1. num_generations can be < 2 in MiniLLMConfig. Scale_rewards must be set to "none" to avoid nan. + _BaseConfig.__post_init__(self) + + self.scale_rewards = {True: "group", False: "none"}.get(self.scale_rewards, self.scale_rewards) + if self.num_generations == 1: + self.scale_rewards = "none" + + num_processes = self.world_size + # The current default effective batch size + if self.generation_batch_size is None and self.steps_per_generation is None: + self.steps_per_generation = self.gradient_accumulation_steps + self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation + elif self.generation_batch_size is not None and self.steps_per_generation is None: + # Just ensure the value is divisible by the global batch size + if self.generation_batch_size % (self.per_device_train_batch_size * num_processes) != 0: + raise ValueError( + f"generation_batch_size ({self.generation_batch_size}) must be divisible by the global batch size " + f"({self.per_device_train_batch_size * num_processes})." + ) + self.steps_per_generation = self.generation_batch_size // ( + self.per_device_train_batch_size * num_processes + ) + elif self.generation_batch_size is None and self.steps_per_generation is not None: + self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation + else: + raise ValueError( + "'generation_batch_size' and 'steps_per_generation' can not be both configured at the same time" + ) + + if self.do_eval and self.eval_strategy != "no": + # Determine the number of generations to use for evaluation + num_generations = self.num_generations_eval or self.num_generations + + # Just ensure the value is divisible by the global batch size + if (self.per_device_eval_batch_size * num_processes) % num_generations != 0: + raise ValueError( + f"The global eval batch size ({self.per_device_eval_batch_size} * {num_processes}) must be " + f"divisible by the number of generations used for evaluation ({num_generations})." + ) + + # The generation batch must contain full prompt groups (no partials), so it must be divisible by + # num_generations. + if self.generation_batch_size % self.num_generations != 0: + raise ValueError( + f"generation_batch_size ({self.generation_batch_size}) must be divisible by num_generations " + f"({self.num_generations})." + ) + + if self.delta is not None and self.use_liger_kernel: + raise ValueError("Liger kernel does not support two-sided GRPO loss yet.") diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/minillm/minillm_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/minillm/minillm_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..14fd46a9fcae4ecfaae673b175bef5d1b6bdca9c --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/minillm/minillm_trainer.py @@ -0,0 +1,410 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import textwrap + +import torch +import torch.nn as nn +import torch.nn.functional as F +import transformers +from datasets import Dataset, IterableDataset +from packaging.version import Version +from transformers import ( + AutoModelForCausalLM, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, +) +from transformers.utils import is_peft_available + +from ...models import prepare_deepspeed +from ...trainer.grpo_trainer import GRPOTrainer, RewardFunc, RolloutFunc +from ...trainer.utils import disable_dropout_in_model, get_config_model_id +from ..utils import empty_cache +from .minillm_config import MiniLLMConfig + + +if is_peft_available(): + from peft import PeftConfig + + +def dummy_reward_func(completions: list, **kwargs): + # placeholder reward function when no reward function is provided + return [1.0 for _ in completions] + + +class MiniLLMTrainer(GRPOTrainer): + """ + Trainer for the Knowledge Distillation of Language Models (MiniLLM) method. This algorithm was initially proposed + in the paper [Knowledge Distillation of Large Language Models](https://huggingface.co/papers/2306.08543). + + Example: + + ```python + from datasets import load_dataset + from trl.experimental.minillm import MiniLLMTrainer + + dataset = load_dataset("trl-lib/tldr", split="train") + + trainer = MiniLLMTrainer( + model="Qwen/Qwen3-0.6B", + teacher_model="Qwen/Qwen3-1.7B", + train_dataset=dataset, + ) + trainer.train() + ``` + + Args: + model (`str | PreTrainedModel`): + Model to be trained. Can be either: + + - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a + path to a *directory* containing model weights saved using + [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded + using [`~transformers.AutoModelForCausalLM.from_pretrained`] with the keyword arguments in + `args.model_init_kwargs`. + - A [`~transformers.PreTrainedModel`] object. Only causal language models are supported. + teacher_model (`PreTrainedModel | nn.Module | str`): + Teacher model used for knowledge distillation. Instantiated similarly to `model`. + reward_funcs (`RewardFunc | list[RewardFunc]`, *optional*): + Reward functions to be used for computing the rewards. To compute the rewards, we call all the reward + functions with the prompts and completions and sum the rewards. Can be either: + + - A single reward function, such as: + - A string: The *model ID* of a pretrained model hosted inside a model repo on huggingface.co, or a + path to a *directory* containing model weights saved using + [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded + using [`~transformers.AutoModelForSequenceClassification.from_pretrained`] with `num_labels=1` and the + keyword arguments in `args.model_init_kwargs`. + - A [`~transformers.PreTrainedModel`] object: Only sequence classification models are supported. + - A custom reward function: The function is provided with the prompts and the generated completions, + plus any additional columns in the dataset. It should return a list of rewards. Custom reward + functions can also return `None` when the reward is not applicable to those samples. This is useful + for multi-task training where different reward functions apply to different types of samples. When a + reward function returns `None` for a sample, that reward function is excluded from the reward + calculation for that sample. For more details, see [Using a custom reward + function](#using-a-custom-reward-function). + + The trainer's state is also passed to the reward function. The trainer's state is an instance of + [`~transformers.TrainerState`] and can be accessed by accessing the `trainer_state` argument to the + reward function's signature. + - A list of reward functions, where each item can independently be any of the above types. Mixing different + types within the list (e.g., a string model ID and a custom reward function) is allowed. + args ([`experimental.minillm.MiniLLMConfig`], *optional*): + Configuration for this trainer. If `None`, a default configuration is used. + train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]): + Dataset to use for training. It must include a column `"prompt"`. Any additional columns in the dataset is + ignored. The format of the samples can be either: + + - [Standard](dataset_formats#standard): Each sample contains plain text. + - [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role + and content). + eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Dataset | IterableDataset]`): + Dataset to use for evaluation. It must meet the same requirements as `train_dataset`. + processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.ProcessorMixin`], *optional*): + Processing class used to process the data. The padding side must be set to "left". If `None`, the + processing class is loaded from the model's name with [`~transformers.AutoProcessor.from_pretrained`]. A + padding token, `tokenizer.pad_token`, must be set. If the processing class has not set a padding token, + `tokenizer.eos_token` will be used as the default. + reward_processing_classes ([`~transformers.PreTrainedTokenizerBase`] or `list[PreTrainedTokenizerBase]`, *optional*): + Processing classes corresponding to the reward functions specified in `reward_funcs`. Can be either: + + - A single processing class: Used when `reward_funcs` contains only one reward function. + - A list of processing classes: Must match the order and length of the reward functions in `reward_funcs`. + If set to `None`, or if an element of the list corresponding to a [`~transformers.PreTrainedModel`] is + `None`, the tokenizer for the model is automatically loaded using + [`~transformers.AutoTokenizer.from_pretrained`]. For elements in `reward_funcs` that are custom reward + functions (not [`~transformers.PreTrainedModel`]), the corresponding entries in `reward_processing_classes` + are ignored. + callbacks (list of [`~transformers.TrainerCallback`], *optional*): + List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed + in [here](https://huggingface.co/docs/transformers/main_classes/callback). + + If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`] + method. + optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`, *optional*, defaults to `(None, None)`): + A tuple containing the optimizer and the scheduler to use. Will default to an instance of [`AdamW`] on your + model and a scheduler given by [`get_linear_schedule_with_warmup`] controlled by `args`. + peft_config ([`~peft.PeftConfig`], *optional*): + PEFT configuration used to wrap the model. If `None`, the model is not wrapped. + rollout_func (`RolloutFunc`, *optional*): + Function to use for generating completions. It must take prompts, args, and processing_class as parameters + and return a dict with `"prompt_ids"`, `"completion_ids"`, and `"logprobs"` fields. Any other fields that + are forwarded to the reward functions. This feature is experimental and may change or be removed at any + time without prior notice. + """ + + _tag_names = ["trl", "minillm"] + _name = "MiniLLM" + _paper = { + "title": "MiniLLM: Knowledge Distillation of Large Language Models", + "id": "2306.08543", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @inproceedings{ + gu2024minillm, + title={{MiniLLM: Knowledge Distillation of Large Language Models}}, + author={Yuxian Gu and Li Dong and Furu Wei and Minlie Huang}, + booktitle={The Twelfth International Conference on Learning Representations}, + year={2024}, + url={https://openreview.net/forum?id=5h0qf7IBZZ} + }"""), + } + + def __init__( + self, + model: str | PreTrainedModel, + teacher_model: PreTrainedModel | nn.Module | str, + reward_funcs: RewardFunc | list[RewardFunc] | None = None, + args: MiniLLMConfig | None = None, + train_dataset: Dataset | IterableDataset | None = None, + eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None, + processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None, + reward_processing_classes: PreTrainedTokenizerBase | list[PreTrainedTokenizerBase] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None), + peft_config: "PeftConfig | None" = None, + rollout_func: RolloutFunc | None = None, + ): + if reward_funcs is None: + reward_funcs = [dummy_reward_func] + + # Args + if args is None: + model_name = model if isinstance(model, str) else get_config_model_id(model.config) + model_name = model_name.split("/")[-1] + args = MiniLLMConfig(f"{model_name}-MiniLLM") + + # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was + # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream + # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we + # default to the recommended non-reentrant behavior here, while preserving any user-provided value. + if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"): + args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {} + args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False) + + super().__init__( + model, + reward_funcs, + args=args, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + reward_processing_classes=reward_processing_classes, + callbacks=callbacks, + optimizers=optimizers, + peft_config=peft_config, + rollout_func=rollout_func, + ) + + if args.teacher_model_init_kwargs is None: + teacher_model_init_kwargs = {} + elif not isinstance(teacher_model, str): + raise ValueError( + "You passed teacher_model_init_kwargs to the MiniLLMConfig, but your teacher_model is already instantiated." + ) + else: + teacher_model_init_kwargs = args.teacher_model_init_kwargs + teacher_model_init_kwargs["dtype"] = ( + teacher_model_init_kwargs["dtype"] + if teacher_model_init_kwargs["dtype"] in ["auto", None] + else getattr(torch, teacher_model_init_kwargs["dtype"]) + ) + + if isinstance(teacher_model, str): + teacher_model = AutoModelForCausalLM.from_pretrained(teacher_model, **teacher_model_init_kwargs) + + # Disable dropout in the model + if args.disable_dropout: + disable_dropout_in_model(self.model) + + if self.is_deepspeed_enabled: + self.teacher_model = prepare_deepspeed(teacher_model, self.accelerator) + else: + self.teacher_model = self.accelerator.prepare_model(teacher_model, evaluation_mode=True) + + self.temperature = args.temperature + self.kd_temperature = args.kd_temperature + self.single_step_decomposition = args.single_step_decomposition + self.rkl_advantage = args.rkl_advantage + self.gamma = args.gamma + self.length_normalization = args.length_normalization + + def _single_step_decomposition_loss( + self, + student_log_probs: torch.Tensor, + teacher_log_probs: torch.Tensor, + mask: torch.Tensor | None = None, + reduction: str = "batchmean", + ): + """ + Compute the MiniLLM loss for knowledge distillation using F.kl_div. See Eq. (1) of + https://huggingface.co/papers/2306.08543 for the definition. + + Args: + student_log_probs: + Per-token log-probabilities from the student, of shape (batch_size, sequence_length) + teacher_log_probs: + Per-token log-probabilities from the teacher, of shape (batch_size, sequence_length) + mask: + Optional boolean tensor of shape (batch_size, sequence_length) selecting the tokens to include in the + loss (e.g. excluding padding) + reduction: + Specifies the reduction to apply to the output: 'batchmean' (default), 'sum' or 'mean'; any other value + returns the unreduced per-token loss + + Returns: + loss: Scalar tensor with the single-step KL regularization loss (unreduced if `reduction` is not one of the + above) + """ + reg_loss = F.kl_div( + teacher_log_probs, student_log_probs, reduction="none", log_target=True + ) # (batch_size, sequence_length) + + # Masking + if mask is not None: + reg_loss = reg_loss[mask] + + # Apply reduction + if reduction == "batchmean": + return reg_loss.sum() / mask.sum() if mask is not None else reg_loss.sum() / reg_loss.size(0) + elif reduction == "sum": + return reg_loss.sum() + elif reduction == "mean": + return reg_loss.mean() + else: + return reg_loss + + def _compute_advantage( + self, + student_log_probs_on_labels: torch.Tensor, + teacher_log_probs_on_labels: torch.Tensor, + mask: torch.Tensor | None = None, + ) -> torch.Tensor: + r"""Compute the advantage for Reverse KL Divergence. + + Mostly following [this + implementation](https://github.com/microsoft/LMOps/blob/e210d2c026b9958617887762400778ace81172e6/minillm/minillm/losses.py#L37-L49). + + $$ \text{rewards}_t = \text{teacher\_log\_probs\_on\_labels}_t - \text{student\_log\_probs\_on\_labels}_t $$ + + If length normalization is enabled: + + $$ \text{lengths}_t = \sum_{i=t}^{T} \gamma^{i-t} $$ + + $$ \text{advantages}_t = \frac{\sum_{i=t}^{T} \gamma^{i-t} R_i}{\text{lengths}_t} $$ + + Otherwise: + + $$ \text{advantages}_t = \sum_{i=t}^{T} \gamma^{i-t} R_i $$ + + Args: + student_log_probs_on_labels: Log probabilities of the student model on the labels. + Shape: (batch_size, sequence_length) + teacher_log_probs_on_labels: Log probabilities of the teacher model on the labels. + Shape: (batch_size, sequence_length) + mask: Optional mask to apply to the log probabilities. Shape: (batch_size, sequence_length) + Returns: + advantage: Computed advantage. Shape: (batch_size, sequence_length) + """ + response_length = student_log_probs_on_labels.size(1) + if mask is None: + mask = torch.ones_like(student_log_probs_on_labels) + mask = mask.float() + student_log_probs_on_labels = student_log_probs_on_labels * mask + teacher_log_probs_on_labels = teacher_log_probs_on_labels * mask + + rewards = teacher_log_probs_on_labels - student_log_probs_on_labels # (batch_size, sequence_length) + + if self.gamma > 0.0: + gamma_pow = torch.pow(self.gamma, torch.arange(response_length, device=rewards.device)) + + advantages = rewards * gamma_pow + advantages = advantages.flip(1).cumsum(dim=1).flip(1) + + if self.length_normalization: + mask = torch.where(mask < 0.5, 1e-4, mask) + lengths = mask * gamma_pow + lengths = lengths.flip(1).cumsum(dim=1).flip(1) + advantages = advantages / lengths + else: + advantages = rewards + + return advantages + + def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): + input_ids = torch.cat([inputs["prompt_ids"], inputs["completion_ids"]], dim=1) + attention_mask = torch.cat([inputs["prompt_mask"], inputs["completion_mask"]], dim=1) + labels = input_ids.clone() + labels[attention_mask == 0] = -100 + + # Compute student output + student_outputs = model(input_ids=input_ids, attention_mask=attention_mask, use_cache=False) + + # Compute teacher output in eval mode + self.teacher_model.eval() + with torch.no_grad(): + teacher_outputs = self.teacher_model(input_ids=input_ids, attention_mask=attention_mask, use_cache=False) + + # Slice the logits for the generated tokens using the inputs["prompts"] lengths + prompt_lengths = inputs["prompt_ids"].shape[1] + student_logits = student_outputs.logits[:, prompt_lengths - 1 : -1, :] + teacher_logits = teacher_outputs.logits[:, prompt_lengths - 1 : -1, :] + shifted_labels = input_ids[:, prompt_lengths:] + + # Apply temperature scaling + student_logits = student_logits / self.kd_temperature + teacher_logits = teacher_logits / self.kd_temperature + + # Compute log probabilities for student and probabilities for teacher + student_log_probs = F.log_softmax(student_logits, dim=-1) + teacher_log_probs = F.log_softmax(teacher_logits, dim=-1) + + student_log_probs_on_labels = torch.gather( + student_log_probs, dim=-1, index=shifted_labels.unsqueeze(-1) + ).squeeze(-1) + teacher_log_probs_on_labels = torch.gather( + teacher_log_probs, dim=-1, index=shifted_labels.unsqueeze(-1) + ).squeeze(-1) + + mask = shifted_labels != -100 + + if self.rkl_advantage: + reverse_kl_advantage = self._compute_advantage( + student_log_probs_on_labels=student_log_probs_on_labels, + teacher_log_probs_on_labels=teacher_log_probs_on_labels, + mask=mask, + ) + + inputs["advantages"] = inputs["advantages"].unsqueeze(1) + reverse_kl_advantage + + # Compute GRPO loss on verifiable reward + loss = self._compute_loss(model, inputs) + + # Compute loss + if self.single_step_decomposition: + single_step_decomposition_loss = self._single_step_decomposition_loss( + student_log_probs=student_log_probs, + teacher_log_probs=teacher_log_probs, + mask=mask, + ) + + loss += single_step_decomposition_loss + + # Empty cache + empty_cache() + + # Return loss + return (loss, student_outputs) if return_outputs else loss diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/nash_md/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/nash_md/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5b80c1515bed13913e9497e35e6f79552deb40dc --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/nash_md/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .nash_md_config import NashMDConfig +from .nash_md_trainer import NashMDTrainer + + +__all__ = ["NashMDConfig", "NashMDTrainer"] diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/nash_md/nash_md_config.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/nash_md/nash_md_config.py new file mode 100644 index 0000000000000000000000000000000000000000..2d52d08ecbe7bde752f9b1ae3455c56bf31e445d --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/nash_md/nash_md_config.py @@ -0,0 +1,46 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field + +from ..online_dpo import OnlineDPOConfig + + +@dataclass +class NashMDConfig(OnlineDPOConfig): + r""" + Configuration class for the [`experimental.nash_md.NashMDTrainer`]. + + Subclass of [`experimental.online_dpo.OnlineDPOConfig`] we can use all its arguments and add the following: + + Parameters: + mixture_coef (`float` or `list[float]`, *optional*, defaults to `0.5`): + Logit mixture coefficient for the model and reference model. If a list of floats is provided then the + mixture coefficient is selected for each new epoch and the last coefficient is used for the rest of the + epochs. + """ + + mixture_coef: list[float] = field( + default_factory=lambda: [0.5], + metadata={ + "help": "Logit mixture coefficient for the model and reference model. If a list of floats is provided " + "then the mixture coefficient is selected for each new epoch and the last coefficient is used for the " + "rest of the epochs." + }, + ) + + def __post_init__(self): + super().__post_init__() + if hasattr(self.mixture_coef, "__len__") and len(self.mixture_coef) == 1: + self.mixture_coef = self.mixture_coef[0] diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/nash_md/nash_md_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/nash_md/nash_md_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..fd2f7c816c38135d376e4ac99f96d5a88a579a91 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/nash_md/nash_md_trainer.py @@ -0,0 +1,509 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import textwrap +from collections.abc import Callable +from typing import Any + +import torch +import torch.nn as nn +import torch.nn.functional as F +from datasets import Dataset, IterableDataset +from transformers import ( + BaseImageProcessor, + FeatureExtractionMixin, + GenerationMixin, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, +) +from transformers.trainer_utils import EvalPrediction +from transformers.training_args import OptimizerNames +from transformers.utils import is_peft_available + +from ...data_utils import maybe_apply_chat_template +from ...models.utils import unwrap_model_for_generation +from ...trainer.utils import selective_log_softmax +from ..online_dpo import OnlineDPOTrainer +from ..utils import empty_cache, get_reward, truncate_right +from .nash_md_config import NashMDConfig + + +if is_peft_available(): + from peft import PeftConfig, PeftModel + + +class GeometricMixtureWrapper(GenerationMixin): + """ + Geometric Mixture generation wrapper that samples from the logits of two model's geometric mixture. + + Args: + model ([`~transformers.PreTrainedModel`]): The model to be wrapped. + ref_model ([`~transformers.PreTrainedModel`]): The reference model. + generation_config ([`~transformers.GenerationConfig`]): The generation config. + mixture_coef (`float`, *optional* - default: 0.5): The mixture coefficient. + """ + + main_input_name = "input_ids" + _supports_cache_class = False + _supports_static_cache = False + _is_stateful = False + + def __init__(self, model, ref_model, generation_config, mixture_coef=0.5, device=None): + super().__init__() + + self.model = model + self.config = model.config + self.ref_model = ref_model + self.generation_config = generation_config + self.mixture_coef = mixture_coef + self.device = device + if hasattr(self.model, "_is_stateful"): + self._is_stateful = self.model._is_stateful + + def __call__(self, *args, **kwargs): + return self.forward(*args, **kwargs) + + @torch.inference_mode() + def forward(self, *args, **kwargs): + model_outputs = self.model(*args, **kwargs) + model_logits = model_outputs.logits + ref_model_logits = self.ref_model(*args, **kwargs).logits + + model_outputs.logits = torch.nn.functional.log_softmax( + self.mixture_coef * ref_model_logits + (1 - self.mixture_coef) * model_logits, dim=-1 + ) + + return model_outputs + + def prepare_inputs_for_generation(self, *args, **kwargs): + # turn off cache in the generation config + kwargs["use_cache"] = False + model_inputs = self.model.prepare_inputs_for_generation(*args, **kwargs) + _ = self.ref_model.prepare_inputs_for_generation(*args, **kwargs) + + return model_inputs + + def _validate_model_class(self): + self.model._validate_model_class() + + def _validate_model_kwargs(self, model_kwargs): + return self.model._validate_model_kwargs(model_kwargs) + + +class NashMDTrainer(OnlineDPOTrainer): + """ + Trainer for the Nash-MD method. + + It is implemented as a subclass of [`experimental.online_dpo.OnlineDPOTrainer`]. + + Args: + model ([`~transformers.PreTrainedModel`]): + The model to train, preferably an `AutoModelForCausalLM`. + ref_model ([`~transformers.PreTrainedModel`]): + Hugging Face transformer model with a casual language modelling head. Used for implicit reward computation + and loss. If no reference model is provided, the trainer will create a reference model with the same + architecture as the model to be optimized. + reward_funcs ([`~transformers.PreTrainedModel`]): + The reward model to score completions with, preferably an + [`~transformers.AutoModelForSequenceClassification`]. + args ([`experimental.nash_md.NashMDConfig`]): + The NashMD config arguments to use for training. + data_collator ([`~transformers.DataCollator`]): + The data collator to use for training. If None is specified, the default data collator + ([`experimental.utils.DPODataCollatorWithPadding`]) will be used which will pad the sequences to the + maximum length of the sequences in the batch, given a dataset of paired sequences. + train_dataset ([`~datasets.Dataset`]): + The dataset to use for training. + eval_dataset ([`~datasets.Dataset`]): + The dataset to use for evaluation. + processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*): + Processing class used to process the data. If provided, will be used to automatically process the inputs + for the model, and it will be saved along the model to make it easier to rerun an interrupted training or + reuse the fine-tuned model. + peft_config ([`~peft.PeftConfig`], *optional*): + The peft config to use for training. + compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*): + The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to + metric values. + callbacks (`list[transformers.TrainerCallback]`): + The callbacks to use for training. + optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`): + The optimizer and scheduler to use for training. + preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`): + The function to use to preprocess the logits before computing the metrics. + """ + + _tag_names = ["trl", "nash-md"] + _name = "Nash-MD" + _paper = { + "title": "Nash Learning from Human Feedback", + "id": "2312.00886", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @inproceedings{munos2024nash, + title = {{Nash Learning from Human Feedback}}, + author = {R{\'{e}}mi Munos and Michal Valko and Daniele Calandriello and Mohammad Gheshlaghi Azar and Mark Rowland and Zhaohan Daniel Guo and Yunhao Tang and Matthieu Geist and Thomas Mesnard and C{\\^{o}}me Fiegel and Andrea Michi and Marco Selvi and Sertan Girgin and Nikola Momchev and Olivier Bachem and Daniel J. Mankowitz and Doina Precup and Bilal Piot}, + year = 2024, + booktitle = {Forty-first International Conference on Machine Learning, {ICML} 2024, Vienna, Austria, July 21-27, 2024}, + publisher = {OpenReview.net}, + url = {https://openreview.net/forum?id=Y5AmNYiyCQ} + }"""), + } + + def __init__( + self, + model: PreTrainedModel | nn.Module = None, + ref_model: PreTrainedModel | nn.Module = None, + reward_funcs: PreTrainedModel | nn.Module | None = None, + args: NashMDConfig | None = None, + data_collator: Callable | None = None, + train_dataset: Dataset | IterableDataset | None = None, + eval_dataset: Dataset | dict[str, Dataset] | None = None, + processing_class: PreTrainedTokenizerBase + | BaseImageProcessor + | FeatureExtractionMixin + | ProcessorMixin + | None = None, + peft_config: "PeftConfig | None" = None, + compute_metrics: Callable[[EvalPrediction], dict] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None, + ) -> None: + super().__init__( + model=model, + ref_model=ref_model, + reward_funcs=reward_funcs, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + reward_processing_classes=processing_class, + peft_config=peft_config, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + ) + + self._mixture_coef = self.args.mixture_coef + + # Overwrite the stats dictionary to include NashMD specific statistics + self.stats = { + # Remove "non_score_reward", "rlhf_reward", "scores_margin" + # Add "mixture_coef" + "loss/kl": [], + "objective/entropy": [], + "loss/score": [], + "rewards/probabilities": [], + "rewards/accuracies": [], + "rewards/margins": [], + "logps/chosen": [], + "logps/rejected": [], + "val/model_contain_eos_token": [], + "val/ref_contain_eos_token": [], + "rewards/chosen": [], + "rewards/rejected": [], + "beta": [], + "mixture_coef": [], + } + if len(self.reward_funcs) != 1: + raise ValueError("NashMDTrainer only supports one reward function/model.") + self.reward_funcs = self.reward_funcs[0] + + @property + def mixture_coef(self): + if isinstance(self._mixture_coef, list): + epoch = self.state.epoch + return self._mixture_coef[epoch] if epoch < len(self._mixture_coef) else self._mixture_coef[-1] + else: + return self._mixture_coef + + def _generate_completions(self, model, prompts): + # Generate completions from the policy model. + with ( + unwrap_model_for_generation( + model, + self.accelerator, + generation_kwargs=self.generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762 + ) as unwrapped_policy_for_gen_ctx + ): + model_output = unwrapped_policy_for_gen_ctx.generate( + input_ids=prompts["input_ids"], + attention_mask=prompts["attention_mask"], + generation_config=self.generation_config, + ) + + # Get the DDP/FSDP unwrapped version of the main model. + # This will be the policy model for GeometricMixtureWrapper (PEFT adapters active if PEFT is used). + policy_model_for_gmw = self.accelerator.unwrap_model(model) + + # Determine the correct reference model for GeometricMixtureWrapper. + # This also needs to be DDP/FSDP unwrapped. + ref_model_for_gmw: torch.nn.Module + if self.ref_model is None: + # No explicit ref_model is provided. + # Use the base of the main `model` if it's a PEFT model. + # policy_model_for_gmw is already DDP-unwrapped. + if is_peft_available() and isinstance(policy_model_for_gmw, PeftModel): + ref_model_for_gmw = policy_model_for_gmw.get_base_model() + else: + # Not a PEFT model (or PEFT not available), or already a base model. + # Use the DDP-unwrapped policy model itself as the reference. + ref_model_for_gmw = policy_model_for_gmw + else: + # An explicit ref_model is provided. Unwrap it for DDP/FSDP. + ref_model_for_gmw = self.accelerator.unwrap_model(self.ref_model) + + # Both models given to GeometricMixtureWrapper (policy_model_for_gmw and ref_model_for_gmw) are DDP-unwrapped. + with torch.no_grad(): # Ensure no_grad context for mixture model generation + mixture_model = GeometricMixtureWrapper( + model=policy_model_for_gmw, + ref_model=ref_model_for_gmw, + generation_config=self.generation_config, + mixture_coef=self.mixture_coef, + device=self.accelerator.device, + ) + + # TODO: use self._override_model_generation_config for both models? + mixture_output = mixture_model.generate( + input_ids=prompts["input_ids"], + attention_mask=prompts["attention_mask"], + generation_config=self.generation_config, + ) + + return model_output, mixture_output + + def _process_completions(self, model_output, mixture_output, prompts): + context_length = prompts["input_ids"].shape[1] + + # Process model completions + model_completion_ids = model_output[:, context_length:] + model_completion_ids, model_completion_mask = truncate_right( + model_completion_ids, self.processing_class.eos_token_id, self.processing_class.pad_token_id + ) + model_data = { + "input_ids": torch.cat((prompts["input_ids"], model_completion_ids), dim=1), + "attention_mask": torch.cat((prompts["attention_mask"], model_completion_mask), dim=1), + "raw": prompts["raw"], + } + + # Process reference model completions + mixture_completion_ids = mixture_output[:, context_length:] + mixture_completion_ids, mixture_completion_mask = truncate_right( + mixture_completion_ids, self.processing_class.eos_token_id, self.processing_class.pad_token_id + ) + mixture_data = { + "input_ids": torch.cat((prompts["input_ids"], mixture_completion_ids), dim=1), + "attention_mask": torch.cat((prompts["attention_mask"], mixture_completion_mask), dim=1), + "raw": prompts["raw"], + } + + return model_data, mixture_data + + def _compute_rewards(self, model_data, mixture_data, context_length): + with torch.no_grad(): + _, model_scores, _ = get_reward( + self.reward_funcs, model_data["input_ids"], self.processing_class.pad_token_id, context_length + ) + _, mixture_scores, _ = get_reward( + self.reward_funcs, mixture_data["input_ids"], self.processing_class.pad_token_id, context_length + ) + + # Apply EOS penalty if needed + if self.args.missing_eos_penalty is not None: + model_contain_eos = torch.any(model_data["input_ids"] == self.processing_class.eos_token_id, dim=-1) + mixture_contain_eos = torch.any(mixture_data["input_ids"] == self.processing_class.eos_token_id, dim=-1) + model_scores[~model_contain_eos] -= self.args.missing_eos_penalty + mixture_scores[~mixture_contain_eos] -= self.args.missing_eos_penalty + + return model_scores, mixture_scores + + def _compute_logprobs(self, model, model_data, context_length): + def compute_logprobs_for_data(m, data): + output = m(data["input_ids"], attention_mask=data["attention_mask"]) + logits = output.logits[:, context_length - 1 : -1] + token_logprobs = selective_log_softmax(logits, data["input_ids"][:, context_length:]) + return token_logprobs + + # Compute logprobs for model completions under the model + model_logprobs_model_data = compute_logprobs_for_data(model, model_data) + + # Compute logprobs of model completions under the reference model + with torch.no_grad(): + if self.ref_model is None: + with model.disable_adapter(): + ref_logprobs_model_data = compute_logprobs_for_data(model, model_data) + else: + ref_logprobs_model_data = compute_logprobs_for_data(self.ref_model, model_data) + + # Mask padding tokens + model_padding_mask = model_data["attention_mask"][:, context_length:] == 0 + model_logprobs_model_data = model_logprobs_model_data.masked_fill(model_padding_mask, 0.0) + ref_logprobs_model_data = ref_logprobs_model_data.masked_fill(model_padding_mask, 0.0) + + return (model_logprobs_model_data, ref_logprobs_model_data) + + def _compute_losses( + self, + model_logprobs_model_data, + ref_logprobs_model_data, + probability, + ): + # reinforce score where 0.5 is a control variate + score = (probability - 0.5) * model_logprobs_model_data.sum(1) + + # kl divergence via reinforce + with torch.no_grad(): + log_ratio = model_logprobs_model_data - ref_logprobs_model_data + kl_div_log = log_ratio.sum(1) + kl_div_loss = (log_ratio * model_logprobs_model_data).sum(1) + + # final loss + loss = self.beta * kl_div_loss - score + + return loss.mean(), score, kl_div_log + + def _log_statistics( + self, + model_data, + mixture_data, + model_logprobs_model_data, + ref_logprobs_model_data, + probability, + score, + kl_div, + context_length, + model_scores, + mixture_scores, + ): + # Helper function to gather and compute mean + def gather_mean(tensor): + return self.accelerator.gather_for_metrics(tensor).mean().item() + + # Log score + self.stats["loss/score"].append(gather_mean(score)) + # Log KL divergence + self.stats["loss/kl"].append(gather_mean(kl_div)) + + # Log logprobs + model_logprobs_model_data_sum = model_logprobs_model_data.sum(1) + ref_logprobs_model_data_sum = ref_logprobs_model_data.sum(1) + + self.stats["logps/chosen"].append(gather_mean(model_logprobs_model_data_sum)) + self.stats["logps/rejected"].append(gather_mean(ref_logprobs_model_data_sum)) + + # Log rewards + self.stats["rewards/chosen"].append(gather_mean(model_scores)) + self.stats["rewards/rejected"].append(gather_mean(mixture_scores)) + + # Log probabilities + self.stats["rewards/probabilities"].append(gather_mean(probability)) + + # Calculate entropy for model data + entropy_model_data = -model_logprobs_model_data.sum(1) + self.stats["objective/entropy"].append(gather_mean(entropy_model_data)) + + # Calculate margins + margin = model_logprobs_model_data_sum - ref_logprobs_model_data_sum + self.stats["rewards/margins"].append(gather_mean(margin)) + + # Calculate accuracy + accuracy = (margin > 0).float() + self.stats["rewards/accuracies"].append(gather_mean(accuracy)) + + # Log EOS token statistics + model_eos = (model_data["input_ids"][:, context_length:] == self.processing_class.eos_token_id).any(dim=1) + mixture_eos = (mixture_data["input_ids"][:, context_length:] == self.processing_class.eos_token_id).any(dim=1) + self.stats["val/model_contain_eos_token"].append(gather_mean(model_eos.float())) + self.stats["val/ref_contain_eos_token"].append(gather_mean(mixture_eos.float())) + + # Log beta and mixture coef + self.stats["beta"].append(self.beta) + self.stats["mixture_coef"].append(self.mixture_coef) + + def training_step( + self, model: nn.Module, inputs: dict[str, torch.Tensor | Any], num_items_in_batch: int | None = None + ) -> torch.Tensor: + model.train() + + # Apply chat template and tokenize the input + batch_size = len(next(iter(inputs.values()))) + prompts = inputs["prompt"] + inputs = [{k: v[i] for k, v in inputs.items()} for i in range(batch_size)] + inputs = [maybe_apply_chat_template(x, self.processing_class) for x in inputs] + inputs = [self.tokenize_row(x, self.model.config.is_encoder_decoder, self.processing_class) for x in inputs] + inputs = self.data_collator(inputs) + + # need the prompt_ only + inputs = self._prepare_inputs(inputs) + context_length = inputs["prompt_input_ids"].shape[1] + prompts = { + "input_ids": inputs["prompt_input_ids"], + "attention_mask": inputs["prompt_attention_mask"], + "raw": prompts, + } + del inputs + + # Sample completions from both the model and the reference model + model_output, mixture_output = self._generate_completions(model, prompts) + + # Process model completions + model_data, mixture_data = self._process_completions(model_output, mixture_output, prompts) + + # Compute rewards + model_scores, mixture_scores = self._compute_rewards(model_data, mixture_data, context_length) + # probability of the model data vs the mixture data + probability = F.sigmoid(model_scores - mixture_scores) + + # Compute logprobs + model_logprobs_model_data, ref_logprobs_model_data = self._compute_logprobs(model, model_data, context_length) + + # Compute loss + loss, score, kl_div = self._compute_losses(model_logprobs_model_data, ref_logprobs_model_data, probability) + + # Log everything + self._log_statistics( + model_data, + mixture_data, + model_logprobs_model_data.detach(), + ref_logprobs_model_data, + probability, + score.detach(), + kl_div.detach(), + context_length, + model_scores, + mixture_scores, + ) + + if ( + self.args.torch_empty_cache_steps is not None + and self.state.global_step % self.args.torch_empty_cache_steps == 0 + ): + empty_cache() + + kwargs = {} + # For LOMO optimizers you need to explicitly use the learning rate + if self.args.optim in [OptimizerNames.LOMO, OptimizerNames.ADALOMO]: + kwargs["learning_rate"] = self._get_learning_rate() + + if self.args.n_gpu > 1: + loss = loss.mean() # mean() to average on multi-gpu parallel training + + self.accelerator.backward(loss, **kwargs) + + return loss.detach() / self.args.gradient_accumulation_steps diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/online_dpo/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/online_dpo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2a109cabc240f871544e5ccc56ee5616794c0ba9 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/online_dpo/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .online_dpo_config import OnlineDPOConfig +from .online_dpo_trainer import OnlineDPOTrainer + + +__all__ = ["OnlineDPOConfig", "OnlineDPOTrainer"] diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/online_dpo/online_dpo_config.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/online_dpo/online_dpo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..04213830a852c84f3234d3e8eac8204150f9417f --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/online_dpo/online_dpo_config.py @@ -0,0 +1,379 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from dataclasses import dataclass, field +from typing import Any + +from ...trainer.base_config import _BaseConfig + + +@dataclass +class OnlineDPOConfig(_BaseConfig): + # docstyle-ignore + r""" + Configuration class for the [`experimental.online_dpo.OnlineDPOTrainer`]. + + This class includes only the parameters that are specific to Online DPO 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: + reward_model_path (`str`, *optional*): + Path to the reward model. + max_new_tokens (`int`, *optional*, defaults to `64`): + Maximum number of tokens to generate per completion. + max_length (`int`, *optional*, defaults to `512`): + Maximum total length of the sequence (prompt + completion) used to compute log probabilities. If the + sequence exceeds this limit, the leftmost tokens will be truncated to preserve as much of the completion as + possible. + temperature (`float`, *optional*, defaults to `0.9`): + Temperature for sampling. The higher the temperature, the more random the completions. + missing_eos_penalty (`float`, *optional*): + Penalty applied to the score when the model fails to generate an EOS token. This is useful to encourage to + generate completions shorter than the maximum length (`max_new_tokens`). The penalty must be a positive + value. + beta (`float` or `list[float]`, *optional*, defaults to `0.1`): + Parameter controlling the deviation from the reference model. Higher β means less deviation from the + reference model. For the IPO loss (`loss_type="ipo"`), β is the regularization parameter denoted by τ in + the [paper](https://huggingface.co/papers/2310.12036). If a list of floats is provided then the β is + selected for each new epoch and the last β is used for the rest of the epochs. + loss_type (`str`, *optional*, defaults to `"sigmoid"`): + Type of loss to use. Possible values are: + + - `"sigmoid"`: sigmoid loss from the original [DPO](https://huggingface.co/papers/2305.18290) paper. + - `"ipo"`: IPO loss from the [IPO](https://huggingface.co/papers/2310.12036) paper. + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the model and reference model. + + > Parameters that control generation + + 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`, *optional*, defaults to `0`): + Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, top-k-filtering is + disabled and all tokens are considered. + min_p (`float`, *optional*): + 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. + cache_implementation (`str`, *optional*): + Implementation of the cache method for faster generation when `use_vllm` is set to `False`. + generation_kwargs (`dict[str, Any]`, *optional*): + Additional keyword arguments to pass to [`~transformers.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 `suppress_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_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. + vllm_mode (`str`, *optional*, defaults to `"colocate"`): + 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_structured_outputs_regex (`str`, *optional*): + Regex for vLLM structured outputs. If `None` (default), structured outputs is disabled. + + > Parameters that control the vLLM server (only used when `vllm_mode` is `"server"`) + + vllm_server_base_url (`str`, *optional*): + 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. + vllm_group_port (`int`, *optional*, defaults to `51216`): + Port number for the weight update group. This is used to communicate with the vLLM server. Unless the port + is occupied, there is no need to change it. + + > Parameters that control colocated vLLM execution (only used when `vllm_mode` is `"colocate"`) + + vllm_gpu_memory_utilization (`float`, *optional*, defaults to `0.55`): + 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_enable_sleep_mode (`bool`, *optional*, defaults to `False`): + Enable vLLM sleep mode to offload weights/cache during the optimizer step. Keeps GPU memory usage low, but + waking the engine adds host–device transfer latency. + + > Other parameters + + 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. + model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model from a + string. + reward_weights (`list[float]`, *optional*): + Weights for combining multiple reward functions. Must match the number of reward functions. If `None`, all + reward functions are equally weighted. + + > [!NOTE] + > These parameters have default values different from [`~transformers.TrainingArguments`]: + > - `logging_steps`: Defaults to `10` instead of `500`. + > - `gradient_checkpointing`: Defaults to `True` instead of `False`. + > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`. + > - `learning_rate`: Defaults to `5e-7` instead of `5e-5`. + > - `remove_unused_columns`: Defaults to `False` instead of `True`. + """ + + _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"] + + # Parameters whose default values are overridden from TrainingArguments + learning_rate: float = field( + default=5e-7, + metadata={"help": "The initial learning rate for AdamW."}, + ) + remove_unused_columns: bool = field( + default=False, + metadata={"help": "Whether or not to automatically remove the columns unused by the model forward method."}, + ) + + reward_model_path: str | None = field( + default=None, + metadata={"help": "Path to the reward model."}, + ) + max_new_tokens: int = field( + default=64, + metadata={"help": "Maximum number of tokens to generate per completion."}, + ) + max_length: int = field( + default=512, + metadata={ + "help": "Maximum total length of the sequence (prompt + completion) used to compute log probabilities. If " + "the sequence exceeds this limit, the leftmost tokens will be truncated to preserve as much of the " + "completion as possible." + }, + ) + temperature: float = field( + default=0.9, + metadata={"help": "Temperature for sampling. The higher the temperature, the more random the completions."}, + ) + top_p: float = field( + default=1.0, + metadata={ + "help": "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 = field( + default=0, + metadata={ + "help": "Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, " + "top-k-filtering is disabled and all tokens are considered." + }, + ) + min_p: float | None = field( + default=None, + metadata={ + "help": "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 = field( + default=1.0, + metadata={ + "help": "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." + }, + ) + generation_kwargs: dict | None = field( + default=None, + metadata={ + "help": "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 `suppress_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." + }, + ) + cache_implementation: str | None = field( + default=None, + metadata={"help": "Implementation of the cache method for faster generation when use_vllm is set to False."}, + ) + missing_eos_penalty: float | None = field( + default=None, + metadata={ + "help": "Penalty applied to the score when the model fails to generate an EOS token. This is useful to " + "encourage to generate completions shorter than the maximum length (`max_new_tokens`). The penalty must be " + "a positive value." + }, + ) + beta: list[float] = field( + default_factory=lambda: [0.1], + metadata={ + "help": "Parameter controlling the deviation from the reference model. Higher β means less deviation from " + "the reference model. For the IPO loss (`loss_type='ipo'`), β is the regularization parameter denoted by " + "τ in the [paper](https://huggingface.co/papers/2310.12036). If a list of floats is provided then the β " + "is selected for each new epoch and the last β is used for the rest of the epochs." + }, + ) + loss_type: str = field( + default="sigmoid", + metadata={ + "help": "Type of loss to use.", + "choices": ["sigmoid", "ipo"], + }, + ) + disable_dropout: bool = field( + default=True, + metadata={"help": "Whether to disable dropout in the model."}, + ) + use_vllm: bool = field( + default=False, + metadata={ + "help": "Whether to use vLLM for generating completions. Requires vLLM to be installed " + "(`pip install trl[vllm]`)." + }, + ) + vllm_model_impl: str = field( + default="vllm", + metadata={ + "help": "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." + }, + ) + vllm_structured_outputs_regex: str | None = field( + default=None, + metadata={"help": "Regex for vLLM structured outputs. If `None` (default), structured outputs is disabled."}, + ) + vllm_gpu_memory_utilization: float | None = field( + default=0.55, + metadata={ + "help": "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_mode: str = field( + default="colocate", + metadata={ + "help": "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_server_base_url: str | None = field( + default=None, + metadata={ + "help": "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 = field( + default="0.0.0.0", + metadata={"help": "Host of the vLLM server to connect to. Ignored if vllm_server_base_url is provided."}, + ) + vllm_server_port: int = field( + default=8000, + metadata={"help": "Port of the vLLM server to connect to. Ignored if vllm_server_base_url is provided."}, + ) + vllm_server_timeout: float = field( + default=240.0, + metadata={ + "help": "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.", + }, + ) + vllm_group_port: int = field( + default=51216, + metadata={ + "help": "Port number for the weight update group. This is used to communicate with the vLLM server. " + "Unless the port is occupied, there is no need to change it.", + }, + ) + vllm_tensor_parallel_size: int = field( + default=1, + metadata={ + "help": "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_enable_sleep_mode: bool = field( + default=False, + metadata={ + "help": "Enable vLLM sleep mode to offload weights/cache during the optimizer step. Keeps GPU memory " + "usage low, but waking the engine adds host–device transfer latency." + }, + ) + ds3_gather_for_generation: bool = field( + default=True, + metadata={ + "help": "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." + }, + ) + model_init_kwargs: dict[str, Any] | str | None = field( + default=None, + metadata={ + "help": "Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model " + "from a string." + }, + ) + reward_weights: list[float] | None = field( + default=None, + metadata={ + "help": "Weights for combining multiple reward functions. Must match the number of reward functions. " + "If None, all reward functions are equally weighted." + }, + ) + + def __post_init__(self): + super().__post_init__() + + if hasattr(self.beta, "__len__") and len(self.beta) == 1: + self.beta = self.beta[0] + + if self.max_new_tokens >= self.max_length: + warnings.warn( + f"The configuration has `max_new_tokens` ({self.max_new_tokens}) >= `max_length` ({self.max_length}). " + "This will cause prompts to be truncated or completely removed in the forward pass. " + "To preserve prompts, ensure e.g. `max_length > max_new_tokens + 512`. ", + stacklevel=3, + ) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/online_dpo/online_dpo_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/online_dpo/online_dpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..b54c4962e4867c4c6f552de6576f21a050fd2a8c --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/online_dpo/online_dpo_trainer.py @@ -0,0 +1,1350 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import re +import textwrap +from collections.abc import Callable +from contextlib import nullcontext +from pathlib import Path +from typing import Any + +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.utils.data +import transformers +from accelerate import logging +from accelerate.utils import broadcast_object_list, gather_object, is_peft_model +from datasets import Dataset +from packaging.version import Version +from torch.distributed.fsdp import FullyShardedDataParallel as FSDP +from torch.utils.data import IterableDataset +from transformers import ( + AutoModelForCausalLM, + AutoModelForSequenceClassification, + AutoTokenizer, + DataCollator, + GenerationConfig, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, + is_bitsandbytes_available, +) +from transformers.models.auto.modeling_auto import MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES +from transformers.trainer_utils import EvalPrediction +from transformers.training_args import OptimizerNames +from transformers.utils import is_peft_available, is_sagemaker_mp_enabled + +from ...data_utils import apply_chat_template, is_conversational, maybe_apply_chat_template +from ...extras.profiling import profiling_context +from ...generation.vllm_client import VLLMClient +from ...import_utils import is_vllm_available +from ...models.utils import prepare_deepspeed, prepare_fsdp, unwrap_model_for_generation +from ...trainer.base_trainer import _BaseTrainer +from ...trainer.utils import disable_dropout_in_model, ensure_master_addr_port, get_config_model_id +from ..utils import DPODataCollatorWithPadding, create_reference_model, empty_cache, prepare_peft_model, truncate_right +from .online_dpo_config import OnlineDPOConfig + + +if is_peft_available(): + from peft import PeftConfig + + +if is_sagemaker_mp_enabled(): + from smdistributed.modelparallel import __version__ as SMP_VERSION + + IS_SAGEMAKER_MP_POST_1_10 = Version(SMP_VERSION) >= Version("1.10") + +else: + IS_SAGEMAKER_MP_POST_1_10 = False + + +if Version(transformers.__version__) >= Version("5.2.0"): + from transformers.trainer_pt_utils import nested_gather + + +if is_vllm_available(): + from vllm import LLM, SamplingParams + from vllm.sampling_params import StructuredOutputsParams + +if is_bitsandbytes_available(): + import bitsandbytes as bnb + +logger = logging.get_logger(__name__) + +# A reward function can be a string, interpreted as a model ID and loaded as a pretrained model, a pretrained model, or +# a callable that returns a list of floats (the rewards). The callable receives prompts, completions, and additional +# arguments from the trainer (refer to the trainer's source for details). To ensure forward compatibility, it should +# accept **kwargs. +RewardFunc = str | PreTrainedModel | Callable[..., list[float | None]] + + +class OnlineDPOTrainer(_BaseTrainer): + r""" + Initialize OnlineDPOTrainer. + + Args: + model (`str | nn.Module | PreTrainedModel`): + Model to be trained. Can be either: + + - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a + path to a *directory* containing model weights saved using + [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded + using [`~transformers.AutoModelForCausalLM.from_pretrained`] with the keyword arguments in + `args.model_init_kwargs`. + - A [`~transformers.PreTrainedModel`] object. Only causal language models are supported. + ref_model ([`~transformers.PreTrainedModel`] or `torch.nn.Module` or `None`): + The reference model to use for training. If None is specified, the reference model will be created from the + model. + reward_funcs (`RewardFunc | list[RewardFunc]`): + Reward functions to be used for computing the rewards. To compute the rewards, we call all the reward + functions with the prompts and completions and sum the rewards. Can be either: + + - A single reward function: Can be a string (path to model), a [`~transformers.PreTrainedModel`], or a + custom callable function. + - A list of reward functions: Must all be of compatible types. + args ([`experimental.online_dpo.OnlineDPOConfig`]): + The online DPO config arguments to use for training. + data_collator ([`~transformers.DataCollator`]): + The data collator to use for training. If None is specified, the default data collator + ([`experimental.utils.DPODataCollatorWithPadding`]) will be used which will pad the sequences to the + maximum length of the sequences in the batch, given a dataset of paired sequences. + train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]): + The dataset to use for training. + eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Dataset | IterableDataset]`): + The dataset to use for evaluation. + processing_class ([`~transformers.PreTrainedTokenizerBase`] or [`~transformers.ProcessorMixin`], *optional*): + Processing class used to process the data. If provided, will be used to automatically process the inputs + for the model, and it will be saved along the model to make it easier to rerun an interrupted training or + reuse the fine-tuned model. + reward_processing_classes ([`~transformers.PreTrainedTokenizerBase`] or `list[PreTrainedTokenizerBase]`, *optional*): + Processing classes corresponding to the reward functions specified in `reward_funcs`. Can be either: + + - A single processing class: Used when `reward_funcs` contains only one reward function. + - A list of processing classes: Must match the order and length of the reward functions in `reward_funcs`. + + If set to `None`, the tokenizer for each model-based reward function is automatically loaded using + [`~transformers.AutoTokenizer.from_pretrained`]. + peft_config ([`~peft.PeftConfig`], *optional*): + PEFT configuration used to wrap the model. If `None`, the model is not wrapped. + compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*): + The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to + metric values. + callbacks (`list[transformers.TrainerCallback]`): + The callbacks to use for training. + optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`): + The optimizer and scheduler to use for training. + preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`): + The function to use to preprocess the logits before computing the metrics. + """ + + _tag_names = ["trl", "online-dpo"] + _name = "Online DPO" + _paper = { + "title": "Direct Language Model Alignment from Online AI Feedback", + "id": "2402.04792", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @article{guo2024direct, + title = {{Direct Language Model Alignment from Online AI Feedback}}, + author = {Shangmin Guo and Biao Zhang and Tianlin Liu and Tianqi Liu and Misha Khalman and Felipe Llinares and Alexandre Ram{\'{e}} and Thomas Mesnard and Yao Zhao and Bilal Piot and Johan Ferret and Mathieu Blondel}, + year = 2024, + eprint = {arXiv:2402.04792} + }"""), + } + + def __init__( + self, + model: PreTrainedModel | nn.Module | str, + ref_model: PreTrainedModel | nn.Module | None = None, + reward_funcs: RewardFunc | list[RewardFunc] | None = None, + args: OnlineDPOConfig | None = None, + data_collator: DataCollator | None = None, + train_dataset: Dataset | IterableDataset | None = None, + eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None, + processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None, + reward_processing_classes: PreTrainedTokenizerBase | list[PreTrainedTokenizerBase] | None = None, + peft_config: "PeftConfig | None" = None, + compute_metrics: Callable[[EvalPrediction], dict] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None, + ) -> None: + if train_dataset is None: + raise ValueError("`train_dataset` is required") + + if ref_model is model: + raise ValueError( + "`model` and `ref_model` cannot be the same object. If you want `ref_model` to be the " + "same as `model`, either omit the `ref_model` argument or pass `None`." + ) + + self.ref_model = ref_model + + if reward_funcs is None: + raise ValueError("`reward_funcs` must be provided.") + + # Handle reward_funcs + if not isinstance(reward_funcs, list): + reward_funcs = [reward_funcs] + self.reward_func_names = [] + + # Process reward functions (convert strings to models, collect names) + model_init_kwargs = args.model_init_kwargs or {} + for i, reward_func in enumerate(reward_funcs): + if isinstance(reward_func, str): + # Load model from string path + reward_funcs[i] = AutoModelForSequenceClassification.from_pretrained( + reward_func, num_labels=1, **model_init_kwargs + ) + if isinstance(reward_funcs[i], nn.Module): + self.reward_func_names.append(get_config_model_id(reward_funcs[i].config).split("/")[-1]) + else: + self.reward_func_names.append(reward_funcs[i].__name__) + self.reward_funcs = reward_funcs + + # Handle reward processing classes for reward_funcs + if reward_processing_classes is None: + reward_processing_classes = [None] * len(reward_funcs) + elif not isinstance(reward_processing_classes, list): + reward_processing_classes = [reward_processing_classes] + else: + if len(reward_processing_classes) != len(reward_funcs): + raise ValueError("The number of reward processing classes must match the number of reward functions.") + + self.reward_processing_classes = [] + for reward_processing_class_i, reward_func in zip(reward_processing_classes, reward_funcs, strict=True): + if isinstance(reward_func, PreTrainedModel): + if reward_processing_class_i is None: + reward_processing_class_i = AutoTokenizer.from_pretrained(reward_func.config._name_or_path) + if reward_processing_class_i.pad_token_id is None: + reward_processing_class_i.pad_token = reward_processing_class_i.eos_token + # Set pad token ID on reward model config + reward_func.config.pad_token_id = reward_processing_class_i.pad_token_id + self.reward_processing_classes.append(reward_processing_class_i) + + # Handle reward_weights + if args.reward_weights is not None: + if len(args.reward_weights) != len(self.reward_funcs): + raise ValueError( + f"Number of reward weights ({len(args.reward_weights)}) must match number of reward " + f"functions ({len(self.reward_funcs)})" + ) + self.reward_weights = torch.tensor(args.reward_weights, dtype=torch.float32) + else: + self.reward_weights = torch.ones(len(self.reward_funcs), dtype=torch.float32) + + if args is None: + raise ValueError("`args` must be provided.") + + # Check that the processing_class is provided + if processing_class is None: + raise ValueError("`processing_class` must be provided.") + + model_init_kwargs = args.model_init_kwargs or {} + if isinstance(model, str): + model_id = model + + # Handle dtype in model_init_kwargs + dtype = model_init_kwargs.get("dtype", "auto") + if isinstance(dtype, torch.dtype) or dtype == "auto" or dtype is None: + pass + elif isinstance(dtype, str): + dtype = getattr(torch, dtype) + model_init_kwargs["dtype"] = dtype + else: + raise ValueError( + "Invalid `dtype` passed to `OnlineDPOConfig`. Expected either 'auto' or a string " + f"representing a `torch.dtype` (e.g., 'float32'), but got {dtype}." + ) + model_init_kwargs["device_map"] = model_init_kwargs.get("device_map", "auto") + + model = AutoModelForCausalLM.from_pretrained(model_id, **model_init_kwargs) + else: + if args.model_init_kwargs is not None: + raise ValueError( + "You passed `model_init_kwargs` to the `OnlineDPOConfig`, but your model is already instantiated. " + "This argument can only be used when the `model` argument is a string." + ) + self.is_encoder_decoder = model.config.is_encoder_decoder + self.is_vision_model = model.config.model_type in MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES.keys() + + # PEFT + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + if peft_config is not None or is_peft_model(model): + model = prepare_peft_model(model, peft_config, args) + + # Enable gradient checkpointing if requested + if args.gradient_checkpointing: + model = self._enable_gradient_checkpointing(model, args) + + # Disable dropout in the model and reference model + if args.disable_dropout: + disable_dropout_in_model(model) + if self.ref_model is not None: + disable_dropout_in_model(self.ref_model) + + # Handle the ref_model + # Usually, the user wants the ref model to be the initial version of the model. When using PEFT, it's easy to + # get the ref model, as it's just the model with a disabled adapter. When not using PEFT, we need to create + # the ref model from the model by copying it and disable the gradients and set it in evaluation mode. + if ref_model is None: # No ref model provided, the most common case + if peft_config is None: + self.ref_model = create_reference_model(model) # copy, disable gradients, set eval mode + else: + self.ref_model = None # we don't need a ref model here, we can just disable the adapter. + else: # rare case, the user provided a ref model + self.ref_model = ref_model + self.ref_model.eval() + + # Disable the gradient and set the reward model in eval mode + if reward_funcs is not None: + for reward_func in reward_funcs: + if isinstance(reward_func, PreTrainedModel): + reward_func.eval() + + self.max_length = args.max_length + + self.stats = { + "objective/kl": [], + "objective/entropy": [], + "objective/non_score_reward": [], + "rewards/chosen": [], + "rewards/rejected": [], + "rewards/accuracies": [], + "rewards/margins": [], + "logps/chosen": [], + "logps/rejected": [], + "val/contain_eos_token": [], + "beta": [], + } + if self.reward_funcs is not None: + self.stats["objective/rlhf_reward"] = [] + self.stats["objective/scores_margin"] = [] + self.stats["objective/scores"] = [] + + # Store generation parameters for later use + self.use_vllm = args.use_vllm + self.num_generations = 2 # Generate 2 completions per prompt for Online DPO + self.temperature = args.temperature + self.top_p = args.top_p + self.top_k = args.top_k + self.min_p = args.min_p + self.repetition_penalty = args.repetition_penalty + self.vllm_mode = args.vllm_mode if args.use_vllm else None + self.vllm_gpu_memory_utilization = args.vllm_gpu_memory_utilization + self.vllm_tensor_parallel_size = args.vllm_tensor_parallel_size + self.vllm_model_impl = args.vllm_model_impl + + # Handle pad token for processors or tokenizers + if isinstance(processing_class, ProcessorMixin): + self._tokenizer = processing_class.tokenizer + elif isinstance(processing_class, PreTrainedTokenizerBase): + self._tokenizer = processing_class + else: + raise TypeError("The `processing_class` must be either a `PreTrainedTokenizerBase` or a `ProcessorMixin`") + + if self._tokenizer.pad_token is None: + self._tokenizer.pad_token = self._tokenizer.eos_token + + # Vision tokens for VLM support + self.image_token_id = getattr(processing_class, "image_token_id", None) + self.vision_start_token_id = getattr(processing_class, "vision_start_token_id", None) + self.vision_end_token_id = getattr(processing_class, "vision_end_token_id", None) + # Get the image token string for token collapsing + self.image_token = None + if self.image_token_id is not None: + self.image_token = self._tokenizer.decode([self.image_token_id]) + + # Define the collator if not provided + if data_collator is None: + data_collator = DPODataCollatorWithPadding(pad_token_id=self._tokenizer.pad_token_id) + + # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was + # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream + # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we + # default to the recommended non-reentrant behavior here, while preserving any user-provided value. + if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"): + args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {} + args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False) + + super().__init__( + model=model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + ) + + # Add tags for models that have been loaded with the correct transformers version + if hasattr(self.model, "add_model_tags"): + self.model.add_model_tags(self._tag_names) + + self._beta = args.beta + + # Set up generation configuration and vLLM after super().__init__ + if self.use_vllm: + if not is_vllm_available(): + raise ImportError( + "vLLM is not available and `use_vllm` is set to True. Please install vLLM with " + "`pip install trl[vllm]` to use it." + ) + + if self.vllm_mode == "server": + if self.accelerator.is_main_process: + if args.vllm_server_base_url is not None: + base_url = args.vllm_server_base_url + else: + base_url = f"http://{args.vllm_server_host}:{args.vllm_server_port}" + self.vllm_client = VLLMClient( + base_url=base_url, group_port=args.vllm_group_port, connection_timeout=args.vllm_server_timeout + ) + + # Determine device type (supports cuda, xpu, etc.) + accelerator_type = torch.accelerator.current_accelerator().type + current_device = getattr(torch, accelerator_type).current_device() + self.vllm_client.init_communicator(device=current_device) + else: + self.vllm_client = None + elif self.vllm_mode == "colocate": + # vLLM dynamically adjusts the size of the key-value cache based on available GPU memory at instantiation. + # A larger cache size improves speed, so we would expect gpu_memory_utilization=1. + # However, at this stage, the optimizer's weights are not yet loaded onto the GPU; they will be loaded + # after the first optimizer step and remain in GPU memory throughout training. So we must reserve enough + # space for them. + # Configure vLLM parameters + vllm_quantization = None + if is_bitsandbytes_available(): + for _, module in model.named_modules(): + if isinstance(module, bnb.nn.Linear4bit): + vllm_quantization = "bitsandbytes" + break + elif isinstance(module, bnb.nn.Linear8bitLt): + raise ValueError("vLLM does not support in-flight 8-bit quantization.") + vllm_kwargs = { + "model": model.name_or_path, + "tensor_parallel_size": self.vllm_tensor_parallel_size, + "gpu_memory_utilization": self.vllm_gpu_memory_utilization, + "model_impl": self.vllm_model_impl, + "max_num_seqs": self.args.per_device_train_batch_size * self.vllm_tensor_parallel_size, + "max_model_len": args.max_length + args.max_new_tokens, # max_length includes prompt + completion + "distributed_executor_backend": "external_launcher", + # Feed identical seed for tp groups to ensure sampling results are the same across workers + "seed": self.accelerator.process_index // self.vllm_tensor_parallel_size, + # Latest vLLM v1 memory profiler is misled by the high default value (i.e., 32768) + "max_num_batched_tokens": 4096, + "enable_sleep_mode": self.args.vllm_enable_sleep_mode, + "quantization": vllm_quantization, + } + + # vLLM requires the environment variables to be set for distributed training. + os.environ["RANK"] = str(self.accelerator.process_index) + os.environ["LOCAL_RANK"] = str(self.accelerator.local_process_index) + os.environ["WORLD_SIZE"] = str(self.accelerator.num_processes) + # Ensure distributed rendezvous variables are set without colliding across concurrent runs + ensure_master_addr_port() + + self.llm = LLM(**vllm_kwargs) + if self.args.vllm_enable_sleep_mode: + self.llm.sleep(level=2) + else: + raise ValueError(f"vllm_mode must be either 'server' or 'colocate', got '{self.vllm_mode}'.") + # vLLM specific sampling arguments + self.structured_outputs_regex = args.vllm_structured_outputs_regex + self._last_loaded_step = -1 # tag to avoid useless loading during grad accumulation + + # Set up vLLM generation config + generation_kwargs = { + "n": 2, # 2 generations per prompt for Online DPO + "repetition_penalty": self.repetition_penalty, + "temperature": self.temperature, + "top_p": self.top_p, + "top_k": self.top_k, + "min_p": 0.0 if self.min_p is None else self.min_p, + "max_tokens": args.max_new_tokens, + "detokenize": False, # to avoid vllm to decode (we don't need it) + } + if args.generation_kwargs is not None: + generation_kwargs.update(args.generation_kwargs) + if self.structured_outputs_regex is not None: + if generation_kwargs.get("structured_outputs") is not None: + logger.warning( + "Both `vllm_structured_outputs_regex` and `generation_kwargs['structured_outputs']` are set; " + "`vllm_structured_outputs_regex` takes precedence." + ) + generation_kwargs["structured_outputs"] = StructuredOutputsParams(regex=self.structured_outputs_regex) + elif isinstance(structured_outputs_kwargs := generation_kwargs.get("structured_outputs"), dict): + generation_kwargs["structured_outputs"] = StructuredOutputsParams(**structured_outputs_kwargs) + self.generation_config = SamplingParams(**generation_kwargs) + + # When using vLLM, the main process is responsible for loading the model weights. This can cause process + # desynchronization and seems to lead to DeepSpeed hanging during initialization. To prevent this, we + # synchronize all processes after vLLM has been fully initialized. + self.accelerator.wait_for_everyone() + else: + # Set up transformers generation config + generation_kwargs = { + "max_new_tokens": args.max_new_tokens, + "do_sample": True, + "pad_token_id": self._tokenizer.pad_token_id, + "bos_token_id": self._tokenizer.bos_token_id, + "eos_token_id": self._tokenizer.eos_token_id, + "temperature": self.temperature, + "top_k": self.top_k, + "top_p": self.top_p, + "repetition_penalty": self.repetition_penalty, + "use_cache": True if not self.args.gradient_checkpointing else False, + } + # Add min_p if supported + if self.min_p is not None: + generation_kwargs["min_p"] = self.min_p + if args.generation_kwargs is not None: + generation_kwargs.update(args.generation_kwargs) + # Remove None values + generation_kwargs = {k: v for k, v in generation_kwargs.items() if v is not None} + self.generation_config = GenerationConfig(**generation_kwargs) + # Keep training-specific generation kwargs to overwrite model's original generation config + self.generation_kwargs = generation_kwargs + + if self.ref_model is not None: + if self.is_deepspeed_enabled: + self.ref_model = prepare_deepspeed(self.ref_model, self.accelerator) + elif self.is_fsdp_enabled: + self.ref_model = prepare_fsdp(self.ref_model, self.accelerator) + else: + self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True) + if self.reward_funcs is not None: + for i, reward_func in enumerate(self.reward_funcs): + if isinstance(reward_func, PreTrainedModel): + if self.is_deepspeed_enabled: + self.reward_funcs[i] = prepare_deepspeed(reward_func, self.accelerator) + else: + # set device placement to True to make `prepare_model` move `reward_func` to device when using fsdp + self.reward_funcs[i] = self.accelerator.prepare_model( + reward_func, evaluation_mode=True, device_placement=True + ) + + @property + def beta(self): + if isinstance(self._beta, list): + epoch = self.state.epoch + return self._beta[epoch] if epoch < len(self._beta) else self._beta[-1] + else: + return self._beta + + @staticmethod + def tokenize_row(feature, is_encoder_decoder: bool, tokenizer: PreTrainedTokenizerBase) -> dict[str, Any]: + """Tokenize a single row from a DPO specific dataset.""" + if not is_encoder_decoder: + batch = tokenizer(feature["prompt"], add_special_tokens=False) + # Add BOS token to head of prompt. Avoid adding if it's already there + if tokenizer.bos_token_id is not None: + prompt_len_input_ids = len(batch["input_ids"]) + if prompt_len_input_ids == 0 or tokenizer.bos_token_id != batch["input_ids"][0]: + batch["input_ids"] = [tokenizer.bos_token_id] + batch["input_ids"] + batch["attention_mask"] = [1] + batch["attention_mask"] + else: + batch = tokenizer(feature["prompt"], add_special_tokens=True) + batch = {f"prompt_{key}": value for key, value in batch.items()} + return batch + + def _enable_gradient_checkpointing(self, model: PreTrainedModel, args: OnlineDPOConfig) -> PreTrainedModel: + """Enables gradient checkpointing for the model.""" + # Ensure use_cache is disabled + model.config.use_cache = False + + # Enable gradient checkpointing on the base model for PEFT + if is_peft_model(model): + model.base_model.gradient_checkpointing_enable() + # Enable gradient checkpointing for non-PEFT models + else: + model.gradient_checkpointing_enable() + + model.enable_input_require_grads() + return model + + def _generate_vllm(self, prompts, images=None): + eos_token_id = self._tokenizer.eos_token_id + pad_token_id = self._tokenizer.pad_token_id + + # Generate completion_ids and prompt_ids based on mode + if self.vllm_mode == "server": + completion_ids, prompt_ids = self._generate_vllm_server(prompts, images) + elif self.vllm_mode == "colocate": + completion_ids, prompt_ids = self._generate_vllm_colocate(prompts, images) + + # Shared padding, masking, and tensor conversion logic + max_prompt_length = max(len(ids) for ids in prompt_ids) + prompt_mask = [[0] * (max_prompt_length - len(ids)) + [1] * len(ids) for ids in prompt_ids] + prompt_ids = [[pad_token_id] * (max_prompt_length - len(ids)) + ids for ids in prompt_ids] + max_tokens = self.generation_config.max_tokens + completion_mask = [[1] * len(ids) + [0] * (max_tokens - len(ids)) for ids in completion_ids] + completion_ids = [ + ids + [eos_token_id] if ids[-1] != eos_token_id and len(ids) < max_tokens else ids + for ids in completion_ids + ] + completion_ids = [ids + [pad_token_id] * (max_tokens - len(ids)) for ids in completion_ids] + + # Convert to tensors + prompt_ids = torch.tensor(prompt_ids, device=self.accelerator.device) + prompt_mask = torch.tensor(prompt_mask, device=self.accelerator.device) + completion_ids = torch.tensor(completion_ids, device=self.accelerator.device) + completion_mask = torch.tensor(completion_mask, device=self.accelerator.device) + + return prompt_ids, prompt_mask, completion_ids, completion_mask + + def _generate_vllm_server(self, prompts, images=None): + """Generate completions using vLLM server mode""" + has_images = images is not None + + # Update vLLM server weights if needed + if hasattr(self, "_last_loaded_step") and self.state.global_step != self._last_loaded_step: + self._move_model_to_vllm() + self._last_loaded_step = self.state.global_step + elif not hasattr(self, "_last_loaded_step"): + self._move_model_to_vllm() + self._last_loaded_step = self.state.global_step + + # Apply chat template if conversational + if is_conversational({"prompt": prompts[0]}): + prompts_text = [apply_chat_template({"prompt": p}, self.processing_class)["prompt"] for p in prompts] + else: + prompts_text = prompts + # Gather all prompts to main process + all_prompts = gather_object(prompts_text) + if has_images: + all_images = gather_object(images) + + if self.accelerator.is_main_process: + # Since 'prompts' contains 'num_generations' duplicates, we first take unique prompts, and generate + # num_generations outputs for each one. This is faster than generating outputs for each duplicate + # prompt individually. + ordered_set_of_prompts = all_prompts[:: self.num_generations] + if has_images: + ordered_set_of_images = [ + [img] if img is not None else None for img in all_images[:: self.num_generations] + ] + else: + ordered_set_of_images = None + completion_ids = self.vllm_client.generate( + prompts=ordered_set_of_prompts, + images=ordered_set_of_images, + n=self.num_generations, + repetition_penalty=self.repetition_penalty, + temperature=self.temperature, + top_p=self.top_p, + top_k=-1 if self.top_k is None else self.top_k, + min_p=0.0 if self.min_p is None else self.min_p, + max_tokens=self.generation_config.max_tokens, + structured_outputs_regex=self.structured_outputs_regex + if hasattr(self, "structured_outputs_regex") + else None, + generation_kwargs=self.args.generation_kwargs, + )["completion_ids"] + # Flatten: each prompt generates 2 completions + completion_ids = [[comp_id] for prompt_completions in completion_ids for comp_id in prompt_completions] + else: + completion_ids = [None] * (len(all_prompts) * 2) + + # Broadcast completions to all processes + completion_ids = broadcast_object_list(completion_ids, from_process=0) + + # Each process takes its slice + process_slice = slice( + self.accelerator.process_index * len(prompts) * 2, + (self.accelerator.process_index + 1) * len(prompts) * 2, + ) + completion_ids = completion_ids[process_slice] + + # Create prompt_ids by tokenizing locally + prompt_inputs = self.processing_class( + text=prompts_text, + return_tensors="pt", + padding=True, + padding_side="left", + add_special_tokens=False, + ) + prompt_ids = [] + for prompt_tokens in prompt_inputs["input_ids"]: + prompt_ids.extend([prompt_tokens.tolist(), prompt_tokens.tolist()]) # 2 copies for 2 completions + return completion_ids, prompt_ids + + def _generate_vllm_colocate(self, prompts, images=None): + """Generate completions using vLLM colocate mode""" + if self.args.vllm_enable_sleep_mode: + # wake up colocated vLLM instances if needed + torch.cuda.empty_cache() # required to avoid OOM in some cases + self.llm.wake_up(tags=["weights"]) + + # Update model weights if needed - only after gradient accumulation completes + if self.state.global_step != self._last_loaded_step: + self._move_model_to_vllm() + self._last_loaded_step = self.state.global_step + + # Apply chat template if conversational + if is_conversational({"prompt": prompts[0]}): + prompts_text = [apply_chat_template({"prompt": p}, self.processing_class)["prompt"] for p in prompts] + else: + prompts_text = prompts + + # Prepare vLLM inputs with images if available + if images is not None: + vllm_inputs = [] + for prompt, image in zip(prompts_text, images, strict=True): + if image is not None: + vllm_inputs.append({"prompt": prompt, "multi_modal_data": {"image": image}}) + else: + vllm_inputs.append(prompt) + else: + vllm_inputs = prompts_text + + if self.args.vllm_enable_sleep_mode: + self.llm.wake_up(tags=["kv_cache"]) + + outputs = self.llm.generate(vllm_inputs, self.generation_config, use_tqdm=False) + + completion_ids = [list(output.outputs[i].token_ids) for i in range(2) for output in outputs] + prompt_ids = [list(output.prompt_token_ids) for _ in range(2) for output in outputs] + if self.args.vllm_enable_sleep_mode: + self.llm.sleep(level=2) + + return completion_ids, prompt_ids + + def _sync_fsdp2_params_to_vllm(self, module: nn.Module): + # For FSDP2, module.state_dict() already covers all parameters, so no need for recursion + for name, param in module.state_dict().items(): + # When using PEFT, we need to recover the original parameter name + name = name.removeprefix("base_model.model.").replace(".base_layer", "") + # Skip PEFT layers: they don’t exist in vLLM, and they are merged already. + if is_peft_model(module) and module.prefix in name: + continue + # When module to save, remove its prefix and discard the original module + if "original_module" in name: + continue + name = self._fix_param_name_to_vllm(name, extra_prefixes=["modules_to_save.default."]) + + if param.is_cpu: + param = param.to(torch.device("cuda")) + param = param.full_tensor() + + if self.vllm_mode == "server" and self.accelerator.is_main_process: + self.vllm_client.update_named_param(name, param) + elif self.vllm_mode == "colocate": + llm_model = self.llm.llm_engine.model_executor.driver_worker.model_runner.model + llm_model.load_weights([(name, param)]) + + def _move_model_to_vllm(self): + # For DeepSpeed ZeRO-3 and FSDP, we need to gather all parameters before operations + deepspeed_plugin = self.accelerator.state.deepspeed_plugin + zero_stage_3 = deepspeed_plugin is not None and deepspeed_plugin.zero_stage == 3 + if zero_stage_3: + import deepspeed + + gather_if_zero3 = deepspeed.zero.GatheredParameters + else: + gather_if_zero3 = nullcontext + + if is_peft_model(self.model): + # With PEFT and FSDP/DeepSpeed ZeRO Stage 3, we must gather the full model at once before merging, as + # merging adapters in a sharded manner is not supported. + # TODO: does this work with FSDP? + with gather_if_zero3(list(self.model.parameters())): + self.model.merge_adapter() + + # Update vLLM weights while parameters are gathered + if self.is_fsdp_enabled: # note if using FSDP, gather_if_zero3 is nullcontext + # Update vLLM weights while parameters are gathered + # For PEFT with FSDP we need to use the memory efficient post-order traversal + fsdp_plugin = getattr(self.accelerator.state, "fsdp_plugin", None) + fsdp_version = getattr(fsdp_plugin, "fsdp_version", 1) if fsdp_plugin else 1 + if fsdp_version == 1: + self._sync_fsdp1_params_to_vllm( + self.model + ) # use memory-efficient post-order traversal for FSDP + elif fsdp_version == 2: + self._sync_fsdp2_params_to_vllm(self.model) + else: + # DeepSpeed ZeRO-3 with PEFT + for name, param in self.model.named_parameters(): + # When using PEFT, we need to recover the original parameter name + name = name.removeprefix("base_model.model.").replace(".base_layer", "") + # Skip PEFT layers: they don’t exist in vLLM, and they are merged already. + if self.model.prefix in name: + continue + # When module to save, remove its prefix and discard the original module + if "original_module" in name: + continue + name = self._fix_param_name_to_vllm(name, extra_prefixes=["modules_to_save.default."]) + + if self.vllm_mode == "server" and self.accelerator.is_main_process: + self.vllm_client.update_named_param(name, param.data) + elif self.vllm_mode == "colocate": + llm_model = self.llm.llm_engine.model_executor.driver_worker.model_runner.model + llm_model.load_weights([(name, param.data)]) + # Unmerge adapters while parameters are still gathered + self.model.unmerge_adapter() + # Parameters will automatically be repartitioned when exiting the context + else: + # For non-PEFT models, simply gather (if needed) and update each parameter individually. + if self.is_fsdp_enabled: + fsdp_plugin = getattr(self.accelerator.state, "fsdp_plugin", None) + fsdp_version = getattr(fsdp_plugin, "fsdp_version", 1) if fsdp_plugin else 1 + if fsdp_version == 1: + self._sync_fsdp1_params_to_vllm(self.model) # use memory-efficient post-order traversal for FSDP + elif fsdp_version == 2: + self._sync_fsdp2_params_to_vllm(self.model) + else: + for name, param in self.model.named_parameters(): + name = self._fix_param_name_to_vllm(name) + with gather_if_zero3([param]): + if self.vllm_mode == "server" and self.accelerator.is_main_process: + self.vllm_client.update_named_param(name, param.data) + elif self.vllm_mode == "colocate": + llm_model = self.llm.llm_engine.model_executor.driver_worker.model_runner.model + llm_model.load_weights([(name, param.data)]) + + # Reset cache on vLLM + if self.vllm_mode == "server" and self.accelerator.is_main_process: + self.vllm_client.reset_prefix_cache() + elif self.vllm_mode == "colocate": + self.llm.reset_prefix_cache() + + def _sync_fsdp1_params_to_vllm(self, module: nn.Module, prefix: str = "", visited=None): + """Memory-efficient post-order traversal of FSDP modules to extract full parameters and sync with vLLM.""" + # For FSDP1, we need to recurse into children and also use summon_full_params + if visited is None: + visited = set() + for child_name, child_module in module.named_children(): + child_prefix = f"{prefix}.{child_name}" if prefix else child_name + self._sync_fsdp1_params_to_vllm( + child_module, prefix=child_prefix, visited=visited + ) # recurse into the child + + if isinstance(module, FSDP): + with FSDP.summon_full_params(module, recurse=False, writeback=False): + for param_name, param in module.named_parameters(): + full_name = f"{prefix}.{param_name}" if prefix else param_name + full_name = self._fix_param_name_to_vllm(full_name, extra_prefixes=["_fsdp_wrapped_module."]) + + if full_name in visited: + continue # skip FSDP subtrees already traversed + visited.add(full_name) + + if self.vllm_mode == "server" and self.accelerator.is_main_process: + self.vllm_client.update_named_param(full_name, param.data) + elif self.vllm_mode == "colocate": + llm_model = self.llm.llm_engine.model_executor.driver_worker.model_runner.model + llm_model.load_weights([(full_name, param.data)]) + + def _fix_param_name_to_vllm(self, name, extra_prefixes: list[str] | None = None): + """Clean parameter names for vLLM compatibility""" + extra_prefixes = extra_prefixes or [] + prefixes = ["_checkpoint_wrapped_module."] + extra_prefixes + for prefix in prefixes: + name = name.replace(prefix, "") + return name + + def process_vision_row( + self, features: dict[str, list | torch.Tensor], processing_class=None + ) -> dict[str, list[int]]: + """ + Process a vision row for VLM models (adapted from DPO trainer) + """ + processor = processing_class or self.processing_class + processed_features = processor(images=[features["image"]], text=features["prompt"], add_special_tokens=False) + + prompt_input_ids = processed_features["input_ids"][0] + + # Create the output dict with required fields + output = { + "prompt_input_ids": prompt_input_ids, + "prompt_attention_mask": processed_features["attention_mask"][0], + } + + # Add vision-specific fields + if "pixel_values" in processed_features: + output["pixel_values"] = processed_features["pixel_values"][0] + if "pixel_attention_mask" in processed_features: + output["pixel_attention_mask"] = processed_features["pixel_attention_mask"][0] + if "image_sizes" in processed_features: + output["image_sizes"] = processed_features["image_sizes"][0] + + return output + + def _generate(self, model, prompts, images=None): + """Generate completions using the model""" + device = next(model.parameters()).device + eos_token_id = self._tokenizer.eos_token_id + pad_token_id = self._tokenizer.pad_token_id + + # Apply chat template and tokenize the input + inputs = [{"prompt": prompt} for prompt in prompts] + + # Add images if provided (VLM support) + if images is not None: + for i, image in enumerate(images): + inputs[i]["image"] = image + + # Apply chat template to get text prompts + prompts_text = [maybe_apply_chat_template(x, self.processing_class)["prompt"] for x in inputs] + + # Handle image token collapsing/removal + # The chat template sometimes inserts a single image token into the prompt text. However, when this text is + # later tokenized, the single image token string is expanded into multiple image token IDs, depending on the + # image size. We need to handle this properly. + if self.image_token is not None and images is not None: + escaped_img_token = re.escape(self.image_token) + # Search for the image token in the chat template + if hasattr(self.processing_class, "chat_template") and self.processing_class.chat_template: + if re.search(escaped_img_token, self.processing_class.chat_template): + # Collapse repeated image tokens back into a single token + prompts_text = [ + re.sub(rf"({escaped_img_token})+", self.image_token, text) for text in prompts_text + ] + else: + # If the chat template doesn't use the image token, remove all instances + if self.vision_end_token_id is not None: + escaped_eoi_token = re.escape(self._tokenizer.decode([self.vision_end_token_id])) + prompts_text = [ + re.sub(rf"({escaped_img_token})+{escaped_eoi_token}", "", text) for text in prompts_text + ] + else: + # If vision_end_token_id is None, just remove the image tokens + prompts_text = [re.sub(rf"({escaped_img_token})+", "", text) for text in prompts_text] + + # Prepare kwargs for processing class + kwargs = {} + if images is not None: + kwargs = {"images": [[img] for img in images]} + + # Process inputs using the processing class (handles both VLM and LLM) + prompt_inputs = self.processing_class( + text=prompts_text, + return_tensors="pt", + padding=True, + padding_side="left", + add_special_tokens=False, + **kwargs, + ) + + prompt_inputs = {k: v.to(device) for k, v in prompt_inputs.items()} + # Convert vision inputs to model's dtype for proper computation + if "pixel_values" in prompt_inputs: + # Handle DataParallel wrapped models + model_dtype = getattr(model, "dtype", None) + if model_dtype is None and hasattr(model, "module"): + model_dtype = model.module.dtype + if model_dtype is not None: + prompt_inputs["pixel_values"] = prompt_inputs["pixel_values"].to(model_dtype) + + # Sample 2 completions per prompt of size `max_new_tokens` from the model + prompt_ids = prompt_inputs["input_ids"].repeat(2, 1) + prompt_mask = prompt_inputs["attention_mask"].repeat(2, 1) + + # Prepare vision inputs if available + vision_generation_kwargs = {} + if self.is_vision_model and images is not None: + if "pixel_values" in prompt_inputs: + vision_generation_kwargs["pixel_values"] = prompt_inputs["pixel_values"].repeat(2, 1, 1, 1) + if "pixel_attention_mask" in prompt_inputs: + vision_generation_kwargs["pixel_attention_mask"] = prompt_inputs["pixel_attention_mask"].repeat(2, 1) + if "image_sizes" in prompt_inputs: + vision_generation_kwargs["image_sizes"] = prompt_inputs["image_sizes"].repeat(2, 1) + if "image_grid_thw" in prompt_inputs: + vision_generation_kwargs["image_grid_thw"] = prompt_inputs["image_grid_thw"].repeat(2, 1) + + with ( + profiling_context(self, "transformers.generate"), + unwrap_model_for_generation( + model, + self.accelerator, + gather_deepspeed3_params=self.args.ds3_gather_for_generation, + generation_kwargs=self.generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762 + ) as unwrapped_model, + torch.no_grad(), + FSDP.summon_full_params(self.model_wrapped, recurse=False) if self.is_fsdp_enabled else nullcontext(), + ): + # Setup cache implementation if specified + if self.args.cache_implementation is not None: + unwrapped_model.generation_config.cache_implementation = self.args.cache_implementation + + # Standard generation + output = unwrapped_model.generate( + input_ids=prompt_ids, + attention_mask=prompt_mask, + generation_config=self.generation_config, + **vision_generation_kwargs, + ) + + completion_ids = output[:, prompt_ids.size(1) :] + completion_ids, completion_mask = truncate_right(completion_ids, eos_token_id, pad_token_id) + + return prompt_ids, prompt_mask, completion_ids, completion_mask + + def _calculate_rewards_from_functions(self, prompts, completions, completion_ids_list, **reward_kwargs): + """ + Calculate rewards using reward functions + """ + device = self.accelerator.device + rewards_per_func = torch.zeros(len(prompts), len(self.reward_funcs), device=device) + + # Add trainer state to reward kwargs for dynamic reward shaping + reward_kwargs["trainer_state"] = self.state + + for i, (reward_func, reward_processing_class) in enumerate( + zip(self.reward_funcs, self.reward_processing_classes, strict=True) + ): + if isinstance(reward_func, nn.Module): # Model-based reward function + # Handle conversational vs text input + if is_conversational({"prompt": prompts[0]}): + messages = [{"messages": p + c} for p, c in zip(prompts, completions, strict=True)] + texts = [apply_chat_template(x, reward_processing_class)["text"] for x in messages] + else: + texts = [p + c for p, c in zip(prompts, completions, strict=True)] + + # Tokenize and get reward scores + reward_inputs = reward_processing_class( + text=texts, return_tensors="pt", padding=True, padding_side="right", add_special_tokens=False + ) + reward_inputs = {k: v.to(device) for k, v in reward_inputs.items()} + + with torch.inference_mode(): + rewards_per_func[:, i] = reward_func(**reward_inputs).logits[:, 0] # Shape (B*G,) + else: + # Custom reward function + output_reward_func = reward_func( + prompts=prompts, completions=completions, completion_ids=completion_ids_list, **reward_kwargs + ) + # Convert None values to NaN + output_reward_func = [reward if reward is not None else torch.nan for reward in output_reward_func] + rewards_per_func[:, i] = torch.tensor(output_reward_func, dtype=torch.float32, device=device) + + # Weight and sum across all reward functions + if self.reward_weights is not None: + total_rewards = (rewards_per_func * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1) + else: + total_rewards = rewards_per_func.nansum(dim=1) + + return total_rewards + + def _forward(self, model, prompt_ids, prompt_mask, completion_ids, completion_mask, vision_inputs=None): + # Get the number of tokens to truncate from prompt + num_tokens_to_truncate = max(prompt_ids.size(1) + completion_ids.size(1) - self.max_length, 0) + + # Truncate left to avoid oom + prompt_ids = prompt_ids[:, num_tokens_to_truncate:] + prompt_mask = prompt_mask[:, num_tokens_to_truncate:] + + # Concat the prompt and completion + prompt_completion_ids = torch.cat((prompt_ids, completion_ids), dim=1) + prompt_completion_mask = torch.cat((prompt_mask, completion_mask), dim=1) + + # Prepare model kwargs with vision inputs if available + model_kwargs = {"attention_mask": prompt_completion_mask} + if vision_inputs is not None: + if "pixel_values" in vision_inputs: + model_kwargs["pixel_values"] = vision_inputs["pixel_values"] + if "pixel_attention_mask" in vision_inputs: + model_kwargs["pixel_attention_mask"] = vision_inputs["pixel_attention_mask"] + if "image_sizes" in vision_inputs: + model_kwargs["image_sizes"] = vision_inputs["image_sizes"] + if "image_grid_thw" in vision_inputs: + model_kwargs["image_grid_thw"] = vision_inputs["image_grid_thw"] + + # Get the logprobs of the completions from the model + output = model(prompt_completion_ids, **model_kwargs) + + # There is 1 offset, because the model predicts the next token + prompt_len = prompt_ids.size(1) + start_idx = prompt_len - 1 if prompt_len > 0 else 0 + # Only slice off the last logit when we have a prompt, otherwise we need all logits + end_idx = -1 if prompt_len > 0 else None + logits = output.logits[:, start_idx:end_idx] + + # Take the completion tokens logprob + logprobs = torch.take_along_dim(logits.log_softmax(dim=-1), completion_ids.unsqueeze(-1), dim=2).squeeze(-1) + return logprobs + + def training_step( + self, model: nn.Module, inputs: dict[str, torch.Tensor | Any], num_items_in_batch: int | None = None + ) -> torch.Tensor: + model.train() + + prompts = inputs["prompt"] + batch_size = len(prompts) + + # Handle images for VLM support + has_images = "image" in inputs + images = None + if has_images: + images = inputs["image"] + # Convert conversational prompts to include image tokens + for prompt in prompts: + if isinstance(prompt, list): + for message in prompt: + if not isinstance(message, dict): + continue + content = message.get("content") + role = message.get("role") + if isinstance(content, str): + if role == "user": + message["content"] = [{"type": "image"}, {"type": "text", "text": content}] + elif role == "system": + message["content"] = [{"type": "text", "text": content}] + + if self.args.use_vllm: + prompt_ids, prompt_mask, completion_ids, completion_mask = self._generate_vllm(prompts, images) + else: + prompt_ids, prompt_mask, completion_ids, completion_mask = self._generate(model, prompts, images) + + contain_eos_token = torch.any(completion_ids == self._tokenizer.eos_token_id, dim=-1) + + # Extract vision inputs if available for VLM support + vision_inputs = None + if has_images and self.is_vision_model and not self.args.use_vllm: + # For vision models with transformers generation, we need to prepare vision inputs + # Process the images to get vision inputs that can be passed through the forward pass + vision_inputs = {} + kwargs = {"images": [[img] for img in images]} + processed = self.processing_class( + text=[""] * len(images), # Dummy text for vision processing + return_tensors="pt", + **kwargs, + ) + # Handle DataParallel wrapped models + model_device = getattr(model, "device", None) + model_dtype = getattr(model, "dtype", None) + if model_device is None and hasattr(model, "module"): + model_device = model.module.device + model_dtype = model.module.dtype + # Move vision tensors to device and convert to model dtype + # Need to duplicate for 2 completions per prompt + if "pixel_values" in processed: + vision_inputs["pixel_values"] = ( + processed["pixel_values"].to(model_device, dtype=model_dtype).repeat(2, 1, 1, 1) + ) + if "pixel_attention_mask" in processed: + vision_inputs["pixel_attention_mask"] = processed["pixel_attention_mask"].to(model_device).repeat(2, 1) + if "image_sizes" in processed: + vision_inputs["image_sizes"] = processed["image_sizes"].to(model_device).repeat(2, 1) + if "image_grid_thw" in processed: + vision_inputs["image_grid_thw"] = processed["image_grid_thw"].to(model_device).repeat(2, 1) + + logprobs = self._forward(model, prompt_ids, prompt_mask, completion_ids, completion_mask, vision_inputs) + with torch.no_grad(): + if self.ref_model is not None: + ref_logprobs = self._forward( + self.ref_model, prompt_ids, prompt_mask, completion_ids, completion_mask, vision_inputs + ) + else: # peft case: we just need to disable the adapter + with self.model.disable_adapter(): + ref_logprobs = self._forward( + self.model, prompt_ids, prompt_mask, completion_ids, completion_mask, vision_inputs + ) + + # Decode the completions, and format them if the input is conversational + device = logprobs.device + completions = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True) + if is_conversational({"prompt": prompts[0]}): + completions = [[{"role": "assistant", "content": completion}] for completion in completions] + + # Get the reward from reward functions + # First create completion_ids_list for custom reward functions + completion_ids_list = [completion_ids[i].tolist() for i in range(completion_ids.shape[0])] + + # Extract additional fields from inputs for reward functions + reward_kwargs = {} + keys = [key for key in inputs if key not in ["prompt"]] + for key in keys: + if isinstance(inputs[key], (list, tuple)): + # Repeat input fields to match number of completions (2 per prompt) + reward_kwargs[key] = inputs[key] * 2 + else: + reward_kwargs[key] = inputs[key] + + # Calculate rewards using reward functions + rewards = self._calculate_rewards_from_functions( + prompts=2 * prompts, completions=completions, completion_ids_list=completion_ids_list, **reward_kwargs + ) + + # Apply missing EOS penalty if configured + if self.args.missing_eos_penalty is not None: + rewards[~contain_eos_token] -= self.args.missing_eos_penalty + + # Split rewards into chosen/rejected pairs + first_half, second_half = rewards.split(batch_size) + mask = first_half >= second_half + + batch_range = torch.arange(batch_size, device=device) + chosen_indices = batch_range + (~mask * batch_size) + rejected_indices = batch_range + (mask * batch_size) + + # Build tensor so that the first half is the chosen examples and the second half the rejected examples + cr_indices = torch.cat((chosen_indices, rejected_indices), dim=0) # cr = chosen and rejected + cr_logprobs = logprobs[cr_indices] + cr_ref_logprobs = ref_logprobs[cr_indices] + + # mask out the padding tokens + padding_mask = ~completion_mask.bool() + cr_padding_mask = padding_mask[cr_indices] + + cr_logprobs_sum = (cr_logprobs * ~cr_padding_mask).sum(1) + cr_ref_logprobs_sum = (cr_ref_logprobs * ~cr_padding_mask).sum(1) + + # Split the chosen and rejected examples + chosen_logprobs_sum, rejected_logprobs_sum = torch.split(cr_logprobs_sum, batch_size) + chosen_ref_logprobs_sum, rejected_ref_logprobs_sum = torch.split(cr_ref_logprobs_sum, batch_size) + pi_logratios = chosen_logprobs_sum - rejected_logprobs_sum + ref_logratios = chosen_ref_logprobs_sum - rejected_ref_logprobs_sum + + logits = pi_logratios - ref_logratios + + if self.args.loss_type == "sigmoid": + losses = -F.logsigmoid(self.beta * logits) + elif self.args.loss_type == "ipo": + losses = (logits - 1 / (2 * self.beta)) ** 2 + else: + raise NotImplementedError(f"invalid loss type {self.args.loss_type}") + + loss = losses.mean() + + # Log everything + if self.reward_funcs is not None: + # When using reward_funcs, we have rewards instead of scores + scores_margin = rewards[chosen_indices] - rewards[rejected_indices] + self.stats["objective/scores_margin"].append( + self.accelerator.gather_for_metrics(scores_margin.mean()).mean().item() + ) + self.stats["objective/scores"].append(self.accelerator.gather_for_metrics(rewards.mean()).mean().item()) + self.stats["val/contain_eos_token"].append(contain_eos_token.float().mean().item()) + self.stats["logps/chosen"].append(self.accelerator.gather_for_metrics(chosen_logprobs_sum).mean().item()) + self.stats["logps/rejected"].append(self.accelerator.gather_for_metrics(rejected_logprobs_sum).mean().item()) + + kl = logprobs - ref_logprobs + mean_kl = kl.sum(1).mean() + self.stats["objective/kl"].append(self.accelerator.gather_for_metrics(mean_kl).mean().item()) + non_score_reward = (-self.beta * kl).sum(1) + mean_non_score_reward = non_score_reward.mean() + self.stats["objective/non_score_reward"].append( + self.accelerator.gather_for_metrics(mean_non_score_reward).mean().item() + ) + if self.reward_funcs is not None: + # Calculate RLHF reward by combining rewards with non_score_reward + rlhf_reward = rewards + non_score_reward + self.stats["objective/rlhf_reward"].append(self.accelerator.gather_for_metrics(rlhf_reward).mean().item()) + + mean_entropy = -logprobs.sum(1).mean() + self.stats["objective/entropy"].append(self.accelerator.gather_for_metrics(mean_entropy).mean().item()) + chosen_rewards = self.beta * (chosen_logprobs_sum - chosen_ref_logprobs_sum) + gathered_chosen_rewards = self.accelerator.gather_for_metrics(chosen_rewards) + self.stats["rewards/chosen"].append(gathered_chosen_rewards.mean().item()) + rejected_rewards = self.beta * (rejected_logprobs_sum - rejected_ref_logprobs_sum) + gathered_rejected_rewards = self.accelerator.gather_for_metrics(rejected_rewards) + self.stats["rewards/rejected"].append(gathered_rejected_rewards.mean().item()) + margin = gathered_chosen_rewards - gathered_rejected_rewards + self.stats["rewards/margins"].append(margin.mean().item()) + accuracy = margin > 0 + self.stats["rewards/accuracies"].append(accuracy.float().mean().item()) + self.stats["beta"].append(self.beta) + + if ( + self.args.torch_empty_cache_steps is not None + and self.state.global_step % self.args.torch_empty_cache_steps == 0 + ): + empty_cache() + + kwargs = {} + + # For LOMO optimizers you need to explicitly use the learning rate + if self.args.optim in [OptimizerNames.LOMO, OptimizerNames.ADALOMO]: + kwargs["learning_rate"] = self._get_learning_rate() + + if self.args.n_gpu > 1: + loss = loss.mean() # mean() to average on multi-gpu parallel training + + self.accelerator.backward(loss, **kwargs) + + return loss.detach() / self.args.gradient_accumulation_steps + + # Same as Trainer._maybe_log_save_evaluate but log our metrics + def _maybe_log_save_evaluate( + self, tr_loss, grad_norm, model, trial, epoch, ignore_keys_for_eval, start_time, learning_rate=None + ): + if self.control.should_log and self.state.global_step > self._globalstep_last_logged: + logs: dict[str, float] = {} + + # all_gather + mean() to get average loss over all processes + if Version(transformers.__version__) >= Version("5.2.0"): + tr_loss_scalar = nested_gather(tr_loss, self.args.parallel_mode).mean().item() + else: + tr_loss_scalar = self._nested_gather(tr_loss).mean().item() + + # reset tr_loss to zero + tr_loss -= tr_loss + + logs["loss"] = round(tr_loss_scalar / (self.state.global_step - self._globalstep_last_logged), 4) + if grad_norm is not None: + logs["grad_norm"] = grad_norm.detach().item() if isinstance(grad_norm, torch.Tensor) else grad_norm + if learning_rate is not None: + logs["learning_rate"] = learning_rate + else: + logs["learning_rate"] = self._get_learning_rate() + + # Add our metrics + for key, val in self.stats.items(): + logs[key] = sum(val) / len(val) + self.stats = {key: [] for key in self.stats} # reset stats + + self._total_loss_scalar += tr_loss_scalar + self._globalstep_last_logged = self.state.global_step + self.store_flos() + self.log(logs, start_time) + + metrics = None + if self.control.should_evaluate: + metrics = self._evaluate(trial, ignore_keys_for_eval) + is_new_best_metric = self._determine_best_metric(metrics=metrics, trial=trial) + + if self.args.save_strategy == "best": + self.control.should_save = is_new_best_metric + + if self.control.should_save: + self._save_checkpoint(model, trial) + self.control = self.callback_handler.on_save(self.args, self.state, self.control) + + # Ensure the model card is saved along with the checkpoint + def _save_checkpoint(self, model, trial): + if self.args.hub_model_id is None: + model_name = Path(self.args.output_dir).name + else: + model_name = self.args.hub_model_id.split("/")[-1] + self.create_model_card(model_name=model_name) + super()._save_checkpoint(model, trial) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/openenv/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/openenv/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4325e17f284102bd02848b432cd9d9ffedd32f58 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/openenv/__init__.py @@ -0,0 +1,18 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .utils import generate_rollout_completions + + +__all__ = ["generate_rollout_completions"] diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/openenv/utils.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/openenv/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f8f4d573854a4fa9cf93fb8f7a354d54c7fad0c9 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/openenv/utils.py @@ -0,0 +1,214 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Any + +import torch + +from ...data_utils import is_conversational +from ...extras.profiling import profiling_context +from ...import_utils import is_vllm_available + + +if is_vllm_available(): + from vllm import SamplingParams + from vllm.sampling_params import StructuredOutputsParams + + +def _build_base_generation_kwargs( + trainer, + overrides: dict[str, Any] | None = None, +) -> dict[str, Any]: + """Build base generation kwargs common to both colocate and server modes.""" + generation_kwargs: dict[str, Any] = { + "n": 1, + "temperature": trainer.temperature, + "top_k": trainer.top_k, + "min_p": 0.0 if trainer.min_p is None else trainer.min_p, + "max_tokens": trainer.max_completion_length, + } + if trainer.repetition_penalty is not None: + generation_kwargs["repetition_penalty"] = trainer.repetition_penalty + if trainer.top_p is not None: + generation_kwargs["top_p"] = trainer.top_p + + if trainer.args.generation_kwargs is not None: + generation_kwargs.update(trainer.args.generation_kwargs) + + if overrides is not None: + generation_kwargs.update(overrides) + + generation_kwargs = {key: value for key, value in generation_kwargs.items() if value is not None} + + if generation_kwargs.get("n", 1) != 1: + raise ValueError("generate_rollout_completions expects n=1.") + + return generation_kwargs + + +def _build_colocate_sampling_params( + trainer, + overrides: dict[str, Any] | None = None, + *, + logprobs: bool = True, +) -> "SamplingParams": + """Build SamplingParams for colocate mode.""" + generation_kwargs = _build_base_generation_kwargs(trainer, overrides) + + # Add colocate-specific parameters + if trainer.vllm_generation.structured_outputs_regex: + generation_kwargs["structured_outputs"] = StructuredOutputsParams( + regex=trainer.vllm_generation.structured_outputs_regex + ) + if logprobs: + generation_kwargs["logprobs"] = 0 + + return SamplingParams(**generation_kwargs) + + +def _build_server_generation_kwargs( + trainer, + overrides: dict[str, Any] | None = None, +) -> dict[str, Any]: + """Build generation kwargs for server mode.""" + return _build_base_generation_kwargs(trainer, overrides) + + +def generate_rollout_completions( + trainer, + prompts: list[str], + *, + generation_overrides: dict[str, Any] | None = None, + as_chat: bool | None = None, +) -> list[dict[str, Any]]: + """ + Generate completions for custom rollouts when vLLM is running in colocate or server mode. + + Returns one result per prompt, containing prompt and completion token ids along with per-token log probabilities + and the generated text. + """ + + if not prompts: + return [] + + if not trainer.use_vllm: + raise RuntimeError("Custom rollouts require vLLM to call generate_rollout_completions.") + + if trainer.vllm_mode == "server": + return _generate_rollout_completions_server(trainer, prompts, generation_overrides, as_chat) + elif trainer.vllm_mode == "colocate": + return _generate_rollout_completions_colocate(trainer, prompts, generation_overrides, as_chat) + else: + raise ValueError(f"vllm_mode must be 'server' or 'colocate', got '{trainer.vllm_mode}'") + + +def _generate_rollout_completions_server( + trainer, + prompts: list[str], + generation_overrides: dict[str, Any] | None = None, + as_chat: bool | None = None, +) -> list[dict[str, Any]]: + """Generate completions using vLLM server mode.""" + generation_kwargs = _build_server_generation_kwargs(trainer, generation_overrides) + + if as_chat is None: + as_chat = prompts and is_conversational({"prompt": prompts[0]}) + + with profiling_context(trainer, "vLLM.generate_rollout_server"): + if as_chat: + # Prompts are raw message dicts; use .chat() so the vLLM server applies the chat template + output = trainer.vllm_generation.vllm_client.chat( + messages=prompts, + **generation_kwargs, + chat_template_kwargs=trainer.chat_template_kwargs, + tools=trainer.tools or None, + chat_template=trainer.chat_template, + ) + else: + output = trainer.vllm_generation.vllm_client.generate(prompts=prompts, **generation_kwargs) + + # Format results to match colocate output format + results: list[dict[str, Any]] = [] + for i in range(len(prompts)): + results.append( + { + "prompt_ids": output["prompt_ids"][i], + "completion_ids": list(output["completion_ids"][i]), + "logprobs": list(output["logprobs"][i]), + "text": trainer.processing_class.decode(output["completion_ids"][i], skip_special_tokens=True), + } + ) + + return results + + +def _generate_rollout_completions_colocate( + trainer, + prompts: list[str], + generation_overrides: dict[str, Any] | None = None, + as_chat: bool | None = None, +) -> list[dict[str, Any]]: + """Generate completions using vLLM colocate mode.""" + sampling_params = _build_colocate_sampling_params(trainer, generation_overrides) + prompts_for_generation = prompts + original_size = len(prompts) + + if trainer.vllm_tensor_parallel_size > 1: + gathered_prompts = [None for _ in range(trainer.vllm_tensor_parallel_size)] + torch.distributed.all_gather_object(gathered_prompts, prompts, group=trainer.vllm_generation.tp_group) + prompts_for_generation = [prompt for group_prompts in gathered_prompts for prompt in group_prompts] + + if as_chat is None: + as_chat = prompts_for_generation and is_conversational({"prompt": prompts_for_generation[0]}) + + if trainer.args.vllm_enable_sleep_mode: + trainer.vllm_generation.llm.wake_up(tags=["kv_cache"]) + # Work around for https://github.com/vllm-project/vllm/issues/29341 + trainer.vllm_generation.llm.collective_rpc("reload_weights") + + with profiling_context(trainer, "vLLM.generate_rollout"): + if as_chat: + vllm_outputs = trainer.vllm_generation.llm.chat( + prompts_for_generation, sampling_params=sampling_params, use_tqdm=False + ) + else: + vllm_outputs = trainer.vllm_generation.llm.generate( + prompts_for_generation, sampling_params=sampling_params, use_tqdm=False + ) + + results: list[dict[str, Any]] = [] + for request in vllm_outputs: + if not request.outputs: + results.append({"prompt_ids": request.prompt_token_ids, "completion_ids": [], "logprobs": [], "text": ""}) + continue + sequence = request.outputs[0] + logprobs = [next(iter(token_logprob.values())).logprob for token_logprob in sequence.logprobs] + results.append( + { + "prompt_ids": request.prompt_token_ids, + "completion_ids": sequence.token_ids, + "logprobs": logprobs, + "text": sequence.text, + } + ) + + if trainer.vllm_tensor_parallel_size > 1: + local_rank_in_group = torch.distributed.get_rank(group=trainer.vllm_generation.tp_group) + tp_slice = slice(local_rank_in_group * original_size, (local_rank_in_group + 1) * original_size) + results = results[tp_slice] + + if trainer.args.vllm_enable_sleep_mode: + trainer.vllm_generation.llm.sleep(level=2) + + return results diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/openreward/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/openreward/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..eae7806a5a213157f814cead9b2d76158ea07bb4 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/openreward/__init__.py @@ -0,0 +1,18 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from ._spec import OpenRewardSpec + + +__all__ = ["OpenRewardSpec"] diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/openreward/_spec.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/openreward/_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..76dd6b0d91e9f29dd428f57983df17c430acb3cf --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/openreward/_spec.py @@ -0,0 +1,359 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""User-facing spec object for the OpenReward × TRL integration. + +The user constructs **one** ``OpenRewardSpec`` (a thin specification holding the env target + a few options) and reads +three properties off of it — ``.train_dataset``, ``.environment_factory``, ``.reward_funcs`` — each of which plugs +directly into the matching ``GRPOTrainer`` kwarg: + +```python +from trl import GRPOConfig, GRPOTrainer +from trl.experimental.openreward import OpenRewardSpec + +spec = OpenRewardSpec("Eigent/SETA", num_tasks=64) + +trainer = GRPOTrainer( + model="Qwen/Qwen3-4B", + args=GRPOConfig(num_generations=2, max_steps=5, max_tool_calling_iterations=20), + train_dataset=spec.train_dataset, + environment_factory=spec.environment_factory, + reward_funcs=spec.reward_funcs, +) +trainer.train() +``` + +Backed by the official ``openreward`` SDK (lazy-imported); install with ``pip install trl[openreward]``. +""" + +from __future__ import annotations + +import logging +import os +from collections.abc import Callable +from functools import cached_property +from typing import Any + +from .environment import _import_openreward, _RolloutEnvironment, _spec_to_dict + + +logger = logging.getLogger(__name__) + + +def _tool_specs_from_session_list_tools(out: Any) -> list[Any]: + """Normalise ``session.list_tools()`` / ``environment.list_tools()`` to a flat list. + + The client SDK (``openreward.api``) returns ``list[ToolSpec]`` directly. + """ + return list(out) + + +def _to_spec(task) -> dict[str, Any]: + """Normalise an SDK ``Task`` (or already-a-dict) to its task_spec dict.""" + if isinstance(task, dict): + return task + return task.task_spec + + +def _outcome_only_reward_func(environments, **_): + """Default reward function: last non-null reward in each rollout's trajectory. + + Suitable for sparse-outcome envs (e.g. SETA, where only `submit_solution` returns a non-null reward). Override by + passing a different callable to ``reward_funcs=``. + """ + return [env.reward for env in environments] + + +class OpenRewardSpec: + """Single spec object that wires an ORS environment into a TRL trainer. + + Args: + target (`str`): + Either an openreward.ai catalog name (`"Eigent/SETA"`) or a URL pointing at any ORS server + (`"https://you-seta.hf.space"`, `"http://localhost:8080"`). Auto-detected by the presence of `://` in the + string. + num_tasks (`int`, *optional*): + Cap on the number of tasks pulled into the dataset. ``None`` uses every task the env exposes. + split (`str`, *optional*, defaults to `"train"`): + Which split's task list to draw from. + indices (`list[int]`, *optional*): + Specific task indices to train on. Mutually exclusive with ``num_tasks``. Useful for debugging or + curriculum subsets. + api_key (`str`, *optional*): + ``OPENREWARD_API_KEY`` override. Only used when ``target`` is a catalog name. + secrets (`dict[str, str]`, *optional*): + Per-session secrets forwarded to ``env.session(secrets=)``. + env_name (`str`, *optional*): + Override for the env name to look up on the server. Rarely needed. + include_metadata (`bool`, *optional*, defaults to `True`): + Fold per-task metadata (`difficulty`, `category`, `tags`, ...) into the dataset rows so reward funcs can + read them via TRL's ``inputs`` argument. + discover_task_tools (`bool`, *optional*, defaults to `True`): + If ``True``, opens a short-lived ORS session and uses ``session.list_tools()`` so task-specific tools + (``GET …/task_tools`` per ORS — e.g. ``@tool(shared=False)`` and ``list_task_tools()``) are bound for GRPO. + If probe fails, falls back to ``environment.list_tools()`` only. Set ``False`` to skip the extra session + (shared tools only / offline quirks). + task_tools_discovery_index (`int`, *optional*): + Task index used only for the discovery session when set; **overrides** multi-index probing below. When + omitted and ``indices=`` is set, discovery opens one probe session per **distinct** entry in ``indices`` + (sorted) and **merges** tool specs by name so task-specific tools from every listed task are bound. When + omitted and ``num_tasks`` / full-list mode is used, probes task ``0`` only. Ignored when + ``discover_task_tools=False``. + """ + + def __init__( + self, + target: str, + *, + num_tasks: int | None = None, + split: str = "train", + indices: list[int] | None = None, + api_key: str | None = None, + secrets: dict[str, str] | None = None, + env_name: str | None = None, + include_metadata: bool = True, + discover_task_tools: bool = True, + task_tools_discovery_index: int | None = None, + ) -> None: + if num_tasks is not None and indices is not None: + raise ValueError("Provide num_tasks or indices, not both.") + + self._target = target + self._is_url = "://" in target + self._num_tasks = num_tasks + self._split = split + self._indices = indices + self._api_key = api_key + self._secrets = secrets + self._env_name = env_name + self._include_metadata = include_metadata + self._discover_task_tools = discover_task_tools + self._task_tools_discovery_index = task_tools_discovery_index + + # ── public surface ────────────────────────────────────────────── + + @cached_property + def train_dataset(self): + """A `datasets.Dataset` derived from the env's task list. + + Plugs directly into TRL's ``train_dataset=`` slot. Built lazily on first access. Has at minimum: + - `prompt`: empty user message (TRL appends the env's prompt). + - `task_index`: int passed to the adapter's `reset()`. + - per-task metadata columns (when `include_metadata=True`). + """ + from datasets import Dataset + + env = self._sdk_env + + # When the user asked for a specific subset (`num_tasks` cap or + # explicit `indices`), fetch only those — `list_tasks` returns + # the whole split (1376 entries for SETA, etc.) and is slow on + # the platform. Per-index `get_task` is fast and cheap. + if self._indices is not None: + indexes = list(self._indices) + task_specs = [_to_spec(env.get_task(self._split, i)) for i in indexes] + elif self._num_tasks is not None: + n_total = env.num_tasks(self._split) + n = min(self._num_tasks, n_total) + indexes = list(range(n)) + task_specs = [_to_spec(env.get_task(self._split, i)) for i in indexes] + else: + # No cap — fetch everything in one shot. + try: + tasks = env.list_tasks(self._split) + except Exception: # noqa: BLE001 + n = env.num_tasks(self._split) + tasks = [env.get_task(self._split, i) for i in range(n)] + task_specs = [_to_spec(t) for t in tasks] + indexes = list(range(len(task_specs))) + + rows: dict[str, list[Any]] = { + "prompt": [[{"role": "user", "content": ""}] for _ in indexes], + "task_index": indexes, + } + + if self._include_metadata and task_specs: + metadata_keys: set[str] = set() + for spec in task_specs: + if isinstance(spec, dict): + metadata_keys.update(spec.keys()) + # Never let a task-spec key overwrite our reserved row columns + # (e.g. an env that exposes a `prompt` task-spec field would + # otherwise replace our chat-format prompt with a raw string). + metadata_keys -= rows.keys() + for key in sorted(metadata_keys): + rows[key] = [s.get(key) if isinstance(s, dict) else None for s in task_specs] + + return Dataset.from_dict(rows) + + @cached_property + def environment_factory(self) -> Callable[[], _RolloutEnvironment]: + """Zero-arg callable that returns a fresh ``_RolloutEnvironment``. + + Plugs directly into TRL's ``environment_factory=`` slot. TRL calls this once per rollout at trainer + construction time, so each rollout has an isolated ORS session. Reuses the spec's already-discovered SDK env + + tool specs to skip per-env HTTP at trainer init. + """ + # Pre-fetch tool specs once at the spec level. ORS exposes shared tools on GET /tools and the full + # shared+task-specific set on GET /task_tools (session-scoped). GRPO inspects methods before reset(), so we + # must bind every tool the episode will see — use session.list_tools() when discover_task_tools=True. + env = self._sdk_env + tool_specs = self._discovered_tool_specs(env) + client = self._sdk_client + + # Each spec gets its own `_RolloutEnvironment` subclass so two specs + # for different envs (different tool sets) never clobber each other's + # bound methods on the shared parent class. + rollout_cls = type(f"_RolloutEnvironment_{id(self):x}", (_RolloutEnvironment,), {}) + + kwargs = { + "split": self._split, + "secrets": self._effective_secrets(), + "env_name": self._env_name, + "_client": client, + "_env": env, + "_tool_specs": tool_specs, + } + if self._is_url: + kwargs["base_url"] = self._target + else: + kwargs["name"] = self._target + if self._api_key: + kwargs["api_key"] = self._api_key + + kwargs = {k: v for k, v in kwargs.items() if v is not None} + + def _make() -> _RolloutEnvironment: + return rollout_cls(**kwargs) + + return _make + + @property + def reward_funcs(self) -> Callable[..., list[float]]: + """Default outcome-only reward function (last non-null reward per rollout). + + Plugs directly into TRL's ``reward_funcs=`` slot. Stable identity — module-level function, picklable for + multi-process workers. + """ + return _outcome_only_reward_func + + # ── internals ─────────────────────────────────────────────────── + + def _effective_secrets(self) -> dict[str, str] | None: + """Auto-forward ``OPENREWARD_API_KEY`` as the conventional ``api_key`` + per-session secret on platform mode (most envs need it).""" + if self._secrets is not None or self._is_url: + return self._secrets + key = self._api_key or os.environ.get("OPENREWARD_API_KEY") + return {"api_key": key} if key else None + + def _task_tools_probe_indices(self) -> list[int]: + """Pick task indices for ``session.list_tools()`` discovery (ORS ``/task_tools``).""" + if self._task_tools_discovery_index is not None: + return [self._task_tools_discovery_index] + if self._indices is not None: + return sorted(set(self._indices)) + return [0] + + def _discovered_tool_specs(self, env): + """Return ToolSpec list for binding on `_RolloutEnvironment`. + + Prefer ``session.list_tools()`` (ORS ``/task_tools``) so task-specific tools match what the OpenReward SDK + exposes during rollouts. Fall back to ``environment.list_tools()`` on failure or when disabled. + """ + shared = env.list_tools() + shared = _tool_specs_from_session_list_tools(shared) + if not self._discover_task_tools: + return shared + + try: + n = env.num_tasks(self._split) + except Exception as e: # noqa: BLE001 + logger.warning("OpenRewardSpec: num_tasks failed (%s); using shared tools only.", e) + return shared + + if n <= 0: + return shared + + probe_indices = self._task_tools_probe_indices() + bad = [idx for idx in probe_indices if idx < 0 or idx >= n] + if bad: + logger.warning( + "OpenRewardSpec: task tool probe index(es) %s out of range for split=%r (num_tasks=%s); ignoring them.", + bad, + self._split, + n, + ) + probe_indices = [idx for idx in probe_indices if 0 <= idx < n] + if not probe_indices: + logger.warning("OpenRewardSpec: no valid task indices for tool discovery; using shared tools only.") + return shared + + secrets = self._effective_secrets() + merged: list[Any] = [] + seen: dict[str, Any] = {} + any_probe_ok = False + + for idx in probe_indices: + try: + with env.session(split=self._split, index=idx, secrets=secrets) as sess: + specs = _tool_specs_from_session_list_tools(sess.list_tools()) + except Exception as e: # noqa: BLE001 + logger.warning( + "OpenRewardSpec: session tool discovery failed for task_index=%s (%s); skipping.", + idx, + e, + ) + continue + any_probe_ok = True + for spec in specs: + d = _spec_to_dict(spec) + name = d["name"] + if name not in seen: + seen[name] = spec + merged.append(spec) + elif _spec_to_dict(seen[name]) != d: + logger.warning( + "OpenRewardSpec: tool %r has differing schemas across probe tasks; keeping first.", + name, + ) + + if not any_probe_ok: + logger.warning("OpenRewardSpec: all task tool probes failed; using shared tools only.") + return shared + return merged + + @cached_property + def _sdk_client(self): + """The shared ``openreward.OpenReward`` client used by `dataset` and `factory`.""" + openreward = _import_openreward() + kwargs: dict[str, Any] = {} + if self._api_key: + kwargs["api_key"] = self._api_key + elif not self._is_url and "OPENREWARD_API_KEY" in os.environ: + kwargs["api_key"] = os.environ["OPENREWARD_API_KEY"] + if self._is_url: + kwargs["base_url"] = self._target + return openreward.OpenReward(**kwargs) + + @cached_property + def _sdk_env(self): + """The shared SDK ``Environment`` handle.""" + if self._is_url: + # Self-hosted single-env URL — pass any name; the SDK redirects. + # Fallback to "env" matches `_RolloutEnvironment.__init__`. + target = self._env_name or "env" + else: + target = self._target + return self._sdk_client.environments.get(target) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/openreward/environment.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/openreward/environment.py new file mode 100644 index 0000000000000000000000000000000000000000..7b969ee1c2c0b2a9ebacd6bb62f00d0ebff74fff --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/openreward/environment.py @@ -0,0 +1,404 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""TRL `environment_factory` adapter for any ORS-compliant server. + +Wraps the official ``openreward`` SDK so platform quirks (X-Secrets encoding, ephemeral session for discovery, +sticky-routing subdomain, SSE chunk reassembly, ping keepalive, …) are handled by code that ships with the spec. Our +job is only to expose the SDK's per-rollout session as a TRL-compatible class with dynamically-bound tool methods. + +Install: ``pip install trl[openreward]``. +""" + +from __future__ import annotations + +import logging +import os +import re +from typing import Any + + +logger = logging.getLogger(__name__) + + +def _import_openreward(): + """Lazy-import the openreward package with a friendly error message.""" + try: + import openreward + + return openreward + except ImportError as e: + raise ImportError( + "trl.experimental.openreward requires the `openreward` package. " + "Install with `pip install trl[openreward]`." + ) from e + + +# ── JSON Schema → Python type mapping (used by dynamic tool binding) ── + +_JSON_TYPE_TO_PY: dict[str, str] = { + "string": "str", + "integer": "int", + "number": "float", + "boolean": "bool", + "array": "list", + "object": "dict", +} + +_PY_TYPE_OBJECTS: dict[str, type] = { + "str": str, + "int": int, + "float": float, + "bool": bool, + "list": list, + "dict": dict, +} + +_PY_TYPE_FROM_VALUE: dict[type, str] = { + bool: "bool", + int: "int", + float: "float", + str: "str", + list: "list", + dict: "dict", +} + + +def _resolve_param_type(pdef: dict[str, Any]) -> str: + """Pick the best Python type name for one JSON-Schema property. + + Handles primitive ``"type"``, Pydantic's ``anyOf``/``oneOf`` form for ``Optional[T]``, and falls back to the type + of ``default``. Critical because transformers' tool-schema generator uses our Python annotations to build the + schema the model sees. + """ + t = pdef.get("type") + if isinstance(t, str) and t in _JSON_TYPE_TO_PY: + return _JSON_TYPE_TO_PY[t] + for key in ("anyOf", "oneOf"): + for opt in pdef.get(key) or []: + if isinstance(opt, dict): + inner = opt.get("type") + if isinstance(inner, str) and inner in _JSON_TYPE_TO_PY and inner != "null": + return _JSON_TYPE_TO_PY[inner] + if "default" in pdef and pdef["default"] is not None: + for value_type, name in _PY_TYPE_FROM_VALUE.items(): + if isinstance(pdef["default"], value_type): + return name + return "str" + + +# ──────────────────────────────────────────────────────────────────── + + +class _RolloutEnvironment: + """Per-rollout TRL adapter backed by the ``openreward`` SDK. + + **Internal class.** Users don't construct this directly; they create an :class:`OpenRewardSpec` and pass + ``spec.environment_factory`` to ``GRPOTrainer``. TRL's trainer then constructs one instance of this per rollout + slot. + + The tool surface is built once at construction by reading the env's tools and binding one Python method per ORS + tool — so swapping the URL or env name is the only thing needed to train against a different environment. + + Args: + name (`str`, *optional*): + openreward.ai catalog name (e.g. ``"Eigent/SETA"``). Mutually exclusive with `base_url`. Requires + ``OPENREWARD_API_KEY`` (env var or `api_key=`). + base_url (`str`, *optional*): + Direct URL of an ORS server (HF Space, local Docker, etc.). Mutually exclusive with `name`. + env_name (`str`, *optional*): + Name to look up on the server. Defaults to the canonical name parsed from `name`/`base_url`. + split (`str`, *optional*, defaults to `"train"`): + Split passed to ``env.session(split=, index=)``. + api_key (`str`, *optional*): + Override for ``OPENREWARD_API_KEY``. Only used with `name=`. + secrets (`dict[str, str]`, *optional*): + Per-session secrets. Forwarded to ``env.session(secrets=)``; the SDK encodes them and adds platform-domain + entries. + timeout (`float`, *optional*): + Reserved for future use. The SDK manages its own timeouts. + + Attributes: + reward (`float`): + Last non-null reward in the trajectory (outcome-only convention). + rewards (`list[float | None]`): + Per-step reward sequence in tool-call order. + metadata (`list[dict | None]`): + Per-step ``ToolOutput.metadata`` dicts. + finished (`bool`): + True after a tool returned ``finished: true``. + last_output (`str`): + Joined text of the most recent tool result. + """ + + def __init__( + self, + *, + name: str | None = None, + base_url: str | None = None, + env_name: str | None = None, + split: str = "train", + api_key: str | None = None, + secrets: dict[str, str] | None = None, + timeout: float | None = None, + _client: Any = None, + _env: Any = None, + _tool_specs: list[Any] | None = None, + ) -> None: + if (name is None) == (base_url is None): + raise ValueError("Provide exactly one of: name, base_url.") + + # Reuse a pre-built client/env when the spec has already discovered + # them (saves N HTTP calls at trainer init); otherwise build fresh. + if _client is None: + openreward = _import_openreward() + client_kwargs: dict[str, Any] = {} + if api_key: + client_kwargs["api_key"] = api_key + elif name and "OPENREWARD_API_KEY" in os.environ: + client_kwargs["api_key"] = os.environ["OPENREWARD_API_KEY"] + if base_url: + client_kwargs["base_url"] = base_url + self._client = openreward.OpenReward(**client_kwargs) + else: + self._client = _client + + if _env is None: + target = name if name is not None else env_name or "" + if base_url and not target: + # Self-hosted single-env URL — pass any name; SDK redirects. + target = "env" + self._env = self._client.environments.get(target) + else: + self._env = _env + + self._split = split + self._secrets = secrets + self._session_cm = None # the SDK context manager itself, retained for clean teardown + self._session = None # the entered Session object + + # Episode state — read by the trainer's reward_func. + self.reward: float = 0.0 + self.rewards: list[float | None] = [] + self.metadata: list[dict[str, Any] | None] = [] + self.finished: bool = False + self.last_output: str = "" + + # Bind one Python method per server-side tool. Pre-fetched specs + # come from the spec object; otherwise we ask the SDK ourselves. + specs = _tool_specs if _tool_specs is not None else self._env.list_tools() + for spec in specs: + _bind_tool_method(self.__class__, _spec_to_dict(spec)) + + # ── TRL contract ───────────────────────────────────────────────── + + def reset( + self, + *, + task_index: int = 0, + task_spec: dict[str, Any] | None = None, + **_: Any, + ) -> str: + """Open a fresh ORS session for this rollout. + + Closes any prior session, starts a new one via the SDK's ``env.session(...)`` context manager, fetches the + prompt, and returns its text (which TRL appends to the user message). + """ + self._teardown_session() + self.reward = 0.0 + self.rewards = [] + self.metadata = [] + self.finished = False + self.last_output = "" + + if task_spec is not None: + from openreward.api.environments.client import Task + + task = Task( + server_name=self._env.server, + environment_name=self._env.name, + task_spec=task_spec, + namespace=self._env.namespace, + ) + cm = self._env.session(task=task, secrets=self._secrets) + else: + cm = self._env.session(split=self._split, index=int(task_index), secrets=self._secrets) + + # Retain the context manager itself so `_teardown_session` can call + # its __exit__; calling __exit__ on the entered Session alone leaves + # the CM's exit logic (which deletes the env state + sid) unrun. + self._session_cm = cm + self._session = cm.__enter__() + prompt = self._session.get_prompt() + return _join_text_blocks(prompt) + + # Leading underscore so TRL's tool collector at grpo_trainer.py:502-506 + # excludes this from the model's tool surface. + def _close(self) -> None: + """Tear down the active session (best-effort).""" + self._teardown_session() + + # ── helpers ────────────────────────────────────────────────────── + + def _teardown_session(self) -> None: + if self._session_cm is None: + return + try: + # Exit the SDK's Session context manager — this deletes both + # the per-rollout env state and the sid on the server. + self._session_cm.__exit__(None, None, None) + except Exception as e: # noqa: BLE001 + logger.debug("session teardown failed: %s", e) + self._session_cm = None + self._session = None + + def _call_ors_tool(self, tool_name: str, tool_input: dict[str, Any]) -> str: + """Invoke a server-side tool and update episode state.""" + if self._session is None: + raise RuntimeError("Cannot call a tool before reset() opens a session.") + + try: + out = self._session.call_tool(tool_name, tool_input) + except Exception as e: # noqa: BLE001 + self.rewards.append(None) + self.metadata.append(None) + self.last_output = f"Error: {e}" + return self.last_output + + # `out` is `openreward.api.environments.types.ToolOutput` — a stable dataclass + # with `blocks: list`, `reward: Optional[float]`, `metadata: Optional[dict]`, `finished: bool`. + text = _join_text_blocks(out.blocks or []) or "(no output)" + + step_reward: float | None = None + if out.reward is not None: + try: + step_reward = float(out.reward) + except (TypeError, ValueError): + step_reward = None + self.rewards.append(step_reward) + if step_reward is not None: + self.reward = step_reward # last-non-null wins (outcome-only convention) + + self.metadata.append(out.metadata if isinstance(out.metadata, dict) else None) + self.finished = bool(out.finished) + self.last_output = text + return text + + +# ── dynamic tool binding ───────────────────────────────────────────── + + +_VALID_TOOL_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") + + +def _bind_tool_method(cls: type, spec: dict[str, Any]) -> None: + """Generate a typed Python method for one ORS tool spec. + + Signature comes from the JSON Schema; docstring is Google-style so ``transformers.utils.get_json_schema`` (used by + vLLM) can produce a correct tool schema for the model. + + Untrusted text from the server (tool name, descriptions) is never spliced raw into the generated source — the name + is validated against a Python-identifier regex and the description / per-param descriptions are passed through + ``repr()`` before being interpolated, so a tool description containing triple quotes can't break binding. + """ + tool_name = spec["name"] + if not _VALID_TOOL_NAME.match(tool_name): + logger.warning("skipping tool with non-identifier name: %r", tool_name) + return + if tool_name in cls.__dict__: + # Already bound by an earlier instance — idempotent skip. + return + + description = spec.get("description") or f"Call the {tool_name} tool." + schema = spec.get("input_schema") or {} + properties: dict[str, dict[str, Any]] = schema.get("properties") or {} + required: set[str] = set(schema.get("required") or []) + + # Required params must come before optional ones in Python — sort. + required_props = [(n, p) for n, p in properties.items() if n in required] + optional_props = [(n, p) for n, p in properties.items() if n not in required] + + params_src: list[str] = [] + annotations: dict[str, type] = {} + args_doc_lines: list[str] = [] + for pname, pdef in required_props + optional_props: + if not _VALID_TOOL_NAME.match(pname): + logger.warning("skipping tool %r — non-identifier param name: %r", tool_name, pname) + return + py_type = _resolve_param_type(pdef) + annotations[pname] = _PY_TYPE_OBJECTS[py_type] + if pname in required: + params_src.append(f"{pname}: {py_type}") + else: + default = pdef.get("default", None) + params_src.append(f"{pname}: {py_type} = {default!r}") + pdesc = pdef.get("description") or pdef.get("title") or pname + args_doc_lines.append(f" {pname}: {pdesc}") + + # Build the docstring as a single repr-quoted string so triple-quotes / quotes / newlines in the description or + # arg text can never close out the generated docstring early. + docstring = description + (("\n\n Args:\n" + "\n".join(args_doc_lines)) if args_doc_lines else "") + src = ( + f"def {tool_name}(self, {', '.join(params_src)}) -> str:\n" + f" {docstring!r}\n" + f" _kwargs = dict(locals()); _kwargs.pop('self', None)\n" + f" return self._call_ors_tool({tool_name!r}, _kwargs)\n" + ) + ns: dict[str, Any] = {} + exec(src, ns) + fn = ns[tool_name] + fn.__qualname__ = f"{cls.__name__}.{tool_name}" + fn.__annotations__ = {**annotations, "return": str} + setattr(cls, tool_name, fn) + + +# ── small utilities ────────────────────────────────────────────────── + + +def _spec_to_dict(spec: Any) -> dict[str, Any]: + """Normalise SDK ``ToolSpec`` and dict shapes to the same dict form. + + ``openreward.api.environments.types.ToolSpec`` is a stable dataclass with ``name``, ``description``, + ``input_schema`` fields, so direct attribute access is safe. + """ + if isinstance(spec, dict): + return spec + return { + "name": spec.name, + "description": spec.description, + "input_schema": spec.input_schema or {}, + } + + +def _join_text_blocks(blocks: list[Any]) -> str: + """Concatenate the ``text`` field of every text block in order. + + Accepts both SDK ``TextBlock`` dataclasses and plain dicts. Both shapes expose a ``type`` discriminator (`"text"` + vs `"image"`); non-text blocks are skipped so e.g. ``ImageBlock`` doesn't trip up the join. + """ + if not blocks: + return "" + parts: list[str] = [] + for b in blocks: + if isinstance(b, dict): + if b.get("type") != "text": + continue + text = b.get("text") + else: + if b.type != "text": + continue + text = b.text + if text: + parts.append(str(text)) + return "\n".join(parts) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/orpo/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/orpo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..88abd9e1826eae8a0d201b84a048614059b9e264 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/orpo/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .orpo_config import ORPOConfig +from .orpo_trainer import ORPOTrainer + + +__all__ = ["ORPOConfig", "ORPOTrainer"] diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/orpo/orpo_config.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/orpo/orpo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..ac2cf84d758d9b8c8e94d6518c934e62e77b9431 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/orpo/orpo_config.py @@ -0,0 +1,124 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field +from typing import Any + +from ...trainer.base_config import _BaseConfig + + +@dataclass +class ORPOConfig(_BaseConfig): + # docstyle-ignore + r""" + Configuration class for the [`experimental.orpo.ORPOTrainer`]. + + This class includes only the parameters that are specific to ORPO 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: + max_length (`int` or `None`, *optional*, defaults to `1024`): + Maximum length of the sequences (prompt + completion) in the batch. This argument is required if you want + to use the default data collator. + max_completion_length (`int`, *optional*): + Maximum length of the completion. This argument is required if you want to use the default data collator + and your model is an encoder-decoder. + beta (`float`, *optional*, defaults to `0.1`): + Parameter controlling the relative ratio loss weight in the ORPO loss. In the + [paper](https://huggingface.co/papers/2403.07691), it is denoted by λ. In the + [code](https://github.com/xfactlab/orpo), it is denoted by `alpha`. + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the model. + padding_value (`int`, *optional*): + Padding value to use. If `None`, the padding value of the tokenizer is used. + generate_during_eval (`bool`, *optional*, defaults to `False`): + If `True`, generates and logs completions from the model to W&B or Comet during evaluation. + is_encoder_decoder (`bool`, *optional*): + When using the `model_init` argument (callable) to instantiate the model instead of the `model` argument, + you need to specify if the model returned by the callable is an encoder-decoder model. + model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model from a + string. + dataset_num_proc (`int`, *optional*): + Number of processes to use for processing the dataset. + + > [!NOTE] + > These parameters have default values different from [`~transformers.TrainingArguments`]: + > - `logging_steps`: Defaults to `10` instead of `500`. + > - `gradient_checkpointing`: Defaults to `True` instead of `False`. + > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`. + > - `learning_rate`: Defaults to `1e-6` instead of `5e-5`. + """ + + _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"] + + # Parameters whose default values are overridden from TrainingArguments + learning_rate: float = field( + default=1e-6, + metadata={"help": "The initial learning rate for AdamW."}, + ) + + max_length: int | None = field( + default=1024, + metadata={"help": "Maximum length of the sequences (prompt + completion) in the batch."}, + ) + max_completion_length: int | None = field( + default=None, + metadata={ + "help": "Maximum length of the completion. This argument is required if you want to use the default data " + "collator and your model is an encoder-decoder." + }, + ) + beta: float = field( + default=0.1, + metadata={ + "help": "Parameter controlling the relative ratio loss weight in the ORPO loss. In the paper, it is " + "denoted by λ." + }, + ) + disable_dropout: bool = field( + default=True, + metadata={"help": "Whether to disable dropout in the model."}, + ) + padding_value: int | None = field( + default=None, + metadata={"help": "Padding value to use. If `None`, the padding value of the tokenizer is used."}, + ) + generate_during_eval: bool = field( + default=False, + metadata={"help": "If `True`, generates and logs completions from the model to W&B during evaluation."}, + ) + is_encoder_decoder: bool | None = field( + default=None, + metadata={ + "help": "When using the `model_init` argument (callable) to instantiate the model instead of the `model` " + "argument, you need to specify if the model returned by the callable is an encoder-decoder model." + }, + ) + model_init_kwargs: dict[str, Any] | str | None = field( + default=None, + metadata={ + "help": "Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model " + "from a string." + }, + ) + dataset_num_proc: int | None = field( + default=None, + metadata={"help": "Number of processes to use for processing the dataset."}, + ) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/orpo/orpo_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/orpo/orpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..575e0d6ce51174374b4bd329cbdbb6af1ec5b1ec --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/orpo/orpo_trainer.py @@ -0,0 +1,1039 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import inspect +import random +import textwrap +from collections import defaultdict +from collections.abc import Callable +from contextlib import nullcontext +from pathlib import Path +from typing import Any, Literal + +import numpy as np +import pandas as pd +import torch +import torch.nn as nn +import torch.nn.functional as F +import transformers +from accelerate import PartialState, logging +from accelerate.utils import is_peft_model +from datasets import Dataset +from packaging.version import Version +from torch import autocast +from torch.utils.data import DataLoader +from transformers import ( + AutoModelForCausalLM, + BaseImageProcessor, + DataCollator, + FeatureExtractionMixin, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, + is_comet_available, + is_torch_xla_available, + is_wandb_available, +) +from transformers.trainer_utils import EvalLoopOutput +from transformers.utils import is_peft_available, is_torch_fx_proxy + +from ...data_utils import maybe_apply_chat_template, maybe_extract_prompt +from ...trainer.base_trainer import _BaseTrainer +from ...trainer.utils import disable_dropout_in_model, log_table_to_comet_experiment, selective_log_softmax +from ..utils import ( + DPODataCollatorWithPadding, + add_bos_token_if_needed, + add_eos_token_if_needed, + pad_to_length, + peft_module_casting_to_bf16, +) +from .orpo_config import ORPOConfig + + +if is_peft_available(): + from peft import PeftConfig, get_peft_model, prepare_model_for_kbit_training + + +if is_wandb_available(): + import wandb + +if is_torch_xla_available(): + import torch_xla.core.xla_model as xm + + +logger = logging.get_logger(__name__) + + +def log1mexp(x: torch.FloatTensor) -> torch.FloatTensor: + """Numerically stable computation of log(1-exp(x)).""" + # branch at -ln 2 ~ -0.693 to avoid cancellation + t = -0.6931471805599453 + return torch.where(x < t, torch.log1p(-torch.exp(x)), torch.log(-torch.expm1(x))) + + +class ORPOTrainer(_BaseTrainer): + r""" + Initialize ORPOTrainer. + + Args: + model ([`~transformers.PreTrainedModel`]): + The model to train, preferably an [`~transformers.AutoModelForSequenceClassification`]. + args ([`experimental.orpo.ORPOConfig`]): + The ORPO config arguments to use for training. + data_collator ([`~transformers.DataCollator`]): + The data collator to use for training. If None is specified, the default data collator + ([`experimental.utils.DPODataCollatorWithPadding`]) will be used which will pad the sequences to the + maximum length of the sequences in the batch, given a dataset of paired sequences. + train_dataset ([`~datasets.Dataset`]): + The dataset to use for training. + eval_dataset ([`~datasets.Dataset`]): + The dataset to use for evaluation. + processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*): + Processing class used to process the data. If provided, will be used to automatically process the inputs + for the model, and it will be saved along the model to make it easier to rerun an interrupted training or + reuse the fine-tuned model. + model_init (`Callable[[], transformers.PreTrainedModel]`): + The model initializer to use for training. If None is specified, the default model initializer will be + used. + callbacks (`list[transformers.TrainerCallback]`): + The callbacks to use for training. + optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`): + The optimizer and scheduler to use for training. + preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`): + The function to use to preprocess the logits before computing the metrics. + peft_config ([`~peft.PeftConfig`], *optional*): + The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in + a PEFT model. + compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*): + The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to + metric values. + """ + + _tag_names = ["trl", "orpo"] + _name = "ORPO" + _paper = { + "title": "ORPO: Monolithic Preference Optimization without Reference Model", + "id": "2403.07691", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @article{hong2024orpo, + title = {{ORPO: Monolithic Preference Optimization without Reference Model}}, + author = {Jiwoo Hong and Noah Lee and James Thorne}, + year = 2024, + eprint = {arXiv:2403.07691} + }"""), + } + + def __init__( + self, + model: PreTrainedModel | nn.Module | str | None = None, + args: ORPOConfig | None = None, + data_collator: DataCollator | None = None, + train_dataset: Dataset | None = None, + eval_dataset: Dataset | dict[str, Dataset] | None = None, + processing_class: PreTrainedTokenizerBase + | BaseImageProcessor + | FeatureExtractionMixin + | ProcessorMixin + | None = None, + model_init: Callable[[], PreTrainedModel] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None, + peft_config: "PeftConfig | None" = None, + compute_metrics: Callable[[EvalLoopOutput], dict] | None = None, + ): + if train_dataset is None: + raise ValueError("`train_dataset` is required") + + if args.model_init_kwargs is None: + model_init_kwargs = {} + elif not isinstance(model, str): + raise ValueError("You passed model_kwargs to the ORPOTrainer. But your model is already instantiated.") + else: + model_init_kwargs = args.model_init_kwargs + dtype = model_init_kwargs.get("dtype", "auto") + if dtype is not None: + # Convert to `torch.dtype` if an str is passed + if isinstance(dtype, str) and dtype != "auto": + dtype = getattr(torch, dtype) + if dtype != "auto" and not isinstance(dtype, torch.dtype): + raise ValueError( + f"Invalid `dtype` passed to the ORPOConfig. Expected a string with either `torch.dtype` or 'auto', but got {dtype}." + ) + model_init_kwargs["dtype"] = dtype + model_init_kwargs["device_map"] = model_init_kwargs.get("device_map", "auto") + + if isinstance(model, str): + model = AutoModelForCausalLM.from_pretrained(model, **model_init_kwargs) + + # PEFT + # Initialize this variable to False. This helps tracking the case when `peft_module_casting_to_bf16` + # has been called in order to properly call autocast if needed. + self._peft_has_been_casted_to_bf16 = False + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + if is_peft_model(model): + raise ValueError( + "You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first " + "merge and unload the existing adapter, save the resulting base model, and then pass that base " + "model along with the new `peft_config` to the trainer." + ) + + if getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False): + _support_gc_kwargs = hasattr( + args, "gradient_checkpointing_kwargs" + ) and "gradient_checkpointing_kwargs" in list( + inspect.signature(prepare_model_for_kbit_training).parameters + ) + + prepare_model_kwargs = {"use_gradient_checkpointing": args.gradient_checkpointing} + + if _support_gc_kwargs: + prepare_model_kwargs["gradient_checkpointing_kwargs"] = args.gradient_checkpointing_kwargs + + model = prepare_model_for_kbit_training(model, **prepare_model_kwargs) + elif args.gradient_checkpointing: + # For backward compatibility with older versions of transformers + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + # get peft model with the given config + model = get_peft_model(model, peft_config) + if args.bf16 and getattr(model, "is_loaded_in_4bit", False): + peft_module_casting_to_bf16(model) + # If args.bf16 we need to explicitly call `generate` with torch amp autocast context manager + self._peft_has_been_casted_to_bf16 = True + + # For models that use gradient_checkpointing, we need to attach a hook that enables input + # to explicitly have `requires_grad=True`, otherwise training will either silently + # fail or completely fail. + elif args.gradient_checkpointing: + # For backward compatibility with older versions of transformers + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + if args.generate_during_eval and not (is_wandb_available() or is_comet_available()): + raise ValueError( + "`generate_during_eval=True` requires Weights and Biases or Comet to be installed." + " Please install `wandb` or `comet-ml` to resolve." + ) + + if model is not None: + self.is_encoder_decoder = model.config.is_encoder_decoder + elif args.is_encoder_decoder is None: + raise ValueError("When no model is provided, you need to pass the parameter is_encoder_decoder.") + else: + self.is_encoder_decoder = args.is_encoder_decoder + + if self.is_encoder_decoder: + self.decoder_start_token_id = model.config.decoder_start_token_id + self.pad_token_id = model.config.pad_token_id + + if processing_class is None: + raise ValueError("processing_class must be specified to tokenize a ORPO dataset.") + if args.max_length is None: + logger.warning( + "`max_length` is not set in the ORPOConfig's init" + " it will default to `512` by default, but you should do it yourself in the future.", + ) + max_length = 512 + else: + max_length = args.max_length + + if args.max_completion_length is None and self.is_encoder_decoder: + logger.warning( + "When using an encoder decoder architecture, you should set `max_completion_length` in the ORPOConfig's init" + " it will default to `128` by default, but you should do it yourself in the future.", + ) + self.max_completion_length = 128 + else: + self.max_completion_length = args.max_completion_length + + if data_collator is None: + data_collator = DPODataCollatorWithPadding( + pad_token_id=processing_class.pad_token_id, + is_encoder_decoder=self.is_encoder_decoder, + ) + + if args.remove_unused_columns: + args.remove_unused_columns = False + # warn users + logger.warning( + "When using DPODataCollatorWithPadding, you should set `remove_unused_columns=False` in your TrainingArguments" + " we have set it for you, but you should do it yourself in the future.", + ) + + self.use_dpo_data_collator = True + else: + self.use_dpo_data_collator = False + + # Disable dropout in the model and reference model + if args.disable_dropout: + disable_dropout_in_model(model) + + self.max_length = max_length + self.generate_during_eval = args.generate_during_eval + self.padding_value = args.padding_value if args.padding_value is not None else processing_class.pad_token_id + self.processing_class = processing_class + + self.beta = args.beta + self.aux_loss_enabled = getattr(model.config, "output_router_logits", False) + self.aux_loss_coef = getattr(model.config, "router_aux_loss_coef", 0.0) + if self.aux_loss_enabled and self.aux_loss_coef == 0.0: + logger.warning( + "You set `output_router_logits` to `True` in the model config, but `router_aux_loss_coef` is set to " + "`0.0`, meaning the auxiliary loss will not be used. Either set `router_aux_loss_coef` to a value " + "greater than `0.0`, or set `output_router_logits` to `False` if you don't want to use the auxiliary " + "loss.", + ) + + self._stored_metrics = defaultdict(lambda: defaultdict(list)) + + # Compute that only on the main process for faster data processing. + # see: https://github.com/huggingface/trl/pull/1255 + with PartialState().main_process_first(): + # Extract the prompt if needed, and apply the chat template if needed + train_dataset = train_dataset.map(maybe_extract_prompt, num_proc=args.dataset_num_proc) + train_dataset = train_dataset.map( + maybe_apply_chat_template, + fn_kwargs={"processing_class": processing_class}, + num_proc=args.dataset_num_proc, + ) + train_dataset = train_dataset.map(self.tokenize_row, num_proc=args.dataset_num_proc) + if eval_dataset is not None: + eval_dataset = eval_dataset.map(maybe_extract_prompt, num_proc=args.dataset_num_proc) + eval_dataset = eval_dataset.map( + maybe_apply_chat_template, + fn_kwargs={"processing_class": processing_class}, + num_proc=args.dataset_num_proc, + ) + eval_dataset = eval_dataset.map(self.tokenize_row, num_proc=args.dataset_num_proc) + + # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was + # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream + # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we + # default to the recommended non-reentrant behavior here, while preserving any user-provided value. + if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"): + args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {} + args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False) + + super().__init__( + model=model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + model_init=model_init, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + ) + + # Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the + # model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set + # self.model_accepts_loss_kwargs to False to enable scaling. + self.model_accepts_loss_kwargs = False + + # Add tags for models that have been loaded with the correct transformers version + if hasattr(self.model, "add_model_tags"): + self.model.add_model_tags(self._tag_names) + + if not hasattr(self, "accelerator"): + raise AttributeError( + "Your `Trainer` does not have an `accelerator` object. Consider upgrading `transformers`." + ) + + def build_tokenized_answer(self, prompt, answer): + """ + Llama tokenizer does satisfy `enc(a + b) = enc(a) + enc(b)`. It does ensure `enc(a + b) = enc(a) + enc(a + + b)[len(enc(a)):]`. Reference: + https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257 + """ + + full_tokenized = self.processing_class(prompt + answer, add_special_tokens=False) + prompt_input_ids = self.processing_class(prompt, add_special_tokens=False)["input_ids"] + + answer_input_ids = full_tokenized["input_ids"][len(prompt_input_ids) :] + answer_attention_mask = full_tokenized["attention_mask"][len(prompt_input_ids) :] + + # Concat tokens to form `enc(a) + enc(a + b)[len(enc(a)):]` + full_concat_input_ids = np.concatenate([prompt_input_ids, answer_input_ids]) + + # Prepare input tokens for token by token comparison + full_input_ids = np.array(full_tokenized["input_ids"]) + + if len(full_input_ids) != len(full_concat_input_ids): + raise ValueError("Prompt input ids and answer input ids should have the same length.") + + # On some tokenizers, like Llama-2 tokenizer, there are occasions where tokens + # can be merged together when tokenizing prompt+answer. This could result + # on the last token from the prompt being different when tokenized on its own + # vs when done as prompt+answer. + response_token_ids_start_idx = len(prompt_input_ids) + + # If tokenized prompt is different than both prompt+answer, then it means the + # last token has changed due to merging. + if prompt_input_ids != full_tokenized["input_ids"][:response_token_ids_start_idx]: + response_token_ids_start_idx -= 1 + + prompt_input_ids = full_tokenized["input_ids"][:response_token_ids_start_idx] + prompt_attention_mask = full_tokenized["attention_mask"][:response_token_ids_start_idx] + + if len(prompt_input_ids) != len(prompt_attention_mask): + raise ValueError("Prompt input ids and attention mask should have the same length.") + + answer_input_ids = full_tokenized["input_ids"][response_token_ids_start_idx:] + answer_attention_mask = full_tokenized["attention_mask"][response_token_ids_start_idx:] + + return dict( + prompt_input_ids=prompt_input_ids, + prompt_attention_mask=prompt_attention_mask, + input_ids=answer_input_ids, + attention_mask=answer_attention_mask, + ) + + def tokenize_row(self, feature, model: PreTrainedModel | nn.Module | None = None) -> dict: + """Tokenize a single row from a ORPO specific dataset. + + At this stage, we don't convert to PyTorch tensors yet; we just handle the truncation in case the prompt + + chosen or prompt + rejected responses is/are too long. First we truncate the prompt; if we're still too long, + we truncate the chosen/rejected. + + We also create the labels for the chosen/rejected responses, which are of length equal to the sum of the length + of the prompt and the chosen/rejected response, with `-100` for the prompt tokens. + """ + batch = {} + prompt = feature["prompt"] + chosen = feature["chosen"] + rejected = feature["rejected"] + + if not self.is_encoder_decoder: + # Check issues below for more details + # 1. https://github.com/huggingface/trl/issues/907 + # 2. https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257 + # 3. https://github.com/LianjiaTech/BELLE/issues/337 + + if not isinstance(prompt, str): + raise ValueError(f"prompt should be an str but got {type(prompt)}") + prompt_tokens = self.processing_class(prompt, add_special_tokens=False) + prompt_tokens = {f"prompt_{k}": v for k, v in prompt_tokens.items()} + + if not isinstance(chosen, str): + raise ValueError(f"chosen should be an str but got {type(chosen)}") + chosen_tokens = self.build_tokenized_answer(prompt, chosen) + + if not isinstance(rejected, str): + raise ValueError(f"rejected should be an str but got {type(rejected)}") + rejected_tokens = self.build_tokenized_answer(prompt, rejected) + + # Last prompt token might get merged by tokenizer and + # it should not be included for generation if that happens + prompt_len_input_ids = len(prompt_tokens["prompt_input_ids"]) + + chosen_prompt_len_input_ids = len(chosen_tokens["prompt_input_ids"]) + rejected_prompt_len_input_ids = len(rejected_tokens["prompt_input_ids"]) + prompt_len_input_ids = min(chosen_prompt_len_input_ids, rejected_prompt_len_input_ids) + + for k, v in prompt_tokens.items(): + prompt_tokens[k] = v[:prompt_len_input_ids] + + # Make sure prompts only have one different token at most an + # and length only differs by 1 at most + num_diff_tokens = sum( + a != b + for a, b in zip(chosen_tokens["prompt_input_ids"], rejected_tokens["prompt_input_ids"], strict=False) + ) + num_diff_len = abs(chosen_prompt_len_input_ids - rejected_prompt_len_input_ids) + if num_diff_tokens > 1 or num_diff_len > 1: + raise ValueError( + "Chosen and rejected prompt_input_ids might only differ on the " + "last token due to tokenizer merge ops." + ) + + # add BOS token to head of prompt. Avoid adding if it's already there + prompt_tokens, chosen_tokens, rejected_tokens = add_bos_token_if_needed( + self.processing_class.bos_token_id, + prompt_len_input_ids, + prompt_tokens, + chosen_prompt_len_input_ids, + chosen_tokens, + rejected_prompt_len_input_ids, + rejected_tokens, + ) + + # add EOS token to end of answer. Avoid adding if it's already there + chosen_tokens, rejected_tokens = add_eos_token_if_needed( + self.processing_class.eos_token_id, chosen_tokens, rejected_tokens + ) + + longer_response_length = max(len(chosen_tokens["input_ids"]), len(rejected_tokens["input_ids"])) + + # if combined sequence is too long, truncate the response + for answer_tokens in [chosen_tokens, rejected_tokens]: + if len(answer_tokens["prompt_input_ids"]) + longer_response_length > self.max_length: + for k in ["input_ids", "attention_mask"]: + answer_tokens[k] = answer_tokens[k][: self.max_length - longer_response_length] + + # Create labels + chosen_sequence_tokens = { + k: chosen_tokens[f"prompt_{k}"] + chosen_tokens[k] for k in ["input_ids", "attention_mask"] + } + rejected_sequence_tokens = { + k: rejected_tokens[f"prompt_{k}"] + rejected_tokens[k] for k in ["input_ids", "attention_mask"] + } + chosen_sequence_tokens["labels"] = chosen_sequence_tokens["input_ids"][:] + chosen_sequence_tokens["labels"][: len(chosen_tokens["prompt_input_ids"])] = [-100] * len( + chosen_tokens["prompt_input_ids"] + ) + rejected_sequence_tokens["labels"] = rejected_sequence_tokens["input_ids"][:] + rejected_sequence_tokens["labels"][: len(rejected_tokens["prompt_input_ids"])] = [-100] * len( + rejected_tokens["prompt_input_ids"] + ) + + for k, toks in { + "chosen_": chosen_sequence_tokens, + "rejected_": rejected_sequence_tokens, + "": prompt_tokens, + }.items(): + for type_key, tokens in toks.items(): + if type_key == "token_type_ids": + continue + batch[f"{k}{type_key}"] = tokens + + else: + chosen_tokens = self.processing_class( + chosen, truncation=True, max_length=self.max_completion_length, add_special_tokens=True + ) + rejected_tokens = self.processing_class( + rejected, truncation=True, max_length=self.max_completion_length, add_special_tokens=True + ) + prompt_tokens = self.processing_class(prompt, add_special_tokens=True) + + batch["chosen_labels"] = chosen_tokens["input_ids"] + batch["rejected_labels"] = rejected_tokens["input_ids"] + batch["prompt_input_ids"] = prompt_tokens["input_ids"] + batch["prompt_attention_mask"] = prompt_tokens["attention_mask"] + + if model is not None and hasattr(model, "prepare_decoder_input_ids_from_labels"): + batch["rejected_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels( + labels=torch.tensor(batch["rejected_labels"]) + ) + batch["chosen_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels( + labels=torch.tensor(batch["chosen_labels"]) + ) + + if is_torch_xla_available(): + # Pad the sequences to global max_length to avoid TorchXLA recompilation + for k in batch: + if "labels" in k or self.is_encoder_decoder: + pad_value = -100 + elif k.endswith("_input_ids"): + pad_value = self.padding_value + elif k.endswith("_attention_mask"): + pad_value = 0 + batch[k] = batch[k] + [pad_value] * (self.max_length - len(batch[k])) + return batch + + @staticmethod + def concatenated_inputs( + batch: dict[str, list | torch.LongTensor], + is_encoder_decoder: bool = False, + padding_value: int = 0, + device: torch.device | None = None, + ) -> dict[str, torch.LongTensor]: + """Concatenate the chosen and rejected inputs into a single tensor. + + Args: + batch: + A batch of data. Must contain the keys 'chosen_input_ids' and 'rejected_input_ids', which are tensors + of shape (batch_size, sequence_length). + is_encoder_decoder: + Whether the model is an encoder-decoder model. + padding_value: + The padding value to use for the concatenated inputs_ids. + device: + The device for the concatenated inputs. + + Returns: + A dictionary containing the concatenated inputs under the key 'concatenated_input_ids'. + """ + concatenated_batch = {} + + if is_encoder_decoder: + max_length = max(batch["chosen_labels"].shape[1], batch["rejected_labels"].shape[1]) + else: + max_length = max(batch["chosen_input_ids"].shape[1], batch["rejected_input_ids"].shape[1]) + + for k in batch: + if k.startswith("chosen") and isinstance(batch[k], torch.Tensor): + if "labels" in k or is_encoder_decoder: + pad_value = -100 + elif k.endswith("_input_ids"): + pad_value = padding_value + elif k.endswith("_attention_mask"): + pad_value = 0 + concatenated_key = k.replace("chosen", "concatenated") + concatenated_batch[concatenated_key] = pad_to_length(batch[k], max_length, pad_value=pad_value) + for k in batch: + if k.startswith("rejected") and isinstance(batch[k], torch.Tensor): + if "labels" in k or is_encoder_decoder: + pad_value = -100 + elif k.endswith("_input_ids"): + pad_value = padding_value + elif k.endswith("_attention_mask"): + pad_value = 0 + concatenated_key = k.replace("rejected", "concatenated") + concatenated_batch[concatenated_key] = torch.cat( + ( + concatenated_batch[concatenated_key], + pad_to_length(batch[k], max_length, pad_value=pad_value), + ), + dim=0, + ).to(device=device) + + if is_encoder_decoder: + concatenated_batch["concatenated_input_ids"] = batch["prompt_input_ids"].repeat(2, 1).to(device=device) + concatenated_batch["concatenated_attention_mask"] = ( + batch["prompt_attention_mask"].repeat(2, 1).to(device=device) + ) + + return concatenated_batch + + def odds_ratio_loss( + self, + policy_chosen_logps: torch.FloatTensor, + policy_rejected_logps: torch.FloatTensor, + ) -> tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: + """Compute ORPO's odds ratio (OR) loss for a batch of policy and reference model log probabilities. + + Args: + policy_chosen_logps: + Log probabilities of the policy model for the chosen responses. Shape: (batch_size,) + policy_rejected_logps: + Log probabilities of the policy model for the rejected responses. Shape: (batch_size,) + + Returns: + A tuple of three tensors: (losses, chosen_rewards, rejected_rewards). The losses tensor contains the ORPO + loss for each example in the batch. The chosen_rewards and rejected_rewards tensors contain the rewards for + the chosen and rejected responses, respectively. The log odds ratio of the chosen responses over the + rejected responses ratio for logging purposes. The `log(sigmoid(log_odds_chosen))` for logging purposes. + """ + + # Derived from Eqs. (4) and (7) from https://huggingface.co/papers/2403.07691 by using log identities and exp(log(P(y|x)) = P(y|x) + policy_chosen_logps = policy_chosen_logps.float() + policy_rejected_logps = policy_rejected_logps.float() + log_odds = (policy_chosen_logps - policy_rejected_logps) - ( + log1mexp(policy_chosen_logps) - log1mexp(policy_rejected_logps) + ) + ratio = F.logsigmoid(log_odds) + losses = self.beta * ratio + + chosen_rewards = self.beta * (policy_chosen_logps.to(self.accelerator.device)).detach() + rejected_rewards = self.beta * (policy_rejected_logps.to(self.accelerator.device)).detach() + + return losses, chosen_rewards, rejected_rewards, torch.mean(ratio), torch.mean(log_odds) + + @staticmethod + def get_batch_logps( + logits: torch.FloatTensor, + labels: torch.LongTensor, + average_log_prob: bool = False, + is_encoder_decoder: bool = False, + ) -> torch.FloatTensor: + """Compute the log probabilities of the given labels under the given logits. + + Args: + logits: Logits of the model (unnormalized). Shape: (batch_size, sequence_length, vocab_size) + labels: + Labels for which to compute the log probabilities. Label tokens with a value of `-100` are ignored. + Shape: (batch_size, sequence_length) + average_log_prob: + If True, return the average log probability per (non-masked) token. Otherwise, return the sum of the + log probabilities of the (non-masked) tokens. + is_encoder_decoder: Whether the model is an encoder-decoder model. + + Returns: + A tensor of shape (batch_size,) containing the average/sum log probabilities of the given labels under the + given logits. + """ + if logits.shape[:-1] != labels.shape: + raise ValueError("Logits (batch and sequence length dim) and labels must have the same shape.") + + if not is_encoder_decoder: + labels = labels[:, 1:].clone() + logits = logits[:, :-1, :] + loss_mask = labels != -100 + + # dummy token; we'll ignore the losses on these tokens later + labels = torch.where(labels == -100, 0, labels) + + per_token_logps = selective_log_softmax(logits, labels) + + if average_log_prob: + return (per_token_logps * loss_mask).sum(-1) / loss_mask.sum(-1) + else: + return (per_token_logps * loss_mask).sum(-1) + + def concatenated_forward( + self, model: nn.Module, batch: dict[str, list | torch.LongTensor] + ) -> tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: + """Run the given model on the given batch of inputs, concatenating the chosen and rejected inputs together. + + We do this to avoid doing two forward passes, because it's faster for FSDP. + """ + concatenated_batch = self.concatenated_inputs( + batch, + is_encoder_decoder=self.is_encoder_decoder, + padding_value=self.padding_value, + device=self.accelerator.device, + ) + len_chosen = batch["chosen_labels"].shape[0] + + model_kwargs = ( + { + "decoder_input_ids": self._shift_right(concatenated_batch["concatenated_labels"]), + } + if self.is_encoder_decoder + else {} + ) + + if self.aux_loss_enabled: + model_kwargs["output_router_logits"] = True + + outputs = model( + concatenated_batch["concatenated_input_ids"], + attention_mask=concatenated_batch["concatenated_attention_mask"], + use_cache=False, + **model_kwargs, + ) + all_logits = outputs.logits + + def cross_entropy_loss(logits, labels): + if not self.is_encoder_decoder: + # Shift so that tokens < n predict n + logits = logits[..., :-1, :].contiguous() + labels = labels[..., 1:].contiguous() + # Flatten the tokens + loss_fct = nn.CrossEntropyLoss() + logits = logits.view(-1, logits.shape[-1]) + labels = labels.view(-1) + # Enable model parallelism + labels = labels.to(logits.device) + loss = loss_fct(logits, labels) + return loss + + if self.is_encoder_decoder: + labels = concatenated_batch["concatenated_labels"].clone() + else: + labels = concatenated_batch["concatenated_input_ids"].clone() + attention_mask = concatenated_batch["concatenated_attention_mask"] + labels = torch.where(attention_mask == 1, labels, -100) + # orpo chosen nll loss is computed over the full prompt and response + chosen_nll_loss = cross_entropy_loss(all_logits[:len_chosen], labels[:len_chosen]) + + all_logps = self.get_batch_logps( + all_logits, + concatenated_batch["concatenated_labels"], + average_log_prob=True, + is_encoder_decoder=self.is_encoder_decoder, + ) + + chosen_logps = all_logps[:len_chosen] + rejected_logps = all_logps[len_chosen:] + + if not self.is_encoder_decoder: + chosen_logits = all_logits[:len_chosen, :-1, :] + rejected_logits = all_logits[len_chosen:, :-1, :] + else: + chosen_logits = all_logits[:len_chosen] + rejected_logits = all_logits[len_chosen:] + + if self.aux_loss_enabled: + return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, chosen_nll_loss, outputs.aux_loss) + + return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, chosen_nll_loss) + + def get_batch_loss_metrics( + self, + model, + batch: dict[str, list | torch.LongTensor], + train_eval: Literal["train", "eval"] = "train", + ): + """Compute the ORPO loss and other metrics for the given batch of inputs for train or test.""" + metrics = {} + + forward_output = self.concatenated_forward(model, batch) + ( + policy_chosen_logps, + policy_rejected_logps, + policy_chosen_logits, + policy_rejected_logits, + policy_nll_loss, + ) = forward_output[:5] + if self.aux_loss_enabled: + aux_loss = forward_output[5] + + losses, chosen_rewards, rejected_rewards, log_odds_ratio, log_odds_chosen = self.odds_ratio_loss( + policy_chosen_logps, policy_rejected_logps + ) + # full ORPO loss + loss = policy_nll_loss - losses.mean() + + reward_accuracies = (chosen_rewards > rejected_rewards).float() + + prefix = "eval_" if train_eval == "eval" else "" + metrics[f"{prefix}rewards/chosen"] = self.accelerator.gather_for_metrics(chosen_rewards).mean() + metrics[f"{prefix}rewards/rejected"] = self.accelerator.gather_for_metrics(rejected_rewards).mean() + metrics[f"{prefix}rewards/accuracies"] = self.accelerator.gather_for_metrics(reward_accuracies).mean() + metrics[f"{prefix}rewards/margins"] = self.accelerator.gather_for_metrics( + chosen_rewards - rejected_rewards + ).mean() + metrics[f"{prefix}logps/rejected"] = self.accelerator.gather_for_metrics(policy_rejected_logps).detach().mean() + metrics[f"{prefix}logps/chosen"] = self.accelerator.gather_for_metrics(policy_chosen_logps).detach().mean() + metrics[f"{prefix}logits/rejected"] = self.accelerator.gather_for_metrics( + policy_rejected_logits.detach().mean() + ).mean() + metrics[f"{prefix}logits/chosen"] = self.accelerator.gather_for_metrics( + policy_chosen_logits.detach().mean() + ).mean() + metrics[f"{prefix}nll_loss"] = self.accelerator.gather_for_metrics(policy_nll_loss).detach().mean() + metrics[f"{prefix}log_odds_ratio"] = self.accelerator.gather_for_metrics(log_odds_ratio).detach().mean() + metrics[f"{prefix}log_odds_chosen"] = self.accelerator.gather_for_metrics(log_odds_chosen).detach().mean() + if is_torch_xla_available(): + xm.mark_step() # needed because .item() calls + for k, v in metrics.items(): + metrics[k] = v.item() + if self.aux_loss_enabled: + loss += self.aux_loss_coef * aux_loss + + return loss, metrics + + def compute_loss( + self, + model: PreTrainedModel | nn.Module, + inputs: dict[str, torch.Tensor | Any], + return_outputs=False, + num_items_in_batch=None, + ) -> torch.Tensor | tuple[torch.Tensor, dict[str, torch.Tensor]]: + compute_loss_context_manager = ( + autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext() + ) + + with compute_loss_context_manager: + loss, metrics = self.get_batch_loss_metrics(model, inputs, train_eval="train") + + # Make sure to move the loss to the device the original accumulating loss is at back in the `Trainer` class: + loss = loss.to(self.args.device) + + # force log the metrics + self.store_metrics(metrics, train_eval="train") + + if return_outputs: + return (loss, metrics) + return loss + + def generate_from_model(self, model, batch: dict[str, torch.LongTensor]) -> str: + """Generate samples from the model and reference model for the given batch of inputs.""" + + # If one uses `generate_during_eval` with peft + bf16, we need to explicitly call generate with + # the torch amp context manager as some hidden states are silently casted to full precision. + generate_context_manager = ( + autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext() + ) + + with generate_context_manager: + policy_output = model.generate( + input_ids=batch["prompt_input_ids"], + attention_mask=batch["prompt_attention_mask"], + max_length=self.max_length, + do_sample=True, + pad_token_id=self.processing_class.pad_token_id, + ) + + policy_output = pad_to_length(policy_output, self.max_length, self.processing_class.pad_token_id) + policy_output_decoded = self.processing_class.batch_decode(policy_output, skip_special_tokens=True) + + return policy_output_decoded + + def prediction_step( + self, + model: PreTrainedModel | nn.Module, + inputs: dict[str, torch.Tensor | Any], + prediction_loss_only: bool, + ignore_keys: list[str] | None = None, + ): + if not self.use_dpo_data_collator: + logger.warning( + "prediction_step is only implemented for DPODataCollatorWithPadding, and you passed a datacollator that is different than " + "DPODataCollatorWithPadding - you might see unexpected behavior. Alternatively, you can implement your own prediction_step method if you are using a custom data collator" + ) + if ignore_keys is None: + if hasattr(model, "config"): + ignore_keys = getattr(model.config, "keys_to_ignore_at_inference", []) + else: + ignore_keys = [] + + prediction_context_manager = ( + autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext() + ) + + with torch.no_grad(), prediction_context_manager: + loss, metrics = self.get_batch_loss_metrics(model, inputs, train_eval="eval") + + # force log the metrics + self.store_metrics(metrics, train_eval="eval") + + if prediction_loss_only: + return (loss.detach(), None, None) + + # logits for the chosen and rejected samples from model + logits_dict = { + "eval_logits/chosen": metrics["eval_logits/chosen"], + "eval_logits/rejected": metrics["eval_logits/rejected"], + } + logits = [v for k, v in logits_dict.items() if k not in ignore_keys] + logits = torch.tensor(logits, device=self.accelerator.device) + labels = torch.zeros(logits.shape[0], device=self.accelerator.device) + + return (loss.detach(), logits, labels) + + def store_metrics(self, metrics: dict[str, float], train_eval: Literal["train", "eval"] = "train") -> None: + for key, value in metrics.items(): + self._stored_metrics[train_eval][key].append(value) + + def evaluation_loop( + self, + dataloader: DataLoader, + description: str, + prediction_loss_only: bool | None = None, + ignore_keys: list[str] | None = None, + metric_key_prefix: str = "eval", + ) -> EvalLoopOutput: + """ + Overriding built-in evaluation loop to store metrics for each batch. Prediction/evaluation loop, shared by + `Trainer.evaluate()` and `Trainer.predict()`. + + Works both with or without labels. + """ + + # Sample and save to game log if requested (for one batch to save time) + if self.generate_during_eval: + # Generate random indices within the range of the total number of samples + num_samples = len(dataloader.dataset) + random_indices = random.sample(range(num_samples), k=self.args.eval_batch_size) + + # Use dataloader.dataset.select to get the random batch without iterating over the DataLoader + random_batch_dataset = dataloader.dataset.select(random_indices) + random_batch = self.data_collator(random_batch_dataset) + random_batch = self._prepare_inputs(random_batch) + + policy_output_decoded = self.generate_from_model(self.model, random_batch) + + table = pd.DataFrame( + columns=["Prompt", "Policy"], + data=[ + [prompt, pol[len(prompt) :]] + for prompt, pol in zip(random_batch["prompt"], policy_output_decoded, strict=True) + ], + ) + if "wandb" in self.args.report_to: + wandb.log({"game_log": wandb.Table(data=table)}) + + if "comet_ml" in self.args.report_to: + log_table_to_comet_experiment( + name="game_log.csv", + table=table, + ) + + # Base evaluation + initial_output = super().evaluation_loop( + dataloader, description, prediction_loss_only, ignore_keys, metric_key_prefix + ) + + return initial_output + + def log(self, logs: dict[str, float], start_time: float | None = None) -> None: + """ + Log `logs` on the various objects watching training, including stored metrics. + + Args: + logs (`dict[str, float]`): + The values to log. + start_time (`float`, *optional*): + Start time of the training. + """ + # logs either has 'loss' or 'eval_loss' + train_eval = "train" if "loss" in logs else "eval" + # Add averaged stored metrics to logs + for key, metrics in self._stored_metrics[train_eval].items(): + logs[key] = torch.tensor(metrics).mean().item() + del self._stored_metrics[train_eval] + return super().log(logs, start_time) + + def _shift_right(self, input_ids): + if self.decoder_start_token_id is None: + raise ValueError( + "model.config.decoder_start_token_id has to be defined. It is usually set to the pad_token_id." + ) + + # shift inputs to the right + if is_torch_fx_proxy(input_ids): + # Item assignment is not supported natively for proxies. + shifted_input_ids = torch.full(input_ids.shape[:-1] + (1,), self.decoder_start_token_id) + shifted_input_ids = torch.cat([shifted_input_ids, input_ids[..., :-1]], dim=-1) + else: + shifted_input_ids = input_ids.new_zeros(input_ids.shape) + shifted_input_ids[..., 1:] = input_ids[..., :-1].clone() + shifted_input_ids[..., 0] = self.decoder_start_token_id + + if self.pad_token_id is None: + raise ValueError("model.config.pad_token_id has to be defined.") + # replace possible -100 values in labels by `pad_token_id` + shifted_input_ids.masked_fill_(shifted_input_ids == -100, self.pad_token_id) + + return shifted_input_ids + + # Ensure the model card is saved along with the checkpoint + def _save_checkpoint(self, model, trial): + if self.args.hub_model_id is None: + model_name = Path(self.args.output_dir).name + else: + model_name = self.args.hub_model_id.split("/")[-1] + self.create_model_card(model_name=model_name) + super()._save_checkpoint(model, trial) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/papo/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/papo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..62fb8105cb446c197570023e388299e1bd96bbc4 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/papo/__init__.py @@ -0,0 +1,17 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +from .papo_config import PAPOConfig +from .papo_trainer import PAPOTrainer diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/papo/papo_config.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/papo/papo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..e142a94a9cdc3128456b6127436c3befd6bc2a93 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/papo/papo_config.py @@ -0,0 +1,73 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass +from typing import Literal + +from ...trainer.grpo_config import GRPOConfig + + +@dataclass +class PAPOConfig(GRPOConfig): + """ + Configuration class for PAPOTrainer. + + PAPO (Perception-Aware Policy Optimization) extends GRPO/DAPO for multimodal reasoning by adding an implicit + perception loss and double entropy regularization. + + Args: + perception_loss_weight (`float`, *optional*, defaults to `0.1`): + gamma Weight coefficient for the perception loss term. This encourages the model to be sensitive to visual + changes. + + mask_ratio (`float`, *optional*, defaults to `0.3`): + Ratio of the image to mask when computing perception loss. + + mask_type (`Literal["random", "patch", "grid"]`, *optional*, defaults to `"random"`): + Type of masking strategy to use. + + der_loss_weight1 (`float`, *optional*, defaults to `0.03`): + eta1 Weight coefficient for the Double Entropy Regularization (DER) term. This term encourages confident + predictions with original images (low entropy) and uncertain predictions with masked images (high entropy). + + der_loss_weight2 (`float`, *optional*, defaults to `0.03`): + eta2 Weight coefficient for the Double Entropy Regularization (DER) term. This term encourages confident + predictions with original images (low entropy) and uncertain predictions with masked images (high entropy). + + loss_type (`Literal["grpo", "dapo"]`, inherited from GRPOConfig): + Base loss type to use. Set to "grpo" for PAPO-G or "dapo" for PAPO-D. + """ + + perception_loss_weight: float = 0.1 + mask_ratio: float = 0.3 + mask_type: Literal["random", "patch", "grid"] = "random" + + # Added for Double Entropy Regularization + der_loss_weight1: float = 0.03 + der_loss_weight2: float = 0.03 + + def __post_init__(self): + super().__post_init__() + + # Validation + if not 0.0 <= self.mask_ratio <= 1.0: + raise ValueError(f"mask_ratio must be between 0 and 1, got {self.mask_ratio}") + + if self.der_loss_weight1 < 0 or self.der_loss_weight2 < 0: + raise ValueError( + f"der_loss_weight1 and der_loss_weight2 must be non-negative, got {self.der_loss_weight1} and {self.der_loss_weight2}" + ) + + if self.mask_type not in ["random", "patch", "grid"]: + raise ValueError(f"mask_type must be one of ['random', 'patch', 'grid'], got {self.mask_type}") diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/papo/papo_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/papo/papo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..931fee3efe993e95b6564dab28987e125e8e96be --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/papo/papo_trainer.py @@ -0,0 +1,354 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import random +import textwrap + +import torch +from datasets import Dataset, IterableDataset +from transformers import PreTrainedModel, PreTrainedTokenizerBase, ProcessorMixin + +from ...trainer.grpo_trainer import GRPOTrainer, RewardFunc +from ...trainer.utils import nanmax, nanmin +from .papo_config import PAPOConfig + + +class PAPOTrainer(GRPOTrainer): + """ + Trainer for Perception-Aware Policy Optimization (PAPO). + + PAPO extends GRPO/DAPO for multimodal reasoning by adding an implicit perception loss that encourages the model to + better utilize visual information. The key innovation is computing KL divergence between model outputs on original + vs. corrupted (masked) images. + + Two variants are supported: + - PAPO-G: PAPO + GRPO (use loss_type="grpo") + - PAPO-D: PAPO + DAPO (use loss_type="dapo") + + Example: + + ```python + from datasets import load_dataset + from trl.experimental.papo import PAPOTrainer, PAPOConfig + + dataset = load_dataset("your-vlm-dataset", split="train") + + + def reward_func(completions, **kwargs): + # Your reward function for multimodal reasoning + return [compute_reward(c) for c in completions] + + + # PAPO-G + config = PAPOConfig( + loss_type="grpo", # Use GRPO as base + perception_loss_weight=0.1, + mask_ratio=0.3, + ) + + # PAPO-G + config = PAPOConfig( + loss_type="dapo", # Use DAPO as base + perception_loss_weight=0.1, + mask_ratio=0.3, + ) + + trainer = PAPOTrainer( + model="Qwen/Qwen2-VL-2B-Instruct", + reward_funcs=reward_func, + args=config, + train_dataset=dataset, + ) + + trainer.train() + ``` + + Args: + model (`Union[str, PreTrainedModel]`): + Model to be trained (must be a vision-language model). + reward_funcs (`Union[RewardFunc, list[RewardFunc]]`): + Reward functions for computing rewards (same as GRPO). + args ([`PAPOConfig`], *optional*, defaults to `None`): + Configuration for this trainer. If `None`, a default configuration is used. + train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]): + Dataset to use for training. Must include "prompt" and "image" columns. + eval_dataset: Same requirements as train_dataset. + processing_class: Processing class (tokenizer/processor) for the model. + reward_processing_classes: Processing classes for reward models. + callbacks: Training callbacks. + optimizers: Optimizer and scheduler tuple. + peft_config: PEFT configuration if using parameter-efficient fine-tuning. + """ + + _tag_names = ["trl", "papo"] + _name = "PAPO" + _paper = { + "title": "Perception-Aware Policy Optimization for Multimodal Reasoning", + "id": "2507.06448", + # docstyle-ignore + "citation": textwrap.dedent( + """\ + @misc{wang2025perceptionawarepolicyoptimizationmultimodal, + title = {{Perception-Aware Policy Optimization for Multimodal Reasoning}}, + author = {Zhenhailong Wang and Xuehang Guo and Sofia Stoica and Haiyang Xu and Hongru Wang and Hyeonjeong Ha and Xiusi Chen and Yangyi Chen and Ming Yan and Fei Huang and Heng Ji}, + year = 2025, + url = {https://arxiv.org/abs/2507.06448}, + archivePrefix= {arXiv}, + eprint = {2507.06448}, + primaryClass = {cs.CL} + }""" + ), + } + + def __init__( + self, + model: str | PreTrainedModel, + reward_funcs: RewardFunc | list[RewardFunc], + args: PAPOConfig | None = None, + train_dataset: Dataset | IterableDataset | None = None, + eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None, + processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None, + reward_processing_classes: PreTrainedTokenizerBase | list[PreTrainedTokenizerBase] | None = None, + callbacks=None, + optimizers=(None, None), + peft_config=None, + ): + # Initialize with default PAPO config if not provided + if args is None: + model_name = model if isinstance(model, str) else model.config._name_or_path + model_name = model_name.split("/")[-1] + args = PAPOConfig(f"{model_name}-PAPO") + + # Store PAPO-specific parameters + self.perception_loss_weight = args.perception_loss_weight + self.mask_ratio = args.mask_ratio + self.mask_type = args.mask_type + self.der_loss_weight1 = args.der_loss_weight1 + self.der_loss_weight2 = args.der_loss_weight2 + + # Initialize parent GRPO trainer + super().__init__( + model=model, + reward_funcs=reward_funcs, + args=args, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + reward_processing_classes=reward_processing_classes, + callbacks=callbacks, + optimizers=optimizers, + peft_config=peft_config, + ) + + def _mask_image(self, pixel_values: torch.Tensor, mask_ratio: float = None) -> torch.Tensor: + """ + Apply masking to image pixel values. + + Args: + pixel_values: Image tensor of shape (B, C, H, W) or (B, N, C, H, W) for multi-image + mask_ratio: Ratio of image to mask (defaults to self.mask_ratio) + + Returns: + Masked pixel values tensor + """ + if mask_ratio is None: + mask_ratio = self.mask_ratio + + masked_pixel_values = pixel_values.clone() + + if self.mask_type == "random": + # Random pixel masking + mask = torch.rand_like(pixel_values) > mask_ratio + masked_pixel_values = masked_pixel_values * mask + + elif self.mask_type == "patch": + # Patch-based masking (mask contiguous regions) + B = pixel_values.shape[0] + if pixel_values.ndim == 4: # (B, C, H, W) + C, H, W = pixel_values.shape[1:] + for i in range(B): + # Calculate patch size to mask + patch_h = int(H * mask_ratio**0.5) + patch_w = int(W * mask_ratio**0.5) + # Random starting position + start_h = random.randint(0, max(0, H - patch_h)) + start_w = random.randint(0, max(0, W - patch_w)) + # Apply mask + masked_pixel_values[i, :, start_h : start_h + patch_h, start_w : start_w + patch_w] = 0 + + elif pixel_values.ndim == 5: # (B, N, C, H, W) for multi-image + N, C, H, W = pixel_values.shape[1:] + for i in range(B): + for n in range(N): + patch_h = int(H * mask_ratio**0.5) + patch_w = int(W * mask_ratio**0.5) + start_h = random.randint(0, max(0, H - patch_h)) + start_w = random.randint(0, max(0, W - patch_w)) + masked_pixel_values[i, n, :, start_h : start_h + patch_h, start_w : start_w + patch_w] = 0 + + elif self.mask_type == "grid": + # Grid-based masking (mask regular grid cells) + if pixel_values.ndim == 4: + C, H, W = pixel_values.shape[1:] + grid_size = int((1 / mask_ratio) ** 0.5) + cell_h, cell_w = H // grid_size, W // grid_size + + for i in range(grid_size): + for j in range(grid_size): + if random.random() < mask_ratio: + masked_pixel_values[:, :, i * cell_h : (i + 1) * cell_h, j * cell_w : (j + 1) * cell_w] = 0 + + return masked_pixel_values + + def _compute_loss(self, model, inputs): + # >>> 1. GRPO loss + # Compute the per-token log probabilities for the model + prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"] + completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"] + input_ids = torch.cat([prompt_ids, completion_ids], dim=1) + attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) + logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens + + # Compute the per_token_logps and the entropy at each position in the completion + per_token_logps, entropies = self._get_per_token_logps_and_entropies( + model, + input_ids, + attention_mask, + logits_to_keep, + compute_entropy=True, + pixel_values=inputs.get("pixel_values"), + image_grid_thw=inputs.get("image_grid_thw"), + num_images=inputs.get("num_images"), + pixel_attention_mask=inputs.get("pixel_attention_mask"), + image_sizes=inputs.get("image_sizes"), + ) + + if self.top_entropy_quantile < 1.0: + entropy_mask = self.get_high_entropy_mask(entropies, completion_mask, 1 - self.top_entropy_quantile) + else: + entropy_mask = None + + # Compute the KL divergence between the model and the reference model + if self.beta != 0.0: + ref_per_token_logps = inputs["ref_per_token_logps"] + per_token_kl = ( + torch.exp(ref_per_token_logps - per_token_logps) - (ref_per_token_logps - per_token_logps) - 1 + ) + + # Compute the loss + advantages = inputs["advantages"] + # When using num_iterations == 1 and steps_per_generation <= gradient_accumulation_steps + # old_per_token_logps == per_token_logps, so we can skip it's computation + # (see _generate_and_score_completions) and use per_token_logps.detach() instead. + old_per_token_logps = inputs.get("old_per_token_logps") + old_per_token_logps = per_token_logps.detach() if old_per_token_logps is None else old_per_token_logps + + log_ratio = per_token_logps - old_per_token_logps + if self.importance_sampling_level == "token": + log_importance_weights = log_ratio + elif self.importance_sampling_level == "sequence": + log_importance_weights = (log_ratio * completion_mask).sum(-1) / completion_mask.sum(-1).clamp(min=1.0) + log_importance_weights = log_importance_weights.unsqueeze(-1) + else: + raise ValueError( + f"Unknown importance sampling level: {self.importance_sampling_level}. Possible values are 'token' " + "and 'sequence'." + ) + # From here, log_importance_weights (and all subsequent tensors, coef_1, coef_2, etc.) shape depends on + # importance_sampling_level: "token" level: (B, T); "sequence" level: (B, 1) + + coef_1 = torch.exp(log_importance_weights) + coef_2 = torch.clamp(coef_1, 1 - self.epsilon_low, 1 + self.epsilon_high) + + # Two-sided clipping + if self.args.delta is not None: + coef_1 = torch.clamp(coef_1, max=self.args.delta) + + per_token_loss1 = coef_1 * advantages.unsqueeze(1) + per_token_loss2 = coef_2 * advantages.unsqueeze(1) + per_token_loss = -torch.min(per_token_loss1, per_token_loss2) + if entropy_mask is not None: + per_token_loss = per_token_loss * entropy_mask + if self.beta != 0.0: + per_token_loss = per_token_loss + self.beta * per_token_kl + + if self.loss_type == "grpo": + loss = ((per_token_loss * completion_mask).sum(-1) / completion_mask.sum(-1).clamp(min=1.0)).mean() + loss = loss / self.current_gradient_accumulation_steps + elif self.loss_type == "dapo": + normalizer = inputs["num_items_in_batch"] / self.accelerator.num_processes + loss = (per_token_loss * completion_mask).sum() / normalizer + else: + raise ValueError(f"Unknown loss type: {self.loss_type}") + # >>> 2. Implicit Perception Loss + inputs["pixel_values"] = self._mask_image(inputs["pixel_values"], self.mask_ratio) + mask_img_per_token_logps, mask_img_entropies = self._get_per_token_logps_and_entropies( + model, + input_ids, + attention_mask, + logits_to_keep, + compute_entropy=True, + pixel_values=inputs.get("pixel_values"), + image_grid_thw=inputs.get("image_grid_thw"), + num_images=inputs.get("num_images"), + pixel_attention_mask=inputs.get("pixel_attention_mask"), + image_sizes=inputs.get("image_sizes"), + ) + perception_kl = ( + torch.exp(mask_img_per_token_logps - per_token_logps) - (mask_img_per_token_logps - per_token_logps) - 1 + ) + perception_kl = torch.clamp(perception_kl, min=0.0, max=0.2) + perception_loss = self.perception_loss_weight * perception_kl + + # >>> 3. Double Entropy Loss + der_loss = self.der_loss_weight1 * entropies + self.der_loss_weight2 * mask_img_entropies + + # PAPO Loss + loss = (loss - perception_loss + der_loss).mean() + # Log the metrics + mode = "train" if self.model.training else "eval" + + completion_token_count = completion_mask.sum().clamp(min=1.0) + + def masked_batch_mean(x): + if x.shape[1] == 1: # when importance_sampling_level == "sequence" + return x.mean() + else: + return (x * completion_mask).sum() / completion_token_count + + if self.beta != 0.0: + mean_kl = masked_batch_mean(per_token_kl) + self._metrics[mode]["kl"].append(self.accelerator.gather(mean_kl).nanmean().item()) + + mean_entropy = masked_batch_mean(entropies) + self._metrics[mode]["entropy"].append(self.accelerator.gather(mean_entropy).nanmean().item()) + + # Compute the clipped probability ratios + is_low_clipped = (coef_1 < 1 - self.epsilon_low) & (advantages.unsqueeze(1) < 0) + is_high_clipped = (coef_1 > 1 + self.epsilon_high) & (advantages.unsqueeze(1) > 0) + is_region_clipped = is_low_clipped | is_high_clipped + + low_clip = masked_batch_mean(is_low_clipped.float()) + high_clip = masked_batch_mean(is_high_clipped.float()) + clip_ratio = masked_batch_mean(is_region_clipped.float()) + + gathered_low_clip = self.accelerator.gather(low_clip) + self._metrics[mode]["clip_ratio/low_mean"].append(gathered_low_clip.nanmean().item()) + self._metrics[mode]["clip_ratio/low_min"].append(nanmin(gathered_low_clip).item()) + gathered_high_clip = self.accelerator.gather(high_clip) + self._metrics[mode]["clip_ratio/high_mean"].append(gathered_high_clip.nanmean().item()) + self._metrics[mode]["clip_ratio/high_max"].append(nanmax(gathered_high_clip).item()) + gathered_clip_ratio = self.accelerator.gather(clip_ratio) + self._metrics[mode]["clip_ratio/region_mean"].append(gathered_clip_ratio.nanmean().item()) + return loss diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/ppo/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/ppo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..09451e973bea4ae1432fe16276907644cd67466c --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/ppo/__init__.py @@ -0,0 +1,30 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .modeling_value_head import ( + AutoModelForCausalLMWithValueHead, + AutoModelForSeq2SeqLMWithValueHead, + PreTrainedModelWrapper, +) +from .ppo_config import PPOConfig +from .ppo_trainer import PPOTrainer + + +__all__ = [ + "AutoModelForCausalLMWithValueHead", + "AutoModelForSeq2SeqLMWithValueHead", + "PreTrainedModelWrapper", + "PPOConfig", + "PPOTrainer", +] diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/ppo/modeling_value_head.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/ppo/modeling_value_head.py new file mode 100644 index 0000000000000000000000000000000000000000..eacd2045b1910b98107929842098725b7f73aab4 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/ppo/modeling_value_head.py @@ -0,0 +1,1020 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +import logging +import os + +import torch +import torch.nn as nn +from accelerate import PartialState +from huggingface_hub import hf_hub_download +from huggingface_hub.utils import ( + EntryNotFoundError, + HFValidationError, + LocalEntryNotFoundError, + RepositoryNotFoundError, +) +from safetensors.torch import load_file as safe_load_file +from transformers import ( + AutoModelForCausalLM, + AutoModelForSeq2SeqLM, + PreTrainedModel, + is_torch_npu_available, + is_torch_xpu_available, +) +from transformers.utils import is_peft_available + + +if is_peft_available(): + from peft import ( + PeftConfig, + PeftModel, + PeftModelForCausalLM, + PeftModelForSeq2SeqLM, + PromptLearningConfig, + get_peft_model, + prepare_model_for_kbit_training, + ) + + +class PreTrainedModelWrapper(nn.Module): + """ + Wrapper for a [`~transformers.PreTrainedModel`] implemented as a standard PyTorch [`torch.nn.Module`]. + + This class provides a compatibility layer that preserves the key attributes and methods of the original + [`~transformers.PreTrainedModel`], while exposing a uniform interface consistent with PyTorch modules. It enables + seamless integration of pretrained Transformer models into custom training, evaluation, or inference workflows. + + Attributes: + pretrained_model ([`~transformers.PreTrainedModel`]): + The model to be wrapped. + parent_class ([`~transformers.PreTrainedModel`]): + The parent class of the model to be wrapped. + supported_args (`list`): + The list of arguments that are supported by the wrapper class. + """ + + transformers_parent_class = None + supported_args = None + supported_modules = ("v_head",) + supported_rm_modules = ("score",) + supported_pretrained_model_architectures = ( + (PreTrainedModel) + if not is_peft_available() + else (PreTrainedModel, PeftModelForCausalLM, PeftModelForSeq2SeqLM) + ) + + def __init__( + self, pretrained_model=None, score_module=None, supports_rm_adapter=False, rm_adapter_name=None, **kwargs + ): + super().__init__() + self.pretrained_model = pretrained_model + + self.config = pretrained_model.config + self.prepare_inputs_for_generation = pretrained_model.prepare_inputs_for_generation + self.is_loaded_in_8bit = getattr(pretrained_model, "is_loaded_in_8bit", False) + self.is_loaded_in_4bit = getattr(pretrained_model, "is_loaded_in_4bit", False) + self.is_sequential_parallel = False + + if hasattr(pretrained_model, "gradient_checkpointing_disable"): + self.gradient_checkpointing_disable = pretrained_model.gradient_checkpointing_disable + + if hasattr(pretrained_model, "gradient_checkpointing_enable"): + self.gradient_checkpointing_enable = pretrained_model.gradient_checkpointing_enable + + if hasattr(pretrained_model, "enable_input_require_grads"): + self.enable_input_require_grads = pretrained_model.enable_input_require_grads + + self.supports_rm_adapter = supports_rm_adapter + self.rm_adapter_name = rm_adapter_name + self.policy_adapter_name = "default" + if score_module is not None: + self.score = score_module + + @classmethod + def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): + r""" + Instantiates a new model from a pretrained model from `transformers`. The pretrained model is loaded using the + `from_pretrained` method of the [`~transformers.PreTrainedModel`] class. The arguments that are specific to the + [`~transformers.PreTrainedModel`] class are passed along this method and filtered out from the `kwargs` + argument. + + Args: + pretrained_model_name_or_path (`str` or [`~transformers.PreTrainedModel`]): + The path to the pretrained model or its name. + *model_args (`list`, *optional*): + Additional positional arguments passed along to the underlying model's `from_pretrained` method. + **kwargs (`dict`, *optional*): + Additional keyword arguments passed along to the underlying model's `from_pretrained` method. We also + pre-process the kwargs to extract the arguments that are specific to the + [`~transformers.PreTrainedModel`] class and the arguments that are specific to trl models. The kwargs + also support `prepare_model_for_kbit_training` arguments from `peft` library. + """ + if kwargs is not None: + peft_config = kwargs.pop("peft_config", None) + reward_adapter = kwargs.pop("reward_adapter", None) + reward_adapter_name = kwargs.pop("reward_adapter_name", "reward_adapter") + is_trainable = kwargs.pop("is_trainable", False) + trl_model_args, pretrained_kwargs, peft_quantization_kwargs = cls._split_kwargs(kwargs) + token = pretrained_kwargs.get("token", None) + else: + peft_config = None + is_trainable = False + trl_model_args = {} + pretrained_kwargs = {} + peft_quantization_kwargs = {} + token = None + + if reward_adapter is not None and not isinstance(reward_adapter, str): + raise ValueError( + "The `reward_adapter` argument should be a string representing the name of local path or the Hub id to the Reward Modeling adapter." + ) + + is_peft_model = False + + current_device = cls._get_current_device() + if isinstance(pretrained_model_name_or_path, str): + quantization_config = pretrained_kwargs.get("quantization_config", None) + if quantization_config is not None: + is_loaded_in_8bit = getattr(quantization_config, "load_in_8bit", False) + is_loaded_in_4bit = getattr(quantization_config, "load_in_4bit", False) + else: + is_loaded_in_8bit = pretrained_kwargs["load_in_8bit"] if "load_in_8bit" in pretrained_kwargs else False + is_loaded_in_4bit = pretrained_kwargs["load_in_4bit"] if "load_in_4bit" in pretrained_kwargs else False + else: + is_loaded_in_8bit = getattr(pretrained_model_name_or_path, "is_loaded_in_8bit", False) + is_loaded_in_4bit = getattr(pretrained_model_name_or_path, "is_loaded_in_4bit", False) + + if (is_loaded_in_8bit or is_loaded_in_4bit) and "device_map" not in pretrained_kwargs: + # warn users + logging.warning( + "The `device_map` argument is not provided. We will override the device_map argument." + " to set the entire" + " model on the current device. If you want to set the model on multiple devices, please provide" + " a custom `device_map` argument." + ) + pretrained_kwargs["device_map"] = {"": current_device} + + if is_peft_available() and peft_config is not None and not isinstance(peft_config, PeftConfig): + raise ValueError("The `peft_config` argument should be an instance of `peft.PeftConfig` class.") + + # First, load the pre-trained model using the parent-class + # either `AutoModelForCausalLM` or `AutoModelForSeq2SeqLM` + if isinstance(pretrained_model_name_or_path, str): + if is_peft_available(): + try: + # If there is a trained peft adapter in the hub, load its config. + remote_adapter_config = hf_hub_download( + pretrained_model_name_or_path, + "adapter_config.json", + token=token, + ) + except (EntryNotFoundError, LocalEntryNotFoundError, HFValidationError, RepositoryNotFoundError): + remote_adapter_config = None + else: + remote_adapter_config = None + + local_adapter_present = os.path.exists(os.path.join(pretrained_model_name_or_path, "adapter_config.json")) + + if (local_adapter_present or remote_adapter_config is not None) and is_peft_available(): + if peft_config is not None: + logging.warning( + "`peft_config` argument ignored since a peft config file was found in " + f"{pretrained_model_name_or_path}" + ) + + # Load the trained peft adapter config + if local_adapter_present: + trained_adapter_config = PeftConfig.from_pretrained(pretrained_model_name_or_path) + else: + remote_adapter_dir = os.path.dirname(remote_adapter_config) + trained_adapter_config = PeftConfig.from_pretrained(remote_adapter_dir) + + # Load the pretrained base model + pretrained_model = cls.transformers_parent_class.from_pretrained( + trained_adapter_config.base_model_name_or_path, *model_args, **pretrained_kwargs + ) + + # Wrap the pretrained model with the trained peft adapter + pretrained_model = PeftModel.from_pretrained( + pretrained_model, pretrained_model_name_or_path, is_trainable=is_trainable, token=token + ) + logging.info("Trained peft adapter loaded") + else: + pretrained_model = cls.transformers_parent_class.from_pretrained( + pretrained_model_name_or_path, *model_args, **pretrained_kwargs + ) + + if peft_config is not None: + # Initialize a new peft adapter with the given config + if is_loaded_in_8bit or is_loaded_in_4bit: + pretrained_model = prepare_model_for_kbit_training( + pretrained_model, + **peft_quantization_kwargs, + ) + pretrained_model = get_peft_model(pretrained_model, peft_config) + logging.info("peft adapter initialised") + + elif isinstance(pretrained_model_name_or_path, cls.supported_pretrained_model_architectures): + pretrained_model = pretrained_model_name_or_path + + if peft_config is not None and isinstance(pretrained_model, PreTrainedModel): + # Initialize a new peft adapter with the given config + if is_loaded_in_8bit or is_loaded_in_4bit: + pretrained_model = prepare_model_for_kbit_training( + pretrained_model, + **peft_quantization_kwargs, + ) + pretrained_model = get_peft_model(pretrained_model, peft_config) + logging.info("peft adapter initialised") + else: + raise ValueError( + "pretrained_model_name_or_path should be a string or a PreTrainedModel, " + f"but is {type(pretrained_model_name_or_path)}" + ) + + if is_peft_available(): + if isinstance(pretrained_model, PeftModel): + is_peft_model = True + # for backward compatibility + if hasattr(pretrained_model, "active_peft_config") and isinstance( + pretrained_model.active_peft_config, PromptLearningConfig + ): + raise ValueError("PromptLearningConfig is not supported for PPO training.") + + # Add reward modeling adapter if specified + if not is_peft_model and reward_adapter is not None: + raise ValueError("reward_adapter can only be used with a PeftModel. ") + elif is_peft_model and reward_adapter is not None: + score_module = cls.add_and_load_reward_modeling_adapter( + pretrained_model, reward_adapter, reward_adapter_name, token=token + ) + multi_adapter_args = { + "score_module": score_module, + "supports_rm_adapter": True, + "rm_adapter_name": reward_adapter_name, + } + else: + multi_adapter_args = {"supports_rm_adapter": False} + + # Then, create the full model by instantiating the wrapper class + model = cls(pretrained_model, **multi_adapter_args, **trl_model_args) + + # if resume_training, load the state_dict again - this is ok since the + # state_dict is removed from the model after loading it. + is_resuming_training = True + if isinstance(pretrained_model_name_or_path, str): + safe_filename = os.path.join(pretrained_model_name_or_path, "model.safetensors") + filename = os.path.join(pretrained_model_name_or_path, "pytorch_model.bin") + + sharded_index_filename = os.path.join(pretrained_model_name_or_path, "pytorch_model.bin.index.json") + safe_sharded_index_filename = os.path.join(pretrained_model_name_or_path, "model.safetensors.index.json") + is_sharded = False + use_safe = os.path.exists(safe_filename) + + if not (os.path.exists(filename) or os.path.exists(safe_filename)): + # Try with `pytorch_model.bin` + filename, files_to_download, is_sharded, is_resuming_training = cls._get_checkpoint_from_hub( + pretrained_model, + pretrained_model_name_or_path, + sharded_index_filename, + token=token, + ) + # Try with safetensors + if filename is None and files_to_download is None: + safe_filename, files_to_download, is_sharded, is_resuming_training = cls._get_checkpoint_from_hub( + pretrained_model, + pretrained_model_name_or_path, + safe_sharded_index_filename, + token=token, + model_name="model.safetensors", + model_index_name="model.safetensors.index.json", + ) + use_safe = True + else: + use_safe = False + + loading_func = safe_load_file if use_safe else torch.load + load_kwargs = {} if use_safe else {"map_location": "cpu", "weights_only": True} + + if is_resuming_training: + if is_sharded: + # download each file and add it to the state_dict + state_dict = {} + + for shard_file in files_to_download: + filename = hf_hub_download( + pretrained_model_name_or_path, + shard_file, + token=token, + ) + state_dict.update(loading_func(filename, **load_kwargs)) + else: + state_dict = loading_func(filename if not use_safe else safe_filename, **load_kwargs) + + else: + state_dict = pretrained_model_name_or_path.state_dict() + + model.is_peft_model = is_peft_model + model.current_device = current_device + + if is_resuming_training: + model.post_init(state_dict=state_dict) + + return model + + @classmethod + def _get_checkpoint_from_hub( + cls, + pretrained_model, + pretrained_model_name_or_path, + index_filename, + token=None, + model_name="pytorch_model.bin", + model_index_name="pytorch_model.bin.index.json", + ): + files_to_download = None + filename = None + is_resuming_training = True + is_sharded = False + + try: + filename = hf_hub_download( + pretrained_model_name_or_path, + model_name, + token=token, + ) + # sharded + except (EntryNotFoundError, LocalEntryNotFoundError, HFValidationError, RepositoryNotFoundError): + if os.path.exists(index_filename): + index_file_name = index_filename + else: + try: + index_file_name = hf_hub_download( + pretrained_model_name_or_path, + model_index_name, + token=token, + ) + except (EntryNotFoundError, LocalEntryNotFoundError, HFValidationError, RepositoryNotFoundError): + # not continue training, do not have v_head weight + is_resuming_training = False + logging.warning( + f"A {type(pretrained_model)} model is loaded from '{pretrained_model_name_or_path}', " + f"and no v_head weight is found. This IS expected if you are not resuming PPO training." + ) + # load json + if is_resuming_training: + with open(index_file_name) as f: + index = json.load(f) + # check filename with `v_head` or any known extra module: + files_to_download = set() + for k, v in index["weight_map"].items(): + if any(module in k for module in cls.supported_modules): + files_to_download.add(v) + is_sharded = True + + return filename, files_to_download, is_sharded, is_resuming_training + + @classmethod + def _get_current_device(cls): + r""" + Get the current device. For GPU & XPU, we return the local process index using the `accelerate.PartialState` + object to handle corner cases when running scripts in distributed environments. + + Returns: + current_device (`int | str`): + The current device. + """ + state = PartialState() + if torch.cuda.is_available() or is_torch_xpu_available(): + return state.local_process_index + elif is_torch_npu_available(): + return f"npu:{state.local_process_index}" + else: + return "cpu" + + @classmethod + def _split_kwargs(cls, kwargs): + """ + Separate the kwargs from the arguments that we support inside `supported_args` and the ones that we don't. + """ + check_peft_kwargs = False + + if is_peft_available(): + from peft import prepare_model_for_kbit_training + + check_peft_kwargs = True + + supported_kwargs = {} + unsupported_kwargs = {} + peft_kwargs = {} + + for key, value in kwargs.items(): + if key in cls.supported_args: + supported_kwargs[key] = value + else: + unsupported_kwargs[key] = value + + if check_peft_kwargs: + if key in prepare_model_for_kbit_training.__code__.co_varnames: + peft_kwargs[key] = value + if key in unsupported_kwargs: + unsupported_kwargs.pop(key) + + return supported_kwargs, unsupported_kwargs, peft_kwargs + + @classmethod + def add_and_load_reward_modeling_adapter( + cls, pretrained_model, adapter_model_id, adapter_name="reward_model_adapter", token=None + ): + r""" + Add and load a reward modeling adapter. This method can only be used if the model is a `PeftModel` and if you + have initialized the model with the `reward_modeling_adapter_id` argument, pointing to the id of the reward + modeling adapter. The latest needs also to contain the score head in order to produce the reward. + """ + pretrained_model.load_adapter(adapter_model_id, adapter_name, is_trainable=False) + pretrained_model.train() + + filename = os.path.join(adapter_model_id, "adapter_model.bin") + safe_loading = False + if not os.path.exists(filename): + try: + local_filename = hf_hub_download( + adapter_model_id, + "adapter_model.bin", + token=token, + ) + except Exception: + filename = os.path.join(adapter_model_id, "adapter_model.safetensors") + safe_loading = True + if not os.path.exists(filename): + try: + local_filename = hf_hub_download( + adapter_model_id, + "adapter_model.safetensors", + token=token, + ) + except Exception as exc: + raise ValueError( + "Could not find adapter model in the Hub, make sure you have the correct adapter model id." + ) from exc + else: + local_filename = filename + else: + local_filename = filename + + loading_func = safe_load_file if safe_loading else torch.load + load_kwargs = {} if safe_loading else {"map_location": "cpu", "weights_only": True} + + adapter_state_dict = loading_func(local_filename, **load_kwargs) + + for score_name_candidate in cls.supported_rm_modules: + if any(score_name_candidate in name for name in adapter_state_dict.keys()): + score_name = score_name_candidate + # we have found the correct head name and can break + break + + score_dict = {} + + for name, param in adapter_state_dict.items(): + if score_name in name: + key_name = ".".join(name.split(".")[-1:]) + score_dict[key_name] = param.to(cls._get_current_device()) + + num_labels, hidden_dim = score_dict["weight"].shape + has_bias = any("bias" in name for name in adapter_state_dict.keys()) + + score = nn.Linear(hidden_dim, num_labels, bias=has_bias).to( + device=cls._get_current_device(), + dtype=pretrained_model.dtype, + ) + score.load_state_dict(score_dict) + for param in score.parameters(): + param.requires_grad = False + + return score + + def push_to_hub(self, *args, **kwargs): + r""" + Push the pretrained model to the hub. This method is a wrapper around + [`~transformers.PreTrainedModel.push_to_hub`]. Please refer to the documentation of + [`~transformers.PreTrainedModel.push_to_hub`] for more information. + + Args: + *args (`list`, *optional*): + Positional arguments passed along to the underlying model's `push_to_hub` method. + **kwargs (`dict`, *optional*): + Keyword arguments passed along to the underlying model's `push_to_hub` method. + """ + raise NotImplementedError + + def save_pretrained(self, *args, **kwargs): + r""" + Save the pretrained model to a directory. This method is a wrapper around + [`~transformers.PreTrainedModel.save_pretrained`]. Please refer to the documentation of + [`~transformers.PreTrainedModel.save_pretrained`] for more information. + + Args: + *args (`list`, *optional*): + Positional arguments passed along to the underlying model's `save_pretrained` method. + **kwargs (`dict`, *optional*): + Keyword arguments passed along to the underlying model's `save_pretrained` method. + """ + state_dict = kwargs.get("state_dict") + if state_dict is None: + state_dict = self.state_dict() + kwargs["state_dict"] = state_dict + + # if it is a peft model only save the `v_head` state_dict and + # pop the `state_dict` from the kwargs to avoid silent bugs with `peft` + if self.is_peft_model: + save_path = args[0] + save_path = os.path.join(save_path, "pytorch_model.bin") + torch.save(state_dict, save_path) + _ = kwargs.pop("state_dict", None) + + return self.pretrained_model.save_pretrained(*args, **kwargs) + + def state_dict(self, *args, **kwargs): + r""" + Return the state_dict of the pretrained model. + """ + raise NotImplementedError + + def post_init(self, *args, **kwargs): + r""" + Post initialization method. This method is called after the model is instantiated and loaded from a checkpoint. + It can be used to perform additional operations such as loading the state_dict. + """ + raise NotImplementedError + + def compute_reward_score(self, input_ids, attention_mask=None, **kwargs): + r""" + Computes the reward score for a given input. The method has first to enable the adapter and then compute the + reward score. After that the model disables the reward modeling adapter and enables the default ppo adapter + again. + """ + if not self.supports_rm_adapter: + raise ValueError("This model does not support reward modeling adapter.") + + # enable rm adapter + self.pretrained_model.set_adapter(self.rm_adapter_name) + self.pretrained_model.eval() + + with torch.no_grad(): + base_model_output = self.pretrained_model( + input_ids=input_ids, + attention_mask=attention_mask, + output_hidden_states=True, + return_dict=True, + **kwargs, + ) + + last_hidden_states = base_model_output.hidden_states[-1] + scores = self.score(last_hidden_states) + + self.pretrained_model.set_adapter(self.policy_adapter_name) + self.pretrained_model.eval() + + return scores + + +class ValueHead(nn.Module): + r""" + The ValueHead class implements a head for GPT2 that returns a scalar for each output token. + """ + + def __init__(self, config, **kwargs): + super().__init__() + if not hasattr(config, "summary_dropout_prob"): + summary_dropout_prob = kwargs.pop("summary_dropout_prob", 0.1) + else: + summary_dropout_prob = config.summary_dropout_prob + + self.dropout = nn.Dropout(summary_dropout_prob) if summary_dropout_prob else nn.Identity() + + # Determine hidden_size in priority order: + # 1. word_embed_proj_dim (OPT-350m): output projection dim, != internal hidden_size + # 2. hidden_size: standard attribute for most decoder-only and seq2seq models + # 3. text_config.hidden_size: multimodal configs (Gemma3, LLaVA,...) with no top-level hidden_size + # 4. decoder.hidden_size: EncoderDecoder compositions (e.g. BERT encoder + BERT decoder) + if hasattr(config, "word_embed_proj_dim"): + hidden_size = config.word_embed_proj_dim + elif hasattr(config, "hidden_size"): + hidden_size = config.hidden_size + elif hasattr(config, "text_config") and hasattr(config.text_config, "hidden_size"): + hidden_size = config.text_config.hidden_size + elif ( + getattr(config, "is_encoder_decoder", False) + and hasattr(config, "decoder") + and hasattr(config.decoder, "hidden_size") + ): + hidden_size = config.decoder.hidden_size + else: + raise ValueError( + "Cannot determine `hidden_size` from model config. " + "Please open an issue or pass a model whose config exposes one of: " + "`hidden_size`, `word_embed_proj_dim`, `text_config.hidden_size`, or `decoder.hidden_size`." + ) + self.summary = nn.Linear(hidden_size, 1) + + self.flatten = nn.Flatten() + + def forward(self, hidden_states): + output = self.dropout(hidden_states) + + # For now force upcast in fp32 if needed. Let's keep the + # output in fp32 for numerical stability. + if output.dtype != self.summary.weight.dtype: + output = output.to(self.summary.weight.dtype) + + output = self.summary(output) + return output + + +class AutoModelForCausalLMWithValueHead(PreTrainedModelWrapper): + """ + An autoregressive model with a value head in addition to the language model head. This class inherits from + [`experimental.ppo.PreTrainedModelWrapper`] and wraps a [`~transformers.PreTrainedModel`] class. The wrapper class + supports classic functions such as `from_pretrained`, `push_to_hub` and `generate`. To call a method of the wrapped + model, simply manipulate the `pretrained_model` attribute of this class. + + Class attributes: + - **transformers_parent_class** ([`~transformers.PreTrainedModel`]) -- The parent class of the wrapped model. + This + should be set to `transformers.AutoModelForCausalLM` for this class. + - **supported_args** (`tuple`) -- A tuple of strings that are used to identify the arguments that are supported + by the [`ValueHead`] class. Currently, the supported args are: + - **summary_dropout_prob** (`float`, `optional`, defaults to `None`) -- The dropout probability for the + [`ValueHead`] class. + - **v_head_initializer_range** (`float`, `optional`, defaults to `0.2`) -- The initializer range for the + [`ValueHead`] if a specific initialization strategy is selected. + - **v_head_init_strategy** (`str`, `optional`, defaults to `None`) -- The initialization strategy for the + [`ValueHead`]. Currently, the supported strategies are: + - **`None`** -- Initializes the weights of the [`ValueHead`] with a random distribution. This is the + default strategy. + - **"normal"** -- Initializes the weights of the [`ValueHead`] with a normal distribution. + """ + + transformers_parent_class = AutoModelForCausalLM + supported_args = ( + "summary_dropout_prob", + "v_head_initializer_range", + "v_head_init_strategy", + ) + + def __init__(self, pretrained_model, **kwargs): + """ + Initializes the model. + + Args: + pretrained_model ([`~transformers.PreTrainedModel`]): + The model to wrap. It should be a causal language model such as GPT2. or any model mapped inside the + `AutoModelForCausalLM` class. + kwargs (`dict`, `optional`): + Additional keyword arguments, that are passed to the [`ValueHead`] class. + """ + super().__init__(pretrained_model, **kwargs) + v_head_kwargs, _, _ = self._split_kwargs(kwargs) + self.v_head = ValueHead(self.pretrained_model.config, **v_head_kwargs) + self._init_weights(**v_head_kwargs) + + def _init_weights(self, **kwargs): + r""" + Initializes the weights of the value head. The default initialization strategy is random. Users can pass a + different initialization strategy by passing the `v_head_init_strategy` argument when calling + `.from_pretrained`. Supported strategies are: + - `normal`: initializes the weights with a normal distribution. + + Args: + **kwargs (`dict`, `optional`): + Additional keyword arguments, that are passed to the [`ValueHead`] class. These arguments can contain + the `v_head_init_strategy` argument as well as the `v_head_initializer_range` argument. + """ + initializer_range = kwargs.pop("v_head_initializer_range", 0.2) + # random init by default + init_strategy = kwargs.pop("v_head_init_strategy", None) + if init_strategy is None: + # do nothing + pass + elif init_strategy == "normal": + self.v_head.summary.weight.data.normal_(mean=0.0, std=initializer_range) + self.v_head.summary.bias.data.zero_() + + def forward( + self, + input_ids=None, + past_key_values=None, + attention_mask=None, + return_past_key_values=False, + **kwargs, + ): + r""" + Applies a forward pass to the wrapped model and returns the logits of the value head. + + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. + past_key_values (`tuple(tuple(torch.FloatTensor))`, `optional`): + Contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model + (see `past_key_values` input) to speed up sequential decoding. + attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, `optional`): + Mask to avoid performing attention on padding token indices. Mask values selected in ``[0, 1]``: + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + return_past_key_values (bool): A flag indicating if the computed hidden-states should be returned. + kwargs (`dict`, `optional`): + Additional keyword arguments, that are passed to the wrapped model. + """ + kwargs["output_hidden_states"] = True # this had already been set in the LORA / PEFT examples + kwargs["past_key_values"] = past_key_values + + if self.is_peft_model and self.pretrained_model.active_peft_config.peft_type == "PREFIX_TUNING": + kwargs.pop("past_key_values") + + base_model_output = self.pretrained_model( + input_ids=input_ids, + attention_mask=attention_mask, + **kwargs, + ) + + last_hidden_state = base_model_output.hidden_states[-1] + lm_logits = base_model_output.logits + loss = base_model_output.loss + + if last_hidden_state.device != self.v_head.summary.weight.device: + last_hidden_state = last_hidden_state.to(self.v_head.summary.weight.device) + + value = self.v_head(last_hidden_state).squeeze(-1) + + # force upcast in fp32 if logits are in half-precision + if lm_logits.dtype != torch.float32: + lm_logits = lm_logits.float() + + if return_past_key_values: + return (lm_logits, loss, value, base_model_output.past_key_values) + else: + return (lm_logits, loss, value) + + def generate(self, *args, **kwargs): + r""" + A simple wrapper around the `generate` method of the wrapped model. Please refer to the + [`generate`](https://huggingface.co/docs/transformers/internal/generation_utils) method of the wrapped model + for more information about the supported arguments. + + Args: + *args (`list`, *optional*): + Positional arguments passed to the `generate` method of the wrapped model. + **kwargs (`dict`, *optional*): + Keyword arguments passed to the `generate` method of the wrapped model. + """ + return self.pretrained_model.generate(*args, **kwargs) + + def state_dict(self, *args, **kwargs): + r""" + Returns the state dictionary of the model. We add the state dictionary of the value head to the state + dictionary of the wrapped model by prepending the key with `v_head.`. + """ + if not self.is_peft_model: + pretrained_model_state_dict = self.pretrained_model.state_dict(*args, **kwargs) + else: + # if it is a peft model, only save the v_head + pretrained_model_state_dict = {} + + v_head_state_dict = self.v_head.state_dict(*args, **kwargs) + for k, v in v_head_state_dict.items(): + pretrained_model_state_dict[f"v_head.{k}"] = v + return pretrained_model_state_dict + + def push_to_hub(self, *args, **kwargs): + self.pretrained_model.v_head = self.v_head + + return self.pretrained_model.push_to_hub(*args, **kwargs) + + def post_init(self, state_dict): + r""" + We add the state dictionary of the value head to the state dictionary of the wrapped model by prepending the + key with `v_head.`. This function removes the `v_head.` prefix from the keys of the value head state + dictionary. + """ + for k in list(state_dict.keys()): + if "v_head." in k: + state_dict[k.replace("v_head.", "")] = state_dict.pop(k) + self.v_head.load_state_dict(state_dict, strict=False) + del state_dict + + if hasattr(self.pretrained_model, "hf_device_map"): + if ( + "cpu" in self.pretrained_model.hf_device_map.values() + or "disk" in self.pretrained_model.hf_device_map.values() + ): + raise ValueError( + "The model is offloaded on CPU or disk - CPU & disk offloading is not supported for ValueHead models." + ) + + first_device = list(set(self.pretrained_model.hf_device_map.values()))[0] + if isinstance(first_device, int): + if is_torch_npu_available(): + first_device = f"npu:{first_device}" + elif is_torch_xpu_available(): + first_device = f"xpu:{first_device}" + else: + first_device = f"cuda:{first_device}" + self.v_head = self.v_head.to(first_device) + + def set_device_hook(module, input, outputs): + new_output = () + for output in outputs: + if isinstance(output, torch.Tensor): + new_output += (output.to(first_device),) + else: + new_output += (output,) + return new_output + + self.register_forward_hook(set_device_hook) + + self.is_sequential_parallel = True + + +class AutoModelForSeq2SeqLMWithValueHead(PreTrainedModelWrapper): + """ + A seq2seq model with a value head in addition to the language model head. This class inherits from + [`experimental.ppo.PreTrainedModelWrapper`] and wraps a [`~transformers.PreTrainedModel`] class. The wrapper class + supports classic functions such as `from_pretrained` and `push_to_hub` and also provides some additional + functionalities such as `generate`. + + Args: + pretrained_model ([`~transformers.PreTrainedModel`]): + The model to wrap. It should be a causal language model such as GPT2. or any model mapped inside the + [`~transformers.AutoModelForSeq2SeqLM`] class. + kwargs: + Additional keyword arguments passed along to the [`ValueHead`] class. + """ + + transformers_parent_class = AutoModelForSeq2SeqLM + lm_head_namings = ["lm_head", "embed_out", "output_projection"] + supported_args = ( + "summary_dropout_prob", + "v_head_initializer_range", + "v_head_init_strategy", + ) + + def __init__(self, pretrained_model, **kwargs): + super().__init__(pretrained_model, **kwargs) + v_head_kwargs, _, _ = self._split_kwargs(kwargs) + self.is_encoder_decoder = True + + if not self._has_lm_head(): + raise ValueError("The model does not have a language model head, please use a model that has one.") + + self.v_head = ValueHead(self.pretrained_model.config, **v_head_kwargs) + + self._init_weights(**v_head_kwargs) + + def _has_lm_head(self): + # check module names of all modules inside `pretrained_model` to find the language model head + for name, _module in self.pretrained_model.named_modules(): + if any(attribute in name for attribute in self.lm_head_namings): + return True + return False + + def post_init(self, state_dict): + r""" + We add the state dictionary of the value head to the state dictionary of the wrapped model by prepending the + key with `v_head.`. This function removes the `v_head.` prefix from the keys of the value head state + dictionary. + """ + for k in list(state_dict.keys()): + if "v_head." in k: + state_dict[k.replace("v_head.", "")] = state_dict.pop(k) + self.v_head.load_state_dict(state_dict, strict=False) + del state_dict + + if hasattr(self.pretrained_model, "hf_device_map"): + if ( + "cpu" in self.pretrained_model.hf_device_map.values() + or "disk" in self.pretrained_model.hf_device_map.values() + ): + raise ValueError( + "The model is offloaded on CPU or disk - CPU & disk offloading is not supported for ValueHead models." + ) + + # get the lm_head device + for name, module in self.pretrained_model.named_modules(): + if any(attribute in name for attribute in self.lm_head_namings): + lm_head_device = module.weight.device + break + + # put v_head on the same device as the lm_head to avoid issues + self.v_head = self.v_head.to(lm_head_device) + + def set_device_hook(module, input, outputs): + r""" + A hook that sets the device of the output of the model to the device of the first parameter of the + model. + + Args: + module (`nn.Module`): + The module to which the hook is attached. + input (`tuple`): + The input to the module. + outputs (`tuple`): + The output of the module. + """ + new_output = () + for output in outputs: + if isinstance(output, torch.Tensor): + new_output += (output.to(lm_head_device),) + else: + new_output += (output,) + return new_output + + self.register_forward_hook(set_device_hook) + self.is_sequential_parallel = True + + def state_dict(self, *args, **kwargs): + r""" + Returns the state dictionary of the model. We add the state dictionary of the value head to the state + dictionary of the wrapped model by prepending the key with `v_head.`. + """ + if not self.is_peft_model: + pretrained_model_state_dict = self.pretrained_model.state_dict(*args, **kwargs) + else: + # if it is a peft model, only save the v_head + pretrained_model_state_dict = {} + + v_head_state_dict = self.v_head.state_dict(*args, **kwargs) + for k, v in v_head_state_dict.items(): + pretrained_model_state_dict[f"v_head.{k}"] = v + return pretrained_model_state_dict + + def push_to_hub(self, *args, **kwargs): + self.pretrained_model.v_head = self.v_head + + return self.pretrained_model.push_to_hub(*args, **kwargs) + + def _init_weights(self, **kwargs): + r""" + We initialize the weights of the value head. + """ + initializer_range = kwargs.pop("v_head_initializer_range", 0.2) + # random init by default + init_strategy = kwargs.pop("v_head_init_strategy", None) + if init_strategy is None: + # do nothing + pass + elif init_strategy == "normal": + self.v_head.summary.weight.data.normal_(mean=0.0, std=initializer_range) + self.v_head.summary.bias.data.zero_() + + def forward( + self, + input_ids=None, + past_key_values=None, + attention_mask=None, + return_past_key_values=False, + **kwargs, + ): + kwargs["past_key_values"] = past_key_values + if self.is_peft_model and self.pretrained_model.active_peft_config.peft_type == "PREFIX_TUNING": + kwargs.pop("past_key_values") + + base_model_output = self.pretrained_model( + input_ids=input_ids, + attention_mask=attention_mask, + output_hidden_states=True, # We force the model to output hidden states + **kwargs, + ) + + last_hidden_state = base_model_output.decoder_hidden_states[-1] + lm_logits = base_model_output.logits + loss = base_model_output.loss + + value = self.v_head(last_hidden_state).squeeze(-1) + + # force upcast in fp32 if logits are in half-precision + if lm_logits.dtype != torch.float32: + lm_logits = lm_logits.float() + + if return_past_key_values: + return (lm_logits, loss, value, base_model_output.past_key_values) + else: + return (lm_logits, loss, value) + + def generate(self, *args, **kwargs): + r""" + We call `generate` on the wrapped model. + """ + return self.pretrained_model.generate(*args, **kwargs) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/ppo/ppo_config.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/ppo/ppo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..b96ee394734982fd82cf6ba2ae87bc6ca7be206f --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/ppo/ppo_config.py @@ -0,0 +1,280 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field +from typing import Literal + +from ...trainer.base_config import _BaseConfig + + +@dataclass +class PPOConfig(_BaseConfig): + # docstyle-ignore + r""" + Configuration class for the [`experimental.ppo.PPOTrainer`]. + + This class includes only the parameters that are specific to PPO 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: + dataset_num_proc (`int`, *optional*): + Number of processes to use for processing the dataset. + num_mini_batches (`int`, *optional*, defaults to `1`): + Number of minibatches to split a batch into. + total_episodes (`int`, *optional*): + Total number of episodes in the dataset. + local_rollout_forward_batch_size (`int`, *optional*, defaults to `64`): + Per rank no grad forward pass in the rollout phase. + num_sample_generations (`int`, *optional*, defaults to `10`): + Number of debugging samples generations (i.e., `generate_completions` calls) throughout training. + response_length (`int`, *optional*, defaults to `53`): + Length of the response. + stop_token (`str`, *optional*): + Specifies the stop token to use for text generation. This parameter is mutually exclusive with + `stop_token_id`. + + - `None`: No stop token is applied, unless `stop_token_id` is specified. + - `'eos'`: Uses the tokenizer's `eos_token`. + + stop_token_id (`int`, *optional*): + Specifies the ID of the stop token to use for text generation. If `None`, no stop token ID is applied, + unless `stop_token` is specified. This parameter is mutually exclusive with `stop_token`. + temperature (`float`, *optional*, defaults to `0.7`): + Sampling temperature. + missing_eos_penalty (`float`, *optional*): + Penalty applied to the score when the model fails to generate an EOS token. This is useful to encourage to + generate completions shorter than the maximum length (`max_new_tokens`). The penalty must be a positive + value. + sft_model_path (`str`, *optional*, defaults to `"EleutherAI/pythia-160m"`): + Path to the SFT model. + world_size (`int`, *optional*): + Number of processes (GPUs) to use for the training. + num_total_batches (`int`, *optional*): + Number of total batches to train. + micro_batch_size (`int`, *optional*): + Micro batch size across devices (HF's `per_device_train_batch_size` * `world_size`). + local_batch_size (`int`, *optional*): + Batch size per GPU (HF's `per_device_train_batch_size` * `gradient_accumulation_steps`). + batch_size (`int`, *optional*): + Batch size across devices (HF's `per_device_train_batch_size` * `world_size` * + `gradient_accumulation_steps`). + local_mini_batch_size (`int`, *optional*): + Mini batch size per GPU. + mini_batch_size (`int`, *optional*): + Mini batch size across GPUs. + push_to_hub (`bool`, *optional*, defaults to `False`): + Whether to push the model to the Hub after training. + reward_model_path (`str`, *optional*, defaults to `"EleutherAI/pythia-160m"`): + Path to the reward model. + model_adapter_name (`str`, *optional*): + Name of the train target PEFT adapter, when using LoRA with multiple adapters. + ref_adapter_name (`str`, *optional*): + Name of the reference PEFT adapter, when using LoRA with multiple adapters. + num_ppo_epochs (`int`, *optional*, defaults to `4`): + Number of epochs to train. + whiten_rewards (`bool`, *optional*, defaults to `False`): + Whether to whiten the rewards. + kl_coef (`float`, *optional*, defaults to `0.05`): + KL coefficient. + kl_estimator (`Literal["k1", "k3"]`, *optional*, defaults to `"k1"`): + Which estimator for KL-Divergence to use from [Approximating KL + Divergence](http://joschu.net/blog/kl-approx.html). Defaults to "k1", a straightforward, unbiased + estimator. Can be set to "k3", an unbiased estimator with lower variance which "appears to be a strictly + better estimator". Cannot be set to "k2", as it is used for logging purposes. + cliprange (`float`, *optional*, defaults to `0.2`): + Clip range. + vf_coef (`float`, *optional*, defaults to `0.1`): + Value function coefficient. + cliprange_value (`float`, *optional*, defaults to `0.2`): + Clip range for the value function. + gamma (`float`, *optional*, defaults to `1.0`): + Discount factor. + lam (`float`, *optional*, defaults to `0.95`): + Lambda value for GAE. + 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. + + > [!NOTE] + > These parameters have default values different from [`~transformers.TrainingArguments`]: + > - `logging_steps`: Defaults to `10` instead of `500`. + > - `gradient_checkpointing`: Defaults to `True` instead of `False`. + > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`. + > - `learning_rate`: Defaults to `3e-6` instead of `5e-5`. + """ + + # Parameters whose default values are overridden from TrainingArguments + learning_rate: float = field( + default=3e-6, + metadata={"help": "The initial learning rate for AdamW."}, + ) + + dataset_num_proc: int | None = field( + default=None, + metadata={"help": "Number of processes to use for processing the dataset."}, + ) + num_mini_batches: int = field( + default=1, + metadata={"help": "Number of minibatches to split a batch into."}, + ) + total_episodes: int | None = field( + default=None, + metadata={"help": "Total number of episodes in the dataset."}, + ) + local_rollout_forward_batch_size: int = field( + default=64, + metadata={"help": "Per rank no grad forward pass in the rollout phase."}, + ) + num_sample_generations: int = field( + default=10, + metadata={ + "help": "Number of debugging samples generations (i.e., `generate_completions` calls) throughout training." + }, + ) + response_length: int = field( + default=53, + metadata={"help": "Length of the response."}, + ) + stop_token: Literal["eos"] | None = field( + default=None, + metadata={ + "help": "Specifies the stop token to use for text generation. This parameter is mutually exclusive with " + "`stop_token_id`." + }, + ) + stop_token_id: int | None = field( + default=None, + metadata={ + "help": "Specifies the ID of the stop token to use for text generation. If `None`, no stop token ID is " + "applied, unless `stop_token` is specified. This parameter is mutually exclusive with `stop_token`." + }, + ) + temperature: float = field( + default=0.7, + metadata={"help": "Sampling temperature."}, + ) + missing_eos_penalty: float | None = field( + default=None, + metadata={ + "help": "Penalty applied to the score when the model fails to generate an EOS token. This is useful to " + "encourage to generate completions shorter than the maximum length (`max_new_tokens`). The penalty must be " + "a positive value." + }, + ) + sft_model_path: str = field( + default="EleutherAI/pythia-160m", + metadata={"help": "Path to the SFT model."}, + ) + world_size: int | None = field( + default=None, + metadata={"help": "Number of processes (GPUs) to use for the training."}, + ) + num_total_batches: int | None = field( + default=None, + metadata={"help": "Number of total batches to train."}, + ) + micro_batch_size: int | None = field( + default=None, + metadata={"help": "Micro batch size across devices (HF's `per_device_train_batch_size` * `world_size`)."}, + ) + local_batch_size: int | None = field( + default=None, + metadata={"help": "Batch size per GPU (HF's `per_device_train_batch_size` * `gradient_accumulation_steps`)."}, + ) + batch_size: int | None = field( + default=None, + metadata={ + "help": "Batch size across devices (HF's `per_device_train_batch_size` * `world_size` * " + "`gradient_accumulation_steps`)." + }, + ) + local_mini_batch_size: int | None = field( + default=None, + metadata={"help": "Mini batch size per GPU."}, + ) + mini_batch_size: int | None = field( + default=None, + metadata={"help": "Mini batch size across GPUs."}, + ) + push_to_hub: bool = field( + default=False, + metadata={"help": "Whether to push the model to the Hub after training."}, + ) + reward_model_path: str = field( + default="EleutherAI/pythia-160m", + metadata={"help": "Path to the reward model."}, + ) + model_adapter_name: str | None = field( + default=None, + metadata={"help": "Name of the train target PEFT adapter, when using LoRA with multiple adapters."}, + ) + ref_adapter_name: str | None = field( + default=None, + metadata={"help": "Name of the reference PEFT adapter, when using LoRA with multiple adapters."}, + ) + num_ppo_epochs: int = field( + default=4, + metadata={"help": "Number of epochs to train."}, + ) + whiten_rewards: bool = field( + default=False, + metadata={"help": "Whether to whiten the rewards."}, + ) + kl_coef: float = field( + default=0.05, + metadata={"help": "KL coefficient."}, + ) + kl_estimator: Literal["k1", "k3"] = field( + default="k1", + metadata={ + "help": "Which estimator for KL-Divergence to use from Approximating KL Divergence " + "(http://joschu.net/blog/kl-approx.html). Defaults to 'k1', a straightforward, unbiased estimator. Can be " + "set to 'k3', an unbiased estimator with lower variance which 'appears to be a strictly better " + "estimator'. Cannot be set to 'k2', as it is used for logging purposes." + }, + ) + cliprange: float = field( + default=0.2, + metadata={"help": "Clip range."}, + ) + vf_coef: float = field( + default=0.1, + metadata={"help": "Value function coefficient."}, + ) + cliprange_value: float = field( + default=0.2, + metadata={"help": "Clip range for the value function."}, + ) + gamma: float = field( + default=1.0, + metadata={"help": "Discount factor."}, + ) + lam: float = field( + default=0.95, + metadata={"help": "Lambda value for GAE."}, + ) + ds3_gather_for_generation: bool = field( + default=True, + metadata={ + "help": "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." + }, + ) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/ppo/ppo_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/ppo/ppo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..0d3e32f0a4639236d51ec63fd696ba83467742b0 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/ppo/ppo_trainer.py @@ -0,0 +1,1037 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import gc +import math +import os +import textwrap +import time +from collections import defaultdict +from contextlib import contextmanager, nullcontext +from dataclasses import dataclass +from pathlib import Path + +import numpy as np +import pandas as pd +import torch +import torch.nn as nn +import transformers +from accelerate import Accelerator, logging +from accelerate.utils import gather_object +from datasets import Dataset +from packaging.version import Version +from torch.utils.data import DataLoader +from transformers import ( + BaseImageProcessor, + DataCollatorWithPadding, + FeatureExtractionMixin, + GenerationConfig, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, + TrainerControl, + TrainerState, +) +from transformers.integrations import get_reporting_integration_callbacks +from transformers.trainer import DEFAULT_CALLBACKS, DEFAULT_PROGRESS_CALLBACK +from transformers.trainer_callback import CallbackHandler, ExportableState, PrinterCallback +from transformers.utils import ModelOutput, is_peft_available, is_rich_available + +from ...models.utils import prepare_deepspeed, unwrap_model_for_generation +from ...trainer.base_trainer import _BaseTrainer +from ...trainer.utils import ( + disable_dropout_in_model, + log_table_to_comet_experiment, + pad, + selective_log_softmax, +) +from ..utils import ( + create_reference_model, + empty_cache, + first_true_indices, + get_reward, + peft_module_casting_to_bf16, +) +from .ppo_config import PPOConfig + + +if is_rich_available(): + from rich.console import Console + from rich.table import Table + + +logger = logging.get_logger(__name__) + +if is_peft_available(): + from peft import PeftConfig, PeftModel, get_peft_model + + +INVALID_LOGPROB = 1.0 + + +def generate( + lm_backbone: torch.nn.Module, queries: torch.Tensor, pad_token_id: int, generation_config: GenerationConfig +) -> tuple[torch.Tensor, torch.Tensor]: + """ + Generates sequences from the language model backbone in a way that does not affect padding tokens. + + Args: + lm_backbone (`torch.nn.Module`): + The language model backbone used for generation. + queries (`torch.Tensor`): + The tensor containing the input queries. + pad_token_id (`int`): + The token ID representing the pad token. + generation_config ([`~transformers.GenerationConfig`]): + The configuration for the generation process. + + Returns: + tuple: + - `generated_sequences` (`torch.Tensor`): + The concatenated tensor of input queries and generated sequences. + - `logits` (`torch.Tensor`): + The logits output from the generation process. + """ + context_length = queries.shape[1] + attention_mask = queries != pad_token_id + input_ids = torch.masked_fill(queries, ~attention_mask, 0) + output = lm_backbone.generate( + input_ids=input_ids, + attention_mask=attention_mask, + # position_ids=attention_mask.cumsum(1) - attention_mask.long(), # not needed: already adjusted in generations + # https://github.com/huggingface/transformers/blob/ac33aeeeee2a7a89b89c93c2962e6feb90daef0a/src/transformers/models/gpt2/modeling_gpt2.py#L1227-L1250 + generation_config=generation_config, + return_dict_in_generate=True, + output_scores=True, + ) + logits = torch.stack(output.scores, 1) + return torch.cat((queries, output.sequences[:, context_length:]), dim=1), logits + + +@torch.no_grad() +def batch_generation( + model: torch.nn.Module, + queries: torch.Tensor, + local_rollout_forward_batch_size: int, + pad_token_id: int, + generation_config: GenerationConfig, +): + query_responses = [] + logitss = [] + batch_size = queries.shape[0] + for i in range(0, batch_size, local_rollout_forward_batch_size): + query = queries[i : i + local_rollout_forward_batch_size] + query_response, logits = generate( + model, + query, + pad_token_id, + generation_config, + ) + query_responses.append(query_response) + logitss.append(logits) + + # padding tensors + padded_query_responses = pad(query_responses, padding_value=pad_token_id, padding_side="right") + padded_logitss = pad(logitss, padding_value=0, padding_side="right") + + # reshaping + padded_query_responses = padded_query_responses.view(-1, padded_query_responses.shape[-1])[:batch_size] + padded_logitss = padded_logitss.view(-1, *padded_logitss.shape[2:])[:batch_size] + + return padded_query_responses, padded_logitss + + +def exact_div(a, b, custom_error_message=""): + q = a // b + if a != q * b: + raise ValueError(f"{custom_error_message}, inexact division: {a} / {b} = {a / b}") + return q + + +def print_rich_table(df: pd.DataFrame) -> None: + if not is_rich_available(): + raise ImportError( + "The function `print_rich_table` requires the `rich` library. Please install it with `pip install rich`." + ) + console = Console() + table = Table(show_lines=True) + for column in df.columns: + table.add_column(column) + for _, row in df.iterrows(): + table.add_row(*row.astype(str).tolist()) + console.print(table) + + +def truncate_response(stop_token_id: int, pad_token_id: int, responses: torch.Tensor) -> torch.Tensor: + """ + Truncates the responses at the first occurrence of the stop token, filling the rest with pad tokens. + + Args: + stop_token_id (`int`): + The token ID representing the stop token where truncation occurs. + pad_token_id (`int`): + The token ID representing the pad token used to fill the truncated responses. + responses (`torch.Tensor`): + The tensor containing the responses to be truncated. + + Returns: + `torch.Tensor`: + The truncated responses tensor with pad tokens filled after the stop token. + """ + trunc_idxs = first_true_indices(responses == stop_token_id).unsqueeze(-1) + new_size = [1] * (len(responses.size()) - 1) + [responses.shape[1]] + idxs = torch.arange(responses.shape[1], device=responses.device).view(*new_size) + postprocessed_responses = torch.masked_fill(responses, idxs > trunc_idxs, pad_token_id) + return postprocessed_responses + + +def forward( + model: torch.nn.Module, + query_responses: torch.Tensor, + pad_token_id: int, +) -> ModelOutput: + """ + Performs a forward pass through the model with the given query responses and pad token ID. + + Args: + model (`torch.nn.Module`): + The model to perform the forward pass. + query_responses (`torch.Tensor`): + The tensor containing the query responses. + pad_token_id (`int`): + The token ID representing the pad token. + + Returns: + `ModelOutput`: + The output of the model, including hidden states. + """ + attention_mask = query_responses != pad_token_id + position_ids = attention_mask.cumsum(1) - attention_mask.long() + input_ids = torch.masked_fill(query_responses, ~attention_mask, 0) + return model( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + return_dict=True, + output_hidden_states=True, + ) + + +@dataclass +class OnlineTrainerState(TrainerState): + """ + Training state for online/on-policy trainers. + + Extends [`~transformers.TrainerState`] with an `episode` counter to track the current rollout/episode. + + Args: + episode (`int`, defaults to 0): Zero-based episode index. + """ + + episode: int = 0 + + +def masked_mean(values: torch.Tensor, mask: torch.Tensor, axis: bool | None = None) -> torch.Tensor: + """Compute mean of tensor with a masked values.""" + if axis is not None: + return (values * mask).sum(axis=axis) / mask.sum(axis=axis) + else: + return (values * mask).sum() / mask.sum() + + +def masked_var(values: torch.Tensor, mask: torch.Tensor, unbiased: bool = True) -> torch.Tensor: + """Compute variance of tensor with masked values.""" + mean = masked_mean(values, mask) + centered_values = values - mean + variance = masked_mean(centered_values**2, mask) + if unbiased: + mask_sum = mask.sum() + if mask_sum == 0: + raise ValueError( + "The sum of the mask is zero, which can happen when `mini_batch_size=1`;" + "try increase the `mini_batch_size` or `gradient_accumulation_steps`" + ) + # note that if mask_sum == 1, then there is a division by zero issue + # to avoid it you just need to use a larger minibatch_size + bessel_correction = mask_sum / (mask_sum - 1) + variance = variance * bessel_correction + return variance + + +def masked_whiten(values: torch.Tensor, mask: torch.Tensor, shift_mean: bool = True) -> torch.Tensor: + """Whiten values with masked values.""" + mean, var = masked_mean(values, mask), masked_var(values, mask) + whitened = (values - mean) * torch.rsqrt(var + 1e-8) + if not shift_mean: + whitened += mean + return whitened + + +# taken from https://github.com/OpenLMLab/MOSS-RLHF/blob/40b91eb2f2b71b16919addede0341d2bef70825d/ppo/ppo_trainer.py#L29 +# we did this we can do a single `model = accelerator.prepare(model)` +class PolicyAndValueWrapper(nn.Module): + def __init__(self, policy, value_model) -> None: + super().__init__() + self.policy = policy + self.value_model = value_model + self.critic_backbone = getattr(value_model, value_model.base_model_prefix) + self.is_gradient_checkpointing = policy.is_gradient_checkpointing + + def gradient_checkpointing_enable(self, **kwargs): + self.policy.gradient_checkpointing_enable(**kwargs) + self.is_gradient_checkpointing = True + + def gradient_checkpointing_disable(self): + self.policy.gradient_checkpointing_disable() + self.is_gradient_checkpointing = False + + def forward(self, **kwargs): + output = self.critic_backbone(**kwargs) + logits = self.value_model.score(output.hidden_states[-1]) + return self.policy(**kwargs), logits + + +class PPOTrainer(_BaseTrainer): + """Trainer for Proximal Policy Optimization (PPO). + + For details on PPO, see the paper: [Proximal Policy Optimization + Algorithms](https://huggingface.co/papers/1707.06347). + + Args: + args ([`experimental.ppo.PPOConfig`]): + Training arguments. + processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`]): + Class to process the data. + model (`torch.nn.Module`): + Model to be trained. This is the policy model. + ref_model (`torch.nn.Module`, *optional*): + Reference model used to compute the KL divergence. If `None`, a copy of the policy model is created. + reward_model (`torch.nn.Module`): + Reward model used to compute the rewards. + train_dataset ([`~datasets.Dataset`]): + Dataset for training. + value_model (`torch.nn.Module`): + Value model used to predict the value of a state. + data_collator ([`~transformers.DataCollatorWithPadding`], *optional*): + Data collator to batch and pad samples from the dataset. If `None`, a default data collator is created + using the `processing_class`. + eval_dataset ([`~datasets.Dataset`] or `dict` of [`~datasets.Dataset`], *optional*): + Dataset for evaluation. + optimizers (`tuple` of `torch.optim.Optimizer` and `torch.optim.lr_scheduler.LambdaLR`, *optional*, defaults to `(None, None)`): + Tuple containing the optimizer and the learning rate scheduler to use for training. If `None`, the + optimizer and the learning rate scheduler are created using the + [`~transformers.Trainer.create_optimizer_and_scheduler`] method. + callbacks (`list` of [`~transformers.TrainerCallback`], *optional*): + Callbacks to use during training. + peft_config ([`~peft.PeftConfig`], *optional*): + PEFT configuration to use PEFT for training. If `None`, PEFT is not used. If provided, the policy `model` + will be wrapped with the specified PEFT adapter. + """ + + _tag_names = ["trl", "ppo"] + _name = "PPO" + _paper = { + "title": "Fine-Tuning Language Models from Human Preferences", + "id": "1909.08593", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @article{mziegler2019fine-tuning, + title = {{Fine-Tuning Language Models from Human Preferences}}, + author = {Daniel M. Ziegler and Nisan Stiennon and Jeffrey Wu and Tom B. Brown and Alec Radford and Dario Amodei and Paul F. Christiano and Geoffrey Irving}, + year = 2019, + eprint = {arXiv:1909.08593} + }"""), + } + + def __init__( + self, + args: PPOConfig, + processing_class: PreTrainedTokenizerBase | BaseImageProcessor | FeatureExtractionMixin | ProcessorMixin, + model: nn.Module, + ref_model: nn.Module | None, + reward_model: nn.Module, + train_dataset: Dataset, + value_model: nn.Module, + data_collator: DataCollatorWithPadding | None = None, + eval_dataset: Dataset | dict[str, Dataset] | None = None, + # less commonly used + optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + callbacks: list[TrainerCallback] | None = None, + peft_config: "PeftConfig | None" = None, + ) -> None: + if train_dataset is None: + raise ValueError("`train_dataset` is required") + + if ref_model is model: + raise ValueError( + "`model` and `ref_model` cannot be the same object. If you want `ref_model` to be the " + "same as `model`, you must make a copy of it, or `None` if you use peft." + ) + + self.args = args + self.processing_class = processing_class + self.policy_model = model + + # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was + # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream + # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we + # default to the recommended non-reentrant behavior here, while preserving any user-provided value. + if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"): + args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {} + args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False) + + # Define the collator if not provided + if data_collator is None: + data_collator = DataCollatorWithPadding(self.processing_class) + + # Handle stop token settings: update policy model's generation_config to use provided stop token + if args.stop_token and args.stop_token_id: + raise ValueError("You cannot set both `stop_token` and `stop_token_id`.") + elif args.stop_token: + if args.stop_token == "eos": + self.policy_model.generation_config.eos_token_id = self.stop_token_id = processing_class.eos_token_id + else: + raise ValueError( + f"Unknown `stop_token` {args.stop_token}. Allowed values are: `'eos'` and `None` (no stop token)." + ) + else: + self.policy_model.generation_config.eos_token_id = self.stop_token_id = args.stop_token_id # None or int + + # Check that the kl estimator is valid + if self.args.kl_estimator not in {"k1", "k3"}: + raise ValueError( + "kl_estimator must be either 'k1' (straightforward, unbiased) or 'k3' (lower variance, unbiased, " + "appears to be a strictly better estimator). See " + "[Approximating KL Divergence](http://joschu.net/blog/kl-approx.html) for details." + ) + + # PEFT + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + if isinstance(self.policy_model, PeftModel): + raise ValueError( + "You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first " + "merge and unload the existing adapter, save the resulting base model, and then pass that base " + "model along with the new `peft_config` to the trainer." + ) + + # get peft model with the given config + self.policy_model = get_peft_model(self.policy_model, peft_config) + if args.bf16 and getattr(self.policy_model, "is_loaded_in_4bit", False): + peft_module_casting_to_bf16(self.policy_model) + + self.is_peft_model = is_peft_available() and isinstance(self.policy_model, PeftModel) + self.model_adapter_name = args.model_adapter_name + self.ref_adapter_name = args.ref_adapter_name + + if ref_model: + self.ref_model = ref_model + elif self.is_peft_model: + self.ref_model = None + else: + self.ref_model = create_reference_model(self.policy_model) + + self.reward_model = reward_model + self.train_dataset = train_dataset + self.train_dataset_len = len(train_dataset) + self.value_model = value_model + self.data_collator = data_collator + self.eval_dataset = eval_dataset + self.optimizer, self.lr_scheduler = optimizers + self.optimizer_cls_and_kwargs = None # needed for transformers >= 4.47 + + ######### + # calculate various batch sizes + ######### + if args.total_episodes is None: # allow the users to define episodes in terms of epochs. + args.total_episodes = int(args.num_train_epochs * self.train_dataset_len) + accelerator = Accelerator(gradient_accumulation_steps=args.gradient_accumulation_steps) + self.accelerator = accelerator + args.world_size = accelerator.num_processes + args.local_batch_size = args.per_device_train_batch_size * args.gradient_accumulation_steps + args.micro_batch_size = int(args.per_device_train_batch_size * args.world_size) + args.batch_size = int(args.local_batch_size * args.world_size) + args.mini_batch_size = exact_div( + args.batch_size, args.num_mini_batches, "`batch_size` must be a multiple of `num_mini_batches`" + ) + args.local_mini_batch_size = exact_div( + args.local_batch_size, args.num_mini_batches, "`local_batch_size` must be a multiple of `num_mini_batches`" + ) + if args.whiten_rewards: + assert args.local_mini_batch_size >= 8, ( + f"Per-rank minibatch size {args.local_mini_batch_size} is insufficient for whitening" + ) + # `per_rank_rollout_batch_size` is our `args.local_batch_size` + # `per_rank_minibatch_size` is our `args.local_mini_batch_size` + args.num_total_batches = math.ceil( + args.total_episodes / args.batch_size + ) # we may train for more than `total_episodes` + self.local_seed = args.seed + accelerator.process_index * 100003 # Prime + if args.num_sample_generations > 0: + self.sample_generations_freq = max(1, args.num_total_batches // args.num_sample_generations) + self.local_dataloader_batch_size = args.local_batch_size + + ######### + # setup model, optimizer, and others + ######### + for module in [self.policy_model, self.ref_model, self.value_model, self.reward_model]: + if module is not None: + disable_dropout_in_model(module) + self.model = PolicyAndValueWrapper(self.policy_model, self.value_model) + self.model.config = self.policy_model.config # needed for pushing to hub + self.create_optimizer_and_scheduler( + num_training_steps=args.num_total_batches + ) # note that we are calling `self.lr_scheduler.step()` manually only at the batch level + + ######### + # trainer specifics + ######### + default_callbacks = DEFAULT_CALLBACKS + get_reporting_integration_callbacks(self.args.report_to) + self.callbacks = default_callbacks if callbacks is None else default_callbacks + callbacks + self.callback_handler = CallbackHandler( + self.callbacks, self.model, self.processing_class, self.optimizer, self.lr_scheduler + ) + self.add_callback(PrinterCallback if self.args.disable_tqdm else DEFAULT_PROGRESS_CALLBACK) + self.control = TrainerControl() + self.state = OnlineTrainerState( + is_local_process_zero=self.is_local_process_zero(), + is_world_process_zero=self.is_world_process_zero(), + stateful_callbacks=[ + cb for cb in self.callback_handler.callbacks + [self.control] if isinstance(cb, ExportableState) + ], + ) + self.current_flos = 0 + self.hp_search_backend = None + self.is_deepspeed_enabled = getattr(self.accelerator.state, "deepspeed_plugin", None) is not None + self.is_fsdp_enabled = getattr(self.accelerator.state, "fsdp_plugin", None) is not None + # Create distant repo and output directory if needed + self.hub_model_id = None + if self.args.push_to_hub: + self.init_hf_repo() + if self.args.should_save: + os.makedirs(self.args.output_dir, exist_ok=True) + + # Add tags for models that have been loaded with the correct transformers version + if hasattr(self.model, "add_model_tags"): + self.model.add_model_tags(self._tag_names) + + ######### + # setup dataloader + ######### + self.dataloader = DataLoader( + self.train_dataset, + batch_size=self.local_dataloader_batch_size, + shuffle=True, + collate_fn=self.data_collator, + drop_last=True, # needed; otherwise the last batch will be of ragged shape + ) + # sync random states for DataLoader(shuffle=True) before `accelerator.prepare` + # see https://gist.github.com/vwxyzjn/2581bff1e48e185e0b85b6dfe1def79c + torch.manual_seed(args.seed) + self.model, self.optimizer, self.dataloader = accelerator.prepare(self.model, self.optimizer, self.dataloader) + torch.manual_seed(self.local_seed) # reset the local seed again + + self.eval_dataloader = DataLoader( + self.eval_dataset, + batch_size=args.per_device_eval_batch_size, + collate_fn=self.data_collator, + drop_last=True, + ) # no need to shuffle eval dataset + self.eval_dataloader = accelerator.prepare(self.eval_dataloader) + + if self.is_deepspeed_enabled: + self.reward_model = prepare_deepspeed(self.reward_model, accelerator) + + if self.ref_model is None: + if not self.is_peft_model: + raise ValueError("No reference model and model is not a Peft model.") + else: + self.ref_model = prepare_deepspeed(self.ref_model, accelerator) + else: + if self.ref_model is None: + if not self.is_peft_model: + raise ValueError("No reference model and model is not a Peft model.") + else: + self.ref_model = self.ref_model.to(self.accelerator.device) + self.reward_model = self.reward_model.to(self.accelerator.device) + + def get_train_dataloader(self) -> DataLoader: + return self.dataloader + + def get_eval_dataloader(self) -> DataLoader: + return self.eval_dataloader + + @contextmanager + def null_ref_context(self): + """Context manager for handling null reference model (that is, peft adapter manipulation).""" + with ( + self.accelerator.unwrap_model(self.model.policy).disable_adapter() + if self.is_peft_model and not self.ref_adapter_name + else nullcontext() + ): + if self.ref_adapter_name: + self.model.policy.set_adapter(self.ref_adapter_name) + yield + if self.ref_adapter_name: + self.model.policy.set_adapter(self.model_adapter_name or "default") + + def save_model(self, output_dir: str | None = None, _internal_call: bool = False): + backup_model = self.model + if hasattr(self.model, "policy"): + self.model = self.model.policy # save only the policy for inference + if self.is_deepspeed_enabled: + backup_deepspeed = self.deepspeed + self.deepspeed = self.model + + super().save_model(output_dir, _internal_call) + + self.model = backup_model + if self.is_deepspeed_enabled: + self.deepspeed = backup_deepspeed + + def train(self): + args = self.args + accelerator = self.accelerator + optimizer = self.optimizer + model = self.model + ref_policy = self.ref_model + reward_model = self.reward_model + processing_class = self.processing_class + dataloader = self.dataloader + device = accelerator.device + + def repeat_generator(): + while True: + yield from dataloader + + iter_dataloader = iter(repeat_generator()) + generation_kwargs = { + "max_new_tokens": args.response_length, + "temperature": (args.temperature + 1e-7), + "top_k": 0.0, + "top_p": 1.0, + "do_sample": True, + } + generation_config = GenerationConfig(**generation_kwargs) + + accelerator.print("===training policy===") + start_time = time.time() + stats_shape = (args.num_ppo_epochs, args.num_mini_batches, args.gradient_accumulation_steps) + approxkl_stats = torch.zeros(stats_shape, device=device) + pg_clipfrac_stats = torch.zeros(stats_shape, device=device) + pg_loss_stats = torch.zeros(stats_shape, device=device) + vf_loss_stats = torch.zeros(stats_shape, device=device) + vf_clipfrac_stats = torch.zeros(stats_shape, device=device) + entropy_stats = torch.zeros(stats_shape, device=device) + ratio_stats = torch.zeros(stats_shape, device=device) + model.train() + + # trainer state initialization + self.state.global_step = 0 + self.state.episode = 0 + self.state.max_steps = args.num_total_batches + self.state.num_train_epochs = args.total_episodes / self.train_dataset_len + # Compute absolute values for logging, eval, and save if given as ratio + if args.logging_steps is not None: + if args.logging_steps < 1: + self.state.logging_steps = math.ceil(self.state.max_steps * args.logging_steps) + else: + self.state.logging_steps = args.logging_steps + if args.eval_steps is not None: + if args.eval_steps < 1: + self.state.eval_steps = math.ceil(self.state.max_steps * args.eval_steps) + else: + self.state.eval_steps = args.eval_steps + if args.save_steps is not None: + if args.save_steps < 1: + self.state.save_steps = math.ceil(self.state.max_steps * args.save_steps) + else: + self.state.save_steps = args.save_steps + self.control = self.callback_handler.on_train_begin(args, self.state, self.control) + + # backward compatibility + if self.is_deepspeed_enabled: + self.deepspeed = self.model + self.model_wrapped = self.model + + for update in range(1, args.num_total_batches + 1): + self.state.episode += 1 * args.batch_size + data = next(iter_dataloader) + with torch.no_grad(): + queries = data["input_ids"].to(device) + context_length = queries.shape[1] + responses = [] + postprocessed_responses = [] + logprobs = [] + ref_logprobs = [] + scores = [] + sequence_lengths = [] + values = [] + with ( + unwrap_model_for_generation( + self.model, + self.accelerator, + gather_deepspeed3_params=self.args.ds3_gather_for_generation, + generation_kwargs=generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762 + ) as unwrapped_model + ): + query_responses, logitss = batch_generation( + unwrapped_model.policy, + queries, + args.local_rollout_forward_batch_size, + processing_class.pad_token_id, + generation_config, + ) + + for i in range(0, queries.shape[0], args.local_rollout_forward_batch_size): + query = queries[i : i + args.local_rollout_forward_batch_size] + query_response = query_responses[i : i + args.local_rollout_forward_batch_size] + response = query_response[:, context_length:] + logits = logitss[i : i + args.local_rollout_forward_batch_size] + logprob = selective_log_softmax(logits, response) + del logits + empty_cache() + + if ref_policy is None: + with self.null_ref_context(): + ref_output = forward(model.policy, query_response, processing_class.pad_token_id) + else: + ref_output = forward(ref_policy, query_response, processing_class.pad_token_id) + ref_logits = ref_output.logits[:, context_length - 1 : -1] + ref_logits /= args.temperature + 1e-7 + ref_logprob = selective_log_softmax(ref_logits, response) + del ref_output, ref_logits + empty_cache() + + # Response Processing 1. truncate response after the first occurrence of `stop_token_id` + postprocessed_response = response + if self.stop_token_id is not None: # handle the edge case when stop_token_id exists but is 0 + postprocessed_response = truncate_response( + self.stop_token_id, processing_class.pad_token_id, response + ) + + # Response Processing 2. run reward model on the truncated responses + postprocessed_query_response = torch.cat((query, postprocessed_response), 1) + sequence_length = first_true_indices(postprocessed_response == processing_class.pad_token_id) - 1 + unwrapped_value_model = accelerator.unwrap_model(model).value_model + full_value, _, _ = get_reward( + unwrapped_value_model, query_response, processing_class.pad_token_id, context_length + ) + value = full_value[:, context_length - 1 : -1].squeeze(-1) + _, score, _ = get_reward( + reward_model, postprocessed_query_response, processing_class.pad_token_id, context_length + ) + + responses.append(response) + postprocessed_responses.append(postprocessed_response) + logprobs.append(logprob) + ref_logprobs.append(ref_logprob) + sequence_lengths.append(sequence_length) + scores.append(score) + values.append(value) + responses = torch.cat(responses, 0) + postprocessed_responses = torch.cat(postprocessed_responses, 0) + logprobs = torch.cat(logprobs, 0) + ref_logprobs = torch.cat(ref_logprobs, 0) + sequence_lengths = torch.cat(sequence_lengths, 0) + scores = torch.cat(scores, 0) + values = torch.cat(values, 0) + del (logprob, ref_logprob, full_value, value, score, unwrapped_model) + empty_cache() + gc.collect() + + # Response Processing 3. Filter completion. Ensure that the sample contains stop_token_id + # Completions not passing that filter will receive a lower score. + contain_eos_token = torch.any(postprocessed_responses == self.processing_class.eos_token_id, dim=-1) + if self.args.missing_eos_penalty is not None: + scores[~contain_eos_token] -= self.args.missing_eos_penalty + # accelerator.print(f"{scores=}, {(contain_eos_token.sum() / len(contain_eos_token))=}") + + # be very careful with `padding_mask_p1`; see https://excalidraw.com/#json=LWnzG4w2k5DjF_EOL_xPt,e2w3a-hFJ_gX5vOfeyXGTw + response_idxs = torch.arange(responses.shape[1], device=responses.device).repeat(responses.shape[0], 1) + padding_mask = response_idxs > sequence_lengths.unsqueeze(1) + logprobs = torch.masked_fill(logprobs, padding_mask, INVALID_LOGPROB) + ref_logprobs = torch.masked_fill(ref_logprobs, padding_mask, INVALID_LOGPROB) + sequence_lengths_p1 = sequence_lengths + 1 + padding_mask_p1 = response_idxs > (sequence_lengths_p1.unsqueeze(1)) + values = torch.masked_fill(values, padding_mask_p1, 0) + + # 4. compute rewards + # Formula used by http://joschu.net/blog/kl-approx.html for the k1 and k3 estimators + logr = ref_logprobs - logprobs + kl = -logr if args.kl_estimator == "k1" else (logr.exp() - 1) - logr # Else statement is k3 + non_score_reward = -args.kl_coef * kl + rewards = non_score_reward.clone() + actual_start = torch.arange(rewards.size(0), device=rewards.device) + actual_end = torch.where(sequence_lengths_p1 < rewards.size(1), sequence_lengths_p1, sequence_lengths) + rewards[actual_start, actual_end] += scores + + # 5. whiten rewards + if args.whiten_rewards: + rewards = masked_whiten(rewards, mask=~padding_mask_p1, shift_mean=False) + rewards = torch.masked_fill(rewards, padding_mask_p1, 0) + + # 6. compute advantages and returns + lastgaelam = 0 + advantages_reversed = [] + gen_length = responses.shape[1] + for t in reversed(range(gen_length)): + nextvalues = values[:, t + 1] if t < gen_length - 1 else 0.0 + delta = rewards[:, t] + args.gamma * nextvalues - values[:, t] + lastgaelam = delta + args.gamma * args.lam * lastgaelam + advantages_reversed.append(lastgaelam) + advantages = torch.stack(advantages_reversed[::-1], axis=1) + returns = advantages + values + advantages = masked_whiten(advantages, ~padding_mask) + advantages = torch.masked_fill(advantages, padding_mask, 0) + empty_cache() + + # Do multiple epochs of PPO training, with a fresh random shuffle in each epoch + for ppo_epoch_idx in range(args.num_ppo_epochs): + b_inds = np.random.permutation(args.local_batch_size) + minibatch_idx = 0 + for mini_batch_start in range(0, args.local_batch_size, args.local_mini_batch_size): + mini_batch_end = mini_batch_start + args.local_mini_batch_size + mini_batch_inds = b_inds[mini_batch_start:mini_batch_end] + gradient_accumulation_idx = 0 + for micro_batch_start in range(0, args.local_mini_batch_size, args.per_device_train_batch_size): + with accelerator.accumulate(model): + micro_batch_end = micro_batch_start + args.per_device_train_batch_size + micro_batch_inds = mini_batch_inds[micro_batch_start:micro_batch_end] + mb_advantage = advantages[micro_batch_inds] + mb_responses = responses[micro_batch_inds] + mb_query_responses = query_responses[micro_batch_inds] + mb_logprobs = logprobs[micro_batch_inds] + mb_return = returns[micro_batch_inds] + mb_values = values[micro_batch_inds] + + output, vpred_temp = forward(model, mb_query_responses, processing_class.pad_token_id) + logits = output.logits[:, context_length - 1 : -1] + logits /= args.temperature + 1e-7 + new_logprobs = selective_log_softmax(logits, mb_responses) + new_logprobs = torch.masked_fill( + new_logprobs, padding_mask[micro_batch_inds], INVALID_LOGPROB + ) + vpred = vpred_temp[:, context_length - 1 : -1].squeeze(-1) + vpred = torch.masked_fill(vpred, padding_mask_p1[micro_batch_inds], 0) + vpredclipped = torch.clamp( + vpred, + mb_values - args.cliprange_value, + mb_values + args.cliprange_value, + ) + vf_losses1 = torch.square(vpred - mb_return) + vf_losses2 = torch.square(vpredclipped - mb_return) + vf_loss_max = torch.max(vf_losses1, vf_losses2) + vf_loss = 0.5 * masked_mean(vf_loss_max, ~padding_mask_p1[micro_batch_inds]) + vf_clipfrac = masked_mean( + (vf_losses2 > vf_losses1).float(), ~padding_mask_p1[micro_batch_inds] + ) + logprobs_diff = new_logprobs - mb_logprobs + ratio = torch.exp(logprobs_diff) + pg_losses = -mb_advantage * ratio + pg_losses2 = -mb_advantage * torch.clamp(ratio, 1.0 - args.cliprange, 1.0 + args.cliprange) + pg_loss_max = torch.max(pg_losses, pg_losses2) + pg_loss = masked_mean(pg_loss_max, ~padding_mask[micro_batch_inds]) + loss = pg_loss + args.vf_coef * vf_loss + accelerator.backward(loss) + optimizer.step() + optimizer.zero_grad() + with torch.no_grad(): + pg_clipfrac = masked_mean( + (pg_losses2 > pg_losses).float(), ~padding_mask[micro_batch_inds] + ) + prob_dist = torch.nn.functional.softmax(logits, dim=-1) + entropy = torch.logsumexp(logits, dim=-1) - torch.sum(prob_dist * logits, dim=-1) + approxkl = 0.5 * (logprobs_diff**2).mean() + approxkl_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = approxkl + pg_clipfrac_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = ( + pg_clipfrac + ) + pg_loss_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = pg_loss + vf_loss_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = vf_loss + vf_clipfrac_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = ( + vf_clipfrac + ) + entropy_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = entropy.mean() + ratio_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = ratio.mean() + gradient_accumulation_idx += 1 + minibatch_idx += 1 + # del everything and empty cache + # fmt: off + del ( + output, vpred_temp, logits, new_logprobs, vpred, vpredclipped, + vf_losses1, vf_losses2, vf_loss, vf_clipfrac, logprobs_diff, ratio, pg_losses, pg_losses2, pg_loss_max, + pg_loss, loss, pg_clipfrac, prob_dist, entropy, approxkl, mb_return, + mb_advantage, mb_values, mb_responses, mb_query_responses, mb_logprobs, + ) + # fmt: on + empty_cache() + with torch.no_grad(): + mean_kl = kl.sum(1).mean() + mean_entropy = (-logprobs).sum(1).mean() + mean_non_score_reward = non_score_reward.sum(1).mean() + rlhf_reward = mean_non_score_reward + scores.mean() + eps = int(self.state.episode / (time.time() - start_time)) + metrics = {} + metrics["eps"] = eps + metrics["objective/kl"] = self.accelerator.gather_for_metrics(mean_kl).mean().item() + metrics["objective/entropy"] = self.accelerator.gather_for_metrics(mean_entropy).mean().item() + metrics["objective/non_score_reward"] = ( + self.accelerator.gather_for_metrics(mean_non_score_reward).mean().item() + ) + metrics["objective/rlhf_reward"] = self.accelerator.gather_for_metrics(rlhf_reward).mean().item() + metrics["objective/scores"] = self.accelerator.gather_for_metrics(scores.mean()).mean().item() + metrics["policy/approxkl_avg"] = self.accelerator.gather_for_metrics(approxkl_stats).mean().item() + metrics["policy/clipfrac_avg"] = self.accelerator.gather_for_metrics(pg_clipfrac_stats).mean().item() + metrics["loss/policy_avg"] = self.accelerator.gather_for_metrics(pg_loss_stats).mean().item() + metrics["loss/value_avg"] = self.accelerator.gather_for_metrics(vf_loss_stats).mean().item() + metrics["val/clipfrac_avg"] = self.accelerator.gather_for_metrics(vf_clipfrac_stats).mean().item() + metrics["policy/entropy_avg"] = self.accelerator.gather_for_metrics(entropy_stats).mean().item() + metrics["val/ratio"] = self.accelerator.gather_for_metrics(ratio_stats).mean().item() + metrics["val/ratio_var"] = self.accelerator.gather_for_metrics(ratio_stats).var().item() + metrics["val/num_eos_tokens"] = (responses == processing_class.eos_token_id).sum().item() + metrics["lr"] = self.lr_scheduler.get_last_lr()[0] + metrics["episode"] = self.state.episode + self.state.epoch = self.state.episode / self.train_dataset_len # used by self.log + self.state.global_step += 1 + self.log(metrics) + + self.lr_scheduler.step() + self.control = self.callback_handler.on_step_end(args, self.state, self.control) + if self.control.should_save: + self._save_checkpoint(model, trial=None) + self.control = self.callback_handler.on_save(self.args, self.state, self.control) + del kl, mean_kl, mean_entropy, mean_non_score_reward, scores, metrics, non_score_reward + empty_cache() + gc.collect() + + if args.num_sample_generations > 0 and (update - 1) % self.sample_generations_freq == 0: + self.generate_completions(sampling=True) + empty_cache() + del ( + query_responses, + responses, + postprocessed_responses, + logprobs, + ref_logprobs, + values, + sequence_lengths, + contain_eos_token, + sequence_lengths_p1, + response_idxs, + padding_mask, + padding_mask_p1, + rewards, + actual_start, + actual_end, + advantages, + returns, + ) + empty_cache() + + # HF trainer specifics + self.control = self.callback_handler.on_train_end(args, self.state, self.control) + if self.control.should_save: + self._save_checkpoint(model, trial=None) + self.control = self.callback_handler.on_save(self.args, self.state, self.control) + + def generate_completions(self, sampling: bool = False): + if self.eval_dataset is None: + return # no eval set to sample from (pass eval_dataset and eval_strategy != "no" for sample generations) + args = self.args + processing_class = self.processing_class + generation_kwargs = { + "max_new_tokens": args.response_length, + "temperature": (0.01 + 1e-7), + "top_k": 0.0, + "top_p": 1.0, + "do_sample": True, + } + generation_config = GenerationConfig(**generation_kwargs) + + table = defaultdict(list) + with ( + unwrap_model_for_generation( + self.model, + self.accelerator, + gather_deepspeed3_params=self.args.ds3_gather_for_generation, + generation_kwargs=generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762 + ) as unwrapped_model + ): + for batch in self.eval_dataloader: + query = batch["input_ids"] + with torch.no_grad(): + context_length = query.shape[1] + query_response, _ = batch_generation( + unwrapped_model.policy, + query, + query.shape[0], + processing_class.pad_token_id, + generation_config, + ) + response = query_response[:, context_length:] + postprocessed_response = response + if self.stop_token_id is not None: # handle the edge case when stop_token_id exists but is 0 + postprocessed_response = truncate_response( + self.stop_token_id, processing_class.pad_token_id, response + ) + table["query"].extend( + gather_object(processing_class.batch_decode(query, skip_special_tokens=True)) + ) + table["model response"].extend( + gather_object(processing_class.batch_decode(postprocessed_response)) + ) + + postprocessed_query_response = torch.cat((query, postprocessed_response), 1) + _, score, _ = get_reward( + self.reward_model, postprocessed_query_response, processing_class.pad_token_id, context_length + ) + table["score"].extend(self.accelerator.gather_for_metrics(score).float().cpu().numpy()) + + if sampling: + break + df = pd.DataFrame(table) + + if self.accelerator.is_main_process: + if is_rich_available(): + print_rich_table(df.iloc[0 : 0 + 5]) + if "wandb" in args.report_to: + import wandb + + if wandb.run is not None: + wandb.log({"completions": wandb.Table(dataframe=df)}) + + if "comet_ml" in args.report_to: + log_table_to_comet_experiment( + name="completions.csv", + table=df, + ) + + # Ensure the model card is saved along with the checkpoint + def _save_checkpoint(self, model, trial): + if self.args.hub_model_id is None: + model_name = Path(self.args.output_dir).name + else: + model_name = self.args.hub_model_id.split("/")[-1] + self.create_model_card(model_name=model_name) + super()._save_checkpoint(model, trial) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/prm/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/prm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..210c474aa459261c71906d4e1b11994a08dddd4c --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/prm/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .prm_config import PRMConfig +from .prm_trainer import PRMTrainer + + +__all__ = ["PRMConfig", "PRMTrainer"] diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/prm/prm_config.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/prm/prm_config.py new file mode 100644 index 0000000000000000000000000000000000000000..b6150c01b2e4739e027ee3072080c5f057478841 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/prm/prm_config.py @@ -0,0 +1,88 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field + +from ...trainer.base_config import _BaseConfig + + +@dataclass +class PRMConfig(_BaseConfig): + # docstyle-ignore + r""" + Configuration class for the [`experimental.prm.PRMTrainer`]. + + This class includes only the parameters that are specific to PRM 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: + max_length (`int` or `None`, *optional*, defaults to `1024`): + Maximum length of the sequences (prompt + completion) used for truncation. + max_completion_length (`int`, *optional*): + Maximum length of the completion used for truncation. The completion is the concatenation of the steps. + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the model. + step_separator (`str`, *optional*, defaults to `"\n"`): + Separator used to separate each step of the reasoning process. + train_on_last_step_only (`bool`, *optional*, defaults to `False`): + Whether to train only on the last step. + dataset_num_proc (`int`, *optional*): + Number of processes to use for processing the dataset. + + > [!NOTE] + > These parameters have default values different from [`~transformers.TrainingArguments`]: + > - `logging_steps`: Defaults to `10` instead of `500`. + > - `gradient_checkpointing`: Defaults to `True` instead of `False`. + > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`. + > - `learning_rate`: Defaults to `1e-5` instead of `5e-5`. + """ + + # Parameters whose default values are overridden from TrainingArguments + learning_rate: float = field( + default=1e-5, + metadata={"help": "The initial learning rate for AdamW."}, + ) + + max_length: int | None = field( + default=1024, + metadata={"help": "Maximum length of the sequences (prompt + completion) used for truncation."}, + ) + max_completion_length: int | None = field( + default=None, + metadata={ + "help": "Maximum length of the completion used for truncation. The completion is the concatenation of the " + "steps." + }, + ) + disable_dropout: bool = field( + default=True, + metadata={"help": "Whether to disable dropout in the model and reference model."}, + ) + step_separator: str = field( + default="\n", + metadata={"help": "Separator used to separate each step of the reasoning process."}, + ) + train_on_last_step_only: bool = field( + default=False, + metadata={"help": "Whether to train only on the last step."}, + ) + dataset_num_proc: int | None = field( + default=None, + metadata={"help": "Number of processes to use for processing the dataset."}, + ) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/prm/prm_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/prm/prm_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..78341a3b832b404791ccf1429129cf2dbbd1abfe --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/prm/prm_trainer.py @@ -0,0 +1,370 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import textwrap +from collections.abc import Callable +from itertools import chain +from pathlib import Path + +import numpy as np +import torch +import torch.nn as nn +import transformers +from accelerate import PartialState, logging +from accelerate.utils import is_peft_model +from datasets import Dataset, features +from packaging.version import Version +from transformers import ( + BaseImageProcessor, + DataCollator, + DataCollatorForTokenClassification, + FeatureExtractionMixin, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, +) +from transformers.trainer_utils import EvalPrediction +from transformers.utils import is_peft_available + +from ...trainer.base_trainer import _BaseTrainer +from ...trainer.utils import disable_dropout_in_model +from ..utils import prepare_peft_model +from .prm_config import PRMConfig + + +if is_peft_available(): + from peft import PeftConfig + +logger = logging.get_logger(__name__) + + +def compute_accuracy(eval_pred: EvalPrediction) -> dict[str, float]: + predictions, labels = eval_pred + if predictions.ndim == 3: + # Token classification task. Shapes are (batch_size, seq_len, num_labels) and (batch_size, seq_len) + # Used to compute the accuracy in the prm_trainer. + predictions = np.argmax(predictions, axis=2) + + # Flatten the predictions and labels to remove the ignored tokens. + predictions = np.array( + [ + p + for prediction, label in zip(predictions, labels, strict=True) + for (p, lbl) in zip(prediction, label, strict=True) + if lbl != -100 + ] + ) + labels = np.array([lbl for label in labels for lbl in label if lbl != -100]) + + else: + # Here, predictions is rewards_chosen and rewards_rejected. Shapes are (batch_size, 2) and (batch_size,) + # We want to see how much of the time rewards_chosen > rewards_rejected. + equal_mask = predictions[:, 0] == predictions[:, 1] + equal_predictions_count = int(equal_mask.sum()) + + if equal_predictions_count > 0: + # Before using the logger, the accelerate state must be initialized. It'susually the case when using this + # function inside a Trainer, but it may not be the case otherwise, in particular when unit testing. + PartialState() + + logger.warning( + f"There are {equal_predictions_count} out of {len(predictions[:, 0])} instances where the predictions " + "for both options are equal. These instances are ignored in the accuracy computation.", + ) + + # Filter out equal predictions + predictions = predictions[~equal_mask] + labels = labels[~equal_mask] + + # Use the remaining predictions for accuracy calculation + predictions = np.argmax(predictions, axis=1) + + accuracy = np.array(predictions == labels, dtype=float).mean().item() + return {"accuracy": accuracy} + + +class PRMTrainer(_BaseTrainer): + """ + Initialize PRMTrainer. + + Args: + model ([`~transformers.PreTrainedModel`]): + The model to train, preferably an `AutoModelForTokenClassification`. + args ([`experimental.prm.PRMConfig`]): + The arguments to use for training. + data_collator ([`~transformers.DataCollator`]): + The data collator to use for training. If None is specified, the default data collator + ([`~transformers.DataCollatorForTokenClassification`]) will be used which will pad the sequences to the + maximum length of the sequences in the batch, given a dataset of paired sequences. + train_dataset ([`~datasets.Dataset`]): + The dataset to use for training. + eval_dataset ([`~datasets.Dataset`]): + The dataset to use for evaluation. + processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*): + Processing class used to process the data. If provided, will be used to automatically process the inputs + for the model, and it will be saved along the model to make it easier to rerun an interrupted training or + reuse the fine-tuned model. + model_init (`Callable[[], transformers.PreTrainedModel]`): + The model initializer to use for training. If None is specified, the default model initializer will be + used. + compute_metrics (`Callable[[transformers.EvalPrediction], dict]`, *optional* defaults to `compute_accuracy`): + The metrics to use for evaluation. If no metrics are specified, the default metric (`compute_accuracy`) + will be used. + callbacks (`list[transformers.TrainerCallback]`): + The callbacks to use for training. + optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`): + The optimizer and scheduler to use for training. + preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`): + The function to use to preprocess the logits before computing the metrics. + peft_config ([`~peft.PeftConfig`], *optional*): + The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in + a PEFT model. + """ + + _tag_names = ["trl", "prm"] + _name = "PRM" + _paper = { + "title": "Solving math word problems with process-and outcome-based feedback", + "id": "2211.14275", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @article{uesato2022solving, + title = {{Solving Math Word Problems With Process- and Outcome-Based Feedback}}, + author = {Uesato, Jonathan and Kushman, Nate and Kumar, Ramana and Song, Francis and Siegel, Noah and Wang, Lisa and Creswell, Antonia and Irving, Geoffrey and Higgins, Irina}, + year = 2022, + journal = {arXiv preprint arXiv:2211.14275} + }"""), + } + + def __init__( + self, + model: PreTrainedModel | nn.Module | None = None, + args: PRMConfig | None = None, + data_collator: DataCollator | None = None, + train_dataset: Dataset | None = None, + eval_dataset: Dataset | dict[str, Dataset] | None = None, + processing_class: PreTrainedTokenizerBase + | BaseImageProcessor + | FeatureExtractionMixin + | ProcessorMixin + | None = None, + model_init: Callable[[], PreTrainedModel] | None = None, + compute_metrics: Callable[[EvalPrediction], dict] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = ( + None, + None, + ), + preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None, + peft_config: "PeftConfig | None" = None, + ): + if train_dataset is None: + raise ValueError("`train_dataset` is required") + + # PEFT + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + if peft_config is not None or is_peft_model(model): + model = prepare_peft_model(model, peft_config, args) + + # Disable dropout in the model + if args.disable_dropout: + disable_dropout_in_model(model) + + if compute_metrics is None: + compute_metrics = compute_accuracy + + if data_collator is None: + if processing_class is None: + raise ValueError( + "A processing_class must be specified when using the default DataCollatorForTokenClassification" + ) + data_collator = DataCollatorForTokenClassification(processing_class) + + if "input_ids" not in train_dataset.column_names: + with PartialState().main_process_first(): + fn_kwargs = { + "tokenizer": processing_class, + "step_separator": args.step_separator, + "max_length": args.max_length, + "max_completion_length": args.max_completion_length, + "train_on_last_step_only": args.train_on_last_step_only, + } + train_fn_kwargs = {**fn_kwargs, "is_eval": False} + train_dataset = train_dataset.map( + self.tokenize_row, + fn_kwargs=train_fn_kwargs, + num_proc=args.dataset_num_proc, + remove_columns=train_dataset.features, + desc="Tokenizing train dataset", + features=features.Features( # needed to avoid map to cast labels to bool + { + "labels": features.Sequence(features.Value("int64")), + "input_ids": features.Sequence(features.Value("int64")), + } + ), + ) + + eval_fn_kwargs = {**fn_kwargs, "is_eval": True} + if eval_dataset is not None: + eval_dataset = eval_dataset.map( + self.tokenize_row, + fn_kwargs=eval_fn_kwargs, + num_proc=args.dataset_num_proc, + remove_columns=eval_dataset.features, + desc="Tokenizing eval dataset", + features=features.Features( # needed to avoid map to cast labels to bool + { + "labels": features.Sequence(features.Value("int64")), + "input_ids": features.Sequence(features.Value("int64")), + } + ), + ) + + # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was + # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream + # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we + # default to the recommended non-reentrant behavior here, while preserving any user-provided value. + if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"): + args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {} + args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False) + + super().__init__( + model=model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + model_init=model_init, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + ) + + # Add tags for models that have been loaded with the correct transformers version + if hasattr(self.model, "add_model_tags"): + self.model.add_model_tags(self._tag_names) + + @staticmethod + def tokenize_row( + features, + tokenizer, + step_separator, + max_length, + max_completion_length, + train_on_last_step_only, + is_eval, + ): + r""" + Tokenize a row of the dataset. + + Args: + features (`dict[str, str]`): + Row of the dataset, should contain the keys `"prompt"`, `"completions"`, and `"labels"`. + tokenizer ([`~transformers.PreTrainedTokenizerBase`]): + Tokenizer used to process the data. + step_separator (`str`): + Separator between steps in the completion. + max_length (`int` or `None`): + Maximum length of the sequences (prompt + completion). If `None`, the sequences are not truncated. + max_completion_length (`int` or `None`): + Maximum length of the completion sequences. If `None`, the completion sequences are not truncated. + train_on_last_step_only (`bool`): + Whether to train only on the last step. If `True`, the labels are `-100` for all tokens except the last + token of the completion. + is_eval (`bool`): + Whether the function is used to tokenize samples from a training or an evaluation dataset. Used only if + `train_on_last_step_only` is set to `True`. + + Returns: + `dict[str, list[int]]`: + Tokenized sequences with the keys `"input_ids"`, and `"labels". + + Example: + ```python + >>> from transformers import AutoTokenizer + + >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B") + >>> features = { + ... "prompt": "Which number is larger, 9.8 or 9.11?", + ... "completions": ["11 is greater than 8.", "Hence, 9.11 > 9.8."], + ... "labels": [True, False], + ... } + >>> PRMTrainer.tokenize_row( + ... features, tokenizer, "\n", max_completion_length=None, train_on_last_step_only=False, is_eval=False + ... ) + {'input_ids': [23085, 1372, 374, 8131, 11, 220, 24, 13, 23, 476, 220, 24, 13, 16, 16, 30, 16, 16, 374, 7046, 1091, 220, 23, 13, 198, 39, 763, 11, 220, 24, 13, 16, 16, 861, 220, 24, 13, 23, 13, 198], + 'labels': [-100, -100, -100, -100, -100, -100, -100, -100, 1, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, 0]} + ``` + """ + # Tokenize the prompt and completions + prompt_ids = tokenizer(features["prompt"], add_special_tokens=False)["input_ids"] + completions_ids = [ + tokenizer(completion, add_special_tokens=False)["input_ids"] for completion in features["completions"] + ] + if train_on_last_step_only and not is_eval: + labels = [-100] * (len(features["labels"]) - 1) + [int(features["labels"][-1])] + else: + labels = [int(label) for label in features["labels"]] + + # Get the ID of the separator token and add it to the completions + separator_ids = tokenizer.encode(step_separator, add_special_tokens=False) + completions_ids = [completion + separator_ids for completion in completions_ids] + + # Create the label + labels = [ + [-100] * (len(completion) - 1) + [label] for completion, label in zip(completions_ids, labels, strict=True) + ] + + # Join the completions and labels steps + completion_ids = list(chain(*completions_ids)) + labels = list(chain(*labels)) + + if tokenizer.bos_token_id is not None: + prompt_ids = [tokenizer.bos_token_id] + prompt_ids + + # Truncate completion sequences + if max_completion_length is not None: + completion_ids = completion_ids[:max_completion_length] + labels = labels[:max_completion_length] + + input_ids = prompt_ids + completion_ids + labels = [-100] * len(prompt_ids) + labels + + if max_length is not None: + input_ids = input_ids[:max_length] + labels = labels[:max_length] + + return {"input_ids": input_ids, "labels": labels} + + # Ensure the model card is saved along with the checkpoint + def _save_checkpoint(self, model, trial): + if self.args.hub_model_id is None: + model_name = Path(self.args.output_dir).name + else: + model_name = self.args.hub_model_id.split("/")[-1] + self.create_model_card(model_name=model_name) + super()._save_checkpoint(model, trial) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdft/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdft/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..85a7818ae5c8b83264ffec56a58c52f344fa5c26 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdft/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .sdft_config import SDFTConfig +from .sdft_trainer import SDFTTrainer + + +__all__ = ["SDFTConfig", "SDFTTrainer"] diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdft/loss_utils.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdft/loss_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5caa8c88713d2088c9c4c728dcea3e62236cf4e4 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdft/loss_utils.py @@ -0,0 +1,135 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Pure helper functions for self-distillation loss computation.""" + +import torch +import torch.nn.functional as F + +from ...trainer.utils import selective_log_softmax + + +def compute_divergence( + student_log_probs: torch.Tensor, + teacher_log_probs: torch.Tensor, + alpha: float, +) -> torch.Tensor: + if alpha == 0.0: + kl = F.kl_div(student_log_probs, teacher_log_probs, reduction="none", log_target=True) + elif alpha == 1.0: + kl = F.kl_div(teacher_log_probs, student_log_probs, reduction="none", log_target=True) + else: + alpha_t = torch.tensor(alpha, dtype=student_log_probs.dtype, device=student_log_probs.device) + mixture = torch.logsumexp( + torch.stack([student_log_probs + torch.log(1 - alpha_t), teacher_log_probs + torch.log(alpha_t)]), + dim=0, + ) + kl_teacher = F.kl_div(mixture, teacher_log_probs, reduction="none", log_target=True) + kl_student = F.kl_div(mixture, student_log_probs, reduction="none", log_target=True) + kl = torch.lerp(kl_student, kl_teacher, alpha) + return kl.sum(-1) + + +def add_tail_bucket(log_probs: torch.Tensor) -> torch.Tensor: + """Append a bucket holding the leftover probability mass to a top-k log-prob support. + + `log_probs` are true log-probabilities over a top-k subset, so they sum to the captured mass `P_topk <= 1`. This + appends one extra category equal to the tail mass `1 - P_topk`, yielding a distribution that sums to exactly 1. + """ + log_s = torch.logsumexp(log_probs, dim=-1, keepdim=True) + log_s = torch.clamp(log_s, max=-1e-7) + tail_log = torch.log(-torch.expm1(log_s)) + return torch.cat([log_probs, tail_log], dim=-1) + + +def apply_importance_sampling_clipping( + per_token_loss: torch.Tensor, + student_log_probs: torch.Tensor, + old_log_probs: torch.Tensor, + clip_coeff: float, +) -> torch.Tensor: + negative_approx_kl = (student_log_probs - old_log_probs).detach() + negative_approx_kl = torch.clamp(negative_approx_kl, min=-20.0, max=20.0) + ratio = torch.exp(negative_approx_kl).clamp(max=clip_coeff) + return per_token_loss * ratio + + +def compute_topk_self_distillation_loss( + student_logits: torch.Tensor, + teacher_logits: torch.Tensor, + *, + distillation_topk: int, + distillation_alpha: float, + distillation_add_tail: bool, +) -> torch.Tensor: + """Compute distillation loss on the student's top-k token support. + + The student's top-k logits define the support. The teacher distribution is projected onto the same token indices. + The selected support is then either renormalized or augmented with a tail bucket before the divergence is computed. + """ + student_logsumexp = torch.logsumexp(student_logits, dim=-1, keepdim=True) + topk_student_logits, topk_indices = torch.topk(student_logits, k=distillation_topk, dim=-1) + topk_student_log_probs = topk_student_logits - student_logsumexp + + teacher_logsumexp = torch.logsumexp(teacher_logits, dim=-1, keepdim=True) + topk_teacher_logits = torch.gather(teacher_logits, dim=-1, index=topk_indices) + topk_teacher_log_probs = topk_teacher_logits - teacher_logsumexp + + # Top-k log-probs sum to the captured mass P_topk <= 1; the rest (1 - P_topk) is the "tail". + if distillation_add_tail: + # Lump the tail into one bucket so the divergence approximates the full-vocab divergence. + topk_student_log_probs = add_tail_bucket(topk_student_log_probs) + topk_teacher_log_probs = add_tail_bucket(topk_teacher_log_probs) + else: + # Drop the tail and renormalize the top-k to sum to 1: divergence over the top-k conditional only. + topk_student_log_probs = topk_student_log_probs - torch.logsumexp(topk_student_log_probs, dim=-1, keepdim=True) + topk_teacher_log_probs = topk_teacher_log_probs - torch.logsumexp(topk_teacher_log_probs, dim=-1, keepdim=True) + + return compute_divergence(topk_student_log_probs, topk_teacher_log_probs, distillation_alpha) + + +def compute_full_logit_self_distillation_loss( + student_logits: torch.Tensor, + teacher_logits: torch.Tensor, + *, + distillation_alpha: float, +) -> torch.Tensor: + """Compute full-vocabulary self-distillation loss between student and teacher logits.""" + student_log_probs = torch.log_softmax(student_logits, dim=-1) + teacher_log_probs = torch.log_softmax(teacher_logits, dim=-1) + return compute_divergence(student_log_probs, teacher_log_probs, distillation_alpha) + + +def compute_sampled_token_self_distillation_loss( + student_logits: torch.Tensor, + teacher_logits: torch.Tensor, + completion_ids: torch.Tensor, + *, + distillation_alpha: float, +) -> torch.Tensor: + """Compute token-level self-distillation loss only on the sampled completion tokens. + + This path compares student and teacher log-probabilities on the realized completion tokens rather than over a + larger token support. + """ + if distillation_alpha != 1.0: + raise ValueError( + "Only reverse KL (alpha=1.0) is supported for token-level distillation when " + f"`distillation_mode='sampled_token'`, got alpha={distillation_alpha}" + ) + + student_per_token_logps = selective_log_softmax(student_logits, completion_ids) + teacher_per_token_logps = selective_log_softmax(teacher_logits, completion_ids) + log_ratio = student_per_token_logps - teacher_per_token_logps + return log_ratio.detach() * student_per_token_logps diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdft/sdft.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdft/sdft.py new file mode 100644 index 0000000000000000000000000000000000000000..6aaef1b94432cba536508f4e0d7b36f615aab7fc --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdft/sdft.py @@ -0,0 +1,432 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# /// script +# dependencies = [ +# "trl", +# "peft", +# "trackio", +# "kernels", +# ] +# /// + +""" +Small-scale SDFT training with Qwen/Qwen3.5-0.8B. + +Expected dataset formats: + +1. Native TRL self-distillation format: + - `prompt` + - `privileged_context` containing only the extra teacher-only information + +2. Demonstration-based format: + - `prompt` + - `golden_response` + +Example: + +```bash +python trl/experimental/sdft/sdft.py \ + --model_name_or_path Qwen/Qwen3.5-0.8B \ + --dataset_name your-org/your-dataset \ + --output_dir outputs/sdft-qwen3.5-0.8b \ + --per_device_train_batch_size 1 \ + --gradient_accumulation_steps 16 \ + --learning_rate 2e-5 \ + --max_prompt_length 1024 \ + --max_completion_length 512 \ + --teacher_model_kind ema \ + --teacher_sync_steps 1 \ + --teacher_update_rate 0.01 \ + --eval_strategy steps \ + --eval_steps 50 \ + --report_to wandb +``` +""" + +import json +import os +import re +from dataclasses import dataclass, field +from string import Template +from typing import Any + +import torch +from datasets import DatasetDict, load_dataset, load_from_disk +from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig + +from trl import ( + LogCompletionsCallback, + ModelConfig, + ScriptArguments, + TrlParser, + get_kbit_device_map, + get_peft_config, + get_quantization_config, +) +from trl.data_utils import maybe_apply_chat_template +from trl.experimental.sdft import SDFTConfig, SDFTTrainer +from trl.models import unwrap_model_for_generation + + +DEFAULT_DEMONSTRATION_TEMPLATE = Template("""Example response: $output_text""") + + +@dataclass +class SDFTScriptArguments(ScriptArguments): + dataset_path: str | None = field( + default=None, + metadata={"help": "Optional local dataset path to load with `load_from_disk`. Overrides `dataset_name`."}, + ) + privileged_context_column: str = field( + default="privileged_context", + metadata={"help": "Column containing precomputed privileged context for SDFT."}, + ) + golden_response_column: str = field( + default="golden_response", + metadata={"help": "Column containing demonstration responses used to build privileged context."}, + ) + eval_num_prompts: int | None = field( + default=8, + metadata={"help": "Number of prompts to log during evaluation. Set to 0 to disable completion logging."}, + ) + demonstration_template: str = field( + default=DEFAULT_DEMONSTRATION_TEMPLATE.template, + metadata={"help": "Template used to build privileged context from demonstration content."}, + ) + tool_eval_num_examples: int | None = field( + default=None, + metadata={ + "help": "Optional number of eval examples to score for tool-use metrics. Defaults to the full eval split." + }, + ) + tool_eval_max_new_tokens: int = field( + default=256, + metadata={"help": "Maximum completion length for task evaluation generation."}, + ) + + +def _extract_prompt_text(prompt: Any) -> str: + if isinstance(prompt, str): + return prompt + if isinstance(prompt, list) and prompt and isinstance(prompt[0], dict): + for message in reversed(prompt): + if message.get("role") == "user": + content = message.get("content", "") + if isinstance(content, list): + return " ".join(part.get("text", "") for part in content if part.get("type") == "text") + return content + return str(prompt) + + +def _stringify_golden_response(response: Any) -> str: + if isinstance(response, str): + return response + if isinstance(response, list): + return "\n".join(_stringify_golden_response(item) for item in response) + return str(response) + + +def _build_privileged_context( + example: dict[str, Any], privileged_context_column: str, golden_response_column: str, template: Template +): + if privileged_context_column in example and example[privileged_context_column] is not None: + privileged_context = example[privileged_context_column] + elif golden_response_column in example: + privileged_context = template.safe_substitute( + orig_content=_extract_prompt_text(example["prompt"]), + output_text=_stringify_golden_response(example[golden_response_column]), + ) + elif "teacher_prompt" in example: + raise ValueError( + "Datasets for `trl.experimental.sdft` should provide `privileged_context` or `golden_response`, not " + "`teacher_prompt`." + ) + else: + raise ValueError("Dataset must contain either `privileged_context` or `golden_response` alongside `prompt`.") + + return { + "prompt": example["prompt"], + "privileged_context": privileged_context, + } + + +def _prepare_split(dataset, script_args: SDFTScriptArguments): + template = Template(script_args.demonstration_template) + return dataset.map( + lambda example: _build_privileged_context( + example, + privileged_context_column=script_args.privileged_context_column, + golden_response_column=script_args.golden_response_column, + template=template, + ), + remove_columns=dataset.column_names, + ) + + +def _can_prepare_privileged_context(dataset) -> bool: + columns = set(dataset.column_names) + return "prompt" in columns and ("privileged_context" in columns or "golden_response" in columns) + + +def _extract_action_and_input(text: str) -> tuple[str | None, str | None]: + action_match = re.search(r"Action:\s*([^\n]+)", text) + action_input_match = re.search(r"Action Input:\s*(.*)", text, flags=re.DOTALL) + action = action_match.group(1).strip() if action_match else None + action_input = action_input_match.group(1).strip() if action_input_match else None + return action, action_input + + +def _parse_json_object(text: str | None) -> tuple[bool, Any]: + if text is None: + return False, None + text = text.strip() + if text.startswith("```"): + text = re.sub(r"^```(?:json)?\s*", "", text) + text = re.sub(r"\s*```$", "", text) + try: + return True, json.loads(text) + except Exception: + return False, None + + +def _normalize_gold_answer(example: dict[str, Any]) -> tuple[str | None, Any]: + answers = example.get("golden_answer") or [] + if not answers: + return None, None + answer = answers[0] + action = answer.get("Action") + valid_json, action_input = _parse_json_object(answer.get("Action_Input")) + return action, action_input if valid_json else answer.get("Action_Input") + + +def _apply_prompt_template(tokenizer, prompt: Any) -> str: + return maybe_apply_chat_template({"prompt": prompt}, tokenizer)["prompt"] + + +def _run_tooluse_eval( + trainer: SDFTTrainer, + eval_dataset, + max_new_tokens: int, + num_examples: int | None = None, + metric_prefix: str = "tool_eval", +) -> dict[str, float]: + if num_examples is not None: + eval_dataset = eval_dataset.select(range(min(num_examples, len(eval_dataset)))) + + prompts = eval_dataset["prompt"] + prompt_texts = [_apply_prompt_template(trainer.processing_class, prompt) for prompt in prompts] + tokenized = trainer.processing_class( + text=prompt_texts, + return_tensors="pt", + padding=True, + padding_side="left", + truncation=True, + max_length=trainer.max_prompt_length, + add_special_tokens=False, + ) + tokenized = {key: value.to(trainer.accelerator.device) for key, value in tokenized.items()} + + with ( + unwrap_model_for_generation( + trainer.model_wrapped, + trainer.accelerator, + gather_deepspeed3_params=trainer.args.ds3_gather_for_generation, + ) as unwrapped_model, + torch.no_grad(), + ): + generated = unwrapped_model.generate( + **tokenized, + max_new_tokens=max_new_tokens, + do_sample=False, + pad_token_id=trainer.processing_class.pad_token_id, + eos_token_id=trainer.processing_class.eos_token_id, + ) + + prompt_length = tokenized["input_ids"].shape[1] + completions = trainer.processing_class.batch_decode(generated[:, prompt_length:], skip_special_tokens=True) + + action_correct = 0 + json_valid = 0 + full_match = 0 + parsed_action_present = 0 + records = [] + + for example, completion in zip(eval_dataset, completions, strict=True): + pred_action, pred_action_input_text = _extract_action_and_input(completion) + if pred_action is not None: + parsed_action_present += 1 + pred_json_valid, pred_action_input = _parse_json_object(pred_action_input_text) + if pred_json_valid: + json_valid += 1 + + gold_action, gold_action_input = _normalize_gold_answer(example) + is_action_correct = pred_action == gold_action and gold_action is not None + if is_action_correct: + action_correct += 1 + is_full_match = is_action_correct and pred_json_valid and pred_action_input == gold_action_input + if is_full_match: + full_match += 1 + + records.append( + { + "prompt": _extract_prompt_text(example["prompt"]), + "completion": completion, + "pred_action": pred_action, + "pred_action_input_text": pred_action_input_text, + "gold_action": gold_action, + "gold_action_input": gold_action_input, + "action_correct": is_action_correct, + "json_valid": pred_json_valid, + "full_match": is_full_match, + } + ) + + total = max(len(eval_dataset), 1) + metrics = { + f"{metric_prefix}/action_present_rate": parsed_action_present / total, + f"{metric_prefix}/valid_json_rate": json_valid / total, + f"{metric_prefix}/action_accuracy": action_correct / total, + f"{metric_prefix}/tool_call_accuracy": full_match / total, + } + + sample_path = os.path.join(trainer.args.output_dir, f"{metric_prefix}_samples.json") + os.makedirs(trainer.args.output_dir, exist_ok=True) + with open(sample_path, "w") as f: + json.dump(records[: min(20, len(records))], f, indent=2) + + return metrics + + +if __name__ == "__main__": + parser = TrlParser((SDFTScriptArguments, SDFTConfig, ModelConfig)) + script_args, training_args, model_args = parser.parse_args_and_config() + + if model_args.model_name_or_path is None: + raise ValueError("`model_name_or_path` is required.") + if model_args.dtype in ["auto", None]: + if training_args.bf16: + dtype = torch.bfloat16 + elif training_args.fp16: + dtype = torch.float16 + else: + dtype = "auto" + else: + dtype = getattr(torch, model_args.dtype) + model_kwargs = dict( + revision=model_args.model_revision, + trust_remote_code=model_args.trust_remote_code, + attn_implementation=model_args.attn_implementation, + dtype=dtype, + ) + quantization_config = get_quantization_config(model_args) + if quantization_config is not None: + model_kwargs["device_map"] = get_kbit_device_map() + model_kwargs["quantization_config"] = quantization_config + + training_args.model_init_kwargs = model_kwargs + + tokenizer = AutoTokenizer.from_pretrained( + model_args.model_name_or_path, + revision=model_args.model_revision, + trust_remote_code=model_args.trust_remote_code, + padding_side="left", + ) + if tokenizer.pad_token is None: + tokenizer.pad_token = tokenizer.eos_token + + if script_args.dataset_path is not None: + dataset = load_from_disk(script_args.dataset_path) + else: + dataset = load_dataset( + script_args.dataset_name, + name=script_args.dataset_config, + streaming=script_args.dataset_streaming, + ) + + if not isinstance(dataset, DatasetDict): + raise ValueError("SDFT example expects a dataset with named splits.") + + train_dataset = _prepare_split(dataset[script_args.dataset_train_split], script_args) + raw_eval_dataset = dataset[script_args.dataset_test_split] if script_args.dataset_test_split in dataset else None + eval_dataset = None + if ( + training_args.eval_strategy != "no" + and raw_eval_dataset is not None + and _can_prepare_privileged_context(raw_eval_dataset) + ): + eval_dataset = _prepare_split(raw_eval_dataset, script_args) + + model = AutoModelForCausalLM.from_pretrained(model_args.model_name_or_path, **model_kwargs) + model.config.use_cache = False if training_args.gradient_checkpointing else True + + trainer = SDFTTrainer( + model=model, + args=training_args, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=tokenizer, + peft_config=get_peft_config(model_args), + ) + + if eval_dataset is not None and script_args.eval_num_prompts: + generation_config = GenerationConfig( + max_new_tokens=training_args.max_completion_length, + do_sample=True, + temperature=training_args.temperature, + ) + trainer.add_callback( + LogCompletionsCallback(trainer, generation_config, num_prompts=script_args.eval_num_prompts) + ) + + pretrain_metrics = None + if raw_eval_dataset is not None and "golden_answer" in raw_eval_dataset.column_names: + pretrain_metrics = _run_tooluse_eval( + trainer, + raw_eval_dataset, + max_new_tokens=script_args.tool_eval_max_new_tokens, + num_examples=script_args.tool_eval_num_examples, + metric_prefix="tool_eval_before", + ) + trainer.log(pretrain_metrics) + trainer.log_metrics("eval", pretrain_metrics) + trainer.save_metrics("eval", pretrain_metrics) + + trainer.train() + + trainer.save_model(training_args.output_dir) + if eval_dataset is not None: + metrics = trainer.evaluate() + trainer.log_metrics("eval", metrics) + trainer.save_metrics("eval", metrics) + if raw_eval_dataset is not None and "golden_answer" in raw_eval_dataset.column_names: + post_metrics = _run_tooluse_eval( + trainer, + raw_eval_dataset, + max_new_tokens=script_args.tool_eval_max_new_tokens, + num_examples=script_args.tool_eval_num_examples, + metric_prefix="tool_eval_after", + ) + if pretrain_metrics is not None: + for key, value in pretrain_metrics.items(): + after_key = key.replace("tool_eval_before/", "tool_eval_after/") + if after_key in post_metrics: + delta_name = after_key.replace("tool_eval_after/", "tool_eval_delta/") + post_metrics[delta_name] = post_metrics[after_key] - value + trainer.log(post_metrics) + trainer.log_metrics("eval", post_metrics) + trainer.save_metrics("eval", post_metrics) + + if training_args.push_to_hub: + trainer.push_to_hub(dataset_name=script_args.dataset_name or script_args.dataset_path) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdft/sdft_config.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdft/sdft_config.py new file mode 100644 index 0000000000000000000000000000000000000000..96547d0093370d0dfc27adc695c35f809831e6e3 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdft/sdft_config.py @@ -0,0 +1,460 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field +from typing import Any, Literal + +from transformers import TrainingArguments + +from ...trainer.base_config import _BaseConfig + + +@dataclass +class SDFTConfig(_BaseConfig): + r""" + Configuration class for the [`SDFTTrainer`]. + + Parameters: + > Parameters that control the SDFT loss + + distillation_alpha (`float`, *optional*, defaults to `0.5`): + Divergence interpolation coefficient for SDFT top-k logit distillation. + distillation_mode (`Literal["sampled_token", "full_logits", "topk_logits"]`, *optional*, defaults to `"topk_logits"`): + Distillation objective mode. SDFT defaults to top-k logit distillation. + distillation_topk (`int`, *optional*, defaults to `100`): + Number of top tokens used by the default SDFT top-k logit objective. + distillation_is_clip (`float`, *optional*, defaults to `2.0`): + Clipping coefficient for importance sampling in self-distillation. `None` disables clipping. + distillation_add_tail (`bool`, *optional*, defaults to `False`): + Whether to add a tail bucket for non-top-k probability mass. + num_loss_tokens_to_skip (`int`, *optional*, defaults to `0`): + Number of initial completion tokens to exclude from the distillation loss. + + > Parameters that control the teacher + + teacher_model_kind (`str`, *optional*, defaults to `"base"`): + Semantic teacher choice for SDFT. `base` uses the initial student, `live` uses the current student, and + `ema` uses an exponentially averaged teacher. + teacher_update_rate (`float`, *optional*, defaults to `0.05`): + EMA update rate used when `teacher_model_kind="ema"`. A value of `1.0` reduces the update to a hard + overwrite, periodically resyncing the teacher to the current student weights. + teacher_sync_steps (`int`, *optional*, defaults to `1`): + Number of optimizer steps between teacher updates. + + > Parameters that control teacher-conditioned generation + + generate_from_teacher (`bool`, *optional*, defaults to `False`): + Whether on-policy generation should use the teacher-conditioned prompt instead of the student prompt. + teacher_prompt_template (`str`, *optional*, defaults to `"{prompt}\n\n{privileged_context}"`): + Template used to combine the student prompt and privileged context into the teacher prompt. + + > Parameters that control the model + + model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments for `transformers.AutoModelForCausalLM.from_pretrained`, used when the `model` argument + of the `SDFTTrainer` is provided as a string. + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the student and teacher models. + + > Parameters that control data preprocessing + + remove_unused_columns (`bool`, *optional*, defaults to `False`): + Whether to only keep the columns required by the trainer in the dataset. Keep this to `False` if you + provide extra columns (such as `privileged_context`) that the trainer needs. + max_prompt_length (`int`, *optional*, defaults to `512`): + Maximum prompt length. Longer prompts are truncated from the left. + shuffle_dataset (`bool`, *optional*, defaults to `True`): + Whether to shuffle the training dataset. + + > Parameters that control generation + + num_generations (`int`, *optional*, defaults to `8`): + Number of generations to sample. The effective batch size (num_processes * per_device_batch_size * + gradient_accumulation_steps) must be evenly divisible by this value. + num_generations_eval (`int`, *optional*): + Number of generations to sample during evaluation. This allows using fewer generations during evaluation to + save computation. If `None`, uses the value of `num_generations`. + max_completion_length (`int`, *optional*, defaults to `256`): + Maximum length of the generated completion. + temperature (`float`, *optional*, 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`, *optional*, defaults to `0`): + Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, top-k-filtering is + disabled and all tokens are considered. + min_p (`float`, *optional*): + 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. + cache_implementation (`str`, *optional*): + Implementation of the cache method for faster generation when use_vllm is set to False. + generation_kwargs (`dict[str, Any]`, *optional*): + 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 `suppress_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. + chat_template_kwargs (`dict[str, Any]`, *optional*): + Additional keyword arguments to pass to the `apply_chat_template` function when generating completions. + 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. + + > 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. + use_teacher_server (`bool`, *optional*, defaults to `False`): + Compute teacher logprobs from the running vLLM generation server instead of a local teacher forward. Only + supported for `teacher_model_kind='live'` with `use_vllm=True` and `vllm_mode='server'`, and + `distillation_mode` in {'sampled_token', 'topk_logits'} (the server returns the teacher's top-k logprobs, + not the full vocabulary; `topk_logits` distills over the teacher's own top-k support). + vllm_mode (`str`, *optional*, defaults to `"colocate"`): + 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_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. + vllm_enable_sleep_mode (`bool`, *optional*, defaults to `False`): + Enable vLLM sleep mode to offload weights/cache during the optimizer step. Keeps GPU memory usage low, but + waking the engine adds host–device transfer latency. + vllm_server_base_url (`str`, *optional*): + 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_group_port (`int`, *optional*, defaults to `51216`): + Port number for the weight update group. This is used to communicate with the vLLM server. Unless the port + is occupied, there is no need to change it. + 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. + 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_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_max_model_length (`int`, *optional*): + Context window for vLLM. Set it to at least the maximum prompt length in the dataset plus + `max_completion_length`; if omitted, it is inferred from the model config. + + > Parameters that control the training + + num_iterations (`int`, *optional*, defaults to `1`): + Number of iterations per batch (denoted as μ in the algorithm). + generation_batch_size (`int`, *optional*): + 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`. + steps_per_generation (`int`, *optional*): + Number of steps per generation. If `None`, it defaults to `gradient_accumulation_steps`. + """ + + _VALID_DICT_FIELDS = TrainingArguments._VALID_DICT_FIELDS + ["model_init_kwargs"] + + model_init_kwargs: dict[str, Any] | None = field( + default=None, + metadata={ + "help": "Keyword arguments for `transformers.AutoModelForCausalLM.from_pretrained`, used when the `model` argument of the `SDFTTrainer` is provided as a string." + }, + ) + disable_dropout: bool = field( + default=True, + metadata={"help": "Whether to disable dropout in the student and teacher models."}, + ) + remove_unused_columns: bool = field( + default=False, + metadata={ + "help": "Whether to only keep the columns required by the trainer in the dataset. Keep this to `False` if you provide extra columns (such as `privileged_context`) that the trainer needs." + }, + ) + max_prompt_length: int | None = field( + default=512, + metadata={"help": "Maximum prompt length. Longer prompts are truncated from the left."}, + ) + num_generations: int = field( + default=8, + metadata={ + "help": "Number of generations to sample. The effective batch size (num_processes * per_device_batch_size * gradient_accumulation_steps) must be evenly divisible by this value." + }, + ) + num_generations_eval: int | None = field( + default=None, + metadata={ + "help": "Number of generations to sample during evaluation. This allows using fewer generations during evaluation to save computation. If `None`, uses the value of `num_generations`." + }, + ) + max_completion_length: int | None = field( + default=256, + metadata={"help": "Maximum length of the generated completion."}, + ) + ds3_gather_for_generation: bool = field( + default=True, + metadata={ + "help": "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 = field( + default=True, + metadata={"help": "Whether to shuffle the training dataset."}, + ) + generation_batch_size: int | None = field( + default=None, + metadata={ + "help": "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`." + }, + ) + steps_per_generation: int | None = field( + default=None, + metadata={"help": "Number of steps per generation. If `None`, it defaults to `gradient_accumulation_steps`."}, + ) + temperature: float = field( + default=1.0, + metadata={"help": "Temperature for sampling. The higher the temperature, the more random the completions."}, + ) + top_p: float = field( + default=1.0, + metadata={ + "help": "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 = field( + default=0, + metadata={ + "help": "Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, top-k-filtering is disabled and all tokens are considered." + }, + ) + min_p: float | None = field( + default=None, + metadata={ + "help": "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." + }, + ) + generation_kwargs: dict[str, Any] | None = field( + default=None, + metadata={ + "help": "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 `suppress_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." + }, + ) + chat_template_kwargs: dict[str, Any] | None = field( + default=None, + metadata={ + "help": "Additional keyword arguments to pass to the `apply_chat_template` function when generating completions." + }, + ) + repetition_penalty: float = field( + default=1.0, + metadata={ + "help": "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." + }, + ) + cache_implementation: str | None = field( + default=None, + metadata={"help": "Implementation of the cache method for faster generation when use_vllm is set to False."}, + ) + use_vllm: bool = field( + default=False, + metadata={ + "help": "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." + }, + ) + use_teacher_server: bool = field( + default=False, + metadata={ + "help": "Compute teacher logprobs from the running vLLM generation server instead of a local teacher " + "forward. Only supported for `teacher_model_kind='live'` with `use_vllm=True` and `vllm_mode='server'`, " + "and `distillation_mode` in {'sampled_token', 'topk_logits'} (the server returns the teacher's top-k " + "logprobs, not the full vocabulary; `topk_logits` distills over the teacher's own top-k support)." + }, + ) + vllm_mode: str = field( + default="colocate", + metadata={ + "help": "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_model_impl: str = field( + default="vllm", + metadata={ + "help": "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." + }, + ) + vllm_enable_sleep_mode: bool = field( + default=False, + metadata={ + "help": "Enable vLLM sleep mode to offload weights/cache during the optimizer step. Keeps GPU memory usage low, but waking the engine adds host–device transfer latency." + }, + ) + vllm_server_base_url: str | None = field( + default=None, + metadata={ + "help": "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 = field( + default="0.0.0.0", + metadata={"help": "Host of the vLLM server to connect to. Ignored if vllm_server_base_url is provided."}, + ) + vllm_server_port: int = field( + default=8000, + metadata={"help": "Port of the vLLM server to connect to. Ignored if vllm_server_base_url is provided."}, + ) + vllm_group_port: int = field( + default=51216, + metadata={ + "help": "Port number for the weight update group. This is used to communicate with the vLLM server. Unless the port is occupied, there is no need to change it." + }, + ) + vllm_server_timeout: float = field( + default=240.0, + metadata={ + "help": "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." + }, + ) + vllm_tensor_parallel_size: int = field( + default=1, + metadata={ + "help": "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_gpu_memory_utilization: float = field( + default=0.3, + metadata={ + "help": "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_max_model_length: int | None = field( + default=None, + metadata={ + "help": "Context window for vLLM. Set it to at least the maximum prompt length in the dataset plus `max_completion_length`; if omitted, it is inferred from the model config." + }, + ) + num_iterations: int = field( + default=1, + metadata={"help": "Number of iterations per batch (denoted as μ in the algorithm)."}, + ) + teacher_model_kind: str = field( + default="base", + metadata={ + "help": "Semantic teacher choice for SDFT. `base` uses the initial student, `live` uses the current " + "student, and `ema` uses an exponentially averaged teacher." + }, + ) + teacher_update_rate: float = field( + default=0.05, + metadata={ + "help": 'EMA update rate used when `teacher_model_kind="ema"`. A value of `1.0` reduces the update ' + "to a hard overwrite, periodically resyncing the teacher to the current student weights." + }, + ) + teacher_sync_steps: int = field( + default=1, + metadata={"help": "Number of optimizer steps between teacher updates."}, + ) + distillation_alpha: float = field( + default=0.5, + metadata={"help": "Divergence interpolation coefficient for SDFT top-k logit distillation."}, + ) + distillation_mode: Literal["sampled_token", "full_logits", "topk_logits"] = field( + default="topk_logits", + metadata={"help": "Distillation objective mode. SDFT defaults to top-k logit distillation."}, + ) + distillation_topk: int | None = field( + default=100, + metadata={"help": "Number of top tokens used by the default SDFT top-k logit objective."}, + ) + distillation_is_clip: float | None = field( + default=2.0, + metadata={ + "help": "Clipping coefficient for importance sampling in self-distillation. `None` disables clipping." + }, + ) + distillation_add_tail: bool = field( + default=False, + metadata={"help": "Whether to add a tail bucket for non-top-k probability mass."}, + ) + generate_from_teacher: bool = field( + default=False, + metadata={ + "help": "Whether on-policy generation should use the teacher-conditioned prompt instead of the student prompt." + }, + ) + teacher_prompt_template: str = field( + default="{prompt}\n\n{privileged_context}", + metadata={ + "help": "Template used to combine the student prompt and privileged context into the teacher prompt." + }, + ) + num_loss_tokens_to_skip: int = field( + default=0, + metadata={"help": "Number of initial completion tokens to exclude from the distillation loss."}, + ) + + def __post_init__(self): + super().__post_init__() + if self.distillation_mode == "sampled_token" and self.distillation_alpha != 1.0: + raise ValueError( + "`distillation_mode='sampled_token'` only supports reverse KL, so it requires " + f"`distillation_alpha=1.0`, got {self.distillation_alpha}." + ) + num_processes = self.world_size + if self.generation_batch_size is None and self.steps_per_generation is None: + self.steps_per_generation = self.gradient_accumulation_steps + self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation + elif self.generation_batch_size is not None and self.steps_per_generation is None: + global_batch_size = self.per_device_train_batch_size * num_processes + if self.generation_batch_size % global_batch_size != 0: + raise ValueError( + f"generation_batch_size ({self.generation_batch_size}) must be divisible by the global batch size ({global_batch_size})." + ) + self.steps_per_generation = self.generation_batch_size // global_batch_size + elif self.generation_batch_size is None and self.steps_per_generation is not None: + self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation + else: + raise ValueError("'generation_batch_size' and 'steps_per_generation' can not both be configured") + + if self.generation_batch_size % self.num_generations != 0: + raise ValueError( + f"generation_batch_size ({self.generation_batch_size}) must be divisible by num_generations ({self.num_generations})." + ) + + if self.do_eval and self.eval_strategy != "no": + num_generations_eval = self.num_generations_eval or self.num_generations + if (self.per_device_eval_batch_size * num_processes) % num_generations_eval != 0: + raise ValueError( + f"The global eval batch size ({self.per_device_eval_batch_size} * {num_processes}) must be " + f"divisible by the number of generations used for evaluation ({num_generations_eval})." + ) + + if ( + "{prompt}" not in self.teacher_prompt_template + or "{privileged_context}" not in self.teacher_prompt_template + ): + raise ValueError( + "teacher_prompt_template must contain both `{prompt}` and `{privileged_context}` placeholders" + ) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdft/sdft_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdft/sdft_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..316b42f46a32888b47aae06b201f423458c2f6e1 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdft/sdft_trainer.py @@ -0,0 +1,1306 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import inspect +import textwrap +from collections import defaultdict +from contextlib import nullcontext +from dataclasses import dataclass +from functools import partial +from typing import Any + +import datasets +import torch +from accelerate.logging import get_logger +from accelerate.utils import is_peft_model +from datasets import Dataset, IterableDataset +from torch import nn +from torch.distributed.fsdp import FullyShardedDataParallel as FSDP +from torch.utils.data import DataLoader, Sampler +from transformers import ( + AutoProcessor, + GenerationConfig, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, +) +from transformers.trainer_utils import seed_worker +from transformers.utils import is_datasets_available, is_liger_kernel_available, is_peft_available + +from ...data_utils import is_conversational +from ...models import prepare_deepspeed, prepare_fsdp, unwrap_model_for_generation +from ...models.utils import _ForwardRedirection +from ...trainer.base_trainer import _BaseTrainer +from ...trainer.utils import ( + RepeatSampler, + create_model_from_path, + disable_dropout_in_model, + get_config_model_id, + identity, + pad, + selective_log_softmax, + split_tensor_dict, + use_adapter, +) +from ..utils import prepare_peft_model +from .loss_utils import ( + add_tail_bucket, + apply_importance_sampling_clipping, + compute_divergence, + compute_full_logit_self_distillation_loss, + compute_sampled_token_self_distillation_loss, + compute_topk_self_distillation_loss, +) +from .sdft_config import SDFTConfig +from .teacher_sync import PEFTAdapterEMACallback, SyncTeacherModelCallback, is_pure_lora_training + + +if is_peft_available(): + from peft import PeftConfig + +if is_liger_kernel_available(): + from liger_kernel.chunked_loss import LigerFusedLinearJSDLoss + + +logger = get_logger(__name__) + + +TrainingBatch = dict[str, torch.Tensor | Any] + + +def build_teacher_request_inputs( + input_ids: torch.Tensor, + attention_mask: torch.Tensor, + prompt_attention_mask: torch.Tensor, +) -> tuple[list[list[int]], list[int], list[int]]: + """Trim padded batch tensors into per-sample (prompt+completion) sequences for teacher-server requests.""" + if input_ids.shape != attention_mask.shape: + raise ValueError( + f"input_ids and attention_mask must have the same shape, got {input_ids.shape} and {attention_mask.shape}." + ) + + input_ids_cpu = input_ids.detach().cpu() + attention_mask_cpu = attention_mask.detach().cpu().bool() + prompt_lengths = prompt_attention_mask.detach().cpu().sum(dim=1).to(torch.long) + + trimmed_input_ids: list[list[int]] = [] + prompt_lengths_list: list[int] = [] + completion_lengths_list: list[int] = [] + for row, mask, prompt_length in zip(input_ids_cpu, attention_mask_cpu, prompt_lengths, strict=True): + trimmed_row = row[mask] + prompt_len = int(prompt_length.item()) + if prompt_len < 0 or prompt_len > trimmed_row.numel(): + raise ValueError( + f"Invalid prompt length {prompt_len} for trimmed sequence of length {trimmed_row.numel()}." + ) + trimmed_input_ids.append(trimmed_row.tolist()) + prompt_lengths_list.append(prompt_len) + completion_lengths_list.append(int(trimmed_row.numel()) - prompt_len) + return trimmed_input_ids, prompt_lengths_list, completion_lengths_list + + +@dataclass +class DistillationLogits: + """Aligned logits and masks used to compute a self-distillation objective.""" + + completion_ids: torch.Tensor + loss_mask: torch.Tensor + student_logits: torch.Tensor + teacher_logits: torch.Tensor + + +def _extract_last_user_text(messages: list[dict[str, Any]]) -> str: + """Extract the text content from the last user message in a conversational prompt.""" + last_message = messages[-1] + if last_message.get("role") != "user": + raise ValueError( + f"Self-distillation teacher prompt construction expects the conversation to end with a user turn, " + f"but the last message has role '{last_message.get('role')}'. " + f"Prompts ending with assistant prefills or tool turns are not supported." + ) + content = last_message.get("content", "") + if isinstance(content, list): + return " ".join(part.get("text", "") for part in content if part.get("type") == "text") + return content + + +class DemonstrationTeacherContextBuilder: + """Builds student and teacher contexts from prompts plus privileged context""" + + def __init__(self, trainer): + self.trainer = trainer + + def _stringify_privileged_context(self, privileged_context: Any) -> str: + if privileged_context is None: + raise ValueError( + "`privileged_context` must not be None for self-distillation teacher prompt construction." + ) + if isinstance(privileged_context, str): + return privileged_context + if isinstance(privileged_context, list) and privileged_context and isinstance(privileged_context[0], dict): + chunks = [] + for message in privileged_context: + content = message.get("content", "") + if isinstance(content, list): + text = " ".join(part.get("text", "") for part in content if part.get("type") == "text") + else: + text = str(content) + if text: + chunks.append(text) + return "\n".join(chunks) + return str(privileged_context) + + def _compose_teacher_prompt(self, prompt: Any, privileged_context: Any) -> Any: + privileged_text = self._stringify_privileged_context(privileged_context) + if isinstance(prompt, list): + system_messages = prompt[:-1] + prompt_text = _extract_last_user_text(prompt) + teacher_text = self.trainer.args.teacher_prompt_template.format( + prompt=prompt_text, + privileged_context=privileged_text, + ) + return system_messages + [{"role": "user", "content": teacher_text}] + return self.trainer.args.teacher_prompt_template.format(prompt=prompt, privileged_context=privileged_text) + + def select_generation_prompts(self, prompts: list[Any], privileged_contexts: list[Any]) -> list[Any]: + return [ + self._compose_teacher_prompt(prompt, privileged_context) + for prompt, privileged_context in zip(prompts, privileged_contexts, strict=True) + ] + + def build( + self, + prompts: list[Any], + privileged_contexts: list[Any], + completion_ids: torch.Tensor, + completion_mask: torch.Tensor, + ) -> dict[str, torch.Tensor]: + teacher_prompts = [ + self._compose_teacher_prompt(prompt, privileged_context) + for prompt, privileged_context in zip(prompts, privileged_contexts, strict=True) + ] + teacher_prompt_ids_list = self.trainer._tokenize_prompts(teacher_prompts) + device = completion_ids.device + teacher_prompt_ids = [torch.tensor(ids) for ids in teacher_prompt_ids_list] + teacher_prompt_mask = [torch.ones_like(ids, dtype=torch.long) for ids in teacher_prompt_ids] + teacher_prompt_ids = pad( + teacher_prompt_ids, padding_value=self.trainer._tokenizer.pad_token_id, padding_side="left" + ).to(device=device) + teacher_prompt_mask = pad(teacher_prompt_mask, padding_value=0, padding_side="left").to(device=device) + teacher_input_ids = torch.cat([teacher_prompt_ids, completion_ids], dim=1) + teacher_attention_mask = torch.cat([teacher_prompt_mask, completion_mask], dim=1) + return { + "teacher_input_ids": teacher_input_ids, + "teacher_attention_mask": teacher_attention_mask, + } + + +class SDFTTrainer(_BaseTrainer): + """Trainer for SDFT-style on-policy self-distillation with explicit teacher prompts.""" + + _tag_names = ["trl", "sdft"] + _name = "SDFT" + config_cls = SDFTConfig + # docstyle-ignore + _paper = { + "title": "Self-Distillation Enables Continual Learning", + "id": "2601.19897", + "citation": textwrap.dedent("""\ + @article{shenfeld2026selfdistillation, + title = {{Self-Distillation Enables Continual Learning}}, + author = {Idan Shenfeld and Mehul Damani and Jonas H\\"ubotter and Pulkit Agrawal}, + year = 2026, + eprint = {arXiv:2601.19897} + }"""), + } + + def __init__( + self, + model: str | PreTrainedModel | nn.Module, + args: SDFTConfig | None = None, + train_dataset: Dataset | IterableDataset | None = None, + eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None, + processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None), + peft_config: PeftConfig | None = None, + ): + if isinstance(train_dataset, IterableDataset): + raise NotImplementedError("Iterable datasets are not yet supported in SDFTTrainer.") + if isinstance(eval_dataset, IterableDataset) or ( + isinstance(eval_dataset, dict) and any(isinstance(ds, IterableDataset) for ds in eval_dataset.values()) + ): + raise NotImplementedError("Iterable eval datasets are not yet supported in SDFTTrainer.") + + self.num_loss_tokens_to_skip = args.num_loss_tokens_to_skip + self.teacher_context_builder = DemonstrationTeacherContextBuilder(self) + + if train_dataset is None: + raise ValueError("`train_dataset` is required") + + if isinstance(model, str): + model_init_kwargs = args.model_init_kwargs or {} + if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + model_init_kwargs["device_map"] = None + model = create_model_from_path(model, **model_init_kwargs) + elif args.model_init_kwargs is not None: + logger.warning( + "You passed `model_init_kwargs` to the self-distillation config, but `model` is already " + "instantiated. The `model_init_kwargs` will be ignored." + ) + + self.model_kwarg_keys = ( + inspect.signature(model.forward).parameters.keys() + if not hasattr(model, "get_base_model") + else inspect.signature(model.get_base_model().forward).parameters.keys() + ) + + if peft_config is None and getattr(model, "peft_config", None) is not None: + logger.warning( + "The provided self-distillation student model already contains a PEFT adapter. " + "This setup is accepted but not directly supported. In particular, `teacher_model_kind='base'` " + "may refer to the underlying base weights rather than the exact initially loaded student state " + "including its adapter. For unambiguous teacher behavior, start from a merged/non-adapter model " + "or manage separate adapters explicitly." + ) + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + if is_peft_model(model): + raise ValueError( + "You passed a `PeftModel` instance together with a `peft_config`. Pass either a base " + "model with `peft_config`, or a pre-wrapped PEFT model." + ) + if peft_config is not None or (is_peft_available() and getattr(model, "peft_config", None) is not None): + model = prepare_peft_model(model, peft_config, args) + + if processing_class is None: + processing_class = AutoProcessor.from_pretrained( + get_config_model_id(model.config), truncation_side="left", padding_side="left" + ) + + if isinstance(processing_class, ProcessorMixin): + self._tokenizer = processing_class.tokenizer + elif isinstance(processing_class, PreTrainedTokenizerBase): + self._tokenizer = processing_class + else: + raise TypeError("The `processing_class` must be either a `PreTrainedTokenizerBase` or a `ProcessorMixin`") + + if self._tokenizer.pad_token is None: + self._tokenizer.pad_token = self._tokenizer.eos_token + + self.max_prompt_length = args.max_prompt_length + self.max_completion_length = args.max_completion_length + self.num_generations = args.num_generations + self.num_generations_eval = args.num_generations_eval or args.num_generations + self.num_iterations = args.num_iterations + self.shuffle_dataset = args.shuffle_dataset + self.temperature = args.temperature + self.generate_from_teacher = args.generate_from_teacher + self.use_vllm = args.use_vllm + self.chat_template_kwargs = args.chat_template_kwargs or {} + self._step = 0 + self._buffered_inputs = None + self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)} + + self.generation_kwargs = { + "max_new_tokens": self.max_completion_length, + "do_sample": True, + "pad_token_id": self._tokenizer.pad_token_id, + "bos_token_id": self._tokenizer.bos_token_id, + "eos_token_id": self._tokenizer.eos_token_id, + "temperature": args.temperature, + "top_p": args.top_p, + "top_k": args.top_k, + "min_p": args.min_p, + "repetition_penalty": args.repetition_penalty, + "cache_implementation": args.cache_implementation, + } + if args.generation_kwargs is not None: + self.generation_kwargs.update(args.generation_kwargs) + self.generation_config = GenerationConfig(**self.generation_kwargs, disable_compile=True) + + if hasattr(model, "warnings_issued"): + model.warnings_issued["estimate_tokens"] = True + + # Teacher logprobs from the running vLLM generation server (reuses the synced student weights) instead of a + # local teacher forward. MVP: `live` teacher only — the generation server holds the current student weights. + self.use_teacher_server = args.use_teacher_server + if self.use_teacher_server: + if not (args.use_vllm and args.vllm_mode == "server"): + raise ValueError( + "`use_teacher_server=True` requires `use_vllm=True` and `vllm_mode='server'`: teacher logprobs are " + "served by the same vLLM server used for generation." + ) + if args.teacher_model_kind != "live": + raise ValueError( + "`use_teacher_server=True` only supports `teacher_model_kind='live'` (the generation server holds " + f"the current student weights), got {args.teacher_model_kind!r}." + ) + if args.distillation_mode not in ("sampled_token", "topk_logits"): + raise ValueError( + "`use_teacher_server=True` only supports `distillation_mode` in {'sampled_token', 'topk_logits'}, " + f"got {args.distillation_mode!r}. The server returns the teacher's top-k logprobs, not the full " + "vocabulary, so `full_logits` is unavailable. Note `topk_logits` distills over the teacher's own " + "top-k support (the server cannot score the student's top-k indices)." + ) + if args.use_liger_kernel: + raise ValueError( + "`use_teacher_server=True` is incompatible with `use_liger_kernel`: the server returns top-k " + "logprobs while the Liger fused loss needs full-vocabulary hidden states." + ) + # Liger fused JSD loss for `full_logits`: same generalized JSD as `compute_divergence`, so alpha maps to beta. + self.use_liger_loss = False + if args.use_liger_kernel: + if not is_liger_kernel_available(): + raise ImportError( + "Liger is required to use `use_liger_kernel` as the self-distillation loss. Run " + "`pip install liger-kernel`." + ) + if args.distillation_mode != "full_logits": + raise ValueError( + "`use_liger_kernel` only supports `distillation_mode='full_logits'`, got " + f"{args.distillation_mode!r}. The fused JSD kernel operates on the full vocabulary and cannot " + "express the top-k support or sampled-token objectives." + ) + if args.distillation_is_clip is not None: + raise ValueError( + "`use_liger_kernel` is incompatible with `distillation_is_clip`: the fused kernel does not expose " + "per-token losses for importance-sampling clipping." + ) + self.liger_jsd_loss = LigerFusedLinearJSDLoss( + beta=args.distillation_alpha, + ignore_index=-100, + temperature=args.temperature, + compiled=False, + weight_hard_loss=0.0, + weight_soft_loss=1.0, + ) + self._forward_redirection = _ForwardRedirection() + self.use_liger_loss = True + + super().__init__( + model=model, + args=args, + data_collator=identity, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + callbacks=callbacks, + optimizers=optimizers, + compute_loss_func="non-None value to disable scaling", + ) + + self._last_loaded_step = -1 if self.use_vllm else 0 + if self.use_vllm: + from ...generation.vllm_generation import VLLMGeneration + + self.vllm_generation = VLLMGeneration( + model=self.model, + accelerator=self.accelerator, + processing_class=self.processing_class, + mode=args.vllm_mode, + server_base_url=args.vllm_server_base_url, + server_host=args.vllm_server_host, + server_port=args.vllm_server_port, + group_port=args.vllm_group_port, + server_timeout=args.vllm_server_timeout, + tensor_parallel_size=args.vllm_tensor_parallel_size, + gpu_memory_utilization=args.vllm_gpu_memory_utilization, + max_model_length=args.vllm_max_model_length, + max_num_seqs=args.per_device_train_batch_size + * args.vllm_tensor_parallel_size + * args.steps_per_generation, + enable_sleep_mode=args.vllm_enable_sleep_mode, + model_impl=args.vllm_model_impl, + repetition_penalty=args.repetition_penalty, + temperature=self.temperature, + top_p=args.top_p, + top_k=args.top_k, + min_p=args.min_p, + max_completion_length=self.max_completion_length, + logprobs=None, + generation_kwargs=args.generation_kwargs, + ) + + # Per-rank read-only client to the same generation server for teacher scoring (weights are synced there by + # `VLLMGeneration`; scoring needs no weight-update communicator). Mirrors the distillation trainer's + # `teacher_client`. + self.teacher_client = None + if self.use_teacher_server: + from ...generation.vllm_client import VLLMClient + + base_url = args.vllm_server_base_url or f"http://{args.vllm_server_host}:{args.vllm_server_port}" + self.teacher_client = VLLMClient(base_url=base_url, connection_timeout=args.vllm_server_timeout) + + if args.disable_dropout: + disable_dropout_in_model(self.model) + + if hasattr(self.model, "add_model_tags"): + self.model.add_model_tags(self._tag_names) + + self._setup_teacher_model() + self.model_accepts_loss_kwargs = False + + def _set_signature_columns_if_needed(self): + if self._signature_columns is None: + self._signature_columns = ["prompt", "privileged_context"] + + def _dispatch_self_distillation_callback(self, event_name: str, **payload) -> None: + for callback in self.callback_handler.callbacks: + callback_fn = getattr(callback, event_name, None) + if callback_fn is not None: + callback_fn( + args=self.args, + state=self.state, + control=self.control, + model=self.model, + processing_class=self.processing_class, + **payload, + ) + + def _setup_teacher_model(self) -> None: + """Prepare teacher state according to the semantic teacher choice. + + Resolve `teacher_model_kind` × PEFT state into the effective teacher: + + - `"live"` (any model): + Teacher is the student. No divergence, no callback. + - `"base"` + PEFT model: + Teacher reuses `self.model`; the base weights are recovered downstream by disabling the adapter via + `use_adapter` during teacher forward. + - `"base"` + non-PEFT model: + Teacher is a frozen deepcopy of the initial student (falls through to the copy branch below). + - `"ema"` + pure-LoRA training: + Teacher reuses `self.model`; a dedicated `"teacher"` LoRA adapter is attached and updated by + `PEFTAdapterEMACallback`. Teacher forward switches to that adapter downstream. + - `"ema"` (otherwise): + Teacher is a frozen deepcopy synchronized each step by `SyncTeacherModelCallback`. + + Must be called after `super().__init__` so that `self.callback_handler` is available. + """ + + teacher_model_kind = self.args.teacher_model_kind + + if teacher_model_kind == "live": + self.teacher_model = self.model + return + + if teacher_model_kind == "base" and is_peft_model(self.model): + self.teacher_model = self.model + return + + if self._use_peft_ema_teacher_adapter(): + # Must run after super().__init__ so self.callback_handler exists. + self.add_callback( + PEFTAdapterEMACallback( + model=self.model, + teacher_adapter_name="teacher", + update_rate=self.args.teacher_update_rate, + sync_steps=self.args.teacher_sync_steps, + accelerator=self.accelerator, + ) + ) + self.teacher_model = self.model + return + + if is_peft_model(self.model): + raise ValueError( + "`teacher_model_kind='ema'` with a non-pure-LoRA PEFT model is not supported: the separate EMA " + "teacher cannot be parameter-matched to the PEFT student. Use pure-LoRA training, a non-PEFT model, " + "or `teacher_model_kind` in {'live', 'base'}." + ) + + # Build the teacher from the model path (like the GRPO/DPO reference model) rather than deep-copying the + # student: under ZeRO-3 the student params are already sharded, so a deep copy would clone empty shards. + model_init_kwargs = self.args.model_init_kwargs or {} + if self.args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + model_init_kwargs["device_map"] = None + self.teacher_model = create_model_from_path(get_config_model_id(self.model.config), **model_init_kwargs) + self.teacher_model.requires_grad_(False) + self.teacher_model.eval() + if self.is_deepspeed_enabled: + self.teacher_model = prepare_deepspeed(self.teacher_model, self.accelerator) + elif self.is_fsdp_enabled: + self.teacher_model = prepare_fsdp(self.teacher_model, self.accelerator) + else: + self.teacher_model = self.accelerator.prepare_model(self.teacher_model, evaluation_mode=True) + + if teacher_model_kind == "ema": + self.add_callback(SyncTeacherModelCallback(teacher_model=self.teacher_model, accelerator=self.accelerator)) + + def _use_peft_ema_teacher_adapter(self) -> bool: + return self.args.teacher_model_kind == "ema" and is_pure_lora_training(self.model, self.accelerator) + + def get_train_dataloader(self): + if self.train_dataset is None: + raise ValueError("Trainer: training requires a train_dataset.") + + train_dataset = self.train_dataset + data_collator = self.data_collator + if is_datasets_available() and isinstance(train_dataset, datasets.Dataset): + train_dataset = self._remove_unused_columns(train_dataset, description="training") + else: + data_collator = self._get_collator_with_removed_columns(data_collator, description="training") + + dataloader_params = { + "batch_size": self._train_batch_size * self.args.steps_per_generation, + "collate_fn": data_collator, + "num_workers": self.args.dataloader_num_workers, + "pin_memory": self.args.dataloader_pin_memory, + "persistent_workers": self.args.dataloader_persistent_workers, + } + if not isinstance(train_dataset, torch.utils.data.IterableDataset): + dataloader_params["sampler"] = self._get_train_sampler() + dataloader_params["drop_last"] = self.args.dataloader_drop_last + dataloader_params["worker_init_fn"] = partial( + seed_worker, num_workers=self.args.dataloader_num_workers, rank=self.args.process_index + ) + dataloader_params["prefetch_factor"] = self.args.dataloader_prefetch_factor + return self.accelerator.prepare(DataLoader(train_dataset, **dataloader_params)) + + def _get_train_sampler(self, dataset=None) -> Sampler: + if dataset is None: + dataset = self.train_dataset + return RepeatSampler( + data_source=dataset, + mini_repeat_count=self.num_generations, + batch_size=self.args.generation_batch_size // self.num_generations, + repeat_count=self.num_iterations * self.args.steps_per_generation, + shuffle=self.shuffle_dataset, + seed=self.args.seed, + ) + + def _get_eval_sampler(self, eval_dataset) -> Sampler: + return RepeatSampler( + data_source=eval_dataset, + mini_repeat_count=self.num_generations_eval, + seed=self.args.seed, + ) + + def training_step(self, model, inputs, num_items_in_batch): + # Gather spans forward+backward: the fused JSD computes the lm_head grad in backward. + with self._get_liger_zero3_lm_head_gather_ctx(model): + output = super().training_step(model, inputs, num_items_in_batch) + self._step += 1 + return output + + def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys=None): + if not isinstance(inputs, dict): + inputs = self._prepare_inputs(inputs) + with torch.no_grad(): + with self.compute_loss_context_manager(): + loss = self.compute_loss(model, inputs) + return loss.detach(), None, None + + def _prepare_inputs(self, generation_batch): + """Return the per-step training batch, regenerating rollouts and buffering them for reuse in train mode. + + In train mode, rollouts are generated once every `steps_per_generation * num_iterations` steps and split into + per-step slices reused until the next regeneration. In eval mode, every batch is freshly prepared. + """ + mode = "train" if self.model.training else "eval" + if mode == "train": + generate_every = self.args.steps_per_generation * self.num_iterations + if self._step % generate_every == 0 or self._buffered_inputs is None: + buffered_batch = self._prepare_training_batch(generation_batch) + self._buffered_inputs = split_tensor_dict(buffered_batch, self.args.steps_per_generation) + self._dispatch_self_distillation_callback( + "on_generation_batch_built", + generate_every=generate_every, + steps_per_generation=self.args.steps_per_generation, + ) + return self._buffered_inputs[self._step % self.args.steps_per_generation] + return self._prepare_training_batch(generation_batch) + + def _prepare_training_batch(self, inputs: list[dict[str, Any]]) -> TrainingBatch: + """Sample student rollouts and construct teacher prompts""" + batch = self.sample_rollouts(inputs) + mode = "train" if self.model.training else "eval" + self._record_completion_metrics(mode, batch) + prompts = [example["prompt"] for example in inputs] + privileged_contexts = [example.get("privileged_context") for example in inputs] + teacher_batch = self.teacher_context_builder.build( + prompts, + privileged_contexts, + batch["completion_ids"], + batch["completion_mask"], + ) + batch.update( + { + "teacher_input_ids": teacher_batch["teacher_input_ids"], + "teacher_attention_mask": teacher_batch["teacher_attention_mask"], + } + ) + + self._dispatch_self_distillation_callback( + "on_self_distillation_batch_prepared", + old_per_token_logps=batch.get("old_per_token_logps"), + prompt_ids=batch["prompt_ids"], + completion_ids=batch["completion_ids"], + teacher_input_ids=batch["teacher_input_ids"], + teacher_attention_mask=batch["teacher_attention_mask"], + ) + return batch + + def sample_rollouts(self, inputs: list[dict[str, Any]]) -> TrainingBatch: + """Generate completions for a batch of prompts and assemble the training batch.""" + prompts = [example["prompt"] for example in inputs] + privileged_contexts = [example.get("privileged_context") for example in inputs] + + student_prompt_ids_list = self._tokenize_prompts(prompts) + if self.generate_from_teacher: + generation_prompts = self.teacher_context_builder.select_generation_prompts(prompts, privileged_contexts) + generation_prompt_ids_list = self._tokenize_prompts(generation_prompts) + else: + generation_prompts = prompts + generation_prompt_ids_list = student_prompt_ids_list + + self._dispatch_self_distillation_callback( + "on_generation_prompts_selected", + generation_prompts=generation_prompts, + generation_prompt_text=None, + ) + + _, completion_ids_list = self._generate(generation_prompt_ids_list) + device = self.accelerator.device + prompt_ids = [torch.tensor(ids) for ids in student_prompt_ids_list] + prompt_mask = [torch.ones_like(ids, dtype=torch.long) for ids in prompt_ids] + prompt_ids = pad(prompt_ids, padding_value=self._tokenizer.pad_token_id, padding_side="left").to(device=device) + prompt_mask = pad(prompt_mask, padding_value=0, padding_side="left").to(device=device) + + completion_ids = [torch.tensor(ids) for ids in completion_ids_list] + completion_mask = [torch.ones_like(ids, dtype=torch.long) for ids in completion_ids] + completion_ids = pad(completion_ids, padding_value=self._tokenizer.pad_token_id, padding_side="right").to( + device=device + ) + completion_mask = pad(completion_mask, padding_value=0, padding_side="right").to(device=device) + + old_per_token_logps = None + if not self.generate_from_teacher: + old_per_token_logps = self._compute_rollout_logps( + prompt_ids=prompt_ids, + prompt_mask=prompt_mask, + completion_ids=completion_ids, + completion_mask=completion_mask, + ) + batch: TrainingBatch = { + "prompt_ids": prompt_ids, + "prompt_mask": prompt_mask, + "completion_ids": completion_ids, + "completion_mask": completion_mask, + "raw_completion_lengths": torch.tensor( + [len(ids) for ids in completion_ids_list], device=device, dtype=torch.long + ), + } + if old_per_token_logps is not None: + batch["old_per_token_logps"] = old_per_token_logps + return batch + + def _get_completion_ids_list(self, batch: TrainingBatch) -> list[list[int]]: + raw_completion_lengths = batch["raw_completion_lengths"].detach().cpu().tolist() + return [ + ids[:length].tolist() + for ids, length in zip(batch["completion_ids"].detach().cpu(), raw_completion_lengths, strict=True) + ] + + def _tokenize_prompts(self, prompts: list[Any]) -> list[list[int]]: + if is_conversational({"prompt": prompts[0]}): + tokenized = self.processing_class.apply_chat_template( + conversation=prompts, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + **self.chat_template_kwargs, + ) + prompt_ids = tokenized["input_ids"] + else: + prompt_ids = self.processing_class(text=prompts)["input_ids"] + if self.max_prompt_length is not None: + prompt_ids = [ids[-self.max_prompt_length :] for ids in prompt_ids] + return prompt_ids + + def _generate(self, prompt_ids: list[list[int]]) -> tuple[list[list[int]], list[list[int]]]: + if self.use_vllm: + return self._generate_vllm(prompt_ids) + return self._generate_transformers(prompt_ids) + + def _generate_vllm(self, prompt_ids: list[list[int]]) -> tuple[list[list[int]], list[list[int]]]: + if self.state.global_step != self._last_loaded_step: + self.vllm_generation.sync_weights() + self._last_loaded_step = self.state.global_step + + mode = "train" if self.model.training else "eval" + num_generations = self.num_generations if mode == "train" else self.num_generations_eval + prompt_ids_out, completion_ids_list, _, _ = self.vllm_generation.generate( + prompts=prompt_ids, + images=None, + num_generations=num_generations, + ) + return prompt_ids_out, completion_ids_list + + def _generate_transformers(self, prompt_ids: list[list[int]]) -> tuple[list[list[int]], list[list[int]]]: + device = self.accelerator.device + prompt_tensors = [torch.tensor(ids) for ids in prompt_ids] + padded_ids = pad(prompt_tensors, padding_value=self._tokenizer.pad_token_id, padding_side="left").to( + device=device + ) + attention_mask = pad([torch.ones_like(t) for t in prompt_tensors], padding_value=0, padding_side="left").to( + device=device + ) + generate_inputs: dict[str, torch.Tensor | Any] = {"input_ids": padded_ids, "attention_mask": attention_mask} + + with ( + unwrap_model_for_generation( + self.model_wrapped, + self.accelerator, + gather_deepspeed3_params=self.args.ds3_gather_for_generation, + generation_kwargs=self.generation_kwargs, + ) as unwrapped_model, + torch.no_grad(), + FSDP.summon_full_params(self.model_wrapped, recurse=False) if self.is_fsdp_enabled else nullcontext(), + ): + prompt_completion_ids = unwrapped_model.generate( + **generate_inputs, generation_config=self.generation_config + ) + + prompt_length = generate_inputs["input_ids"].size(1) + completion_ids = prompt_completion_ids[:, prompt_length:] + is_eos = completion_ids == self._tokenizer.eos_token_id + eos_idx = torch.full((is_eos.size(0),), is_eos.size(1), dtype=torch.long, device=device) + eos_idx[is_eos.any(dim=1)] = is_eos.int().argmax(dim=1)[is_eos.any(dim=1)] + seq_idx = torch.arange(is_eos.size(1), device=device).expand(is_eos.size(0), -1) + completion_mask = (seq_idx <= eos_idx.unsqueeze(1)).int() + completion_ids_list = [ + c[m].tolist() for c, m in zip(completion_ids.cpu(), completion_mask.bool().cpu(), strict=True) + ] + return prompt_ids, completion_ids_list + + def _compute_rollout_logps( + self, + prompt_ids: torch.Tensor, + prompt_mask: torch.Tensor, + completion_ids: torch.Tensor, + completion_mask: torch.Tensor, + ) -> torch.Tensor | None: + generate_every = self.args.steps_per_generation * self.num_iterations + old_per_token_logps = None + + if self.args.gradient_accumulation_steps % generate_every != 0: + prompt_completion_ids = torch.cat([prompt_ids, completion_ids], dim=1) + attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) + logits_to_keep = completion_ids.size(1) + with torch.no_grad(): + logits = self._forward_logits( + self.model, + prompt_completion_ids, + attention_mask, + logits_to_keep, + ) + old_per_token_logps = selective_log_softmax(logits, completion_ids) + + return old_per_token_logps + + def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): + if return_outputs: + raise ValueError("The SDFTTrainer does not support returning outputs") + + if self.use_teacher_server: + loss = self._compute_server_distillation_loss(model, inputs) + elif self.use_liger_loss: + loss = self._compute_liger_loss(model, inputs) + else: + distillation_logits = self._compute_teacher_student_logits(model, self.teacher_model, inputs) + loss = self._compute_self_distillation_loss(model, inputs, distillation_logits) + accumulation_scale = self.current_gradient_accumulation_steps if self.model.training else 1.0 + return loss / accumulation_scale + + def _compute_self_distillation_loss( + self, + model, + inputs: TrainingBatch, + distillation_logits: DistillationLogits, + ) -> torch.Tensor: + """Compute the per-token distillation loss and aggregate by normalizing over sequence length. + + Dispatches between three objectives based on `distillation_mode`: + + - `"topk_logits"`: top-k approximation of the divergence, optionally with a tail bucket for the remaining + probability mass (`distillation_add_tail`). + - `"full_logits"`: full-vocab divergence. + - `"sampled_token"`: token-level (reverse-KL) distillation on sampled `completion_ids`. + + When `distillation_is_clip` is set and `old_per_token_logps` are available, the loss is corrected by a clipped + importance-sampling ratio between the current student and the student at rollout time. + """ + if distillation_logits.loss_mask.sum() == 0: + mode = "train" if model.training else "eval" + self._log_self_distillation_metric(mode, 0.0) + # Keep the zero loss attached to the student graph so backward produces zero gradients instead of stopping. + return distillation_logits.student_logits.sum() * 0.0 + + if self.args.distillation_mode == "topk_logits": + if self.args.distillation_topk is None: + raise ValueError("`distillation_mode='topk_logits'` requires `distillation_topk` to be set.") + per_token_loss = compute_topk_self_distillation_loss( + distillation_logits.student_logits, + distillation_logits.teacher_logits, + distillation_topk=self.args.distillation_topk, + distillation_alpha=self.args.distillation_alpha, + distillation_add_tail=self.args.distillation_add_tail, + ) + elif self.args.distillation_mode == "full_logits": + per_token_loss = compute_full_logit_self_distillation_loss( + distillation_logits.student_logits, + distillation_logits.teacher_logits, + distillation_alpha=self.args.distillation_alpha, + ) + elif self.args.distillation_mode == "sampled_token": + per_token_loss = compute_sampled_token_self_distillation_loss( + distillation_logits.student_logits, + distillation_logits.teacher_logits, + distillation_logits.completion_ids, + distillation_alpha=self.args.distillation_alpha, + ) + else: + raise ValueError( + "distillation_mode must be one of: 'sampled_token', 'full_logits', 'topk_logits', " + f"got {self.args.distillation_mode!r}" + ) + + old_per_token_logps = inputs.get("old_per_token_logps") + if self.args.distillation_is_clip is not None and old_per_token_logps is not None: + student_per_token_logps = selective_log_softmax( + distillation_logits.student_logits, + distillation_logits.completion_ids, + ) + per_token_loss = apply_importance_sampling_clipping( + per_token_loss, + student_per_token_logps, + old_per_token_logps, + self.args.distillation_is_clip, + ) + + loss = (per_token_loss * distillation_logits.loss_mask).sum(-1) / distillation_logits.loss_mask.sum(-1).clamp( + min=1.0 + ) + loss = loss.mean() + + mode = "train" if model.training else "eval" + mean_distill_loss = ( + per_token_loss * distillation_logits.loss_mask + ).sum() / distillation_logits.loss_mask.sum().clamp(min=1.0) + self._log_self_distillation_metric( + mode, + self.accelerator.gather(mean_distill_loss).mean().item(), + ) + return loss + + def _compute_server_distillation_loss(self, model, inputs: TrainingBatch) -> torch.Tensor: + """Distillation loss with teacher logprobs served by the vLLM generation server (`teacher_model_kind='live'`). + + The student is forwarded locally (grad) for its logits; the teacher logprobs are fetched from the server (no + local teacher forward). `sampled_token` distills the realized token (reverse KL); `topk_logits` distills over + the teacher's own top-k support (the server cannot score the student's top-k indices). + """ + # Buffered batches are reused across optimizer steps (`num_iterations > 1`), so the server weights can lag the + # live student; re-sync before scoring. + if self.state.global_step != self._last_loaded_step: + self.vllm_generation.sync_weights() + # Only the main process pushes weights to the server, so hold every rank here until the push completes; + # otherwise non-main ranks could score against half-updated weights. + self.accelerator.wait_for_everyone() + self._last_loaded_step = self.state.global_step + + completion_ids = inputs["completion_ids"] + completion_mask = inputs["completion_mask"] + logits_to_keep = completion_ids.size(1) + + # SDFT skips the first few completion tokens in the distillation loss to suppress teacher-prompt artifacts. + loss_mask = completion_mask + if self.num_loss_tokens_to_skip > 0: + token_positions = torch.arange(completion_mask.size(1), device=completion_mask.device).unsqueeze(0) + loss_mask = completion_mask * (token_positions >= self.num_loss_tokens_to_skip).long() + + student_input_ids = torch.cat([inputs["prompt_ids"], completion_ids], dim=1) + student_attention_mask = torch.cat([inputs["prompt_mask"], completion_mask], dim=1) + student_logits = self._forward_logits( + model=model, + input_ids=student_input_ids, + attention_mask=student_attention_mask, + logits_to_keep=logits_to_keep, + ) + + mode = "train" if model.training else "eval" + teacher = self._get_teacher_token_logprobs_from_server(inputs, logits_to_keep) + # Padding positions come back as `-inf`; the masked-out positions are neutralized to finite values below so the + # divergence does not leak `+inf` through them (mirrors the distillation trainer). + required = loss_mask.bool() + student_per_token_logps = selective_log_softmax(student_logits, completion_ids) + + teacher_per_token_logps = teacher["actual_logprobs"] + if (required & ~torch.isfinite(teacher_per_token_logps)).any(): + raise ValueError("Teacher server returned no logprob for a required completion token.") + teacher_per_token_logps = torch.where( + required, teacher_per_token_logps, torch.zeros_like(teacher_per_token_logps) + ) + + # Diagnostic for disagreement between local student scores and server teacher scores on realized tokens. + # Sudden jumps can indicate stale server weights or numerical drift. + abs_diff = ((student_per_token_logps.detach() - teacher_per_token_logps).abs() * loss_mask).sum() / ( + loss_mask.sum().clamp(min=1.0) + ) + self._metrics[mode]["self_distillation/server_logprob_abs_diff"].append( + self.accelerator.gather(abs_diff).mean().item() + ) + + if self.args.distillation_mode == "sampled_token": + # Reverse-KL token-level objective, matching `compute_sampled_token_self_distillation_loss`. + per_token_loss = (student_per_token_logps - teacher_per_token_logps).detach() * student_per_token_logps + else: + teacher_topk_logps = teacher["topk_logprobs"] + teacher_topk_ids = teacher["topk_token_ids"] + # Project the student onto the teacher's top-k support, then renormalize (or add a tail bucket) before the + # divergence, matching `compute_topk_self_distillation_loss` on the teacher's support. + keep = required.unsqueeze(-1) + student_topk_logps = torch.gather( + torch.log_softmax(student_logits, dim=-1), dim=-1, index=teacher_topk_ids + ) + student_topk_logps = torch.where(keep, student_topk_logps, torch.zeros_like(student_topk_logps)) + teacher_topk_logps = torch.where(keep, teacher_topk_logps, torch.zeros_like(teacher_topk_logps)) + if self.args.distillation_add_tail: + student_topk_logps = add_tail_bucket(student_topk_logps) + teacher_topk_logps = add_tail_bucket(teacher_topk_logps) + else: + student_topk_logps = student_topk_logps - torch.logsumexp(student_topk_logps, dim=-1, keepdim=True) + teacher_topk_logps = teacher_topk_logps - torch.logsumexp(teacher_topk_logps, dim=-1, keepdim=True) + per_token_loss = compute_divergence(student_topk_logps, teacher_topk_logps, self.args.distillation_alpha) + + old_per_token_logps = inputs.get("old_per_token_logps") + if self.args.distillation_is_clip is not None and old_per_token_logps is not None: + per_token_loss = apply_importance_sampling_clipping( + per_token_loss, student_per_token_logps, old_per_token_logps, self.args.distillation_is_clip + ) + + loss = (per_token_loss * loss_mask).sum(-1) / loss_mask.sum(-1).clamp(min=1.0) + loss = loss.mean() + mean_distill_loss = (per_token_loss * loss_mask).sum() / loss_mask.sum().clamp(min=1.0) + self._log_self_distillation_metric(mode, self.accelerator.gather(mean_distill_loss).mean().item()) + return loss + + def _get_teacher_token_logprobs_from_server( + self, inputs: TrainingBatch, logits_to_keep: int + ) -> dict[str, torch.Tensor]: + """Per-token teacher logprobs from the vLLM server. + + Returns a dict with `actual_logprobs` (`(B, T)`, the realized-token logprob for reverse KL) and `topk_logprobs` + / `topk_token_ids` (`(B, T, K)`, the teacher's top-k support for top-k logit distillation). Completions are + right-padded, so server values fill the leading positions of each row and the trailing padding keeps the `-inf` + / `0` sentinels (neutralized by the caller). + """ + import numpy as np + + teacher_input_ids = inputs["teacher_input_ids"] + teacher_attention_mask = inputs["teacher_attention_mask"] + device = teacher_input_ids.device + batch_size = teacher_input_ids.size(0) + prompt_attention_mask = teacher_attention_mask[:, : teacher_attention_mask.size(1) - logits_to_keep] + if self.args.distillation_mode == "topk_logits" and self.args.distillation_topk is None: + raise ValueError("`distillation_mode='topk_logits'` requires `distillation_topk` to be set.") + top_logprobs = self.args.distillation_topk if self.args.distillation_mode == "topk_logits" else 1 + + sequences, prompt_lengths, _ = build_teacher_request_inputs( + teacher_input_ids, teacher_attention_mask, prompt_attention_mask + ) + result = self.teacher_client.get_sequence_logprobs( + sequences=sequences, + prompt_lengths=prompt_lengths, + top_logprobs=top_logprobs, + temperature=self.temperature, + ) + + actual = np.full((batch_size, logits_to_keep), float("-inf"), dtype=np.float32) + topk = np.full((batch_size, logits_to_keep, top_logprobs), float("-inf"), dtype=np.float32) + topk_ids = np.zeros((batch_size, logits_to_keep, top_logprobs), dtype=np.int64) + for i in range(batch_size): + seq_actual = result["actual_logprobs"][i] + n = min(len(seq_actual), logits_to_keep) + if n: + actual[i, :n] = np.array(seq_actual, dtype=np.float32)[:n, 0] + topk[i, :n] = np.array(result["logprobs"][i], dtype=np.float32)[:n] + topk_ids[i, :n] = np.array(result["logprob_token_ids"][i], dtype=np.int64)[:n] + return { + "actual_logprobs": torch.from_numpy(actual).to(device), + "topk_logprobs": torch.from_numpy(topk).to(device), + "topk_token_ids": torch.from_numpy(topk_ids).to(device), + } + + def _compute_teacher_student_logits( + self, + model, + teacher_model, + inputs: TrainingBatch, + ) -> DistillationLogits: + """Compute the per-token logits of the student and teacher over the completion tokens. + + The student is forwarded on its own input (original prompt plus the sampled completion) while the teacher is + forwarded on its input (prompt, privileged context, and the same completion). Both sets of logits are aligned + to the completion tokens so they can be compared position-by-position in the distillation loss. + + The teacher forward runs under `torch.no_grad()` and the context resolved by + `_get_teacher_context_for_self_distillation`, which routes it to the correct weights. + """ + prompt_ids = inputs["prompt_ids"] + prompt_mask = inputs["prompt_mask"] + completion_ids = inputs["completion_ids"] + completion_mask = inputs["completion_mask"] + logits_to_keep = completion_ids.size(1) + + # SDFT skips the first few completion tokens in the distillation loss to suppress teacher-prompt artifacts. + loss_mask = completion_mask + if self.num_loss_tokens_to_skip > 0: + token_positions = torch.arange(completion_mask.size(1), device=completion_mask.device).unsqueeze(0) + loss_mask = completion_mask * (token_positions >= self.num_loss_tokens_to_skip).long() + + student_input_ids = torch.cat([prompt_ids, completion_ids], dim=1) + student_attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) + student_logits = self._forward_logits( + model=model, + input_ids=student_input_ids, + attention_mask=student_attention_mask, + logits_to_keep=logits_to_keep, + ) + + with torch.no_grad(), self._get_teacher_context_for_self_distillation(): + teacher_logits = self._forward_logits( + model=teacher_model, + input_ids=inputs["teacher_input_ids"], + attention_mask=inputs["teacher_attention_mask"], + logits_to_keep=logits_to_keep, + ) + + return DistillationLogits( + completion_ids=completion_ids, + loss_mask=loss_mask, + student_logits=student_logits, + teacher_logits=teacher_logits, + ) + + def _forward_logits( + self, + model, + input_ids: torch.Tensor, + attention_mask: torch.Tensor, + logits_to_keep: int, + ) -> torch.Tensor: + """Forward the model and return temperature-scaled logits aligned to the completion tokens.""" + model_inputs = { + "input_ids": input_ids, + "attention_mask": attention_mask, + "use_cache": False, + } + if "logits_to_keep" in self.model_kwarg_keys: + model_inputs["logits_to_keep"] = logits_to_keep + 1 + + logits = model(**model_inputs).logits + logits = logits[:, :-1, :] + logits = logits[:, -logits_to_keep:, :] + return logits / self.temperature + + def _compute_liger_loss(self, model, inputs: TrainingBatch) -> torch.Tensor: + """`full_logits` distillation via the Liger fused JSD kernel: forwards the base models for hidden states and + fuses the lm_head projection with the divergence, never materializing the full-vocab logits. + + Each model is forwarded through its own wrapper via `_forward_redirection` so FSDP2/DeepSpeed materialize the + sharded params during the unwrapped base forward. The fused kernel needs both lm_head weights live at once, so + the frozen teacher weight is captured while the teacher is materialized and handed to the student pass. + """ + logits_to_keep = inputs["completion_ids"].size(1) + completion_mask = inputs["completion_mask"] + loss_mask = completion_mask + if self.num_loss_tokens_to_skip > 0: + token_positions = torch.arange(completion_mask.size(1), device=completion_mask.device).unsqueeze(0) + loss_mask = completion_mask * (token_positions >= self.num_loss_tokens_to_skip).long() + + unwrapped_student = self.accelerator.unwrap_model(model) + unwrapped_teacher = self.accelerator.unwrap_model(self.teacher_model) + + with torch.no_grad(), self._get_teacher_context_for_self_distillation(): + teacher_hidden, teacher_weight, teacher_bias = self._forward_redirection( + self.teacher_model, + unwrapped_teacher, + self._liger_teacher_side, + unwrapped_teacher, + inputs, + logits_to_keep, + ) + + return self._forward_redirection( + model, + unwrapped_student, + self._liger_student_loss, + unwrapped_student, + inputs, + logits_to_keep, + loss_mask, + teacher_hidden, + teacher_weight, + teacher_bias, + ) + + def _liger_teacher_side(self, teacher, inputs: TrainingBatch, logits_to_keep: int): + """Teacher hidden states + frozen lm_head weight, captured while the teacher params are materialized.""" + hidden = teacher.get_decoder()( + input_ids=inputs["teacher_input_ids"], + attention_mask=inputs["teacher_attention_mask"], + use_cache=False, + ).last_hidden_state + hidden = hidden[:, :-1][:, -logits_to_keep:] + head = teacher.get_output_embeddings() + # Clone so the weight survives re-sharding once this forward context exits. + weight = head.weight.detach().clone() + bias = head.bias.detach().clone() if head.bias is not None else None + return hidden, weight, bias + + def _liger_student_loss( + self, + student, + inputs: TrainingBatch, + logits_to_keep, + loss_mask, + teacher_hidden, + teacher_weight, + teacher_bias, + ): + student_input_ids = torch.cat([inputs["prompt_ids"], inputs["completion_ids"]], dim=1) + student_attention_mask = torch.cat([inputs["prompt_mask"], inputs["completion_mask"]], dim=1) + student_hidden = student.get_decoder()( + input_ids=student_input_ids, + attention_mask=student_attention_mask, + use_cache=False, + ).last_hidden_state + # Align hidden states to the completion-predicting positions, matching `_forward_logits`. + student_hidden = student_hidden[:, :-1][:, -logits_to_keep:] + + # `ignore_index` masks non-response positions; the token values only feed the disabled hard-CE term. + completion_ids = inputs["completion_ids"] + true_labels = torch.where(loss_mask.bool(), completion_ids, torch.full_like(completion_ids, -100)) + + student_head = student.get_output_embeddings() + # Per-sequence then batch mean (grpo), matching the non-Liger path: the fused kernel reduces by total tokens + # (bnpo), so we call it per sequence and average. + seq_losses = [ + self.liger_jsd_loss( + student_input=student_hidden[i], + student_weight=student_head.weight, + teacher_input=teacher_hidden[i], + teacher_weight=teacher_weight, + true_labels=true_labels[i], + student_bias=student_head.bias, + teacher_bias=teacher_bias, + ) + for i in range(student_hidden.size(0)) + ] + loss = torch.stack(seq_losses).mean() + + mode = "train" if student.training else "eval" + self._log_self_distillation_metric(mode, self.accelerator.gather(loss.detach()).mean().item()) + return loss + + def _get_liger_zero3_lm_head_gather_ctx(self, model): + """Gather the sharded student/teacher lm_head weights for the fused matmul under ZeRO-3. Liger reads + `lm_head.weight` by attribute, so the gather hook never fires; the decoder forward gathers itself. No-op + outside ZeRO-3.""" + if not self.use_liger_loss: + return nullcontext() + + deepspeed_plugin = self.accelerator.state.deepspeed_plugin + if deepspeed_plugin is None or deepspeed_plugin.zero_stage != 3: + return nullcontext() + + import deepspeed + + unwrapped_student = self.accelerator.unwrap_model(model) + unwrapped_teacher = self.accelerator.unwrap_model(self.teacher_model) + student_head = unwrapped_student.get_output_embeddings() + teacher_head = unwrapped_teacher.get_output_embeddings() + params = [student_head.weight, teacher_head.weight] + if student_head.bias is not None: + params.append(student_head.bias) + if teacher_head.bias is not None: + params.append(teacher_head.bias) + return deepspeed.zero.GatheredParameters(params, modifier_rank=None) + + def _get_teacher_context_for_self_distillation(self): + """Return the context manager that routes the teacher forward to the correct weights. + + For non-PEFT models this is a no-op. For PEFT models: + + - `teacher_model_kind == "base"`: disable the student adapter so the teacher forward uses the base weights. + - `teacher_model_kind == "ema"` under pure-LoRA training: switch to the `"teacher"` LoRA adapter. + - otherwise: no-op; the teacher is a separate deepcopy. + """ + teacher_model_kind = self.args.teacher_model_kind + if not is_peft_model(self.model): + return nullcontext() + + target_model = self.accelerator.unwrap_model(self.teacher_model) + + if teacher_model_kind == "base": + return use_adapter(target_model, adapter_name=None) + if teacher_model_kind == "ema" and self._use_peft_ema_teacher_adapter(): + return use_adapter(target_model, adapter_name="teacher") + return nullcontext() + + def _record_completion_metrics(self, mode: str, batch: TrainingBatch) -> None: + device = self.accelerator.device + completion_ids_list = self._get_completion_ids_list(batch) + agg_completion_lengths = self.accelerator.gather(batch["raw_completion_lengths"]) + self._metrics[mode]["completions/mean_length"].append(agg_completion_lengths.float().mean().item()) + self._metrics[mode]["completions/min_length"].append(agg_completion_lengths.float().min().item()) + self._metrics[mode]["completions/max_length"].append(agg_completion_lengths.float().max().item()) + + eos_and_pad = [self._tokenizer.eos_token_id, self._tokenizer.pad_token_id] + is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids_list], device=device) + agg_is_truncated = self.accelerator.gather(is_truncated) + self._metrics[mode]["completions/clipped_ratio"].append(agg_is_truncated.float().mean().item()) + term_completion_lengths = agg_completion_lengths[~agg_is_truncated] + if len(term_completion_lengths) == 0: + term_completion_lengths = torch.zeros(1, device=device) + self._metrics[mode]["completions/mean_terminated_length"].append(term_completion_lengths.float().mean().item()) + self._metrics[mode]["completions/min_terminated_length"].append(term_completion_lengths.float().min().item()) + self._metrics[mode]["completions/max_terminated_length"].append(term_completion_lengths.float().max().item()) + + def _log_self_distillation_metric(self, mode: str, value: float) -> None: + metric_prefix = self._name.lower().replace(" ", "_") + self._metrics[mode]["self_distillation/distillation_loss"].append(value) + self._metrics[mode][f"{metric_prefix}/distillation_loss"].append(value) + + def log(self, logs: dict[str, float], start_time: float | None = None) -> None: + mode = "train" if self.model.training else "eval" + metrics = {k: sum(v) / len(v) for k, v in self._metrics[mode].items() if v} + if mode == "eval": + metrics = {f"eval_{k}": v for k, v in metrics.items()} + logs = {**logs, **metrics} + super().log(logs, start_time) + self._metrics[mode].clear() diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdft/teacher_sync.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdft/teacher_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..8fb0f751a0bb5f4ae69ce9d201b29c09263bf21c --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdft/teacher_sync.py @@ -0,0 +1,184 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging + +import torch +from accelerate.utils import is_peft_model +from transformers import ( + TrainerCallback, + TrainerControl, + TrainerState, + TrainingArguments, +) + +from ...trainer.callbacks import SyncRefModelCallback + + +logger = logging.getLogger(__name__) + + +def is_pure_lora_training(model, accelerator=None) -> bool: + """Return `True` when the active adapter is LoRA and every trainable parameter is a LoRA parameter.""" + if not is_peft_model(model): + return False + + if accelerator is not None: + model = accelerator.unwrap_model(model) + + adapter_name = model.active_adapter + if adapter_name is None: + adapter_name = "default" + adapter_config = model.peft_config.get(adapter_name) + peft_type = adapter_config.peft_type + if peft_type is None or str(peft_type).split(".")[-1] != "LORA": + return False + + for name, param in model.named_parameters(): + if param.requires_grad and "lora_" not in name: + return False + return True + + +class SyncTeacherModelCallback(SyncRefModelCallback): + """Synchronize an EMA teacher model with the student model on each configured sync step.""" + + def __init__(self, teacher_model, accelerator=None): + super().__init__(ref_model=teacher_model, accelerator=accelerator) + + def on_step_end(self, args, state, control, **kwargs): + model = kwargs["model"] + if self.ref_model is not None and state.global_step % args.teacher_sync_steps == 0: + if self.accelerator: + model = self.accelerator.unwrap_model(model) + self.sync_target_model(model, self.ref_model, args.teacher_update_rate) + + +class PEFTAdapterEMACallback(TrainerCallback): + """ + Callback that maintains an EMA copy of PEFT adapter weights for use as a teacher model in self-distillation. + + The callback creates a secondary adapter ("teacher") with zero-initialized weights and maintains shadow weights + that are updated via exponential moving average: `teacher_weight = (1-α) * teacher_weight + α * student_weight` + + Usage: + ```python + trainer.add_callback( + PEFTAdapterEMACallback( + model=model, + teacher_adapter_name="teacher", + update_rate=0.05, + ) + ) + ``` + """ + + def __init__( + self, + model, + teacher_adapter_name: str = "teacher", + update_rate: float = 0.05, + sync_steps: int = 1, + accelerator=None, + ): + self.model = model + self.teacher_adapter_name = teacher_adapter_name + self.update_rate = update_rate + self.sync_steps = sync_steps + self.accelerator = accelerator + self.shadow_weights: dict[str, torch.Tensor] | None = None + self.teacher_adapter_config = None + self._initialized = False + + def _get_student_state_dict(self): + """Get student adapter state dict using PEFT keys (without adapter name).""" + from peft import get_peft_model_state_dict + + if self.accelerator is not None: + model = self.accelerator.unwrap_model(self.model) + else: + model = self.model + return get_peft_model_state_dict(model) + + def _initialize_teacher_adapter(self): + """Create teacher adapter with zero weights initialized from student adapter.""" + from peft import get_peft_model_state_dict, set_peft_model_state_dict + + if self._initialized: + return + + if self.accelerator is not None: + model = self.accelerator.unwrap_model(self.model) + else: + model = self.model + + adapter_name = model.active_adapter + if adapter_name is None: + adapter_name = "default" + + self.teacher_adapter_config = model.peft_config.get(adapter_name) + + student_state = get_peft_model_state_dict(model) + + teacher_state = {k: torch.zeros_like(v) for k, v in student_state.items()} + + model.add_adapter(self.teacher_adapter_name, self.teacher_adapter_config) + + model.set_adapter(self.teacher_adapter_name) + set_peft_model_state_dict(model, teacher_state, adapter_name=self.teacher_adapter_name) + + model.set_adapter(adapter_name) + + self.shadow_weights = {k: v.clone().zero_() for k, v in teacher_state.items()} + + self._initialized = True + logger.info(f"Initialized PEFT adapter EMA teacher with adapter name: {self.teacher_adapter_name}") + + @torch.no_grad() + def on_step_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): + if state.global_step % self.sync_steps != 0: + return + + if not self._initialized: + self._initialize_teacher_adapter() + + if self.shadow_weights is None: + return + + if self.accelerator is None and "accelerator" in kwargs: + self.accelerator = kwargs["accelerator"] + + student_state = self._get_student_state_dict() + + for key, student_param in student_state.items(): + if key in self.shadow_weights: + shadow = self.shadow_weights[key] + shadow.data = (1 - self.update_rate) * shadow.data + self.update_rate * student_param.data + + from peft import set_peft_model_state_dict + + if self.accelerator is not None: + unwrapped_model = self.accelerator.unwrap_model(self.model) + else: + unwrapped_model = self.model + + original_adapter = unwrapped_model.active_adapter + unwrapped_model.set_adapter(self.teacher_adapter_name) + set_peft_model_state_dict(unwrapped_model, self.shadow_weights, adapter_name=self.teacher_adapter_name) + unwrapped_model.set_adapter(original_adapter) + + def on_train_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): + if self.accelerator is None and "accelerator" in kwargs: + self.accelerator = kwargs["accelerator"] + self._initialize_teacher_adapter() diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdpo/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdpo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f50a54cf7c8d3dcc907361da9caa07e53cd21d9f --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdpo/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .sdpo_config import SDPOConfig +from .sdpo_trainer import SDPOTrainer + + +__all__ = ["SDPOConfig", "SDPOTrainer"] diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdpo/loss_utils.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdpo/loss_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5caa8c88713d2088c9c4c728dcea3e62236cf4e4 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdpo/loss_utils.py @@ -0,0 +1,135 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Pure helper functions for self-distillation loss computation.""" + +import torch +import torch.nn.functional as F + +from ...trainer.utils import selective_log_softmax + + +def compute_divergence( + student_log_probs: torch.Tensor, + teacher_log_probs: torch.Tensor, + alpha: float, +) -> torch.Tensor: + if alpha == 0.0: + kl = F.kl_div(student_log_probs, teacher_log_probs, reduction="none", log_target=True) + elif alpha == 1.0: + kl = F.kl_div(teacher_log_probs, student_log_probs, reduction="none", log_target=True) + else: + alpha_t = torch.tensor(alpha, dtype=student_log_probs.dtype, device=student_log_probs.device) + mixture = torch.logsumexp( + torch.stack([student_log_probs + torch.log(1 - alpha_t), teacher_log_probs + torch.log(alpha_t)]), + dim=0, + ) + kl_teacher = F.kl_div(mixture, teacher_log_probs, reduction="none", log_target=True) + kl_student = F.kl_div(mixture, student_log_probs, reduction="none", log_target=True) + kl = torch.lerp(kl_student, kl_teacher, alpha) + return kl.sum(-1) + + +def add_tail_bucket(log_probs: torch.Tensor) -> torch.Tensor: + """Append a bucket holding the leftover probability mass to a top-k log-prob support. + + `log_probs` are true log-probabilities over a top-k subset, so they sum to the captured mass `P_topk <= 1`. This + appends one extra category equal to the tail mass `1 - P_topk`, yielding a distribution that sums to exactly 1. + """ + log_s = torch.logsumexp(log_probs, dim=-1, keepdim=True) + log_s = torch.clamp(log_s, max=-1e-7) + tail_log = torch.log(-torch.expm1(log_s)) + return torch.cat([log_probs, tail_log], dim=-1) + + +def apply_importance_sampling_clipping( + per_token_loss: torch.Tensor, + student_log_probs: torch.Tensor, + old_log_probs: torch.Tensor, + clip_coeff: float, +) -> torch.Tensor: + negative_approx_kl = (student_log_probs - old_log_probs).detach() + negative_approx_kl = torch.clamp(negative_approx_kl, min=-20.0, max=20.0) + ratio = torch.exp(negative_approx_kl).clamp(max=clip_coeff) + return per_token_loss * ratio + + +def compute_topk_self_distillation_loss( + student_logits: torch.Tensor, + teacher_logits: torch.Tensor, + *, + distillation_topk: int, + distillation_alpha: float, + distillation_add_tail: bool, +) -> torch.Tensor: + """Compute distillation loss on the student's top-k token support. + + The student's top-k logits define the support. The teacher distribution is projected onto the same token indices. + The selected support is then either renormalized or augmented with a tail bucket before the divergence is computed. + """ + student_logsumexp = torch.logsumexp(student_logits, dim=-1, keepdim=True) + topk_student_logits, topk_indices = torch.topk(student_logits, k=distillation_topk, dim=-1) + topk_student_log_probs = topk_student_logits - student_logsumexp + + teacher_logsumexp = torch.logsumexp(teacher_logits, dim=-1, keepdim=True) + topk_teacher_logits = torch.gather(teacher_logits, dim=-1, index=topk_indices) + topk_teacher_log_probs = topk_teacher_logits - teacher_logsumexp + + # Top-k log-probs sum to the captured mass P_topk <= 1; the rest (1 - P_topk) is the "tail". + if distillation_add_tail: + # Lump the tail into one bucket so the divergence approximates the full-vocab divergence. + topk_student_log_probs = add_tail_bucket(topk_student_log_probs) + topk_teacher_log_probs = add_tail_bucket(topk_teacher_log_probs) + else: + # Drop the tail and renormalize the top-k to sum to 1: divergence over the top-k conditional only. + topk_student_log_probs = topk_student_log_probs - torch.logsumexp(topk_student_log_probs, dim=-1, keepdim=True) + topk_teacher_log_probs = topk_teacher_log_probs - torch.logsumexp(topk_teacher_log_probs, dim=-1, keepdim=True) + + return compute_divergence(topk_student_log_probs, topk_teacher_log_probs, distillation_alpha) + + +def compute_full_logit_self_distillation_loss( + student_logits: torch.Tensor, + teacher_logits: torch.Tensor, + *, + distillation_alpha: float, +) -> torch.Tensor: + """Compute full-vocabulary self-distillation loss between student and teacher logits.""" + student_log_probs = torch.log_softmax(student_logits, dim=-1) + teacher_log_probs = torch.log_softmax(teacher_logits, dim=-1) + return compute_divergence(student_log_probs, teacher_log_probs, distillation_alpha) + + +def compute_sampled_token_self_distillation_loss( + student_logits: torch.Tensor, + teacher_logits: torch.Tensor, + completion_ids: torch.Tensor, + *, + distillation_alpha: float, +) -> torch.Tensor: + """Compute token-level self-distillation loss only on the sampled completion tokens. + + This path compares student and teacher log-probabilities on the realized completion tokens rather than over a + larger token support. + """ + if distillation_alpha != 1.0: + raise ValueError( + "Only reverse KL (alpha=1.0) is supported for token-level distillation when " + f"`distillation_mode='sampled_token'`, got alpha={distillation_alpha}" + ) + + student_per_token_logps = selective_log_softmax(student_logits, completion_ids) + teacher_per_token_logps = selective_log_softmax(teacher_logits, completion_ids) + log_ratio = student_per_token_logps - teacher_per_token_logps + return log_ratio.detach() * student_per_token_logps diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdpo/sdpo.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdpo/sdpo.py new file mode 100644 index 0000000000000000000000000000000000000000..a49c6a8f547afb230017e322b47f72d88bac2bd8 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdpo/sdpo.py @@ -0,0 +1,390 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# /// script +# dependencies = [ +# "trl", +# "peft", +# "math-verify", +# "latex2sympy2_extended", +# "trackio", +# "kernels", +# ] +# /// + +""" +Usage: + +```bash +python trl/experimental/sdpo/sdpo.py \ + --model_name_or_path Qwen/Qwen2.5-Math-1.5B-Instruct \ + --dataset_name openai/gsm8k \ + --dataset_config main \ + --output_dir outputs/sdpo-qwen35-2b-gsm8k \ + --learning_rate 5e-5 \ + --dtype bfloat16 \ + --bf16 true \ + --max_completion_length 128 \ + --use_peft \ + --lora_target_modules q_proj k_proj v_proj o_proj gate_proj up_proj down_proj \ + --per_device_train_batch_size 1 \ + --gradient_accumulation_steps 2 \ + --num_generations 8 \ + --generation_batch_size 32 \ + --distillation_alpha 1.0 \ + --distillation_mode sampled_token \ + --distillation_weight 0.5 \ + --report_to none \ + --eval_strategy steps \ + --eval_steps 1000 \ + --save_strategy no \ + --eval_num_prompts 0 \ + --accuracy_eval_num_examples 64 \ + --max_train_examples 256 \ + --max_eval_examples 128 +``` + +This example uses verifiable math rewards and reports answer accuracy before and after training. If your dataset +already contains textual environment feedback, pass the column name via `--feedback_column`; it will be forwarded as +`privileged_context` for SDPO reprompting. +""" + +import re +from dataclasses import dataclass, field +from typing import Any + +import torch +from datasets import DatasetDict, load_dataset, load_from_disk +from transformers import AutoTokenizer, GenerationConfig + +from trl import ( + LogCompletionsCallback, + ModelConfig, + ScriptArguments, + TrlParser, + get_kbit_device_map, + get_peft_config, + get_quantization_config, +) +from trl.data_utils import maybe_apply_chat_template +from trl.experimental.sdpo import SDPOConfig, SDPOTrainer + + +SYSTEM_PROMPT = ( + "A conversation between user and assistant. The user asks a question, and the assistant solves it. The assistant " + "first thinks about the reasoning process in the mind and then provides the user with the answer. The reasoning " + "must be enclosed within tags, and the final answer must be on its own line in the format " + "`#### `." +) + + +@dataclass +class SDPOScriptArguments(ScriptArguments): + dataset_path: str | None = field( + default=None, + metadata={"help": "Optional local dataset path to load with `load_from_disk`. Overrides `dataset_name`."}, + ) + feedback_column: str | None = field( + default=None, + metadata={ + "help": "Optional dataset column containing textual environment feedback to pass as `privileged_context`." + }, + ) + eval_num_prompts: int | None = field( + default=8, + metadata={"help": "Number of prompts to log during evaluation. Set to 0 to disable completion logging."}, + ) + accuracy_eval_num_examples: int | None = field( + default=128, + metadata={"help": "Optional number of eval examples to score for answer accuracy. Defaults to 128."}, + ) + accuracy_eval_max_new_tokens: int = field( + default=128, + metadata={"help": "Maximum completion length for answer-accuracy evaluation generation."}, + ) + feedback_from_solution: str | None = field( + default=None, + metadata={ + "help": "Optional synthesized feedback source when the dataset has no feedback column. Supported: " + "`final_answer`, `full_solution`." + }, + ) + max_train_examples: int | None = field( + default=None, + metadata={"help": "Optional cap on the number of training examples loaded from the selected train split."}, + ) + max_eval_examples: int | None = field( + default=None, + metadata={"help": "Optional cap on the number of evaluation examples loaded from the selected eval split."}, + ) + dataset_shuffle_seed: int = field( + default=42, + metadata={"help": "Random seed used before applying `max_train_examples` or `max_eval_examples`."}, + ) + + +@dataclass +class ExampleSDPOConfig(SDPOConfig): + scale_rewards: str = field( + default="group", + metadata={"help": "Reward normalization mode. Supported: `group`, `batch`, `none`."}, + ) + + +def _make_solution_feedback(final_answer: str, worked_solution: str, feedback_from_solution: str | None) -> str | None: + if feedback_from_solution is None: + return None + if feedback_from_solution == "final_answer": + return ( + "Your previous answer was incorrect. The correct final answer is:\n\n" + f"#### {final_answer}\n\n" + "Revise your reasoning and end with the same final answer format." + ) + if feedback_from_solution == "full_solution": + return ( + "Your previous answer was incorrect. Here is a correct worked solution:\n\n" + f"{worked_solution}\n\n" + "Use it to solve the original question correctly." + ) + raise ValueError("feedback_from_solution must be one of: `final_answer`, `full_solution`.") + + +def _make_conversation( + example: dict[str, Any], feedback_column: str | None, feedback_from_solution: str | None +) -> dict[str, Any]: + prompt = example.get("prompt") + if prompt is None and "problem" in example: + prompt = [ + {"role": "system", "content": SYSTEM_PROMPT}, + {"role": "user", "content": example["problem"]}, + ] + if prompt is None and "question" in example: + prompt = [ + {"role": "system", "content": SYSTEM_PROMPT}, + {"role": "user", "content": example["question"]}, + ] + + if prompt is None: + raise ValueError("Each example must provide one of: `prompt`, `problem`, or `question`.") + + output = {"prompt": prompt} + + solution = None + if "solution" in example: + solution = example["solution"] + elif "answer" in example: + solution = _normalize_gsm8k_answer(example["answer"]) + + if solution is not None: + output["solution"] = solution + + if feedback_column is not None and feedback_column in example: + output["privileged_context"] = example[feedback_column] + elif "privileged_context" in example: + output["privileged_context"] = example["privileged_context"] + elif solution is not None: + worked_solution = example.get("solution") + if worked_solution is None and "answer" in example: + worked_solution = example["answer"].strip() + if worked_solution is None: + worked_solution = f"#### {solution}" + synthesized_feedback = _make_solution_feedback(solution, worked_solution, feedback_from_solution) + if synthesized_feedback is not None: + output["privileged_context"] = synthesized_feedback + + return output + + +def _normalize_gsm8k_answer(answer_text: str) -> str: + if "####" not in answer_text: + return answer_text.strip() + return answer_text.split("####", 1)[1].strip().replace(",", "") + + +def _extract_predicted_answer(completion_text: str) -> str | None: + match = re.search(r"####\s*([^\n]+)", completion_text) + if match: + return match.group(1).strip().replace(",", "") + + matches = re.findall(r"(-?\$?[0-9][0-9,]*(?:\.[0-9]+)?)", completion_text) + if not matches: + return None + return matches[-1].replace("$", "").replace(",", "").strip() + + +def _gsm8k_accuracy_reward(completions, solution, **kwargs) -> list[float]: + rewards = [] + for completion, gold in zip(completions, solution, strict=True): + content = completion[0]["content"] if isinstance(completion, list) else completion + pred = _extract_predicted_answer(content) + rewards.append(1.0 if pred is not None and pred == gold else 0.0) + return rewards + + +def _gsm8k_soft_format_reward(completions, **kwargs) -> list[float]: + pattern = r".*?\s*####\s*[^\n]+" + rewards = [] + for completion in completions: + content = completion[0]["content"] if isinstance(completion, list) else completion + rewards.append(0.25 if re.match(pattern, content, flags=re.DOTALL) else 0.0) + return rewards + + +def _run_accuracy_eval( + trainer: SDPOTrainer, eval_dataset, max_new_tokens: int, num_examples: int | None, metric_prefix: str = "math_eval" +) -> dict[str, float]: + if num_examples is not None: + eval_dataset = eval_dataset.select(range(min(num_examples, len(eval_dataset)))) + + prompts = eval_dataset["prompt"] + prompt_texts = [ + maybe_apply_chat_template({"prompt": prompt}, trainer.processing_class)["prompt"] for prompt in prompts + ] + tokenized = trainer.processing_class( + text=prompt_texts, + return_tensors="pt", + padding=True, + padding_side="left", + truncation=True, + max_length=trainer.max_prompt_length, + add_special_tokens=False, + ) + tokenized = {key: value.to(trainer.accelerator.device) for key, value in tokenized.items()} + model = trainer.accelerator.unwrap_model(trainer.model) + was_training = model.training + model.eval() + with torch.no_grad(): + generated = model.generate( + **tokenized, + max_new_tokens=max_new_tokens, + do_sample=False, + pad_token_id=trainer.processing_class.pad_token_id, + eos_token_id=trainer.processing_class.eos_token_id, + ) + if was_training: + model.train() + + prompt_length = tokenized["input_ids"].shape[1] + completions = trainer.processing_class.batch_decode(generated[:, prompt_length:], skip_special_tokens=True) + completion_messages = [[{"role": "assistant", "content": completion}] for completion in completions] + rewards = _gsm8k_accuracy_reward(completion_messages, solution=eval_dataset["solution"]) + total = max(len(rewards), 1) + return { + f"{metric_prefix}/accuracy": sum(rewards) / total, + f"{metric_prefix}/num_scored": float(len(rewards)), + } + + +if __name__ == "__main__": + parser = TrlParser((SDPOScriptArguments, ExampleSDPOConfig, ModelConfig)) + script_args, training_args, model_args = parser.parse_args_and_config() + + dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype) + training_args.model_init_kwargs = dict( + revision=model_args.model_revision, + attn_implementation=model_args.attn_implementation, + dtype=dtype, + ) + quantization_config = get_quantization_config(model_args) + if quantization_config is not None: + training_args.model_init_kwargs["device_map"] = get_kbit_device_map() + training_args.model_init_kwargs["quantization_config"] = quantization_config + + if script_args.dataset_path is not None: + dataset = load_from_disk(script_args.dataset_path) + else: + dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config) + + if not isinstance(dataset, DatasetDict): + raise ValueError("SDPO example expects a dataset with named splits.") + + train_split = dataset[script_args.dataset_train_split] + if script_args.max_train_examples is not None: + train_split = train_split.shuffle(seed=script_args.dataset_shuffle_seed).select( + range(min(script_args.max_train_examples, len(train_split))) + ) + + train_dataset = train_split.map( + lambda example: _make_conversation(example, script_args.feedback_column, script_args.feedback_from_solution), + remove_columns=train_split.column_names, + ) + eval_dataset = None + if training_args.eval_strategy != "no": + eval_split = dataset[script_args.dataset_test_split] + if script_args.max_eval_examples is not None: + eval_split = eval_split.shuffle(seed=script_args.dataset_shuffle_seed).select( + range(min(script_args.max_eval_examples, len(eval_split))) + ) + + eval_dataset = eval_split.map( + lambda example: _make_conversation( + example, script_args.feedback_column, script_args.feedback_from_solution + ), + remove_columns=eval_split.column_names, + ) + + reward_funcs = [_gsm8k_soft_format_reward, _gsm8k_accuracy_reward] + + tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path) + if tokenizer.pad_token is None: + tokenizer.pad_token = tokenizer.eos_token + + trainer = SDPOTrainer( + model=model_args.model_name_or_path, + args=training_args, + reward_funcs=reward_funcs, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + peft_config=get_peft_config(model_args), + processing_class=tokenizer, + ) + + if eval_dataset is not None and script_args.eval_num_prompts: + generation_config = GenerationConfig( + max_new_tokens=training_args.max_completion_length, + do_sample=True, + temperature=training_args.temperature, + ) + trainer.add_callback( + LogCompletionsCallback(trainer, generation_config, num_prompts=script_args.eval_num_prompts) + ) + + if eval_dataset is not None: + pre_metrics = _run_accuracy_eval( + trainer, + eval_dataset, + max_new_tokens=script_args.accuracy_eval_max_new_tokens, + num_examples=script_args.accuracy_eval_num_examples, + ) + trainer.log_metrics("eval", {f"before_{k}": v for k, v in pre_metrics.items()}) + trainer.save_metrics("eval", {f"before_{k}": v for k, v in pre_metrics.items()}) + + trainer.train() + + trainer.save_model(training_args.output_dir) + if eval_dataset is not None: + post_metrics = _run_accuracy_eval( + trainer, + eval_dataset, + max_new_tokens=script_args.accuracy_eval_max_new_tokens, + num_examples=script_args.accuracy_eval_num_examples, + ) + after_metrics = {f"after_{k}": v for k, v in post_metrics.items()} + delta_metrics = { + f"delta_{k.split('/', 1)[1]}": after_metrics[f"after_{k}"] - pre_metrics[k] for k in pre_metrics + } + trainer.log_metrics("eval", after_metrics | delta_metrics) + trainer.save_metrics("eval", after_metrics | delta_metrics) + if training_args.push_to_hub: + trainer.push_to_hub(dataset_name=script_args.dataset_name or script_args.dataset_path) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdpo/sdpo_config.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdpo/sdpo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..3273aa60242ad29378ddc45afeb770c052e7ed81 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdpo/sdpo_config.py @@ -0,0 +1,632 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field +from typing import Any, Literal + +from transformers import TrainingArguments + +from ...trainer.base_config import _BaseConfig + + +@dataclass +class SDPOConfig(_BaseConfig): + r""" + Configuration class for the [`SDPOTrainer`]. + + Parameters: + > Parameters that control the online policy objective + + 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. [DeepSeek-R1 incentivizes reasoning in LLMs through reinforcement + learning](https://huggingface.co/papers/2501.12948) use a value of `0.001`. + epsilon (`float`, *optional*, defaults to `0.2`): + Epsilon value for clipping. + epsilon_high (`float`, *optional*): + 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 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 shows + that sequence-level sampling often yields more stable training and better alignment with sequence-level + rewards. + reward_weights (`list[float]`, *optional*): + 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 (`str` or `bool`, *optional*, defaults to `"group"`): + Specifies the scaling strategy for rewards. Supported values are: `True` or `'group'` (default): rewards + are scaled by the standard deviation within each group, ensuring unit variance within a group. `'batch'`: + rewards are scaled by the standard deviation across the entire batch, as recommended in the PPO Lite paper. + `False` or `'none'`: no scaling is applied. The Dr. GRPO paper recommends not scaling rewards, as scaling + by the standard deviation introduces a question-level difficulty bias. + + > Parameters that control the SDPO loss + + distillation_weight (`float`, *optional*, defaults to `1.0`): + Convex combination weight between the policy and self-distillation objectives. The loss is `(1 - + distillation_weight) * policy_loss + distillation_weight * distillation_loss`. Must be in `[0, 1]`. `1.0` + (default) trains purely on self-distillation, `0.0` falls back to the standard GRPO-style policy gradient, + and intermediate values blend both. + distillation_alpha (`float`, *optional*, defaults to `1.0`): + Divergence interpolation coefficient. Sampled-token SDPO requires the official reverse-KL setting + `distillation_alpha=1.0`. + distillation_mode (`Literal["sampled_token", "full_logits", "topk_logits"]`, *optional*, defaults to `"sampled_token"`): + Distillation objective mode. `sampled_token` is the default SDPO mode and requires + `distillation_alpha=1.0`. + distillation_topk (`int`, *optional*): + Top-k approximation for logit-level SDPO. Must be set when `distillation_mode=topk_logits` and left unset + otherwise. + distillation_is_clip (`float`, *optional*, defaults to `2.0`): + Clipping coefficient for importance sampling in self-distillation. `None` disables clipping. + distillation_add_tail (`bool`, *optional*, defaults to `False`): + Whether to add a tail bucket for non-top-k probability mass. + + > Parameters that control the teacher + + teacher_model_kind (`str`, *optional*, defaults to `"ema"`): + Semantic teacher choice. `base` uses the initial student, `live` uses the current student, and `ema` uses + an exponentially averaged teacher. + teacher_update_rate (`float`, *optional*, defaults to `0.05`): + Teacher update rate used for EMA teacher synchronization. + teacher_sync_steps (`int`, *optional*, defaults to `1`): + How often to synchronize the EMA teacher model. + + > Parameters that control reprompting + + use_successful_as_teacher (`bool`, *optional*, defaults to `True`): + Use successful rollouts as implicit feedback for self-distillation. + success_reward_threshold (`float`, *optional*, defaults to `1.0`): + Minimum reward for a rollout to be considered a successful demonstration. + dont_reprompt_on_self_success (`bool`, *optional*, defaults to `True`): + Skip reprompting when model generates correct response. + max_reprompt_len (`int`, *optional*, defaults to `10240`): + Maximum length for reprompting in self-distillation. + reprompt_template (`str`, *optional*, defaults to `"{prompt}{solution}{feedback}\n\nCorrectly solve the original question.\n"`): + Template for reprompting the teacher with a successful demonstration. + solution_template (`str`, *optional*, defaults to `"\nCorrect solution: + \n\n{successful_previous_attempt}\n\n"`): Template for formatting the successful demonstration text. + feedback_template (`str`, *optional*, defaults to `"\nThe following is feedback from your unsuccessful earlier attempt: + \n\n{feedback_raw}\n\n"`): Template for formatting environment feedback for reprompting. + include_environment_feedback (`bool`, *optional*, defaults to `False`): + Whether to include environment feedback in teacher reprompts when available. + environment_feedback_only_without_solution (`bool`, *optional*, defaults to `False`): + Whether to use feedback only when no successful solution is available. + remove_thinking_from_demonstration (`bool`, *optional*, defaults to `False`): + Whether to remove ... blocks from the demonstration text. + + > Parameters that control diagnostics + + diagnostics_warning_interval (`int`, *optional*, defaults to `10`): + Emit repeated trainer diagnostics every N consecutive degenerate steps. Set to 0 to disable. + diagnostics_flat_tolerance (`float`, *optional*, defaults to `1e-8`): + Tolerance used to decide whether reward variance or reprompt activity is effectively zero. + + > Parameters that control the model + + model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments for `transformers.AutoModelForCausalLM.from_pretrained`, used when the `model` argument + of the `SDPOTrainer` is provided as a string. + disable_dropout (`bool`, *optional*, defaults to `True`): + 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 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`, *optional*, defaults to `512`): + Maximum prompt length. Longer prompts are truncated from the left. + shuffle_dataset (`bool`, *optional*, defaults to `True`): + Whether to shuffle the training dataset. + + > Parameters that control generation + + num_generations (`int`, *optional*, defaults to `8`): + Number of generations to sample. The effective batch size (num_processes * per_device_batch_size * + gradient_accumulation_steps) must be evenly divisible by this value. + num_generations_eval (`int`, *optional*): + Number of generations to sample during evaluation. This allows using fewer generations during evaluation to + save computation. If `None`, uses the value of `num_generations`. + max_completion_length (`int`, *optional*, defaults to `256`): + Maximum length of the generated completion. + temperature (`float`, *optional*, 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`, *optional*, defaults to `0`): + Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, top-k-filtering is + disabled and all tokens are considered. + min_p (`float`, *optional*): + 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. + cache_implementation (`str`, *optional*): + Implementation of the cache method for faster generation when use_vllm is set to False. + generation_kwargs (`dict[str, Any]`, *optional*): + 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 `suppress_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. + chat_template_kwargs (`dict[str, Any]`, *optional*): + Additional keyword arguments to pass to the `apply_chat_template` function when generating completions. + 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. + + > 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. + use_teacher_server (`bool`, *optional*, defaults to `False`): + Compute teacher logprobs from the running vLLM generation server instead of a local teacher forward. Only + supported for `teacher_model_kind='live'` with `use_vllm=True`, `vllm_mode='server'`, + `distillation_weight=1.0` (pure distillation), and `distillation_mode` in {'sampled_token', 'topk_logits'} + (the server returns the teacher's top-k logprobs, not the full vocabulary; `topk_logits` distills over the + teacher's own top-k support). + vllm_mode (`str`, *optional*, defaults to `"colocate"`): + 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_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. + vllm_enable_sleep_mode (`bool`, *optional*, defaults to `False`): + Enable vLLM sleep mode to offload weights/cache during the optimizer step. Keeps GPU memory usage low, but + waking the engine adds host–device transfer latency. + vllm_server_base_url (`str`, *optional*): + 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_group_port (`int`, *optional*, defaults to `51216`): + Port number for the weight update group. This is used to communicate with the vLLM server. Unless the port + is occupied, there is no need to change it. + 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. + 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_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_max_model_length (`int`, *optional*): + Context window for vLLM. Set it to at least the maximum prompt length in the dataset plus + `max_completion_length`; if omitted, it is inferred from the model config. + + > Parameters that control the training + + loss_type (`str`, *optional*, defaults to `"dapo"`): + Specifies the loss formulation to use. Supported values are 'grpo', 'bnpo', 'dr_grpo', and 'dapo'. '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. 'dapo' (default): Aggregates token-level losses by normalizing with the number of active tokens + in the global accumulated batch. This method was introduced in the DAPO paper to eliminate length bias. + 'dr_grpo': Aggregates token-level losses by normalizing with a global constant. This method was introduced + in the Dr. GRPO paper to eliminate length bias. The value of the constant corresponds to + `max_completion_length`. 'bnpo': Aggregates token-level losses by normalizing with the number of active + tokens 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. + num_iterations (`int`, *optional*, defaults to `1`): + Number of iterations per batch (denoted as μ in the algorithm). + generation_batch_size (`int`, *optional*): + 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`. + steps_per_generation (`int`, *optional*): + Number of steps per generation. If `None`, it defaults to `gradient_accumulation_steps`. + 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 paper, this is a good + practice for training stability. + """ + + _VALID_DICT_FIELDS = TrainingArguments._VALID_DICT_FIELDS + ["model_init_kwargs"] + + model_init_kwargs: dict[str, Any] | None = field( + default=None, + metadata={ + "help": "Keyword arguments for `transformers.AutoModelForCausalLM.from_pretrained`, used when the `model` argument of the `SDPOTrainer` is provided as a string." + }, + ) + disable_dropout: bool = field( + default=True, + metadata={ + "help": "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." + }, + ) + remove_unused_columns: bool = field( + default=False, + metadata={ + "help": "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 | None = field( + default=512, + metadata={"help": "Maximum prompt length. Longer prompts are truncated from the left."}, + ) + num_generations: int = field( + default=8, + metadata={ + "help": "Number of generations to sample. The effective batch size (num_processes * per_device_batch_size * gradient_accumulation_steps) must be evenly divisible by this value." + }, + ) + num_generations_eval: int | None = field( + default=None, + metadata={ + "help": "Number of generations to sample during evaluation. This allows using fewer generations during evaluation to save computation. If `None`, uses the value of `num_generations`." + }, + ) + max_completion_length: int | None = field( + default=256, + metadata={"help": "Maximum length of the generated completion."}, + ) + ds3_gather_for_generation: bool = field( + default=True, + metadata={ + "help": "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 = field( + default=True, + metadata={"help": "Whether to shuffle the training dataset."}, + ) + generation_batch_size: int | None = field( + default=None, + metadata={ + "help": "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`." + }, + ) + steps_per_generation: int | None = field( + default=None, + metadata={"help": "Number of steps per generation. If `None`, it defaults to `gradient_accumulation_steps`."}, + ) + temperature: float = field( + default=1.0, + metadata={"help": "Temperature for sampling. The higher the temperature, the more random the completions."}, + ) + top_p: float = field( + default=1.0, + metadata={ + "help": "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 = field( + default=0, + metadata={ + "help": "Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, top-k-filtering is disabled and all tokens are considered." + }, + ) + min_p: float | None = field( + default=None, + metadata={ + "help": "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." + }, + ) + generation_kwargs: dict[str, Any] | None = field( + default=None, + metadata={ + "help": "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 `suppress_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." + }, + ) + chat_template_kwargs: dict[str, Any] | None = field( + default=None, + metadata={ + "help": "Additional keyword arguments to pass to the `apply_chat_template` function when generating completions." + }, + ) + repetition_penalty: float = field( + default=1.0, + metadata={ + "help": "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." + }, + ) + cache_implementation: str | None = field( + default=None, + metadata={"help": "Implementation of the cache method for faster generation when use_vllm is set to False."}, + ) + use_vllm: bool = field( + default=False, + metadata={ + "help": "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." + }, + ) + use_teacher_server: bool = field( + default=False, + metadata={ + "help": "Compute teacher logprobs from the running vLLM generation server instead of a local teacher " + "forward. Only supported for `teacher_model_kind='live'` with `use_vllm=True`, `vllm_mode='server'`, " + "`distillation_weight=1.0` (pure distillation), and `distillation_mode` in {'sampled_token', " + "'topk_logits'} (the server returns the teacher's top-k logprobs, not the full vocabulary; `topk_logits` " + "distills over the teacher's own top-k support)." + }, + ) + vllm_mode: str = field( + default="colocate", + metadata={ + "help": "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_model_impl: str = field( + default="vllm", + metadata={ + "help": "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." + }, + ) + vllm_enable_sleep_mode: bool = field( + default=False, + metadata={ + "help": "Enable vLLM sleep mode to offload weights/cache during the optimizer step. Keeps GPU memory usage low, but waking the engine adds host–device transfer latency." + }, + ) + vllm_server_base_url: str | None = field( + default=None, + metadata={ + "help": "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 = field( + default="0.0.0.0", + metadata={"help": "Host of the vLLM server to connect to. Ignored if vllm_server_base_url is provided."}, + ) + vllm_server_port: int = field( + default=8000, + metadata={"help": "Port of the vLLM server to connect to. Ignored if vllm_server_base_url is provided."}, + ) + vllm_group_port: int = field( + default=51216, + metadata={ + "help": "Port number for the weight update group. This is used to communicate with the vLLM server. Unless the port is occupied, there is no need to change it." + }, + ) + vllm_server_timeout: float = field( + default=240.0, + metadata={ + "help": "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." + }, + ) + vllm_tensor_parallel_size: int = field( + default=1, + metadata={ + "help": "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_gpu_memory_utilization: float = field( + default=0.3, + metadata={ + "help": "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_max_model_length: int | None = field( + default=None, + metadata={ + "help": "Context window for vLLM. Set it to at least the maximum prompt length in the dataset plus `max_completion_length`; if omitted, it is inferred from the model config." + }, + ) + num_iterations: int = field( + default=1, + metadata={"help": "Number of iterations per batch (denoted as μ in the algorithm)."}, + ) + loss_type: str = field( + default="dapo", + metadata={ + "help": "Specifies the loss formulation to use. Supported values are 'grpo', 'bnpo', 'dr_grpo', and 'dapo'. '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. 'dapo' (default): Aggregates token-level losses by normalizing with the number of active tokens in the global accumulated batch. This method was introduced in the DAPO paper to eliminate length bias. 'dr_grpo': Aggregates token-level losses by normalizing with a global constant. This method was introduced in the Dr. GRPO paper to eliminate length bias. The value of the constant corresponds to `max_completion_length`. 'bnpo': Aggregates token-level losses by normalizing with the number of active tokens 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." + }, + ) + mask_truncated_completions: bool = field( + default=False, + metadata={ + "help": "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 paper, this is a good practice for training stability." + }, + ) + dont_reprompt_on_self_success: bool = field( + default=True, + metadata={"help": "Skip reprompting when model generates correct response."}, + ) + beta: float = field( + default=0.0, + metadata={ + "help": "KL coefficient. If `0.0` (default), the reference model is not loaded, reducing memory usage and improving training speed. [DeepSeek-R1 incentivizes reasoning in LLMs through reinforcement learning](https://huggingface.co/papers/2501.12948) use a value of `0.001`." + }, + ) + epsilon: float = field( + default=0.2, + metadata={"help": "Epsilon value for clipping."}, + ) + epsilon_high: float | None = field( + default=None, + metadata={ + "help": "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 recommends `0.28`." + }, + ) + importance_sampling_level: str = field( + default="token", + metadata={ + "help": "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 shows that sequence-level sampling often yields more stable training and better alignment with sequence-level rewards." + }, + ) + reward_weights: list[float] | None = field( + default=None, + metadata={ + "help": "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: str | bool = field( + default="group", + metadata={ + "help": "Specifies the scaling strategy for rewards. Supported values are: `True` or `'group'` (default): rewards are scaled by the standard deviation within each group, ensuring unit variance within a group. `'batch'`: rewards are scaled by the standard deviation across the entire batch, as recommended in the PPO Lite paper. `False` or `'none'`: no scaling is applied. The Dr. GRPO paper recommends not scaling rewards, as scaling by the standard deviation introduces a question-level difficulty bias." + }, + ) + distillation_alpha: float = field( + default=1.0, + metadata={ + "help": "Divergence interpolation coefficient. Sampled-token SDPO requires the official reverse-KL setting " + "`distillation_alpha=1.0`." + }, + ) + distillation_mode: Literal["sampled_token", "full_logits", "topk_logits"] = field( + default="sampled_token", + metadata={ + "help": "Distillation objective mode. `sampled_token` is the default SDPO mode and requires " + "`distillation_alpha=1.0`." + }, + ) + distillation_topk: int | None = field( + default=None, + metadata={ + "help": "Top-k approximation for logit-level SDPO. Must be set when `distillation_mode=topk_logits` and left " + "unset otherwise." + }, + ) + distillation_is_clip: float | None = field( + default=2.0, + metadata={ + "help": "Clipping coefficient for importance sampling in self-distillation. `None` disables clipping." + }, + ) + distillation_add_tail: bool = field( + default=False, + metadata={"help": "Whether to add a tail bucket for non-top-k probability mass."}, + ) + distillation_weight: float = field( + default=1.0, + metadata={ + "help": "Convex combination weight between the policy and self-distillation objectives. The loss is " + "`(1 - distillation_weight) * policy_loss + distillation_weight * distillation_loss`. Must be in `[0, 1]`. " + "`1.0` (default) trains purely on self-distillation, `0.0` falls back to the standard GRPO-style policy " + "gradient, and intermediate values blend both." + }, + ) + teacher_model_kind: str = field( + default="ema", + metadata={ + "help": "Semantic teacher choice. `base` uses the initial student, `live` uses the current student, " + "and `ema` uses an exponentially averaged teacher." + }, + ) + teacher_update_rate: float = field( + default=0.05, + metadata={"help": "Teacher update rate used for EMA teacher synchronization."}, + ) + teacher_sync_steps: int = field( + default=1, + metadata={"help": "How often to synchronize the EMA teacher model."}, + ) + max_reprompt_len: int = field( + default=10240, + metadata={"help": "Maximum length for reprompting in self-distillation."}, + ) + use_successful_as_teacher: bool = field( + default=True, + metadata={"help": "Use successful rollouts as implicit feedback for self-distillation."}, + ) + success_reward_threshold: float = field( + default=1.0, + metadata={"help": "Minimum reward for a rollout to be considered a successful demonstration."}, + ) + reprompt_template: str = field( + default="{prompt}{solution}{feedback}\n\nCorrectly solve the original question.\n", + metadata={"help": "Template for reprompting the teacher with a successful demonstration."}, + ) + solution_template: str = field( + default="\nCorrect solution:\n\n{successful_previous_attempt}\n\n", + metadata={"help": "Template for formatting the successful demonstration text."}, + ) + feedback_template: str = field( + default="\nThe following is feedback from your unsuccessful earlier attempt:\n\n{feedback_raw}\n\n", + metadata={"help": "Template for formatting environment feedback for reprompting."}, + ) + include_environment_feedback: bool = field( + default=False, + metadata={"help": "Whether to include environment feedback in teacher reprompts when available."}, + ) + environment_feedback_only_without_solution: bool = field( + default=False, + metadata={"help": "Whether to use feedback only when no successful solution is available."}, + ) + remove_thinking_from_demonstration: bool = field( + default=False, + metadata={"help": "Whether to remove ... blocks from the demonstration text."}, + ) + diagnostics_warning_interval: int = field( + default=10, + metadata={ + "help": "Emit repeated trainer diagnostics every N consecutive degenerate steps. Set to 0 to disable." + }, + ) + diagnostics_flat_tolerance: float = field( + default=1e-8, + metadata={ + "help": "Tolerance used to decide whether reward variance or reprompt activity is effectively zero." + }, + ) + + def __post_init__(self): + super().__post_init__() + if not 0.0 <= self.distillation_weight <= 1.0: + raise ValueError(f"`distillation_weight` must be in [0, 1], got {self.distillation_weight}.") + if self.distillation_mode == "sampled_token" and self.distillation_alpha != 1.0: + raise ValueError( + "`distillation_mode='sampled_token'` only supports reverse KL, so it requires " + f"`distillation_alpha=1.0`, got {self.distillation_alpha}." + ) + num_processes = self.world_size + if self.generation_batch_size is None and self.steps_per_generation is None: + self.steps_per_generation = self.gradient_accumulation_steps + self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation + elif self.generation_batch_size is not None and self.steps_per_generation is None: + global_batch_size = self.per_device_train_batch_size * num_processes + if self.generation_batch_size % global_batch_size != 0: + raise ValueError( + f"generation_batch_size ({self.generation_batch_size}) must be divisible by the global batch size ({global_batch_size})." + ) + self.steps_per_generation = self.generation_batch_size // global_batch_size + elif self.generation_batch_size is None and self.steps_per_generation is not None: + self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation + else: + raise ValueError("'generation_batch_size' and 'steps_per_generation' can not both be configured") + + if self.generation_batch_size % self.num_generations != 0: + raise ValueError( + f"generation_batch_size ({self.generation_batch_size}) must be divisible by num_generations ({self.num_generations})." + ) + + if self.do_eval and self.eval_strategy != "no": + num_generations_eval = self.num_generations_eval or self.num_generations + if (self.per_device_eval_batch_size * num_processes) % num_generations_eval != 0: + raise ValueError( + f"The global eval batch size ({self.per_device_eval_batch_size} * {num_processes}) must be " + f"divisible by the number of generations used for evaluation ({num_generations_eval})." + ) + + self.scale_rewards = {True: "group", False: "none"}.get(self.scale_rewards, self.scale_rewards) + + if self.epsilon_high is None: + self.epsilon_high = self.epsilon diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdpo/sdpo_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdpo/sdpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..868b426bbd9d4f19b0345e54748e107ae5c4542f --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdpo/sdpo_trainer.py @@ -0,0 +1,1751 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import inspect +import re +import textwrap +from collections import defaultdict +from contextlib import nullcontext +from dataclasses import dataclass +from functools import partial +from typing import Any + +import datasets +import torch +from accelerate.utils import gather_object, is_peft_model +from datasets import Dataset, IterableDataset +from torch import nn +from torch.distributed.fsdp import FullyShardedDataParallel as FSDP +from torch.utils.data import DataLoader, Sampler +from transformers import ( + AutoModelForSequenceClassification, + AutoProcessor, + AutoTokenizer, + GenerationConfig, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, +) +from transformers.trainer_utils import seed_worker +from transformers.utils import is_datasets_available, is_liger_kernel_available, is_peft_available, logging + +from ...data_utils import apply_chat_template, is_conversational +from ...models import prepare_deepspeed, prepare_fsdp, unwrap_model_for_generation +from ...models.utils import _ForwardRedirection +from ...trainer.base_trainer import _BaseTrainer +from ...trainer.utils import ( + RepeatSampler, + create_model_from_path, + disable_dropout_in_model, + get_config_model_id, + identity, + pad, + selective_log_softmax, + split_tensor_dict, + use_adapter, +) +from ..utils import prepare_peft_model +from .loss_utils import ( + add_tail_bucket, + apply_importance_sampling_clipping, + compute_divergence, + compute_full_logit_self_distillation_loss, + compute_sampled_token_self_distillation_loss, + compute_topk_self_distillation_loss, +) +from .sdpo_config import SDPOConfig +from .teacher_sync import PEFTAdapterEMACallback, SyncTeacherModelCallback, is_pure_lora_training + + +logger = logging.get_logger(__name__) + + +if is_peft_available(): + from peft import PeftConfig + +if is_liger_kernel_available(): + from liger_kernel.chunked_loss import LigerFusedLinearJSDLoss + + +TrainingBatch = dict[str, torch.Tensor | Any] + + +def build_teacher_request_inputs( + input_ids: torch.Tensor, + attention_mask: torch.Tensor, + prompt_attention_mask: torch.Tensor, +) -> tuple[list[list[int]], list[int], list[int]]: + """Trim padded batch tensors into per-sample (prompt+completion) sequences for teacher-server requests.""" + if input_ids.shape != attention_mask.shape: + raise ValueError( + f"input_ids and attention_mask must have the same shape, got {input_ids.shape} and {attention_mask.shape}." + ) + + input_ids_cpu = input_ids.detach().cpu() + attention_mask_cpu = attention_mask.detach().cpu().bool() + prompt_lengths = prompt_attention_mask.detach().cpu().sum(dim=1).to(torch.long) + + trimmed_input_ids: list[list[int]] = [] + prompt_lengths_list: list[int] = [] + completion_lengths_list: list[int] = [] + for row, mask, prompt_length in zip(input_ids_cpu, attention_mask_cpu, prompt_lengths, strict=True): + trimmed_row = row[mask] + prompt_len = int(prompt_length.item()) + if prompt_len < 0 or prompt_len > trimmed_row.numel(): + raise ValueError( + f"Invalid prompt length {prompt_len} for trimmed sequence of length {trimmed_row.numel()}." + ) + trimmed_input_ids.append(trimmed_row.tolist()) + prompt_lengths_list.append(prompt_len) + completion_lengths_list.append(int(trimmed_row.numel()) - prompt_len) + return trimmed_input_ids, prompt_lengths_list, completion_lengths_list + + +@dataclass +class DistillationLogits: + """Aligned logits and masks used to compute a self-distillation objective.""" + + completion_ids: torch.Tensor + completion_mask: torch.Tensor + loss_mask: torch.Tensor + student_logits: torch.Tensor + teacher_logits: torch.Tensor + + +def _extract_last_user_text(messages: list[dict[str, Any]]) -> str: + """Extract the text content from the last user message in a conversational prompt.""" + last_message = messages[-1] + if last_message.get("role") != "user": + raise ValueError( + f"Self-distillation teacher prompt construction expects the conversation to end with a user turn, " + f"but the last message has role '{last_message.get('role')}'. " + f"Prompts ending with assistant prefills or tool turns are not supported." + ) + content = last_message.get("content", "") + if isinstance(content, list): + return " ".join(part.get("text", "") for part in content if part.get("type") == "text") + return content + + +class SuccessfulRolloutTeacherContextBuilder: + """Builds teacher contexts from successful rollouts""" + + def __init__(self, trainer): + self.trainer = trainer + self.last_metrics: dict[str, float] = {} + + def _build_reprompt_text(self, prompt_text: str, solution_text: str, feedback_text: str) -> str: + return self.trainer.args.reprompt_template.format( + prompt=prompt_text, + solution=solution_text, + feedback=feedback_text, + ) + + def _tokenize_teacher_messages( + self, teacher_messages_list: list[str | list[dict[str, Any]]] + ) -> dict[str, torch.Tensor]: + device = self.trainer.accelerator.device + teacher_prompt_ids_list = self.trainer._tokenize_prompts_untruncated(teacher_messages_list) + teacher_prompt_ids = [ + torch.as_tensor(ids[-self.trainer.args.max_reprompt_len :], device=device) + for ids in teacher_prompt_ids_list + ] + teacher_prompt_mask = [torch.ones(len(ids), dtype=torch.long, device=device) for ids in teacher_prompt_ids] + return { + "prompt_ids": pad( + teacher_prompt_ids, padding_value=self.trainer._tokenizer.pad_token_id, padding_side="left" + ), + "prompt_mask": pad(teacher_prompt_mask, padding_value=0, padding_side="left"), + } + + def build( + self, + output: dict[str, torch.Tensor | Any], + prompts: list[Any], + rewards: torch.Tensor, + feedbacks: list[Any] | None = None, + ) -> dict[str, torch.Tensor]: + device = self.trainer.accelerator.device + mode = "train" if self.trainer.model.training else "eval" + num_generations = self.trainer.num_generations if mode == "train" else self.trainer.num_generations_eval + completion_ids = output["completion_ids"] + completion_mask = output["completion_mask"] + + num_local = len(prompts) + process_start = self.trainer.accelerator.process_index * num_local + process_slice = slice(process_start, process_start + num_local) + + # Rewards arrive already locally sliced (per-process) from the rollout mixin; re-gather them so + # the mining loop can find successful rollouts across all processes within each generation group. + all_rewards = self.trainer.accelerator.gather(rewards) + # Completion tensors are padded to the local max length per rank; align shapes before gathering. + # Use separate variables so the original completion_ids/completion_mask stay unpadded for the + # teacher concat (they must match the student's sequence length for logits_to_keep alignment). + padded_completion_ids = self.trainer.accelerator.pad_across_processes( + completion_ids, dim=1, pad_index=self.trainer._tokenizer.pad_token_id + ) + all_completion_ids = self.trainer.accelerator.gather(padded_completion_ids) + all_prompts = gather_object(prompts) + total_samples = all_rewards.shape[0] + all_feedbacks = gather_object(feedbacks) if feedbacks is not None else [None] * total_samples + + threshold = self.trainer.args.success_reward_threshold + dont_reprompt_self = self.trainer.args.dont_reprompt_on_self_success + feedback_only_without_solution = self.trainer.args.environment_feedback_only_without_solution + self_distillation_mask = torch.zeros(total_samples, device=device) + num_with_solution = 0 + num_with_feedback_available = 0 + num_with_feedback_used = 0 + success_group_count = 0 + successful_demo_indices: list[int | None] = [None] * total_samples + use_feedback_flags: list[bool] = [False] * total_samples + has_solution_flags: list[bool] = [False] * total_samples + + for i in range(total_samples): + group_start = (i // num_generations) * num_generations + group_end = group_start + num_generations + + successful = [] + if self.trainer.args.use_successful_as_teacher: + for j in range(group_start, group_end): + if dont_reprompt_self and j == i: + continue + if all_rewards[j].item() >= threshold: + successful.append(j) + + if i % num_generations == 0: + # Count groups with any successful rollout, ignoring self-exclusion which only + # affects per-sample teacher assignment, not whether the group has successes. + group_has_success = any(all_rewards[j].item() >= threshold for j in range(group_start, group_end)) + if group_has_success: + success_group_count += 1 + + raw_feedback = all_feedbacks[i] + has_feedback = isinstance(raw_feedback, str) and raw_feedback.strip() != "" + if has_feedback: + num_with_feedback_available += 1 + + has_solution = len(successful) > 0 + has_solution_flags[i] = has_solution + if has_solution: + successful_demo_indices[i] = successful[0] + use_feedback = ( + self.trainer.args.include_environment_feedback + and has_feedback + and (not feedback_only_without_solution or not has_solution) + ) + use_feedback_flags[i] = use_feedback + if use_feedback: + num_with_feedback_used += 1 + if has_solution or use_feedback: + self_distillation_mask[i] = 1.0 + if has_solution: + num_with_solution += 1 + + local_teacher_messages = [] + local_self_distillation_mask = self_distillation_mask[process_slice] + for global_idx in range(process_start, process_start + num_local): + original_prompt = all_prompts[global_idx] + raw_feedback = all_feedbacks[global_idx] + has_solution = has_solution_flags[global_idx] + use_feedback = use_feedback_flags[global_idx] + + if not has_solution and not use_feedback: + local_teacher_messages.append(original_prompt) + continue + + solution_text = "" + if has_solution: + demo_idx = successful_demo_indices[global_idx] + if demo_idx is None: + raise RuntimeError("Expected a successful demonstration index for an active SDPO teacher prompt.") + demo_ids = all_completion_ids[demo_idx] + demo_ids = demo_ids[demo_ids != self.trainer._tokenizer.pad_token_id] + demo_text = self.trainer.processing_class.decode(demo_ids, skip_special_tokens=True) + + if self.trainer.args.remove_thinking_from_demonstration: + demo_text = re.sub(r".*?", "", demo_text, flags=re.DOTALL).strip() + + solution_text = self.trainer.args.solution_template.format(successful_previous_attempt=demo_text) + + feedback_text = "" + if use_feedback: + feedback_text = self.trainer.args.feedback_template.format(feedback_raw=raw_feedback) + + if isinstance(original_prompt, list): + system_messages = original_prompt[:-1] + prompt_text = _extract_last_user_text(original_prompt) + reprompt_text = self._build_reprompt_text(prompt_text, solution_text, feedback_text) + local_teacher_messages.append(system_messages + [{"role": "user", "content": reprompt_text}]) + else: + local_teacher_messages.append(self._build_reprompt_text(original_prompt, solution_text, feedback_text)) + + teacher_batch = self._tokenize_teacher_messages(local_teacher_messages) + teacher_input_ids = torch.cat([teacher_batch["prompt_ids"], completion_ids], dim=1) + teacher_attention_mask = torch.cat([teacher_batch["prompt_mask"], completion_mask], dim=1) + + batch_size = total_samples if total_samples > 0 else 1 + num_groups = max(1, total_samples // max(1, num_generations)) + self.last_metrics = { + "self_distillation/success_group_fraction": success_group_count / num_groups, + "self_distillation/success_sample_fraction": num_with_solution / batch_size, + "self_distillation/feedback_available_fraction": num_with_feedback_available / batch_size, + "self_distillation/feedback_used_fraction": num_with_feedback_used / batch_size, + "self_distillation/reprompt_sample_fraction": self_distillation_mask.float().mean().item(), + } + + return { + "teacher_input_ids": teacher_input_ids, + "teacher_attention_mask": teacher_attention_mask, + "self_distillation_mask": local_self_distillation_mask, + } + + +class SDPOTrainer(_BaseTrainer): + """ + Trainer for Self-Distillation Policy Optimization (SDPO). + + SDPO augments on-policy optimization with self-distillation from the model's own high-reward trajectories. It + converts tokenized feedback into a dense learning signal without any external teacher or explicit reward model. + SDPO treats the current model conditioned on feedback as a self-teacher and distills its feedback-informed + next-token predictions back into the policy. + """ + + config_cls = SDPOConfig + _tag_names = ["trl", "sdpo"] + _name = "SDPO" + # docstyle-ignore + _paper = { + "title": "Reinforcement Learning via Self-Distillation", + "id": "2601.20802", + "citation": textwrap.dedent("""\ + @article{hubotter2026sdpo, + title = {{Reinforcement Learning via Self-Distillation}}, + author = {Jonas H\\"ubotter and Frederike L\\"ubeck and Lejs Behric and Anton Baumann and Marco Bagatella and Daniel Marta and Ido Hakimi and Idan Shenfeld and Thomas Kleine Buening and Carlos Guestrin and Andreas Krause}, + year = 2026, + eprint = {arXiv:2601.20802} + }"""), + } + + def __init__( + self, + model: str | PreTrainedModel | nn.Module, + reward_funcs: Any | list[Any] | None = None, + args: SDPOConfig | None = None, + train_dataset: Dataset | IterableDataset | None = None, + eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None, + processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None, + reward_processing_classes: PreTrainedTokenizerBase | list[PreTrainedTokenizerBase] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None), + peft_config=None, + ): + if reward_funcs is None or (isinstance(reward_funcs, list) and len(reward_funcs) == 0): + raise ValueError("`reward_funcs` is required for SDPOTrainer because SDPO must score rollouts.") + if train_dataset is None: + raise ValueError("`train_dataset` is required") + + if isinstance(model, str): + model_init_kwargs = args.model_init_kwargs or {} + if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + model_init_kwargs["device_map"] = None + model = create_model_from_path(model, **model_init_kwargs) + elif args.model_init_kwargs is not None: + logger.warning( + "You passed `model_init_kwargs` to the self-distillation config, but `model` is already " + "instantiated. The `model_init_kwargs` will be ignored." + ) + + self.model_kwarg_keys = ( + inspect.signature(model.forward).parameters.keys() + if not hasattr(model, "get_base_model") + else inspect.signature(model.get_base_model().forward).parameters.keys() + ) + + if peft_config is None and getattr(model, "peft_config", None) is not None: + logger.warning( + "The provided self-distillation student model already contains a PEFT adapter. " + "This setup is accepted but not directly supported. In particular, `teacher_model_kind='base'` " + "may refer to the underlying base weights rather than the exact initially loaded student state " + "including its adapter. For unambiguous teacher behavior, start from a merged/non-adapter model " + "or manage separate adapters explicitly." + ) + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + if is_peft_model(model): + raise ValueError( + "You passed a `PeftModel` instance together with a `peft_config`. Pass either a base " + "model with `peft_config`, or a pre-wrapped PEFT model." + ) + if peft_config is not None or (is_peft_available() and getattr(model, "peft_config", None) is not None): + model = prepare_peft_model(model, peft_config, args) + + if processing_class is None: + processing_class = AutoProcessor.from_pretrained( + get_config_model_id(model.config), truncation_side="left", padding_side="left" + ) + + if isinstance(processing_class, ProcessorMixin): + self._tokenizer = processing_class.tokenizer + elif isinstance(processing_class, PreTrainedTokenizerBase): + self._tokenizer = processing_class + else: + raise TypeError("The `processing_class` must be either a `PreTrainedTokenizerBase` or a `ProcessorMixin`") + + if self._tokenizer.pad_token is None: + self._tokenizer.pad_token = self._tokenizer.eos_token + + self.max_prompt_length = args.max_prompt_length + self.max_completion_length = args.max_completion_length + self.num_generations = args.num_generations + self.num_generations_eval = args.num_generations_eval or args.num_generations + self.num_iterations = args.num_iterations + self.shuffle_dataset = args.shuffle_dataset + self.loss_type = args.loss_type + self.mask_truncated_completions = args.mask_truncated_completions + self.temperature = args.temperature + self.use_vllm = args.use_vllm + self.chat_template_kwargs = args.chat_template_kwargs or {} + self._step = 0 + self._buffered_inputs = None + self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)} + self._diagnostic_counters = { + "train": defaultdict(int), + "eval": defaultdict(int), + } + + self.generation_kwargs = { + "max_new_tokens": self.max_completion_length, + "do_sample": True, + "pad_token_id": self._tokenizer.pad_token_id, + "bos_token_id": self._tokenizer.bos_token_id, + "eos_token_id": self._tokenizer.eos_token_id, + "temperature": args.temperature, + "top_p": args.top_p, + "top_k": args.top_k, + "min_p": args.min_p, + "repetition_penalty": args.repetition_penalty, + "cache_implementation": args.cache_implementation, + } + if args.generation_kwargs is not None: + self.generation_kwargs.update(args.generation_kwargs) + self.generation_config = GenerationConfig(**self.generation_kwargs, disable_compile=True) + + if hasattr(model, "warnings_issued"): + model.warnings_issued["estimate_tokens"] = True + + # Teacher logprobs from the running vLLM generation server (reuses the synced student weights) instead of a + # local teacher forward. MVP: `live` teacher only — the generation server holds the current student weights. + self.use_teacher_server = args.use_teacher_server + if self.use_teacher_server: + if not (args.use_vllm and args.vllm_mode == "server"): + raise ValueError( + "`use_teacher_server=True` requires `use_vllm=True` and `vllm_mode='server'`: teacher logprobs are " + "served by the same vLLM server used for generation." + ) + if args.teacher_model_kind != "live": + raise ValueError( + "`use_teacher_server=True` only supports `teacher_model_kind='live'` (the generation server holds " + f"the current student weights), got {args.teacher_model_kind!r}." + ) + if args.distillation_weight != 1.0: + raise ValueError( + "`use_teacher_server=True` only supports pure self-distillation with `distillation_weight=1.0`, " + f"got {args.distillation_weight}. A convex blend with the policy loss needs the full-vocabulary " + "logits, which the server does not return." + ) + if args.distillation_mode not in ("sampled_token", "topk_logits"): + raise ValueError( + "`use_teacher_server=True` only supports `distillation_mode` in {'sampled_token', 'topk_logits'}, " + f"got {args.distillation_mode!r}. The server returns the teacher's top-k logprobs, not the full " + "vocabulary, so `full_logits` is unavailable. Note `topk_logits` distills over the teacher's own " + "top-k support (the server cannot score the student's top-k indices)." + ) + if args.use_liger_kernel: + raise ValueError( + "`use_teacher_server=True` is incompatible with `use_liger_kernel`: the server returns top-k " + "logprobs while the Liger fused loss needs full-vocabulary hidden states." + ) + # Liger fused JSD loss for `full_logits`: same generalized JSD as `compute_divergence`, so alpha maps to beta. + self.use_liger_loss = False + if args.use_liger_kernel: + if not is_liger_kernel_available(): + raise ImportError( + "Liger is required to use `use_liger_kernel` as the self-distillation loss. Run " + "`pip install liger-kernel`." + ) + if args.distillation_weight != 1.0: + raise ValueError( + "`use_liger_kernel` only supports pure self-distillation with `distillation_weight=1.0`, got " + f"{args.distillation_weight}. A convex blend with the policy loss needs the policy-gradient term, " + "so the fused distillation kernel offers no benefit there." + ) + if args.distillation_mode != "full_logits": + raise ValueError( + "`use_liger_kernel` only supports `distillation_mode='full_logits'`, got " + f"{args.distillation_mode!r}. The fused JSD kernel operates on the full vocabulary and cannot " + "express the top-k support or sampled-token objectives." + ) + if args.distillation_is_clip is not None: + raise ValueError( + "`use_liger_kernel` is incompatible with `distillation_is_clip`: the fused kernel does not expose " + "per-token losses for importance-sampling clipping." + ) + if args.loss_type != "bnpo": + logger.warning( + "The Liger fused loss reduces with a token-level mean (equivalent to `loss_type='bnpo'`); the " + f"configured `loss_type={args.loss_type!r}` is ignored on the Liger path." + ) + self.liger_jsd_loss = LigerFusedLinearJSDLoss( + beta=args.distillation_alpha, + ignore_index=-100, + temperature=args.temperature, + compiled=False, + weight_hard_loss=0.0, + weight_soft_loss=1.0, + ) + self._forward_redirection = _ForwardRedirection() + self.use_liger_loss = True + + super().__init__( + model=model, + args=args, + data_collator=identity, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + callbacks=callbacks, + optimizers=optimizers, + compute_loss_func="non-None value to disable scaling", + ) + + self._last_loaded_step = -1 if self.use_vllm else 0 + if self.use_vllm: + from ...generation.vllm_generation import VLLMGeneration + + self.vllm_generation = VLLMGeneration( + model=self.model, + accelerator=self.accelerator, + processing_class=self.processing_class, + mode=args.vllm_mode, + server_base_url=args.vllm_server_base_url, + server_host=args.vllm_server_host, + server_port=args.vllm_server_port, + group_port=args.vllm_group_port, + server_timeout=args.vllm_server_timeout, + tensor_parallel_size=args.vllm_tensor_parallel_size, + gpu_memory_utilization=args.vllm_gpu_memory_utilization, + max_model_length=args.vllm_max_model_length, + max_num_seqs=args.per_device_train_batch_size + * args.vllm_tensor_parallel_size + * args.steps_per_generation, + enable_sleep_mode=args.vllm_enable_sleep_mode, + model_impl=args.vllm_model_impl, + repetition_penalty=args.repetition_penalty, + temperature=self.temperature, + top_p=args.top_p, + top_k=args.top_k, + min_p=args.min_p, + max_completion_length=self.max_completion_length, + logprobs=None, + generation_kwargs=args.generation_kwargs, + ) + + # Per-rank read-only client to the same generation server for teacher scoring (weights are synced there by + # `VLLMGeneration`; scoring needs no weight-update communicator). Mirrors the distillation trainer's + # `teacher_client`. + self.teacher_client = None + if self.use_teacher_server: + from ...generation.vllm_client import VLLMClient + + base_url = args.vllm_server_base_url or f"http://{args.vllm_server_host}:{args.vllm_server_port}" + self.teacher_client = VLLMClient(base_url=base_url, connection_timeout=args.vllm_server_timeout) + + if args.disable_dropout: + disable_dropout_in_model(self.model) + + if hasattr(self.model, "add_model_tags"): + self.model.add_model_tags(self._tag_names) + + self._setup_teacher_model() + self.model_accepts_loss_kwargs = False + + self.importance_sampling_level = args.importance_sampling_level + self.scale_rewards = args.scale_rewards + self.epsilon_low = args.epsilon + self.epsilon_high = args.epsilon_high + self.beta = args.beta + + if not isinstance(reward_funcs, list): + reward_funcs = [reward_funcs] + self.reward_func_names = [] + for i, reward_func in enumerate(reward_funcs): + if isinstance(reward_func, str): + reward_model_init_kwargs = args.model_init_kwargs or {} + if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + reward_model_init_kwargs["device_map"] = None + reward_funcs[i] = AutoModelForSequenceClassification.from_pretrained( + reward_func, + num_labels=1, + **reward_model_init_kwargs, + ) + if isinstance(reward_funcs[i], nn.Module): + self.reward_func_names.append(get_config_model_id(reward_funcs[i].config).split("/")[-1]) + else: + self.reward_func_names.append(reward_funcs[i].__name__) + self.reward_funcs = reward_funcs + + if args.reward_weights is not None: + if len(args.reward_weights) != len(self.reward_funcs): + raise ValueError("Number of reward weights must match number of reward functions") + self.reward_weights = torch.tensor(args.reward_weights, dtype=torch.float32) + else: + self.reward_weights = torch.ones(len(self.reward_funcs), dtype=torch.float32) + + if reward_processing_classes is None: + reward_processing_classes = [None] * len(self.reward_funcs) + elif not isinstance(reward_processing_classes, list): + reward_processing_classes = [reward_processing_classes] + if len(reward_processing_classes) != len(self.reward_funcs): + raise ValueError("Number of reward processing classes must match number of reward functions") + + for i, (reward_processing_class, reward_func) in enumerate( + zip(reward_processing_classes, self.reward_funcs, strict=True) + ): + if isinstance(reward_func, PreTrainedModel): + if reward_processing_class is None: + reward_processing_class = AutoTokenizer.from_pretrained(get_config_model_id(reward_func.config)) + if reward_processing_class.pad_token_id is None: + reward_processing_class.pad_token = reward_processing_class.eos_token + reward_func.config.pad_token_id = reward_processing_class.pad_token_id + reward_processing_classes[i] = reward_processing_class + self.reward_processing_classes = reward_processing_classes + + for i, reward_func in enumerate(self.reward_funcs): + if isinstance(reward_func, nn.Module): + if self.is_deepspeed_enabled: + self.reward_funcs[i] = prepare_deepspeed(reward_func, self.accelerator) + elif self.is_fsdp_enabled: + self.reward_funcs[i] = prepare_fsdp(reward_func, self.accelerator) + else: + self.reward_funcs[i] = self.accelerator.prepare_model(reward_func, evaluation_mode=True) + + self.teacher_context_builder = SuccessfulRolloutTeacherContextBuilder(self) + + def _set_signature_columns_if_needed(self): + if self._signature_columns is None: + self._signature_columns = ["prompt", "privileged_context"] + + def _dispatch_self_distillation_callback(self, event_name: str, **payload) -> None: + for callback in self.callback_handler.callbacks: + callback_fn = getattr(callback, event_name, None) + if callback_fn is not None: + callback_fn( + args=self.args, + state=self.state, + control=self.control, + model=self.model, + processing_class=self.processing_class, + **payload, + ) + + def _setup_teacher_model(self) -> None: + """Prepare teacher state according to the semantic teacher choice. + + Resolve `teacher_model_kind` × PEFT state into the effective teacher: + + - `"live"` (any model): + Teacher is the student. No divergence, no callback. + - `"base"` + PEFT model: + Teacher reuses `self.model`; the base weights are recovered downstream by disabling the adapter via + `use_adapter` during teacher forward. + - `"base"` + non-PEFT model: + Teacher is a frozen deepcopy of the initial student (falls through to the copy branch below). + - `"ema"` + pure-LoRA training: + Teacher reuses `self.model`; a dedicated `"teacher"` LoRA adapter is attached and updated by + `PEFTAdapterEMACallback`. Teacher forward switches to that adapter downstream. + - `"ema"` (otherwise): + Teacher is a frozen deepcopy synchronized each step by `SyncTeacherModelCallback`. + + Must be called after `super().__init__` so that `self.callback_handler` is available. + """ + + teacher_model_kind = self.args.teacher_model_kind + + if teacher_model_kind == "live": + self.teacher_model = self.model + return + + if teacher_model_kind == "base" and is_peft_model(self.model): + self.teacher_model = self.model + return + + if self._use_peft_ema_teacher_adapter(): + # Must run after super().__init__ so self.callback_handler exists. + self.add_callback( + PEFTAdapterEMACallback( + model=self.model, + teacher_adapter_name="teacher", + update_rate=self.args.teacher_update_rate, + sync_steps=self.args.teacher_sync_steps, + accelerator=self.accelerator, + ) + ) + self.teacher_model = self.model + return + + if is_peft_model(self.model): + raise ValueError( + "`teacher_model_kind='ema'` with a non-pure-LoRA PEFT model is not supported: the separate EMA " + "teacher cannot be parameter-matched to the PEFT student. Use pure-LoRA training, a non-PEFT model, " + "or `teacher_model_kind` in {'live', 'base'}." + ) + + # Build the teacher from the model path (like the GRPO/DPO reference model) rather than deep-copying the + # student: under ZeRO-3 the student params are already sharded, so a deep copy would clone empty shards. + model_init_kwargs = self.args.model_init_kwargs or {} + if self.args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + model_init_kwargs["device_map"] = None + self.teacher_model = create_model_from_path(get_config_model_id(self.model.config), **model_init_kwargs) + self.teacher_model.requires_grad_(False) + self.teacher_model.eval() + if self.is_deepspeed_enabled: + self.teacher_model = prepare_deepspeed(self.teacher_model, self.accelerator) + elif self.is_fsdp_enabled: + self.teacher_model = prepare_fsdp(self.teacher_model, self.accelerator) + else: + self.teacher_model = self.accelerator.prepare_model(self.teacher_model, evaluation_mode=True) + + if teacher_model_kind == "ema": + self.add_callback(SyncTeacherModelCallback(teacher_model=self.teacher_model, accelerator=self.accelerator)) + + def _use_peft_ema_teacher_adapter(self) -> bool: + return self.args.teacher_model_kind == "ema" and is_pure_lora_training(self.model, self.accelerator) + + def get_train_dataloader(self): + if self.train_dataset is None: + raise ValueError("Trainer: training requires a train_dataset.") + + train_dataset = self.train_dataset + data_collator = self.data_collator + if is_datasets_available() and isinstance(train_dataset, datasets.Dataset): + train_dataset = self._remove_unused_columns(train_dataset, description="training") + else: + data_collator = self._get_collator_with_removed_columns(data_collator, description="training") + + dataloader_params = { + "batch_size": self._train_batch_size * self.args.steps_per_generation, + "collate_fn": data_collator, + "num_workers": self.args.dataloader_num_workers, + "pin_memory": self.args.dataloader_pin_memory, + "persistent_workers": self.args.dataloader_persistent_workers, + } + if not isinstance(train_dataset, torch.utils.data.IterableDataset): + dataloader_params["sampler"] = self._get_train_sampler() + dataloader_params["drop_last"] = self.args.dataloader_drop_last + dataloader_params["worker_init_fn"] = partial( + seed_worker, num_workers=self.args.dataloader_num_workers, rank=self.args.process_index + ) + dataloader_params["prefetch_factor"] = self.args.dataloader_prefetch_factor + return self.accelerator.prepare(DataLoader(train_dataset, **dataloader_params)) + + def _get_train_sampler(self, dataset=None) -> Sampler: + if dataset is None: + dataset = self.train_dataset + return RepeatSampler( + data_source=dataset, + mini_repeat_count=self.num_generations, + batch_size=self.args.generation_batch_size // self.num_generations, + repeat_count=self.num_iterations * self.args.steps_per_generation, + shuffle=self.shuffle_dataset, + seed=self.args.seed, + ) + + def _get_eval_sampler(self, eval_dataset) -> Sampler: + return RepeatSampler( + data_source=eval_dataset, + mini_repeat_count=self.num_generations_eval, + seed=self.args.seed, + ) + + def training_step(self, model, inputs, num_items_in_batch): + # Gather spans forward+backward: the fused JSD computes the lm_head grad in backward. + with self._get_liger_zero3_lm_head_gather_ctx(model): + output = super().training_step(model, inputs, num_items_in_batch) + self._step += 1 + return output + + def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys=None): + if not isinstance(inputs, dict): + inputs = self._prepare_inputs(inputs) + with torch.no_grad(): + with self.compute_loss_context_manager(): + loss = self.compute_loss(model, inputs) + return loss.detach(), None, None + + def _prepare_inputs(self, generation_batch): + """Return the per-step training batch, regenerating rollouts and buffering them for reuse in train mode. + + In train mode, rollouts are generated once every `steps_per_generation * num_iterations` steps and split into + per-step slices reused until the next regeneration. In eval mode, every batch is freshly prepared. + """ + mode = "train" if self.model.training else "eval" + if mode == "train": + generate_every = self.args.steps_per_generation * self.num_iterations + if self._step % generate_every == 0 or self._buffered_inputs is None: + buffered_batch = self._prepare_training_batch(generation_batch) + self._buffered_inputs = split_tensor_dict(buffered_batch, self.args.steps_per_generation) + self._dispatch_self_distillation_callback( + "on_generation_batch_built", + generate_every=generate_every, + steps_per_generation=self.args.steps_per_generation, + ) + return self._buffered_inputs[self._step % self.args.steps_per_generation] + return self._prepare_training_batch(generation_batch) + + def _prepare_training_batch(self, inputs: list[dict[str, Any]]) -> TrainingBatch: + """Sample student rollouts, calculate advantage and construct teacher prompts""" + device = self.accelerator.device + mode = "train" if self.model.training else "eval" + + # Generate student rollouts and decode completions for reward functions + batch = self.sample_rollouts(inputs) + prompts = [example["prompt"] for example in inputs] + privileged_contexts = [example.get("privileged_context") for example in inputs] + completion_ids_list = self._get_completion_ids_list(batch) + if is_conversational({"prompt": prompts[0]}): + completions_text = self.processing_class.batch_decode(batch["completion_ids"], skip_special_tokens=True) + completions = [[{"role": "assistant", "content": content}] for content in completions_text] + else: + completions = self.processing_class.batch_decode(batch["completion_ids"], skip_special_tokens=True) + + # Compute rewards over the globally gathered rollout batch + rewards_per_func = self._calculate_rewards(inputs, prompts, completions, completion_ids_list) + if rewards_per_func.numel() == 0: + rewards = torch.zeros(self.accelerator.num_processes * len(prompts), device=device) + else: + rewards = (rewards_per_func * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1) + + # Normalize rewards within generation groups to produce local policy advantages + num_generations = self.num_generations if mode == "train" else self.num_generations_eval + mean_grouped_rewards = rewards.view(-1, num_generations).mean(dim=1).repeat_interleave(num_generations, dim=0) + if self.scale_rewards == "batch": + std_rewards = rewards.std().expand_as(rewards) if rewards.numel() > 1 else torch.zeros_like(rewards) + group_std_rewards = rewards.view(-1, num_generations).std(dim=1) + elif self.scale_rewards == "none": + std_rewards = torch.ones_like(rewards) + group_std_rewards = torch.ones(rewards.numel() // num_generations, device=device, dtype=rewards.dtype) + else: + group_std_rewards = rewards.view(-1, num_generations).std(dim=1) + std_rewards = group_std_rewards.repeat_interleave(num_generations, dim=0) + advantages = (rewards - mean_grouped_rewards) / (std_rewards + 1e-4) + local_batch_size = batch["completion_ids"].size(0) + process_start = self.accelerator.process_index * local_batch_size + process_slice = slice(process_start, process_start + local_batch_size) + local_rewards = rewards[process_slice] + local_advantages = advantages[process_slice] + + self._record_reward_diagnostics(mode, rewards, rewards_per_func, group_std_rewards) + self._record_completion_metrics(mode, batch) + + batch["rewards"] = local_rewards + batch["advantages"] = local_advantages + teacher_context = self.teacher_context_builder.build( + batch, + prompts, + batch["rewards"], + feedbacks=privileged_contexts, + ) + + for key, value in self.teacher_context_builder.last_metrics.items(): + self._metrics[mode][key].append(value) + self._warn_on_inactive_self_distillation(mode) + + self._dispatch_self_distillation_callback( + "on_teacher_context_built", + teacher_input_ids=teacher_context["teacher_input_ids"], + teacher_attention_mask=teacher_context["teacher_attention_mask"], + completion_mask=batch["completion_mask"], + self_distillation_mask=teacher_context["self_distillation_mask"], + ) + + batch.update( + { + "teacher_input_ids": teacher_context["teacher_input_ids"], + "teacher_attention_mask": teacher_context["teacher_attention_mask"], + "self_distillation_mask": teacher_context["self_distillation_mask"], + } + ) + + self._dispatch_self_distillation_callback( + "on_self_distillation_batch_prepared", + old_per_token_logps=batch.get("old_per_token_logps"), + prompt_ids=batch["prompt_ids"], + completion_ids=batch["completion_ids"], + teacher_input_ids=batch["teacher_input_ids"], + teacher_attention_mask=batch["teacher_attention_mask"], + self_distillation_mask=batch.get("self_distillation_mask"), + ) + return batch + + def sample_rollouts(self, inputs: list[dict[str, Any]]) -> TrainingBatch: + """Generate completions for a batch of prompts and assemble the training batch.""" + prompts = [example["prompt"] for example in inputs] + prompt_ids = self._tokenize_prompts(prompts) + self._dispatch_self_distillation_callback( + "on_generation_prompts_selected", + generation_prompts=prompts, + generation_prompt_text=None, + ) + + prompt_ids_list, completion_ids_list = self._generate(prompt_ids) + device = self.accelerator.device + prompt_ids = [torch.tensor(ids) for ids in prompt_ids_list] + prompt_mask = [torch.ones_like(ids, dtype=torch.long) for ids in prompt_ids] + prompt_ids = pad(prompt_ids, padding_value=self._tokenizer.pad_token_id, padding_side="left").to(device=device) + prompt_mask = pad(prompt_mask, padding_value=0, padding_side="left").to(device=device) + + completion_ids = [torch.tensor(ids) for ids in completion_ids_list] + completion_mask = [torch.ones_like(ids, dtype=torch.long) for ids in completion_ids] + completion_ids = pad(completion_ids, padding_value=self._tokenizer.pad_token_id, padding_side="right").to( + device=device + ) + completion_mask = pad(completion_mask, padding_value=0, padding_side="right").to(device=device) + + if self.mask_truncated_completions: + eos_and_pad = [self._tokenizer.eos_token_id, self._tokenizer.pad_token_id] + is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids_list], device=device) + completion_mask = completion_mask * (~is_truncated).unsqueeze(1).int() + + old_per_token_logps = self._compute_rollout_logps( + prompt_ids=prompt_ids, + prompt_mask=prompt_mask, + completion_ids=completion_ids, + completion_mask=completion_mask, + ) + batch: TrainingBatch = { + "prompt_ids": prompt_ids, + "prompt_mask": prompt_mask, + "completion_ids": completion_ids, + "completion_mask": completion_mask, + "raw_completion_lengths": torch.tensor( + [len(ids) for ids in completion_ids_list], device=device, dtype=torch.long + ), + } + if old_per_token_logps is not None: + batch["old_per_token_logps"] = old_per_token_logps + return batch + + def _get_completion_ids_list(self, batch: TrainingBatch) -> list[list[int]]: + raw_completion_lengths = batch["raw_completion_lengths"].detach().cpu().tolist() + return [ + ids[:length].tolist() + for ids, length in zip(batch["completion_ids"].detach().cpu(), raw_completion_lengths, strict=True) + ] + + def _tokenize_prompts_untruncated(self, prompts: list[Any]) -> list[list[int]]: + if is_conversational({"prompt": prompts[0]}): + tokenized = self.processing_class.apply_chat_template( + conversation=prompts, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + **self.chat_template_kwargs, + ) + prompt_ids = tokenized["input_ids"] + else: + prompt_ids = self.processing_class(text=prompts)["input_ids"] + return prompt_ids + + def _tokenize_prompts(self, prompts: list[Any]) -> list[list[int]]: + prompt_ids = self._tokenize_prompts_untruncated(prompts) + if self.max_prompt_length is not None: + prompt_ids = [ids[-self.max_prompt_length :] for ids in prompt_ids] + return prompt_ids + + def _generate(self, prompt_ids: list[list[int]]) -> tuple[list[list[int]], list[list[int]]]: + if self.use_vllm: + return self._generate_vllm(prompt_ids) + return self._generate_transformers(prompt_ids) + + def _generate_vllm(self, prompt_ids: list[list[int]]) -> tuple[list[list[int]], list[list[int]]]: + if self.state.global_step != self._last_loaded_step: + self.vllm_generation.sync_weights() + self._last_loaded_step = self.state.global_step + + mode = "train" if self.model.training else "eval" + num_generations = self.num_generations if mode == "train" else self.num_generations_eval + prompt_ids_out, completion_ids_list, _, _ = self.vllm_generation.generate( + prompts=prompt_ids, + images=None, + num_generations=num_generations, + ) + return prompt_ids_out, completion_ids_list + + def _generate_transformers(self, prompt_ids: list[list[int]]) -> tuple[list[list[int]], list[list[int]]]: + device = self.accelerator.device + prompt_tensors = [torch.tensor(ids) for ids in prompt_ids] + padded_ids = pad(prompt_tensors, padding_value=self._tokenizer.pad_token_id, padding_side="left").to( + device=device + ) + attention_mask = pad([torch.ones_like(t) for t in prompt_tensors], padding_value=0, padding_side="left").to( + device=device + ) + generate_inputs: dict[str, torch.Tensor | Any] = {"input_ids": padded_ids, "attention_mask": attention_mask} + + with ( + unwrap_model_for_generation( + self.model_wrapped, + self.accelerator, + gather_deepspeed3_params=self.args.ds3_gather_for_generation, + generation_kwargs=self.generation_kwargs, + ) as unwrapped_model, + torch.no_grad(), + FSDP.summon_full_params(self.model_wrapped, recurse=False) if self.is_fsdp_enabled else nullcontext(), + ): + prompt_completion_ids = unwrapped_model.generate( + **generate_inputs, generation_config=self.generation_config + ) + + prompt_length = generate_inputs["input_ids"].size(1) + completion_ids = prompt_completion_ids[:, prompt_length:] + is_eos = completion_ids == self._tokenizer.eos_token_id + eos_idx = torch.full((is_eos.size(0),), is_eos.size(1), dtype=torch.long, device=device) + eos_idx[is_eos.any(dim=1)] = is_eos.int().argmax(dim=1)[is_eos.any(dim=1)] + seq_idx = torch.arange(is_eos.size(1), device=device).expand(is_eos.size(0), -1) + completion_mask = (seq_idx <= eos_idx.unsqueeze(1)).int() + completion_ids_list = [ + c[m].tolist() for c, m in zip(completion_ids.cpu(), completion_mask.bool().cpu(), strict=True) + ] + return prompt_ids, completion_ids_list + + def _compute_rollout_logps( + self, + prompt_ids: torch.Tensor, + prompt_mask: torch.Tensor, + completion_ids: torch.Tensor, + completion_mask: torch.Tensor, + ) -> torch.Tensor | None: + generate_every = self.args.steps_per_generation * self.num_iterations + old_per_token_logps = None + + if self.args.gradient_accumulation_steps % generate_every != 0: + prompt_completion_ids = torch.cat([prompt_ids, completion_ids], dim=1) + attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) + logits_to_keep = completion_ids.size(1) + with torch.no_grad(): + logits = self._forward_logits( + self.model, + prompt_completion_ids, + attention_mask, + logits_to_keep, + ) + old_per_token_logps = selective_log_softmax(logits, completion_ids) + + return old_per_token_logps + + def _calculate_rewards(self, inputs, prompts, completions, completion_ids_list): + device = self.accelerator.device + if len(self.reward_funcs) == 0: + return torch.zeros((len(prompts), 0), device=device) + + rewards_per_func = torch.zeros(len(prompts), len(self.reward_funcs), device=device) + keys = [key for key in inputs[0] if key not in ["prompt", "completion", "completion_ids"]] + reward_kwargs = {key: [example[key] for example in inputs] for key in keys} + reward_kwargs["trainer_state"] = self.state + + for i, (reward_func, reward_processing_class) in enumerate( + zip(self.reward_funcs, self.reward_processing_classes, strict=True) + ): + if isinstance(reward_func, nn.Module): + if is_conversational(inputs[0]): + messages = [{"messages": p + c} for p, c in zip(prompts, completions, strict=True)] + texts = [ + apply_chat_template(x, reward_processing_class, **self.chat_template_kwargs)["text"] + for x in messages + ] + else: + texts = [p + c for p, c in zip(prompts, completions, strict=True)] + reward_inputs = reward_processing_class( + text=texts, + return_tensors="pt", + padding=True, + padding_side="right", + add_special_tokens=False, + ) + reward_inputs = _BaseTrainer._prepare_inputs(self, reward_inputs) + with torch.inference_mode(): + rewards_per_func[:, i] = reward_func(**reward_inputs).logits[:, 0] + else: + output_reward_func = reward_func( + prompts=prompts, + completions=completions, + completion_ids=completion_ids_list, + **reward_kwargs, + ) + output_reward_func = [reward if reward is not None else torch.nan for reward in output_reward_func] + rewards_per_func[:, i] = torch.tensor(output_reward_func, dtype=torch.float32, device=device) + + return self.accelerator.gather(rewards_per_func) + + def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): + if return_outputs: + raise ValueError("The SDPOTrainer does not support returning outputs") + + if self.args.distillation_weight == 1.0: + if self.use_teacher_server: + loss = self._compute_server_distillation_loss(model, inputs) + elif self.use_liger_loss: + accumulation_scale = self.current_gradient_accumulation_steps if self.model.training else 1.0 + return self._compute_liger_loss(model, inputs) / accumulation_scale + else: + distillation_logits = self._compute_teacher_student_logits(model, self.teacher_model, inputs) + loss = self._compute_self_distillation_loss(model, inputs, distillation_logits) + elif self.args.distillation_weight == 0.0: + student_input_ids = torch.cat([inputs["prompt_ids"], inputs["completion_ids"]], dim=1) + student_attention_mask = torch.cat([inputs["prompt_mask"], inputs["completion_mask"]], dim=1) + student_logits = self._forward_logits( + model=model, + input_ids=student_input_ids, + attention_mask=student_attention_mask, + logits_to_keep=inputs["completion_ids"].size(1), + ) + loss = self._compute_policy_loss(inputs, student_logits) + else: + distillation_logits = self._compute_teacher_student_logits(model, self.teacher_model, inputs) + policy_loss = self._compute_policy_loss(inputs, distillation_logits.student_logits) + distillation_loss = self._compute_self_distillation_loss(model, inputs, distillation_logits) + loss = ( + 1 - self.args.distillation_weight + ) * policy_loss + self.args.distillation_weight * distillation_loss + + accumulation_scale = self.current_gradient_accumulation_steps if self.model.training else 1.0 + return loss / accumulation_scale + + def _compute_policy_loss( + self, + inputs, + student_logits, + ) -> torch.Tensor: + completion_ids = inputs["completion_ids"] + completion_mask = inputs["completion_mask"] + per_token_logps = selective_log_softmax(student_logits, completion_ids) + old_per_token_logps = inputs.get("old_per_token_logps") + old_per_token_logps = per_token_logps.detach() if old_per_token_logps is None else old_per_token_logps + advantages = inputs["advantages"] + if advantages.dim() == 1: + advantages = advantages.unsqueeze(1) + log_ratio = per_token_logps - old_per_token_logps + if self.importance_sampling_level == "sequence": + log_ratio = (log_ratio * completion_mask).sum(-1, keepdim=True) / completion_mask.sum( + -1, keepdim=True + ).clamp(min=1.0) + coef_1 = torch.exp(log_ratio) + coef_2 = torch.clamp(coef_1, 1 - self.epsilon_low, 1 + self.epsilon_high) + per_token_loss = -torch.min(coef_1 * advantages, coef_2 * advantages) + + if self.loss_type == "grpo": + loss = (per_token_loss * completion_mask).sum(-1) / completion_mask.sum(-1).clamp(min=1.0) + loss = loss.mean() + elif self.loss_type == "bnpo": + loss = (per_token_loss * completion_mask).sum() / completion_mask.sum().clamp(min=1.0) + elif self.loss_type == "dr_grpo": + loss = (per_token_loss * completion_mask).sum() / (per_token_loss.size(0) * self.max_completion_length) + elif self.loss_type == "dapo": + loss = (per_token_loss * completion_mask).sum() / completion_mask.sum().clamp(min=1.0) + else: + raise ValueError(f"Unsupported loss_type: {self.loss_type}") + + mode = "train" if self.model.training else "eval" + self._metrics[mode]["self_distillation/policy_loss"].append( + self.accelerator.gather(loss.detach()).mean().item() + ) + + return loss + + def _compute_self_distillation_loss( + self, + model, + inputs: TrainingBatch, + distillation_logits: DistillationLogits, + ) -> torch.Tensor: + """Compute the per-token distillation loss and aggregate by normalizing over sequence length. + + Dispatches between three objectives based on `distillation_mode`: + + - `"topk_logits"`: top-k approximation of the divergence, optionally with a tail bucket for the remaining + probability mass (`distillation_add_tail`). + - `"full_logits"`: full-vocab divergence. + - `"sampled_token"`: token-level (reverse-KL) distillation on sampled `completion_ids`. + + When `distillation_is_clip` is set and `old_per_token_logps` are available, the loss is corrected by a clipped + importance-sampling ratio between the current student and the student at rollout time. + """ + if distillation_logits.loss_mask.sum() == 0: + mode = "train" if model.training else "eval" + self._log_self_distillation_metric(mode, 0.0) + # Keep the zero loss attached to the student graph so backward produces zero gradients instead of stopping. + return distillation_logits.student_logits.sum() * 0.0 + + if self.args.distillation_mode == "topk_logits": + if self.args.distillation_topk is None: + raise ValueError("`distillation_mode='topk_logits'` requires `distillation_topk` to be set.") + per_token_loss = compute_topk_self_distillation_loss( + distillation_logits.student_logits, + distillation_logits.teacher_logits, + distillation_topk=self.args.distillation_topk, + distillation_alpha=self.args.distillation_alpha, + distillation_add_tail=self.args.distillation_add_tail, + ) + elif self.args.distillation_mode == "full_logits": + per_token_loss = compute_full_logit_self_distillation_loss( + distillation_logits.student_logits, + distillation_logits.teacher_logits, + distillation_alpha=self.args.distillation_alpha, + ) + elif self.args.distillation_mode == "sampled_token": + per_token_loss = compute_sampled_token_self_distillation_loss( + distillation_logits.student_logits, + distillation_logits.teacher_logits, + distillation_logits.completion_ids, + distillation_alpha=self.args.distillation_alpha, + ) + else: + raise ValueError( + "distillation_mode must be one of: 'sampled_token', 'full_logits', 'topk_logits', " + f"got {self.args.distillation_mode!r}" + ) + + old_per_token_logps = inputs.get("old_per_token_logps") + if self.args.distillation_is_clip is not None and old_per_token_logps is not None: + student_per_token_logps = selective_log_softmax( + distillation_logits.student_logits, + distillation_logits.completion_ids, + ) + per_token_loss = apply_importance_sampling_clipping( + per_token_loss, + student_per_token_logps, + old_per_token_logps, + self.args.distillation_is_clip, + ) + + loss = (per_token_loss * distillation_logits.loss_mask).sum(-1) / distillation_logits.loss_mask.sum(-1).clamp( + min=1.0 + ) + loss = loss.mean() + + mode = "train" if model.training else "eval" + mean_distill_loss = ( + per_token_loss * distillation_logits.loss_mask + ).sum() / distillation_logits.loss_mask.sum().clamp(min=1.0) + self._log_self_distillation_metric( + mode, + self.accelerator.gather(mean_distill_loss).mean().item(), + ) + return loss + + def _compute_server_distillation_loss(self, model, inputs: TrainingBatch) -> torch.Tensor: + """Distillation loss with teacher logprobs served by the vLLM generation server (`teacher_model_kind='live'`). + + The student is forwarded locally (grad) for its logits; the teacher logprobs are fetched from the server (no + local teacher forward). `sampled_token` distills the realized token (reverse KL); `topk_logits` distills over + the teacher's own top-k support (the server cannot score the student's top-k indices). + """ + # Buffered batches are reused across optimizer steps (`num_iterations > 1`), so the server weights can lag the + # live student; re-sync before scoring. + if self.state.global_step != self._last_loaded_step: + self.vllm_generation.sync_weights() + # Only the main process pushes weights to the server, so hold every rank here until the push completes; + # otherwise non-main ranks could score against half-updated weights. + self.accelerator.wait_for_everyone() + self._last_loaded_step = self.state.global_step + + completion_ids = inputs["completion_ids"] + completion_mask = inputs["completion_mask"] + logits_to_keep = completion_ids.size(1) + + self_distillation_mask = inputs.get("self_distillation_mask") + if self_distillation_mask is None: + loss_mask = completion_mask + else: + loss_mask = completion_mask * self_distillation_mask.unsqueeze(1) + + student_input_ids = torch.cat([inputs["prompt_ids"], completion_ids], dim=1) + student_attention_mask = torch.cat([inputs["prompt_mask"], completion_mask], dim=1) + student_logits = self._forward_logits( + model=model, + input_ids=student_input_ids, + attention_mask=student_attention_mask, + logits_to_keep=logits_to_keep, + ) + + mode = "train" if model.training else "eval" + teacher = self._get_teacher_token_logprobs_from_server(inputs, logits_to_keep) + # Padding positions come back as `-inf`; the masked-out positions are neutralized to finite values below so the + # divergence does not leak `+inf` through them (mirrors the distillation trainer). + required = loss_mask.bool() + student_per_token_logps = selective_log_softmax(student_logits, completion_ids) + + teacher_per_token_logps = teacher["actual_logprobs"] + if (required & ~torch.isfinite(teacher_per_token_logps)).any(): + raise ValueError("Teacher server returned no logprob for a required completion token.") + teacher_per_token_logps = torch.where( + required, teacher_per_token_logps, torch.zeros_like(teacher_per_token_logps) + ) + + # Diagnostic for disagreement between local student scores and server teacher scores on realized tokens. + # Sudden jumps can indicate stale server weights or numerical drift. + abs_diff = ((student_per_token_logps.detach() - teacher_per_token_logps).abs() * loss_mask).sum() / ( + loss_mask.sum().clamp(min=1.0) + ) + self._metrics[mode]["self_distillation/server_logprob_abs_diff"].append( + self.accelerator.gather(abs_diff).mean().item() + ) + + if self.args.distillation_mode == "sampled_token": + # Reverse-KL token-level objective, matching `compute_sampled_token_self_distillation_loss`. + per_token_loss = (student_per_token_logps - teacher_per_token_logps).detach() * student_per_token_logps + else: + teacher_topk_logps = teacher["topk_logprobs"] + teacher_topk_ids = teacher["topk_token_ids"] + # Project the student onto the teacher's top-k support, then renormalize (or add a tail bucket) before the + # divergence, matching `compute_topk_self_distillation_loss` on the teacher's support. + keep = required.unsqueeze(-1) + student_topk_logps = torch.gather( + torch.log_softmax(student_logits, dim=-1), dim=-1, index=teacher_topk_ids + ) + student_topk_logps = torch.where(keep, student_topk_logps, torch.zeros_like(student_topk_logps)) + teacher_topk_logps = torch.where(keep, teacher_topk_logps, torch.zeros_like(teacher_topk_logps)) + if self.args.distillation_add_tail: + student_topk_logps = add_tail_bucket(student_topk_logps) + teacher_topk_logps = add_tail_bucket(teacher_topk_logps) + else: + student_topk_logps = student_topk_logps - torch.logsumexp(student_topk_logps, dim=-1, keepdim=True) + teacher_topk_logps = teacher_topk_logps - torch.logsumexp(teacher_topk_logps, dim=-1, keepdim=True) + per_token_loss = compute_divergence(student_topk_logps, teacher_topk_logps, self.args.distillation_alpha) + + old_per_token_logps = inputs.get("old_per_token_logps") + if self.args.distillation_is_clip is not None and old_per_token_logps is not None: + per_token_loss = apply_importance_sampling_clipping( + per_token_loss, student_per_token_logps, old_per_token_logps, self.args.distillation_is_clip + ) + + loss = (per_token_loss * loss_mask).sum(-1) / loss_mask.sum(-1).clamp(min=1.0) + loss = loss.mean() + mean_distill_loss = (per_token_loss * loss_mask).sum() / loss_mask.sum().clamp(min=1.0) + self._log_self_distillation_metric(mode, self.accelerator.gather(mean_distill_loss).mean().item()) + return loss + + def _get_teacher_token_logprobs_from_server( + self, inputs: TrainingBatch, logits_to_keep: int + ) -> dict[str, torch.Tensor]: + """Per-token teacher logprobs from the vLLM server. + + Returns a dict with `actual_logprobs` (`(B, T)`, the realized-token logprob for reverse KL) and `topk_logprobs` + / `topk_token_ids` (`(B, T, K)`, the teacher's top-k support for top-k logit distillation). Completions are + right-padded, so server values fill the leading positions of each row and the trailing padding keeps the `-inf` + / `0` sentinels (neutralized by the caller). + """ + import numpy as np + + teacher_input_ids = inputs["teacher_input_ids"] + teacher_attention_mask = inputs["teacher_attention_mask"] + device = teacher_input_ids.device + batch_size = teacher_input_ids.size(0) + prompt_attention_mask = teacher_attention_mask[:, : teacher_attention_mask.size(1) - logits_to_keep] + if self.args.distillation_mode == "topk_logits" and self.args.distillation_topk is None: + raise ValueError("`distillation_mode='topk_logits'` requires `distillation_topk` to be set.") + top_logprobs = self.args.distillation_topk if self.args.distillation_mode == "topk_logits" else 1 + + sequences, prompt_lengths, _ = build_teacher_request_inputs( + teacher_input_ids, teacher_attention_mask, prompt_attention_mask + ) + result = self.teacher_client.get_sequence_logprobs( + sequences=sequences, + prompt_lengths=prompt_lengths, + top_logprobs=top_logprobs, + temperature=self.temperature, + ) + + actual = np.full((batch_size, logits_to_keep), float("-inf"), dtype=np.float32) + topk = np.full((batch_size, logits_to_keep, top_logprobs), float("-inf"), dtype=np.float32) + topk_ids = np.zeros((batch_size, logits_to_keep, top_logprobs), dtype=np.int64) + for i in range(batch_size): + seq_actual = result["actual_logprobs"][i] + n = min(len(seq_actual), logits_to_keep) + if n: + actual[i, :n] = np.array(seq_actual, dtype=np.float32)[:n, 0] + topk[i, :n] = np.array(result["logprobs"][i], dtype=np.float32)[:n] + topk_ids[i, :n] = np.array(result["logprob_token_ids"][i], dtype=np.int64)[:n] + return { + "actual_logprobs": torch.from_numpy(actual).to(device), + "topk_logprobs": torch.from_numpy(topk).to(device), + "topk_token_ids": torch.from_numpy(topk_ids).to(device), + } + + def _compute_teacher_student_logits( + self, + model, + teacher_model, + inputs: TrainingBatch, + ) -> DistillationLogits: + """Compute the per-token logits of the student and teacher over the completion tokens. + + The student is forwarded on its own input (original prompt plus the sampled completion) while the teacher is + forwarded on its input (prompt, privileged context, and the same completion). Both sets of logits are aligned + to the completion tokens so they can be compared position-by-position in the distillation loss. + + The teacher forward runs under `torch.no_grad()` and the context resolved by + `_get_teacher_context_for_self_distillation`, which routes it to the correct weights. + """ + prompt_ids = inputs["prompt_ids"] + prompt_mask = inputs["prompt_mask"] + completion_ids = inputs["completion_ids"] + completion_mask = inputs["completion_mask"] + logits_to_keep = completion_ids.size(1) + + self_distillation_mask = inputs.get("self_distillation_mask") + if self_distillation_mask is None: + loss_mask = completion_mask + else: + loss_mask = completion_mask * self_distillation_mask.unsqueeze(1) + student_input_ids = torch.cat([prompt_ids, completion_ids], dim=1) + student_attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) + student_logits = self._forward_logits( + model=model, + input_ids=student_input_ids, + attention_mask=student_attention_mask, + logits_to_keep=logits_to_keep, + ) + + with torch.no_grad(), self._get_teacher_context_for_self_distillation(): + teacher_logits = self._forward_logits( + model=teacher_model, + input_ids=inputs["teacher_input_ids"], + attention_mask=inputs["teacher_attention_mask"], + logits_to_keep=logits_to_keep, + ) + + return DistillationLogits( + completion_ids=completion_ids, + completion_mask=completion_mask, + loss_mask=loss_mask, + student_logits=student_logits, + teacher_logits=teacher_logits, + ) + + def _forward_logits( + self, + model, + input_ids: torch.Tensor, + attention_mask: torch.Tensor, + logits_to_keep: int, + ) -> torch.Tensor: + """Forward the model and return temperature-scaled logits aligned to the completion tokens.""" + model_inputs = { + "input_ids": input_ids, + "attention_mask": attention_mask, + "use_cache": False, + } + if "logits_to_keep" in self.model_kwarg_keys: + model_inputs["logits_to_keep"] = logits_to_keep + 1 + + logits = model(**model_inputs).logits + logits = logits[:, :-1, :] + logits = logits[:, -logits_to_keep:, :] + return logits / self.temperature + + def _compute_liger_loss(self, model, inputs: TrainingBatch) -> torch.Tensor: + """`full_logits` distillation via the Liger fused JSD kernel: forwards the base models for hidden states and + fuses the lm_head projection with the divergence, never materializing the full-vocab logits. + + Each model is forwarded through its own wrapper via `_forward_redirection` so FSDP2/DeepSpeed materialize the + sharded params during the unwrapped base forward. The fused kernel needs both lm_head weights live at once, so + the frozen teacher weight is captured while the teacher is materialized and handed to the student pass. + """ + logits_to_keep = inputs["completion_ids"].size(1) + self_distillation_mask = inputs.get("self_distillation_mask") + if self_distillation_mask is None: + loss_mask = inputs["completion_mask"] + else: + loss_mask = inputs["completion_mask"] * self_distillation_mask.unsqueeze(1) + + unwrapped_student = self.accelerator.unwrap_model(model) + unwrapped_teacher = self.accelerator.unwrap_model(self.teacher_model) + + with torch.no_grad(), self._get_teacher_context_for_self_distillation(): + teacher_hidden, teacher_weight, teacher_bias = self._forward_redirection( + self.teacher_model, + unwrapped_teacher, + self._liger_teacher_side, + unwrapped_teacher, + inputs, + logits_to_keep, + ) + + return self._forward_redirection( + model, + unwrapped_student, + self._liger_student_loss, + unwrapped_student, + inputs, + logits_to_keep, + loss_mask, + teacher_hidden, + teacher_weight, + teacher_bias, + ) + + def _liger_teacher_side(self, teacher, inputs: TrainingBatch, logits_to_keep: int): + """Teacher hidden states + frozen lm_head weight, captured while the teacher params are materialized.""" + hidden = teacher.get_decoder()( + input_ids=inputs["teacher_input_ids"], + attention_mask=inputs["teacher_attention_mask"], + use_cache=False, + ).last_hidden_state + hidden = hidden[:, :-1][:, -logits_to_keep:] + head = teacher.get_output_embeddings() + # Clone so the weight survives re-sharding once this forward context exits. + weight = head.weight.detach().clone() + bias = head.bias.detach().clone() if head.bias is not None else None + return hidden, weight, bias + + def _liger_student_loss( + self, + student, + inputs: TrainingBatch, + logits_to_keep, + loss_mask, + teacher_hidden, + teacher_weight, + teacher_bias, + ): + student_input_ids = torch.cat([inputs["prompt_ids"], inputs["completion_ids"]], dim=1) + student_attention_mask = torch.cat([inputs["prompt_mask"], inputs["completion_mask"]], dim=1) + student_hidden = student.get_decoder()( + input_ids=student_input_ids, + attention_mask=student_attention_mask, + use_cache=False, + ).last_hidden_state + # Align hidden states to the completion-predicting positions, matching `_forward_logits`. + student_hidden = student_hidden[:, :-1][:, -logits_to_keep:] + + # `ignore_index` masks non-response positions; the token values only feed the disabled hard-CE term. + completion_ids = inputs["completion_ids"] + true_labels = torch.where(loss_mask.bool(), completion_ids, torch.full_like(completion_ids, -100)) + + student_head = student.get_output_embeddings() + # Per-sequence then batch mean (grpo), matching the non-Liger path: the fused kernel reduces by total tokens + # (bnpo), so we call it per sequence and average. + seq_losses = [ + self.liger_jsd_loss( + student_input=student_hidden[i], + student_weight=student_head.weight, + teacher_input=teacher_hidden[i], + teacher_weight=teacher_weight, + true_labels=true_labels[i], + student_bias=student_head.bias, + teacher_bias=teacher_bias, + ) + for i in range(student_hidden.size(0)) + ] + loss = torch.stack(seq_losses).mean() + + mode = "train" if student.training else "eval" + self._log_self_distillation_metric(mode, self.accelerator.gather(loss.detach()).mean().item()) + return loss + + def _get_liger_zero3_lm_head_gather_ctx(self, model): + """Gather the sharded student/teacher lm_head weights for the fused matmul under ZeRO-3. Liger reads + `lm_head.weight` by attribute, so the gather hook never fires; the decoder forward gathers itself. No-op + outside ZeRO-3.""" + if not self.use_liger_loss: + return nullcontext() + + deepspeed_plugin = self.accelerator.state.deepspeed_plugin + if deepspeed_plugin is None or deepspeed_plugin.zero_stage != 3: + return nullcontext() + + import deepspeed + + unwrapped_student = self.accelerator.unwrap_model(model) + unwrapped_teacher = self.accelerator.unwrap_model(self.teacher_model) + student_head = unwrapped_student.get_output_embeddings() + teacher_head = unwrapped_teacher.get_output_embeddings() + params = [student_head.weight, teacher_head.weight] + if student_head.bias is not None: + params.append(student_head.bias) + if teacher_head.bias is not None: + params.append(teacher_head.bias) + return deepspeed.zero.GatheredParameters(params, modifier_rank=None) + + def _get_teacher_context_for_self_distillation(self): + """Return the context manager that routes the teacher forward to the correct weights. + + For non-PEFT models this is a no-op. For PEFT models: + + - `teacher_model_kind == "base"`: disable the student adapter so the teacher forward uses the base weights. + - `teacher_model_kind == "ema"` under pure-LoRA training: switch to the `"teacher"` LoRA adapter. + - otherwise: no-op; the teacher is a separate deepcopy. + """ + teacher_model_kind = self.args.teacher_model_kind + if not is_peft_model(self.model): + return nullcontext() + + target_model = self.accelerator.unwrap_model(self.teacher_model) + + if teacher_model_kind == "base": + return use_adapter(target_model, adapter_name=None) + if teacher_model_kind == "ema" and self._use_peft_ema_teacher_adapter(): + return use_adapter(target_model, adapter_name="teacher") + return nullcontext() + + def _record_completion_metrics(self, mode: str, batch: TrainingBatch) -> None: + device = self.accelerator.device + completion_ids_list = self._get_completion_ids_list(batch) + agg_completion_lengths = self.accelerator.gather(batch["raw_completion_lengths"]) + self._metrics[mode]["completions/mean_length"].append(agg_completion_lengths.float().mean().item()) + self._metrics[mode]["completions/min_length"].append(agg_completion_lengths.float().min().item()) + self._metrics[mode]["completions/max_length"].append(agg_completion_lengths.float().max().item()) + + eos_and_pad = [self._tokenizer.eos_token_id, self._tokenizer.pad_token_id] + is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids_list], device=device) + agg_is_truncated = self.accelerator.gather(is_truncated) + self._metrics[mode]["completions/clipped_ratio"].append(agg_is_truncated.float().mean().item()) + term_completion_lengths = agg_completion_lengths[~agg_is_truncated] + if len(term_completion_lengths) == 0: + term_completion_lengths = torch.zeros(1, device=device) + self._metrics[mode]["completions/mean_terminated_length"].append(term_completion_lengths.float().mean().item()) + self._metrics[mode]["completions/min_terminated_length"].append(term_completion_lengths.float().min().item()) + self._metrics[mode]["completions/max_terminated_length"].append(term_completion_lengths.float().max().item()) + + def _log_self_distillation_metric(self, mode: str, value: float) -> None: + metric_prefix = self._name.lower().replace(" ", "_") + self._metrics[mode]["self_distillation/distillation_loss"].append(value) + self._metrics[mode][f"{metric_prefix}/distillation_loss"].append(value) + + def log(self, logs: dict[str, float], start_time: float | None = None) -> None: + mode = "train" if self.model.training else "eval" + metrics = {k: sum(v) / len(v) for k, v in self._metrics[mode].items() if v} + if mode == "eval": + metrics = {f"eval_{k}": v for k, v in metrics.items()} + logs = {**logs, **metrics} + super().log(logs, start_time) + self._metrics[mode].clear() + + def _record_reward_diagnostics( + self, + mode: str, + rewards: torch.Tensor, + rewards_per_func: torch.Tensor, + group_std_rewards: torch.Tensor, + ) -> None: + tolerance = self.args.diagnostics_flat_tolerance + + reward_mean = rewards.mean() if rewards.numel() > 0 else torch.tensor(0.0, device=self.accelerator.device) + reward_std = rewards.std() if rewards.numel() > 1 else torch.tensor(0.0, device=self.accelerator.device) + reward_min = rewards.min() if rewards.numel() > 0 else torch.tensor(0.0, device=self.accelerator.device) + reward_max = rewards.max() if rewards.numel() > 0 else torch.tensor(0.0, device=self.accelerator.device) + flat_group_fraction = ( + (group_std_rewards <= tolerance).float().mean() + if group_std_rewards.numel() > 0 + else torch.tensor(1.0, device=self.accelerator.device) + ) + + self._metrics[mode]["self_distillation/reward_mean"].append(self.accelerator.gather(reward_mean).mean().item()) + self._metrics[mode]["self_distillation/reward_std"].append(self.accelerator.gather(reward_std).mean().item()) + self._metrics[mode]["self_distillation/reward_min"].append(self.accelerator.gather(reward_min).min().item()) + self._metrics[mode]["self_distillation/reward_max"].append(self.accelerator.gather(reward_max).max().item()) + self._metrics[mode]["self_distillation/group_reward_std_mean"].append( + self.accelerator.gather(group_std_rewards.mean() if group_std_rewards.numel() > 0 else reward_std) + .mean() + .item() + ) + self._metrics[mode]["self_distillation/flat_group_fraction"].append( + self.accelerator.gather(flat_group_fraction).mean().item() + ) + + if rewards_per_func.numel() > 0: + reward_func_means = rewards_per_func.nanmean(dim=0) + gathered_means = self.accelerator.gather(reward_func_means).view(-1, reward_func_means.numel()).mean(dim=0) + for reward_name, reward_func_mean in zip(self.reward_func_names, gathered_means.tolist(), strict=True): + self._metrics[mode][f"self_distillation/rewards/{reward_name}"].append(reward_func_mean) + + reward_is_flat = reward_std.item() <= tolerance + grouped_rewards_are_flat = flat_group_fraction.item() >= 1.0 - tolerance + if reward_is_flat and grouped_rewards_are_flat: + self._warn_on_degenerate_diagnostics( + mode=mode, + counter_key="flat_rewards", + message=( + "Observed flat SDPO rewards across all sampled generations. " + "Policy advantages will collapse to zero, and SDPO will not learn. " + "Check reward density, reward shaping, or `success_reward_threshold`." + ), + ) + else: + self._diagnostic_counters[mode]["flat_rewards"] = 0 + + def _warn_on_inactive_self_distillation(self, mode: str) -> None: + metrics = self.teacher_context_builder.last_metrics + tolerance = self.args.diagnostics_flat_tolerance + + reprompt_fraction = metrics.get("self_distillation/reprompt_sample_fraction", 0.0) + success_fraction = metrics.get("self_distillation/success_group_fraction", 0.0) + + if reprompt_fraction <= tolerance: + self._warn_on_degenerate_diagnostics( + mode=mode, + counter_key="inactive_self_distillation", + message=( + "SDPO self-distillation is inactive because no reprompted samples were constructed. " + "This usually means no rollout exceeded `success_reward_threshold` and no usable privileged " + "feedback was available." + ), + ) + else: + self._diagnostic_counters[mode]["inactive_self_distillation"] = 0 + + if success_fraction <= tolerance: + self._warn_on_degenerate_diagnostics( + mode=mode, + counter_key="no_successful_rollouts", + message=( + "SDPO did not find any successful rollouts in the current generation groups. " + "If this persists, reduce task difficulty, adjust reward shaping, or lower " + "`success_reward_threshold`." + ), + ) + else: + self._diagnostic_counters[mode]["no_successful_rollouts"] = 0 + + def _warn_on_degenerate_diagnostics(self, mode: str, counter_key: str, message: str) -> None: + interval = self.args.diagnostics_warning_interval + if interval == 0: + return + + self._diagnostic_counters[mode][counter_key] += 1 + count = self._diagnostic_counters[mode][counter_key] + if count == 1 or count % interval == 0: + logger.warning("%s Consecutive degenerate steps: %s.", message, count) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdpo/teacher_sync.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdpo/teacher_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..8fb0f751a0bb5f4ae69ce9d201b29c09263bf21c --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/sdpo/teacher_sync.py @@ -0,0 +1,184 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging + +import torch +from accelerate.utils import is_peft_model +from transformers import ( + TrainerCallback, + TrainerControl, + TrainerState, + TrainingArguments, +) + +from ...trainer.callbacks import SyncRefModelCallback + + +logger = logging.getLogger(__name__) + + +def is_pure_lora_training(model, accelerator=None) -> bool: + """Return `True` when the active adapter is LoRA and every trainable parameter is a LoRA parameter.""" + if not is_peft_model(model): + return False + + if accelerator is not None: + model = accelerator.unwrap_model(model) + + adapter_name = model.active_adapter + if adapter_name is None: + adapter_name = "default" + adapter_config = model.peft_config.get(adapter_name) + peft_type = adapter_config.peft_type + if peft_type is None or str(peft_type).split(".")[-1] != "LORA": + return False + + for name, param in model.named_parameters(): + if param.requires_grad and "lora_" not in name: + return False + return True + + +class SyncTeacherModelCallback(SyncRefModelCallback): + """Synchronize an EMA teacher model with the student model on each configured sync step.""" + + def __init__(self, teacher_model, accelerator=None): + super().__init__(ref_model=teacher_model, accelerator=accelerator) + + def on_step_end(self, args, state, control, **kwargs): + model = kwargs["model"] + if self.ref_model is not None and state.global_step % args.teacher_sync_steps == 0: + if self.accelerator: + model = self.accelerator.unwrap_model(model) + self.sync_target_model(model, self.ref_model, args.teacher_update_rate) + + +class PEFTAdapterEMACallback(TrainerCallback): + """ + Callback that maintains an EMA copy of PEFT adapter weights for use as a teacher model in self-distillation. + + The callback creates a secondary adapter ("teacher") with zero-initialized weights and maintains shadow weights + that are updated via exponential moving average: `teacher_weight = (1-α) * teacher_weight + α * student_weight` + + Usage: + ```python + trainer.add_callback( + PEFTAdapterEMACallback( + model=model, + teacher_adapter_name="teacher", + update_rate=0.05, + ) + ) + ``` + """ + + def __init__( + self, + model, + teacher_adapter_name: str = "teacher", + update_rate: float = 0.05, + sync_steps: int = 1, + accelerator=None, + ): + self.model = model + self.teacher_adapter_name = teacher_adapter_name + self.update_rate = update_rate + self.sync_steps = sync_steps + self.accelerator = accelerator + self.shadow_weights: dict[str, torch.Tensor] | None = None + self.teacher_adapter_config = None + self._initialized = False + + def _get_student_state_dict(self): + """Get student adapter state dict using PEFT keys (without adapter name).""" + from peft import get_peft_model_state_dict + + if self.accelerator is not None: + model = self.accelerator.unwrap_model(self.model) + else: + model = self.model + return get_peft_model_state_dict(model) + + def _initialize_teacher_adapter(self): + """Create teacher adapter with zero weights initialized from student adapter.""" + from peft import get_peft_model_state_dict, set_peft_model_state_dict + + if self._initialized: + return + + if self.accelerator is not None: + model = self.accelerator.unwrap_model(self.model) + else: + model = self.model + + adapter_name = model.active_adapter + if adapter_name is None: + adapter_name = "default" + + self.teacher_adapter_config = model.peft_config.get(adapter_name) + + student_state = get_peft_model_state_dict(model) + + teacher_state = {k: torch.zeros_like(v) for k, v in student_state.items()} + + model.add_adapter(self.teacher_adapter_name, self.teacher_adapter_config) + + model.set_adapter(self.teacher_adapter_name) + set_peft_model_state_dict(model, teacher_state, adapter_name=self.teacher_adapter_name) + + model.set_adapter(adapter_name) + + self.shadow_weights = {k: v.clone().zero_() for k, v in teacher_state.items()} + + self._initialized = True + logger.info(f"Initialized PEFT adapter EMA teacher with adapter name: {self.teacher_adapter_name}") + + @torch.no_grad() + def on_step_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): + if state.global_step % self.sync_steps != 0: + return + + if not self._initialized: + self._initialize_teacher_adapter() + + if self.shadow_weights is None: + return + + if self.accelerator is None and "accelerator" in kwargs: + self.accelerator = kwargs["accelerator"] + + student_state = self._get_student_state_dict() + + for key, student_param in student_state.items(): + if key in self.shadow_weights: + shadow = self.shadow_weights[key] + shadow.data = (1 - self.update_rate) * shadow.data + self.update_rate * student_param.data + + from peft import set_peft_model_state_dict + + if self.accelerator is not None: + unwrapped_model = self.accelerator.unwrap_model(self.model) + else: + unwrapped_model = self.model + + original_adapter = unwrapped_model.active_adapter + unwrapped_model.set_adapter(self.teacher_adapter_name) + set_peft_model_state_dict(unwrapped_model, self.shadow_weights, adapter_name=self.teacher_adapter_name) + unwrapped_model.set_adapter(original_adapter) + + def on_train_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): + if self.accelerator is None and "accelerator" in kwargs: + self.accelerator = kwargs["accelerator"] + self._initialize_teacher_adapter() diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/ssd/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/ssd/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d62e42ef96cc9cd6e4ff4de23ce39460420e34b7 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/ssd/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .ssd_config import SSDConfig +from .ssd_trainer import SSDTrainer + + +__all__ = ["SSDConfig", "SSDTrainer"] diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/ssd/ssd.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/ssd/ssd.py new file mode 100644 index 0000000000000000000000000000000000000000..0359c3aa6fc76168f667c3ff991ccd525e7d144e --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/ssd/ssd.py @@ -0,0 +1,170 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# /// script +# dependencies = [ +# "trl", +# "peft", +# "trackio", +# "kernels", +# ] +# /// + +""" +Simple Self-Distillation (SSD) training for code generation. + +Implements the method from "Embarrassingly Simple Self-Distillation Improves Code Generation" (Zhang et al., 2026): +sample completions from the model at a training-time temperature and truncation, then fine-tune on those raw, +unverified samples with standard cross-entropy loss. No reward model, verifier, teacher, or RL needed. + +The dataset only requires a ``prompt`` column containing coding problem prompts. + +Example: + +```bash +python trl/experimental/ssd/ssd.py \ + --model_name_or_path Qwen/Qwen3-4B-Instruct-2507 \ + --dataset_name microsoft/rStar-Coder \ + --dataset_config seed_sft \ + --prompt_column question \ + --output_dir outputs/ssd-qwen3-4b \ + --per_device_train_batch_size 1 \ + --gradient_accumulation_steps 32 \ + --learning_rate 5e-6 \ + --lr_scheduler_type cosine \ + --max_prompt_length 1024 \ + --max_completion_length 65536 \ + --temperature 1.6 \ + --top_k 20 \ + --top_p 0.8 \ + --num_train_epochs 1 \ + --bf16 \ + --report_to trackio +``` +""" + +from dataclasses import dataclass, field + +import torch +from datasets import DatasetDict, load_dataset, load_from_disk +from transformers import AutoModelForCausalLM, AutoTokenizer + +from trl import ( + ModelConfig, + ScriptArguments, + TrlParser, + get_kbit_device_map, + get_peft_config, + get_quantization_config, +) +from trl.experimental.ssd import SSDConfig, SSDTrainer + + +@dataclass +class SSDScriptArguments(ScriptArguments): + dataset_path: str | None = field( + default=None, + metadata={"help": "Optional local dataset path to load with `load_from_disk`. Overrides `dataset_name`."}, + ) + prompt_column: str = field( + default="prompt", + metadata={"help": "Column containing the problem prompts."}, + ) + + +if __name__ == "__main__": + parser = TrlParser((SSDScriptArguments, SSDConfig, ModelConfig)) + script_args, training_args, model_args = parser.parse_args_and_config() + + if model_args.model_name_or_path is None: + raise ValueError("`model_name_or_path` is required.") + + if model_args.dtype in ["auto", None]: + if training_args.bf16: + dtype = torch.bfloat16 + elif training_args.fp16: + dtype = torch.float16 + else: + dtype = "auto" + else: + dtype = getattr(torch, model_args.dtype) + model_kwargs = dict( + revision=model_args.model_revision, + trust_remote_code=model_args.trust_remote_code, + attn_implementation=model_args.attn_implementation, + dtype=dtype, + ) + quantization_config = get_quantization_config(model_args) + if quantization_config is not None: + model_kwargs["device_map"] = get_kbit_device_map() + model_kwargs["quantization_config"] = quantization_config + + training_args.model_init_kwargs = model_kwargs + + tokenizer = AutoTokenizer.from_pretrained( + model_args.model_name_or_path, + revision=model_args.model_revision, + trust_remote_code=model_args.trust_remote_code, + padding_side="left", + ) + if tokenizer.pad_token is None: + tokenizer.pad_token = tokenizer.eos_token + + # Load dataset + if script_args.dataset_path is not None: + dataset = load_from_disk(script_args.dataset_path) + else: + dataset = load_dataset( + script_args.dataset_name, + name=script_args.dataset_config, + streaming=script_args.dataset_streaming, + ) + + # Ensure the dataset has a `prompt` column + def _prepare_split(ds): + if script_args.prompt_column != "prompt" and script_args.prompt_column in ds.column_names: + ds = ds.rename_column(script_args.prompt_column, "prompt") + return ds.select_columns(["prompt"]) + + if isinstance(dataset, DatasetDict): + train_dataset = _prepare_split(dataset[script_args.dataset_train_split]) + eval_dataset = None + if script_args.dataset_test_split in dataset: + eval_dataset = _prepare_split(dataset[script_args.dataset_test_split]) + else: + train_dataset = _prepare_split(dataset) + eval_dataset = None + + model = AutoModelForCausalLM.from_pretrained(model_args.model_name_or_path, **model_kwargs) + model.config.use_cache = False if training_args.gradient_checkpointing else True + + trainer = SSDTrainer( + model=model, + args=training_args, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=tokenizer, + peft_config=get_peft_config(model_args), + ) + + trainer.train() + + trainer.save_model(training_args.output_dir) + if eval_dataset is not None: + metrics = trainer.evaluate() + trainer.log_metrics("eval", metrics) + trainer.save_metrics("eval", metrics) + + if training_args.push_to_hub: + trainer.push_to_hub(dataset_name=script_args.dataset_name or script_args.dataset_path) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/ssd/ssd_config.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/ssd/ssd_config.py new file mode 100644 index 0000000000000000000000000000000000000000..e86057eab8d962487ff2a5992acf8ad06ce11bb6 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/ssd/ssd_config.py @@ -0,0 +1,253 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field +from typing import Any + +from transformers import TrainingArguments + +from ...trainer.base_config import _BaseConfig + + +@dataclass +class SSDConfig(_BaseConfig): + r""" + Configuration class for [`SSDTrainer`]. + + Implements Simple Self-Distillation (SSD) from [*Embarrassingly Simple Self-Distillation Improves Code + Generation*](https://huggingface.co/papers/2604.01193). SSD samples completions from the model at a training-time + temperature and truncation configuration, then fine-tunes on those raw, unverified samples with standard + cross-entropy loss. + + The `temperature`, `top_k`, and `top_p` parameters control the training-time sampling configuration (T_train, + rho_train in the paper). The evaluation-time configuration (T_eval, rho_eval) is set independently at inference + time. + + Parameters: + > Parameters that control generation and rollout reuse + + model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments used when the `model` argument is passed as a string. + max_prompt_length (`int` or `None`, *optional*, defaults to `512`): + Maximum prompt length. Longer prompts are truncated from the left. + max_completion_length (`int` or `None`, *optional*, defaults to `256`): + Maximum generated completion length. + generation_batch_size (`int` or `None`, *optional*): + Global batch size used for generation. Mutually exclusive with `steps_per_generation`. + steps_per_generation (`int` or `None`, *optional*): + Number of optimizer steps that reuse one generated batch. Mutually exclusive with `generation_batch_size`. + + > Parameters that control sampling + + temperature (`float`, *optional*, defaults to `1.0`): + Sampling temperature (T_train in the paper). + top_k (`int`, *optional*, defaults to `0`): + Top-k sampling parameter. `0` disables top-k filtering. + top_p (`float`, *optional*, defaults to `1.0`): + Top-p (nucleus) sampling parameter. + min_p (`float` or `None`, *optional*): + Minimum token probability for sampling. + repetition_penalty (`float`, *optional*, defaults to `1.0`): + Repetition penalty used during generation. + generation_kwargs (`dict[str, Any]` or `None`, *optional*): + Extra generation kwargs passed to `GenerationConfig`. + + > Parameters that control vLLM generation + + use_vllm (`bool`, *optional*, defaults to `False`): + Whether to use vLLM for generation instead of the training model. + vllm_mode (`str`, *optional*, defaults to `"colocate"`): + vLLM mode: `"colocate"` (shared GPU) or `"server"` (separate vLLM server). + vllm_model_impl (`str`, *optional*, defaults to `"vllm"`): + Model implementation for vLLM: `"vllm"`, `"transformers"`, or `"auto"`. + vllm_server_base_url (`str` or `None`, *optional*): + Base URL for the vLLM server. 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 (server mode only). + vllm_server_port (`int`, *optional*, defaults to `8000`): + Port of the vLLM server (server mode only). + vllm_server_timeout (`float`, *optional*, defaults to `240.0`): + Timeout in seconds to wait for the vLLM server. + vllm_group_port (`int`, *optional*, defaults to `51216`): + Port for the weight update group (server mode only). + vllm_tensor_parallel_size (`int`, *optional*, defaults to `1`): + Tensor parallel size for colocated vLLM. + vllm_gpu_memory_utilization (`float`, *optional*, defaults to `0.3`): + GPU memory utilization ratio for colocated vLLM. + vllm_max_model_length (`int` or `None`, *optional*): + Model context length for vLLM. Inferred from model config if not set. + vllm_enable_sleep_mode (`bool`, *optional*, defaults to `False`): + Whether to enable sleep mode for colocated vLLM engine. + + > Parameters that control training behavior + + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the model during training. + filter_empty (`bool`, *optional*, defaults to `True`): + Whether to filter out empty or single-line stub completions from the generated data. + num_iterations (`int`, *optional*, defaults to `1`): + Number of optimization iterations per generated batch. + shuffle_dataset (`bool`, *optional*, defaults to `True`): + Whether to shuffle the training dataset. + ds3_gather_for_generation (`bool`, *optional*, defaults to `True`): + Whether to gather ZeRO-3 weights for generation. + cache_implementation (`str` or `None`, *optional*): + Cache implementation used by transformers generation. + chat_template_kwargs (`dict[str, Any]` or `None`, *optional*): + Extra kwargs forwarded to chat template application. + """ + + _VALID_DICT_FIELDS = TrainingArguments._VALID_DICT_FIELDS + ["model_init_kwargs"] + + model_init_kwargs: dict[str, Any] | None = field( + default=None, + metadata={"help": "Keyword arguments for model initialization when `model` is passed as a string."}, + ) + max_prompt_length: int | None = field( + default=512, + metadata={"help": "Maximum prompt length. Longer prompts are truncated from the left."}, + ) + max_completion_length: int | None = field( + default=256, + metadata={"help": "Maximum generated completion length."}, + ) + generation_batch_size: int | None = field( + default=None, + metadata={"help": "Global batch size used for generation. Mutually exclusive with `steps_per_generation`."}, + ) + steps_per_generation: int | None = field( + default=None, + metadata={"help": "Number of optimizer steps that reuse one generated batch."}, + ) + temperature: float = field( + default=1.0, + metadata={"help": "Sampling temperature (T_train in the paper)."}, + ) + top_k: int = field( + default=0, + metadata={"help": "Top-k sampling parameter. `0` disables top-k filtering."}, + ) + top_p: float = field( + default=1.0, + metadata={"help": "Top-p (nucleus) sampling parameter."}, + ) + min_p: float | None = field( + default=None, + metadata={"help": "Minimum token probability for sampling."}, + ) + repetition_penalty: float = field( + default=1.0, + metadata={"help": "Repetition penalty used during generation."}, + ) + generation_kwargs: dict[str, Any] | None = field( + default=None, + metadata={"help": "Extra generation kwargs passed to `GenerationConfig`."}, + ) + cache_implementation: str | None = field( + default=None, + metadata={"help": "Cache implementation used by transformers generation."}, + ) + chat_template_kwargs: dict[str, Any] | None = field( + default=None, + metadata={"help": "Extra kwargs forwarded to chat template application."}, + ) + use_vllm: bool = field( + default=False, + metadata={"help": "Whether to use vLLM for generation."}, + ) + vllm_mode: str = field( + default="colocate", + metadata={"help": "vLLM mode: 'colocate' (shared GPU) or 'server' (separate vLLM server)."}, + ) + vllm_model_impl: str = field( + default="vllm", + metadata={"help": "Model implementation for vLLM: 'vllm', 'transformers', or 'auto'."}, + ) + vllm_server_base_url: str | None = field( + default=None, + metadata={ + "help": "Base URL for the vLLM server. If provided, vllm_server_host and vllm_server_port are ignored." + }, + ) + vllm_server_host: str = field( + default="0.0.0.0", + metadata={"help": "Host of the vLLM server (server mode only)."}, + ) + vllm_server_port: int = field( + default=8000, + metadata={"help": "Port of the vLLM server (server mode only)."}, + ) + vllm_server_timeout: float = field( + default=240.0, + metadata={"help": "Timeout in seconds to wait for the vLLM server."}, + ) + vllm_group_port: int = field( + default=51216, + metadata={"help": "Port for the weight update group (server mode only)."}, + ) + vllm_tensor_parallel_size: int = field( + default=1, + metadata={"help": "Tensor parallel size for colocated vLLM."}, + ) + vllm_gpu_memory_utilization: float = field( + default=0.3, + metadata={"help": "GPU memory utilization ratio for colocated vLLM."}, + ) + vllm_max_model_length: int | None = field( + default=None, + metadata={"help": "Model context length for vLLM. Inferred from model config if not set."}, + ) + vllm_enable_sleep_mode: bool = field( + default=False, + metadata={"help": "Whether to enable sleep mode for colocated vLLM engine."}, + ) + disable_dropout: bool = field( + default=True, + metadata={"help": "Whether to disable dropout in the model during training."}, + ) + filter_empty: bool = field( + default=True, + metadata={"help": "Whether to filter out empty or single-line stub completions."}, + ) + num_iterations: int = field( + default=1, + metadata={"help": "Number of optimization iterations per generated batch."}, + ) + shuffle_dataset: bool = field( + default=True, + metadata={"help": "Whether to shuffle the training dataset."}, + ) + ds3_gather_for_generation: bool = field( + default=True, + metadata={"help": "Whether to gather ZeRO-3 weights for generation."}, + ) + + def __post_init__(self): + super().__post_init__() + + num_processes = self.world_size + if self.generation_batch_size is None and self.steps_per_generation is None: + self.steps_per_generation = self.gradient_accumulation_steps + self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation + elif self.generation_batch_size is not None and self.steps_per_generation is None: + global_batch_size = self.per_device_train_batch_size * num_processes + if self.generation_batch_size % global_batch_size != 0: + raise ValueError( + f"generation_batch_size ({self.generation_batch_size}) must be divisible by the global batch size ({global_batch_size})." + ) + self.steps_per_generation = self.generation_batch_size // global_batch_size + elif self.generation_batch_size is None and self.steps_per_generation is not None: + self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation + else: + raise ValueError("'generation_batch_size' and 'steps_per_generation' can not both be configured") diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/ssd/ssd_eval.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/ssd/ssd_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..cb3f6d24995cad889062c4b2bc3889b978a61a37 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/ssd/ssd_eval.py @@ -0,0 +1,260 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# /// script +# dependencies = [ +# "trl", +# "vllm", +# "huggingface_hub", +# "livecodebench @ git+https://github.com/LiveCodeBench/LiveCodeBench.git", +# ] +# /// + +""" +LiveCodeBench v6 evaluation script. + +Generates completions with vLLM at a configurable decoding setting and scores them with LiveCodeBench's official +``codegen_metrics`` (pass@k via sandboxed test execution). The default decoding configuration matches Table 3 of +*Embarrassingly Simple Self-Distillation Improves Code Generation* (Zhang et al., 2026), making this script suitable +for evaluating SSD-trained checkpoints alongside their base models. + +Example — evaluate the base Qwen3-4B-Instruct-2507 on the v6 delta (the new problems released in v6): + +```bash +python trl/experimental/ssd/ssd_eval.py \\ + --model_name_or_path Qwen/Qwen3-4B-Instruct-2507 \\ + --temperature 1.1 \\ + --top_k 20 \\ + --top_p 0.8 \\ + --n 1 \\ + --output_file outputs/qwen3_4b_base_lcb_v6.json +``` + +Evaluate an SSD-trained checkpoint with the same decoding configuration: + +```bash +python trl/experimental/ssd/ssd_eval.py \\ + --model_name_or_path outputs/ssd-qwen3-4b-instruct \\ + --temperature 1.1 \\ + --top_k 20 \\ + --top_p 0.8 \\ + --n 5 \\ + --output_file outputs/qwen3_4b_ssd_lcb_v6.json +``` +""" + +# ruff: noqa: T201 + +from __future__ import annotations + +import json +import re +from dataclasses import dataclass, field +from datetime import datetime + +from huggingface_hub import hf_hub_download +from lcb_runner.benchmarks.code_generation import CodeGenerationProblem +from lcb_runner.evaluation.compute_code_generation_metrics import codegen_metrics +from transformers import AutoTokenizer +from vllm import LLM, SamplingParams + +from trl import TrlParser + + +# LiveCodeBench stores new problems added in each release version in a separate JSONL file: +# ``test.jsonl`` = v1, ``test2.jsonl`` = v2, …, ``test6.jsonl`` = v6 (the delta added in release v6). +# The paper's "LCB v6" refers to exactly this delta. +LCB_REPO = "livecodebench/code_generation_lite" +LCB_V6_FILE = "test6.jsonl" + + +SYSTEM_MESSAGE = ( + "You are an expert Python programmer. You will be given a question (problem specification) and will " + "generate a correct Python program that matches the specification and passes all tests." +) +FORMATTING_WITHOUT_STARTER = ( + "Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on " + "the sample inputs). Enclose your code within delimiters as follows. Ensure that when the python " + "program runs, it reads the inputs, runs the algorithm and writes output to STDOUT." +) +FORMATTING_WITH_STARTER = ( + "You will use the following starter code to write the solution to the problem and enclose your code " + "within delimiters." +) + +CODE_FENCE_RE = re.compile(r"```(?:python)?\s*\n(.*?)```", re.DOTALL) + + +@dataclass +class SSDEvalArguments: + model_name_or_path: str = field(metadata={"help": "Model path or Hub repo id to evaluate."}) + output_file: str = field(metadata={"help": "Path to write generations + metrics JSON."}) + temperature: float = field(default=1.1, metadata={"help": "Evaluation-time sampling temperature (T_eval)."}) + top_k: int = field(default=20, metadata={"help": "Evaluation-time top-k truncation."}) + top_p: float = field(default=0.8, metadata={"help": "Evaluation-time top-p (nucleus) truncation."}) + n: int = field(default=1, metadata={"help": "Number of samples per problem (pass@1 uses 1, pass@5 uses 5)."}) + max_tokens: int = field(default=32768, metadata={"help": "Maximum tokens to generate per completion."}) + max_model_len: int = field(default=65536, metadata={"help": "vLLM max model length."}) + gpu_memory_utilization: float = field(default=0.9, metadata={"help": "vLLM GPU memory ratio."}) + tensor_parallel_size: int = field(default=1, metadata={"help": "vLLM tensor parallel size."}) + dtype: str = field(default="bfloat16", metadata={"help": "vLLM model dtype."}) + start_date: str | None = field( + default=None, metadata={"help": "Keep only problems with contest_date >= YYYY-MM-DD."} + ) + end_date: str | None = field( + default=None, metadata={"help": "Keep only problems with contest_date <= YYYY-MM-DD."} + ) + max_problems: int | None = field( + default=None, metadata={"help": "Evaluate at most N problems (useful for quick smoke tests)."} + ) + difficulty: str | None = field( + default=None, metadata={"help": "Filter to a single difficulty: 'easy', 'medium', or 'hard'."} + ) + timeout: int = field(default=6, metadata={"help": "Per-test execution timeout in seconds."}) + num_process_evaluate: int = field(default=8, metadata={"help": "Parallel processes for sandboxed evaluation."}) + seed: int = field(default=0, metadata={"help": "vLLM sampling seed."}) + + +def _build_prompt(tokenizer, question_content: str, starter_code: str) -> str: + """Build the LCB prompt and apply the model's chat template.""" + body = f"### Question:\n{question_content}\n\n" + if starter_code: + body += f"### Format: {FORMATTING_WITH_STARTER}\n" + body += f"```python\n{starter_code}\n```\n\n" + else: + body += f"### Format: {FORMATTING_WITHOUT_STARTER}\n" + body += "```python\n# YOUR CODE HERE\n```\n\n" + body += "### Answer: (use the provided format with backticks)\n\n" + messages = [ + {"role": "system", "content": SYSTEM_MESSAGE}, + {"role": "user", "content": body}, + ] + return tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) + + +def _extract_code(text: str) -> str: + """Extract the first Python code fence from a model completion.""" + match = CODE_FENCE_RE.search(text) + if match: + return match.group(1).strip() + # Fallback: if the model returned bare code without a fence, return the whole thing. + return text.strip() + + +def _load_lcb_v6_problems(args: SSDEvalArguments): + """Load LiveCodeBench v6 problems, filter by date/difficulty/count, and return as a list.""" + jsonl_path = hf_hub_download(repo_id=LCB_REPO, filename=LCB_V6_FILE, repo_type="dataset") + with open(jsonl_path) as f: + problems = [CodeGenerationProblem(**json.loads(line)) for line in f] + + if args.start_date is not None: + start = datetime.fromisoformat(args.start_date) + problems = [p for p in problems if p.contest_date >= start] + if args.end_date is not None: + end = datetime.fromisoformat(args.end_date) + problems = [p for p in problems if p.contest_date <= end] + if args.difficulty is not None: + problems = [p for p in problems if p.difficulty.value == args.difficulty] + if args.max_problems is not None: + problems = problems[: args.max_problems] + + return problems + + +def main(): + parser = TrlParser(SSDEvalArguments) + (args,) = parser.parse_args_and_config() + + problems = _load_lcb_v6_problems(args) + print(f"Evaluating {len(problems)} problems from LiveCodeBench v6") + + tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path) + prompts = [_build_prompt(tokenizer, p.question_content, p.starter_code) for p in problems] + + llm = LLM( + model=args.model_name_or_path, + dtype=args.dtype, + tensor_parallel_size=args.tensor_parallel_size, + max_model_len=args.max_model_len, + gpu_memory_utilization=args.gpu_memory_utilization, + ) + sampling_params = SamplingParams( + n=args.n, + temperature=args.temperature, + top_k=args.top_k, + top_p=args.top_p, + max_tokens=args.max_tokens, + seed=args.seed, + ) + outputs = llm.generate(prompts, sampling_params) + + generations_list = [] + for out in outputs: + code_list = [_extract_code(o.text) for o in out.outputs] + generations_list.append(code_list) + + samples_list = [p.get_evaluation_sample() for p in problems] + k_list = [1] if args.n == 1 else [1, args.n] + metrics, results, _metadata = codegen_metrics( + samples_list, + generations_list, + k_list=k_list, + num_process_evaluate=args.num_process_evaluate, + timeout=args.timeout, + ) + + # Break down pass@1 by difficulty for easier comparison with the paper's tables. `codegen_metrics` + # returns a nested `detail` dict keyed by problem index. + per_problem_pass1 = metrics["detail"]["pass@1"] + per_difficulty = {} + for difficulty in ("easy", "medium", "hard"): + idxs = [i for i, p in enumerate(problems) if p.difficulty.value == difficulty] + if not idxs: + continue + per_difficulty[difficulty] = { + "num_problems": len(idxs), + "pass@1": sum(per_problem_pass1[i] for i in idxs) / len(idxs), + } + + summary = { + "model": args.model_name_or_path, + "num_problems": len(problems), + "temperature": args.temperature, + "top_k": args.top_k, + "top_p": args.top_p, + "n": args.n, + "metrics": {k: float(v) for k, v in metrics.items() if k != "detail"}, + "per_difficulty": per_difficulty, + } + + detail = [ + { + "question_id": p.question_id, + "difficulty": p.difficulty.value, + "code_list": code_list, + "pass@1": per_problem_pass1[i], + } + for i, (p, code_list) in enumerate(zip(problems, generations_list, strict=False)) + ] + + with open(args.output_file, "w") as f: + json.dump({"summary": summary, "detail": detail}, f, indent=2) + + print("\n=== Summary ===") + print(json.dumps(summary, indent=2)) + print(f"\nFull results written to {args.output_file}") + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/ssd/ssd_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/ssd/ssd_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..2b7eb8561e930a1a0876e4143763a0ae976a2bb2 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/ssd/ssd_trainer.py @@ -0,0 +1,528 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Trainer for Simple Self-Distillation (SSD). + +Implements the method from *Embarrassingly Simple Self-Distillation Improves Code Generation* (Zhang et al., 2026): +sample completions from the frozen model at a training-time temperature and truncation configuration, then fine-tune on +those raw, unverified samples with standard cross-entropy loss. No reward model, verifier, teacher model, or +reinforcement learning is needed. +""" + +from __future__ import annotations + +import inspect +import math +import textwrap +from collections import defaultdict +from functools import partial +from typing import Any + +import datasets +import torch +from accelerate.logging import get_logger +from accelerate.utils import is_peft_model +from datasets import Dataset, IterableDataset +from torch import nn +from torch.utils.data import DataLoader, Sampler +from transformers import ( + AutoProcessor, + GenerationConfig, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, +) +from transformers.trainer_utils import seed_worker +from transformers.utils import is_datasets_available, is_peft_available + +from ...data_utils import maybe_apply_chat_template +from ...models import unwrap_model_for_generation +from ...trainer.base_trainer import _BaseTrainer +from ...trainer.utils import ( + RepeatSampler, + create_model_from_path, + disable_dropout_in_model, + get_config_model_id, + identity, + pad, + selective_log_softmax, + split_tensor_dict, +) +from ..utils import prepare_peft_model +from .ssd_config import SSDConfig + + +if is_peft_available(): + from peft import PeftConfig + + +logger = get_logger(__name__) + + +class SSDTrainer(_BaseTrainer): + """Trainer for SSD-style on-policy self-distillation with cross-entropy loss. + + SSD generates completions from the model at a specified training-time temperature and truncation configuration, + then fine-tunes on those raw, unverified samples using standard cross-entropy loss. The dataset only requires a + ``prompt`` column. + """ + + _tag_names = ["trl", "ssd"] + _name = "SSD" + config_cls = SSDConfig + # docstyle-ignore + _paper = { + "title": "Embarrassingly Simple Self-Distillation Improves Code Generation", + "id": "2604.01193", + "citation": textwrap.dedent("""\ + @article{zhang2026ssd, + title = {{Embarrassingly Simple Self-Distillation Improves Code Generation}}, + author = {Ruixiang Zhang and Richard He Bai and Huangjie Zheng and Navdeep Jaitly and Ronan Collobert and Yizhe Zhang}, + year = 2026, + eprint = {arXiv:2604.01193} + }"""), + } + + def __init__( + self, + model: str | PreTrainedModel | nn.Module, + args: SSDConfig | None = None, + train_dataset: Dataset | IterableDataset | None = None, + eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None, + processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None), + peft_config: PeftConfig | None = None, + ): + if train_dataset is None: + raise ValueError("`train_dataset` is required") + if isinstance(train_dataset, IterableDataset): + raise NotImplementedError("Iterable datasets are not yet supported in SSDTrainer.") + if isinstance(eval_dataset, IterableDataset) or ( + isinstance(eval_dataset, dict) and any(isinstance(ds, IterableDataset) for ds in eval_dataset.values()) + ): + raise NotImplementedError("Iterable eval datasets are not yet supported in SSDTrainer.") + if args is None: + model_name = model if isinstance(model, str) else get_config_model_id(model.config) + model_name = model_name.split("/")[-1] + args = SSDConfig(f"{model_name}-SSD") + if isinstance(model, str): + model_init_kwargs = args.model_init_kwargs or {} + if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + model_init_kwargs["device_map"] = None + model = create_model_from_path(model, **model_init_kwargs) + elif args.model_init_kwargs is not None: + logger.warning( + "You passed `model_init_kwargs` to `SSDConfig`, but `model` is already instantiated. " + "The `model_init_kwargs` will be ignored." + ) + + self.model_kwarg_keys = ( + inspect.signature(model.forward).parameters.keys() + if not hasattr(model, "get_base_model") + else inspect.signature(model.get_base_model().forward).parameters.keys() + ) + + # PEFT + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + if is_peft_model(model): + raise ValueError( + "You passed a `PeftModel` instance together with a `peft_config` to SSDTrainer. Pass either a base " + "model with `peft_config`, or a pre-wrapped PEFT model." + ) + if peft_config is not None or (is_peft_available() and getattr(model, "peft_config", None) is not None): + model = prepare_peft_model(model, peft_config, args) + + if processing_class is None: + processing_class = AutoProcessor.from_pretrained( + get_config_model_id(model.config), truncation_side="left", padding_side="left" + ) + + if isinstance(processing_class, ProcessorMixin): + self._tokenizer = processing_class.tokenizer + elif isinstance(processing_class, PreTrainedTokenizerBase): + self._tokenizer = processing_class + else: + raise TypeError("The `processing_class` must be either a `PreTrainedTokenizerBase` or a `ProcessorMixin`") + + if self._tokenizer.pad_token is None: + self._tokenizer.pad_token = self._tokenizer.eos_token + + self.max_prompt_length = args.max_prompt_length + self.max_completion_length = args.max_completion_length + # SSD always samples a single completion per prompt (N=1 in the paper). + self.num_generations = 1 + self.num_iterations = args.num_iterations + self.temperature = args.temperature + self.shuffle_dataset = args.shuffle_dataset + self.filter_empty = args.filter_empty + self.use_vllm = args.use_vllm + self.chat_template_kwargs = args.chat_template_kwargs or {} + self._step = 0 + self._buffered_inputs = None + self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)} + + generation_kwargs = { + "max_new_tokens": self.max_completion_length, + "do_sample": True, + "pad_token_id": self._tokenizer.pad_token_id, + "bos_token_id": self._tokenizer.bos_token_id, + "eos_token_id": self._tokenizer.eos_token_id, + "temperature": args.temperature, + "top_p": args.top_p, + "top_k": args.top_k, + "min_p": args.min_p, + "repetition_penalty": args.repetition_penalty, + "cache_implementation": args.cache_implementation, + } + if args.generation_kwargs is not None: + generation_kwargs.update(args.generation_kwargs) + self.generation_config = GenerationConfig(**generation_kwargs, disable_compile=True) + + if hasattr(model, "warnings_issued"): + model.warnings_issued["estimate_tokens"] = True + + super().__init__( + model=model, + args=args, + data_collator=identity, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + callbacks=callbacks, + optimizers=optimizers, + compute_loss_func="non-None value to disable scaling", + ) + + if args.disable_dropout: + disable_dropout_in_model(self.model) + + self.model.add_model_tags(self._tag_names) + + self.model_accepts_loss_kwargs = False + + if self.use_vllm: + from ...generation.vllm_generation import VLLMGeneration + + self.vllm_generation = VLLMGeneration( + model=self.model, + accelerator=self.accelerator, + processing_class=self.processing_class, + mode=args.vllm_mode, + server_base_url=args.vllm_server_base_url, + server_host=args.vllm_server_host, + server_port=args.vllm_server_port, + group_port=args.vllm_group_port, + server_timeout=args.vllm_server_timeout, + tensor_parallel_size=args.vllm_tensor_parallel_size, + gpu_memory_utilization=args.vllm_gpu_memory_utilization, + max_model_length=args.vllm_max_model_length, + max_num_seqs=args.per_device_train_batch_size + * args.vllm_tensor_parallel_size + * args.steps_per_generation, + enable_sleep_mode=args.vllm_enable_sleep_mode, + model_impl=args.vllm_model_impl, + repetition_penalty=args.repetition_penalty, + temperature=self.temperature, + top_p=args.top_p, + top_k=args.top_k, + min_p=args.min_p, + max_completion_length=self.max_completion_length, + logprobs=None, + generation_kwargs=args.generation_kwargs, + ) + self._last_loaded_step = -1 + + def _set_signature_columns_if_needed(self): + if self._signature_columns is None: + self._signature_columns = ["prompt"] + + def _apply_prompt_template(self, prompts): + return [ + maybe_apply_chat_template({"prompt": prompt}, self.processing_class, **self.chat_template_kwargs)["prompt"] + for prompt in prompts + ] + + # ------------------------------------------------------------------ + # DataLoader + # ------------------------------------------------------------------ + + def get_train_dataloader(self): + if self.train_dataset is None: + raise ValueError("Trainer: training requires a train_dataset.") + + train_dataset = self.train_dataset + data_collator = self.data_collator + if is_datasets_available() and isinstance(train_dataset, datasets.Dataset): + train_dataset = self._remove_unused_columns(train_dataset, description="training") + else: + data_collator = self._get_collator_with_removed_columns(data_collator, description="training") + + dataloader_params = { + "batch_size": self._train_batch_size * self.args.steps_per_generation, + "collate_fn": data_collator, + "num_workers": self.args.dataloader_num_workers, + "pin_memory": self.args.dataloader_pin_memory, + "persistent_workers": self.args.dataloader_persistent_workers, + } + if not isinstance(train_dataset, torch.utils.data.IterableDataset): + dataloader_params["sampler"] = self._get_train_sampler() + dataloader_params["drop_last"] = self.args.dataloader_drop_last + dataloader_params["worker_init_fn"] = partial( + seed_worker, num_workers=self.args.dataloader_num_workers, rank=self.args.process_index + ) + dataloader_params["prefetch_factor"] = self.args.dataloader_prefetch_factor + return self.accelerator.prepare(DataLoader(train_dataset, **dataloader_params)) + + def _get_train_sampler(self, dataset=None) -> Sampler: + if dataset is None: + dataset = self.train_dataset + return RepeatSampler( + data_source=dataset, + mini_repeat_count=self.num_generations, + batch_size=self.args.generation_batch_size // self.num_generations, + repeat_count=self.num_iterations * self.args.steps_per_generation, + shuffle=self.shuffle_dataset, + seed=self.args.seed, + ) + + def _get_eval_sampler(self, eval_dataset) -> Sampler: + return RepeatSampler( + data_source=eval_dataset, + mini_repeat_count=self.num_generations, + seed=self.args.seed, + ) + + # ------------------------------------------------------------------ + # Training step management + # ------------------------------------------------------------------ + + def training_step(self, model, inputs, num_items_in_batch): + output = super().training_step(model, inputs, num_items_in_batch) + self._step += 1 + return output + + def _prepare_inputs(self, generation_batch): + mode = "train" if self.model.training else "eval" + if mode == "train": + generate_every = self.args.steps_per_generation * self.num_iterations + if self._step % generate_every == 0 or self._buffered_inputs is None: + generation_batch = self._build_buffered_batch(generation_batch) + self._buffered_inputs = split_tensor_dict(generation_batch, self.args.steps_per_generation) + return self._buffered_inputs[self._step % self.args.steps_per_generation] + return self._build_buffered_batch(generation_batch) + + # ------------------------------------------------------------------ + # Generation + # ------------------------------------------------------------------ + + def _generate_completion_ids(self, prompts: list[Any]) -> tuple[torch.Tensor, torch.Tensor]: + """Generate completions from the model at the configured training-time temperature and truncation.""" + if self.use_vllm: + return self._generate_completion_ids_vllm(prompts) + return self._generate_completion_ids_transformers(prompts) + + def _generate_completion_ids_vllm(self, prompts: list[Any]) -> tuple[torch.Tensor, torch.Tensor]: + """Generate completions using vLLM.""" + if self.state.global_step != self._last_loaded_step: + self.vllm_generation.sync_weights() + self._last_loaded_step = self.state.global_step + + prompts_text = self._apply_prompt_template(prompts) + tokenized = self.processing_class( + text=prompts_text, + return_tensors=None, + padding=False, + max_length=self.max_prompt_length, + truncation=True, + add_special_tokens=False, + ) + prompt_ids = tokenized["input_ids"] + + _, completion_ids_list, _, _ = self.vllm_generation.generate( + prompts=prompt_ids, + images=None, + num_generations=self.num_generations, + ) + + device = self.accelerator.device + completion_ids = [torch.tensor(ids, device=device) for ids in completion_ids_list] + completion_mask = [torch.ones(len(ids), dtype=torch.long, device=device) for ids in completion_ids_list] + return ( + pad(completion_ids, padding_value=self._tokenizer.pad_token_id, padding_side="right"), + pad(completion_mask, padding_value=0, padding_side="right"), + ) + + def _generate_completion_ids_transformers(self, prompts: list[Any]) -> tuple[torch.Tensor, torch.Tensor]: + """Generate completions using the training model with transformers.""" + generate_inputs = self.processing_class( + text=self._apply_prompt_template(prompts), + return_tensors="pt", + padding=True, + padding_side="left", + max_length=self.max_prompt_length, + truncation=True, + add_special_tokens=False, + ) + # Use the base Trainer tensor preparation instead of re-entering the buffered outer training hook. + generate_inputs = _BaseTrainer._prepare_inputs(self, generate_inputs) + + with ( + unwrap_model_for_generation( + self.model_wrapped, + self.accelerator, + gather_deepspeed3_params=self.args.ds3_gather_for_generation, + ) as unwrapped_model, + torch.no_grad(), + ): + prompt_completion_ids = unwrapped_model.generate( + **generate_inputs, generation_config=self.generation_config + ) + + prompt_length = generate_inputs["input_ids"].size(1) + completion_ids = prompt_completion_ids[:, prompt_length:] + is_eos = completion_ids == self._tokenizer.eos_token_id + eos_idx = torch.full((is_eos.size(0),), is_eos.size(1), dtype=torch.long, device=completion_ids.device) + eos_idx[is_eos.any(dim=1)] = is_eos.int().argmax(dim=1)[is_eos.any(dim=1)] + seq_idx = torch.arange(is_eos.size(1), device=completion_ids.device).expand(is_eos.size(0), -1) + completion_mask = (seq_idx <= eos_idx.unsqueeze(1)).long() + + completion_ids_list = [c[m].tolist() for c, m in zip(completion_ids, completion_mask.bool(), strict=True)] + completion_ids = [torch.tensor(ids, device=self.accelerator.device) for ids in completion_ids_list] + completion_mask = [torch.ones_like(ids, dtype=torch.long) for ids in completion_ids] + return ( + pad(completion_ids, padding_value=self._tokenizer.pad_token_id, padding_side="right"), + pad(completion_mask, padding_value=0, padding_side="right"), + ) + + # ------------------------------------------------------------------ + # Batch construction + # ------------------------------------------------------------------ + + def _build_buffered_batch(self, inputs: list[dict[str, Any]]) -> dict[str, torch.Tensor | Any]: + """Generate completions and build the training batch.""" + prompts = [example["prompt"] for example in inputs] + completion_ids, completion_mask = self._generate_completion_ids(prompts) + + # Optionally filter empty or single-line stub completions (the paper applies minimal syntactic filtering) + if self.filter_empty: + completions_text = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True) + keep = torch.ones(len(completions_text), dtype=torch.bool, device=completion_ids.device) + for i, text in enumerate(completions_text): + stripped = text.strip() + if len(stripped) == 0 or stripped.count("\n") == 0 and len(stripped) < 10: + keep[i] = False + completion_mask = completion_mask * keep.unsqueeze(1).long() + + # Tokenize prompts for the training forward pass + prompt_text = self._apply_prompt_template(prompts) + prompt_inputs = self.processing_class( + text=prompt_text, + return_tensors="pt", + padding=True, + padding_side="left", + max_length=self.max_prompt_length, + truncation=True, + add_special_tokens=False, + ) + prompt_inputs = _BaseTrainer._prepare_inputs(self, prompt_inputs) + prompt_ids = prompt_inputs["input_ids"] + prompt_mask = prompt_inputs["attention_mask"] + + # Log completion statistics + mode = "train" if self.model.training else "eval" + completion_lengths = completion_mask.sum(dim=1).float() + agg_lengths = self.accelerator.gather(completion_lengths) + self._metrics[mode]["completions/mean_length"].append(agg_lengths.mean().item()) + self._metrics[mode]["completions/min_length"].append(agg_lengths.min().item()) + self._metrics[mode]["completions/max_length"].append(agg_lengths.max().item()) + active_ratio = (completion_mask.sum(dim=1) > 0).float().mean() + self._metrics[mode]["ssd/active_sample_ratio"].append(self.accelerator.gather(active_ratio).mean().item()) + + return { + "prompt_ids": prompt_ids, + "prompt_mask": prompt_mask, + "completion_ids": completion_ids, + "completion_mask": completion_mask, + } + + # ------------------------------------------------------------------ + # Loss computation + # ------------------------------------------------------------------ + + def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): + if return_outputs: + raise ValueError("The SSDTrainer does not support returning outputs") + + prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"] + completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"] + input_ids = torch.cat([prompt_ids, completion_ids], dim=1) + attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) + logits_to_keep = completion_ids.size(1) + + # Forward pass + model_inputs = {"input_ids": input_ids, "attention_mask": attention_mask, "use_cache": False} + if "logits_to_keep" in self.model_kwarg_keys: + model_inputs["logits_to_keep"] = logits_to_keep + 1 + logits = model(**model_inputs).logits + logits = logits[:, :-1, :] + logits = logits[:, -logits_to_keep:, :] + + # Standard cross-entropy loss: -log p(y_t | x, y None: + mode = "train" if self.model.training else "eval" + metrics = {} + for key, val in self._metrics[mode].items(): + valid = [v for v in val if not math.isnan(v)] + metrics[key] = sum(valid) / len(valid) if valid else None + + # When called in evaluation, the keys in `logs` start with "eval_". We need to add the prefix "eval_" to the + # keys in `metrics` to match the format. + if mode == "eval": + metrics = {f"eval_{key}": val for key, val in metrics.items()} + + logs.update(metrics) + super().log(logs, start_time) + self._metrics[mode].clear() diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/tpo/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/tpo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e07ec04eb1b9f4d8a0cfeef4b64460f3c991c1fc --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/tpo/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .tpo_config import TPOConfig +from .tpo_trainer import TPOTrainer + + +__all__ = ["TPOConfig", "TPOTrainer"] diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/tpo/tpo.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/tpo/tpo.py new file mode 100644 index 0000000000000000000000000000000000000000..e755ecf1a08150f99ee54373db4331f343b45ba8 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/tpo/tpo.py @@ -0,0 +1,215 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# /// script +# dependencies = [ +# "trl[peft]", +# "trackio", +# "kernels", +# ] +# /// + +""" +Triple Preference Optimization (TPO) training. + +TPO requires a *triple-preference* dataset where each example contains a `chosen`, a `rejected` and a `reference` +(gold) completion for the same prompt. Two dataset paths are supported out of the box: + +- Use the published + [`tpo-alignment/triple-preference-ultrafeedback-40K`](https://huggingface.co/datasets/tpo-alignment/triple-preference-ultrafeedback-40K) + dataset directly. It already has the `prompt` / `reference` / `chosen` / `rejected` schema. +- Pass `--dataset_name openbmb/UltraFeedback` and the script automatically builds the triple-preference dataset as + described in the TPO paper (Saeidi et al., 2025): the response with the highest `overall_score` becomes `reference`, + the second-highest becomes `chosen`, and the lowest becomes `rejected`. + +In both cases, if the dataset is in standard (plain-string) format it is auto-wrapped into the conversational format so +that the model's chat template is applied — this matches how Instruct models like `Qwen/Qwen3-0.6B` are trained. + +Usage: + +Full training: + +```bash +python trl/experimental/tpo/tpo.py \ + --dataset_name tpo-alignment/triple-preference-ultrafeedback-40K \ + --model_name_or_path Qwen/Qwen3-0.6B \ + --per_device_train_batch_size 2 \ + --max_steps 1000 \ + --learning_rate 5e-7 \ + --gradient_accumulation_steps 8 \ + --beta 0.01 \ + --tpo_alpha 1.0 \ + --output_dir Qwen3-0.6B-TPO \ + --no_remove_unused_columns +``` + +TPO-L (length-normalized variant with target reward margin): + +```bash +python trl/experimental/tpo/tpo.py \ + --dataset_name tpo-alignment/triple-preference-ultrafeedback-40K \ + --model_name_or_path Qwen/Qwen3-0.6B \ + --per_device_train_batch_size 2 \ + --max_steps 1000 \ + --learning_rate 5e-7 \ + --gradient_accumulation_steps 8 \ + --beta 0.01 \ + --tpo_alpha 1.0 \ + --loss_type tpo-l \ + --tpo_l_gamma 0.5 \ + --output_dir Qwen3-0.6B-TPO-L \ + --no_remove_unused_columns +``` + +LoRA: + +```bash +python trl/experimental/tpo/tpo.py \ + --dataset_name tpo-alignment/triple-preference-ultrafeedback-40K \ + --model_name_or_path Qwen/Qwen3-0.6B \ + --per_device_train_batch_size 2 \ + --max_steps 1000 \ + --learning_rate 5e-6 \ + --gradient_accumulation_steps 8 \ + --output_dir Qwen3-0.6B-TPO-LoRA \ + --no_remove_unused_columns \ + --use_peft \ + --lora_r 32 \ + --lora_alpha 16 +``` +""" + +import torch +from datasets import load_dataset +from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser + +from trl import ModelConfig, ScriptArguments, get_kbit_device_map, get_peft_config, get_quantization_config +from trl.experimental.tpo import TPOConfig, TPOTrainer + + +def build_triple_preference_from_ultrafeedback(example): + """ + Build a TPO triple-preference example from a raw UltraFeedback row. + + Following the TPO paper (Saeidi et al., 2025), completions are sorted by `overall_score` and we pick: + - the highest-scored response as the gold `reference`, + - the second-highest as `chosen`, + - the lowest as `rejected`. + + Emits the *conversational* format so that [`TPOTrainer`] applies the model's chat template automatically (see + `trl.data_utils.is_conversational`). Completions with a missing `overall_score` or `response` are filtered out; if + fewer than 3 valid completions remain, the returned example contains `None` values and should be filtered out + downstream. + """ + scored = [c for c in example["completions"] if c.get("overall_score") is not None and c.get("response")] + if len(scored) < 3: + return {"prompt": None, "reference": None, "chosen": None, "rejected": None} + scored.sort(key=lambda c: c["overall_score"], reverse=True) + return { + "prompt": [{"role": "user", "content": example["instruction"]}], + "reference": [{"role": "assistant", "content": scored[0]["response"]}], + "chosen": [{"role": "assistant", "content": scored[1]["response"]}], + "rejected": [{"role": "assistant", "content": scored[-1]["response"]}], + } + + +def to_conversational(example): + """ + Wrap a standard-format triple-preference example (plain strings) in the *conversational* format, so that + [`TPOTrainer`] applies the model's chat template automatically. This is the format expected by Instruct models; for + non-Instruct base models the standard format can be used directly. + """ + return { + "prompt": [{"role": "user", "content": example["prompt"]}], + "reference": [{"role": "assistant", "content": example["reference"]}], + "chosen": [{"role": "assistant", "content": example["chosen"]}], + "rejected": [{"role": "assistant", "content": example["rejected"]}], + } + + +if __name__ == "__main__": + parser = HfArgumentParser((ScriptArguments, TPOConfig, ModelConfig)) + script_args, training_args, model_args = parser.parse_args_into_dataclasses() + + ################ + # Model & Tokenizer + ################ + dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype) + model_kwargs = dict( + revision=model_args.model_revision, + attn_implementation=model_args.attn_implementation, + dtype=dtype, + ) + quantization_config = get_quantization_config(model_args) + if quantization_config is not None: + model_kwargs["device_map"] = get_kbit_device_map() + model_kwargs["quantization_config"] = quantization_config + + model = AutoModelForCausalLM.from_pretrained( + model_args.model_name_or_path, trust_remote_code=model_args.trust_remote_code, **model_kwargs + ) + tokenizer = AutoTokenizer.from_pretrained( + model_args.model_name_or_path, trust_remote_code=model_args.trust_remote_code + ) + if tokenizer.pad_token is None: + tokenizer.pad_token = tokenizer.eos_token + + ################ + # Dataset + ################ + dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config) + + # Auto-build the triple-preference schema from raw UltraFeedback. + first_example = next(iter(dataset[script_args.dataset_train_split])) + if "completions" in first_example and "instruction" in first_example: + dataset = dataset.map( + build_triple_preference_from_ultrafeedback, + remove_columns=list(first_example.keys()), + ) + dataset = dataset.filter(lambda ex: ex["reference"] is not None) + first_example = next(iter(dataset[script_args.dataset_train_split])) + + # Auto-wrap standard-format triple-preference data (plain strings) into conversational messages so the + # model's chat template gets applied. This matches how Instruct models are trained and is what the TPO + # paper's data preparation produces. + if {"prompt", "chosen", "rejected", "reference"}.issubset(first_example) and isinstance( + first_example["prompt"], str + ): + dataset = dataset.map(to_conversational) + + ################ + # Training + ################ + trainer = TPOTrainer( + model, + args=training_args, + train_dataset=dataset[script_args.dataset_train_split], + eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None, + processing_class=tokenizer, + peft_config=get_peft_config(model_args), + ) + + # train and save the model + trainer.train() + + # Run a final evaluation pass and persist the metrics + if training_args.eval_strategy != "no": + metrics = trainer.evaluate() + trainer.log_metrics("eval", metrics) + trainer.save_metrics("eval", metrics) + + # Save and push to hub + trainer.save_model(training_args.output_dir) + if training_args.push_to_hub: + trainer.push_to_hub(dataset_name=script_args.dataset_name) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/tpo/tpo_config.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/tpo/tpo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..f2b4c4a30fa5a61bdcb9afab1c328697e876bdfe --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/tpo/tpo_config.py @@ -0,0 +1,163 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field +from typing import Any + +from ...trainer.base_config import _BaseConfig + + +@dataclass +class TPOConfig(_BaseConfig): + # docstyle-ignore + r""" + Configuration class for the [`experimental.tpo.TPOTrainer`]. + + This class includes only the parameters that are specific to TPO 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 + + model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments for [`~transformers.AutoModelForCausalLM.from_pretrained`], used when the `model` + argument of the [`experimental.tpo.TPOTrainer`] is provided as a string. + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the model. + + > Parameters that control the data preprocessing + + dataset_num_proc (`int`, *optional*): + Number of processes to use for processing the dataset. + max_length (`int` or `None`, *optional*, defaults to `1024`): + Maximum length of the tokenized sequence. Sequences longer than `max_length` are truncated from the left or + right depending on the `truncation_mode`. If `None`, no truncation is applied. + truncation_mode (`str`, *optional*, defaults to `"keep_start"`): + Truncation mode to use when the sequence exceeds `max_length`. Possible values are `"keep_start"` and + `"keep_end"`. + pad_to_multiple_of (`int`, *optional*): + If set, the sequences will be padded to a multiple of this value. + + > Parameters that control the training + + loss_type (`str`, *optional*, defaults to `"sigmoid"`): + Type of loss to use. Possible values are: + + - `"sigmoid"`: sigmoid loss from the original [TPO](https://huggingface.co/papers/2405.16681) paper. + - `"hinge"`: hinge loss on the normalized likelihood from the + [SLiC](https://huggingface.co/papers/2305.10425) paper. + - `"ipo"`: IPO loss from the [IPO](https://huggingface.co/papers/2310.12036) paper. + - `"tpo-l"`: length-normalized TPO variant from the + [TPO](https://huggingface.co/papers/2405.16681) paper, which adds a target reward margin + `tpo_l_gamma` to the Bradley-Terry objective. + + beta (`float`, *optional*, defaults to `0.01`): + Parameter controlling the temperature of the TPO loss. For the IPO loss (`loss_type="ipo"`), β is the + regularization parameter denoted by τ in the [paper](https://huggingface.co/papers/2310.12036). + label_smoothing (`float`, *optional*, defaults to `0.0`): + Label smoothing factor. + tpo_alpha (`float`, *optional*, defaults to `1.0`): + Weight of the supervised negative log-likelihood term computed on the gold (`reference`) response in TPO + training. Setting `tpo_alpha=0.0` disables the NLL term and skips the corresponding forward pass. + tpo_l_gamma (`float`, *optional*, defaults to `0.5`): + Target reward margin γ for the TPO-L loss, used only when `loss_type="tpo-l"`. + + > [!NOTE] + > These parameters have default values different from [`~transformers.TrainingArguments`]: + > - `logging_steps`: Defaults to `10` instead of `500`. + > - `gradient_checkpointing`: Defaults to `True` instead of `False`. + > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`. + > - `learning_rate`: Defaults to `5e-7` instead of `5e-5`. + """ + + _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"] + + # Parameters whose default values are overridden from TrainingArguments + learning_rate: float = field( + default=5e-7, + metadata={"help": "The initial learning rate for AdamW."}, + ) + + # Parameters that control the model + model_init_kwargs: dict[str, Any] | str | None = field( + default=None, + metadata={ + "help": "Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `model` argument of " + "the `TPOTrainer` is provided as a string." + }, + ) + disable_dropout: bool = field( + default=True, + metadata={"help": "Whether to disable dropout in the model."}, + ) + + # Parameters that control the data preprocessing + dataset_num_proc: int | None = field( + default=None, + metadata={"help": "Number of processes to use for processing the dataset."}, + ) + max_length: int | None = field( + default=1024, + metadata={ + "help": "Maximum length of the tokenized sequence. Sequences longer than `max_length` are truncated from " + "the left or right depending on the `truncation_mode`. If `None`, no truncation is applied." + }, + ) + truncation_mode: str = field( + default="keep_start", + metadata={ + "help": "Truncation mode to use when the sequence exceeds `max_length`.", + "choices": ["keep_end", "keep_start"], + }, + ) + pad_to_multiple_of: int | None = field( + default=None, + metadata={"help": "If set, the sequences will be padded to a multiple of this value."}, + ) + + # Parameters that control the training + loss_type: str = field( + default="sigmoid", + metadata={ + "help": "Type of loss to use.", + "choices": ["sigmoid", "hinge", "ipo", "tpo-l"], + }, + ) + beta: float = field( + default=0.01, + metadata={ + "help": "Parameter controlling the temperature of the TPO loss. For the IPO loss (`loss_type='ipo'`), this " + "value is the regularization parameter denoted by τ in the IPO paper." + }, + ) + label_smoothing: float = field( + default=0.0, + metadata={"help": "Label smoothing factor."}, + ) + tpo_alpha: float = field( + default=1.0, + metadata={ + "help": "Weight of the supervised NLL term computed on the gold (`reference`) response in TPO training. " + "Setting `tpo_alpha=0.0` disables the NLL term and skips the corresponding forward pass." + }, + ) + tpo_l_gamma: float = field( + default=0.5, + metadata={"help": "Target reward margin γ for the TPO-L loss, used only when `loss_type='tpo-l'`."}, + ) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/tpo/tpo_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/tpo/tpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..c0f1a57dd9ce4c435c3490df9392e2e666de58ae --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/tpo/tpo_trainer.py @@ -0,0 +1,787 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +import textwrap +from collections import defaultdict +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import torch +import torch.nn.functional as F +import transformers +from accelerate import PartialState +from accelerate.logging import get_logger +from accelerate.utils import is_peft_model +from datasets import Dataset, IterableDataset +from packaging.version import Version +from transformers import ( + AutoProcessor, + DataCollator, + PreTrainedModel, + PreTrainedTokenizerBase, +) +from transformers.data.data_collator import DataCollatorMixin +from transformers.trainer_callback import TrainerCallback +from transformers.trainer_utils import EvalPrediction +from transformers.utils import is_peft_available + +from ...data_utils import extract_prompt, is_conversational +from ...trainer.base_trainer import _BaseTrainer +from ...trainer.utils import ( + create_model_from_path, + disable_dropout_in_model, + entropy_from_logits, + get_config_model_id, + pad, + selective_log_softmax, +) +from .tpo_config import TPOConfig + + +if is_peft_available(): + from peft import PeftConfig, PeftModel, get_peft_model + + +logger = get_logger(__name__) + + +def _extract_triple_prompt(example: dict) -> dict: + """Extract the shared prompt from `chosen`/`rejected` and also strip it from `reference`. + + Wraps [`~trl.data_utils.extract_prompt`] — which only rewrites `chosen` and `rejected` — and additionally strips + the extracted prompt prefix from the `reference` (gold) completion. This is specific to TPO and assumes that the + `reference` completion shares the same implicit prompt prefix as `chosen` and `rejected`. If it does not, a + `ValueError` is raised asking the caller to provide an explicit `prompt` column. + """ + extracted = extract_prompt(example) + prompt = extracted["prompt"] + reference = example["reference"] + if reference[: len(prompt)] != prompt: + raise ValueError( + "The `reference` completion does not start with the implicit prompt extracted from `chosen`/`rejected`. " + "Either provide an explicit `prompt` column, or make sure the `reference` completion shares the same " + "prompt prefix as the `chosen` and `rejected` completions." + ) + extracted["reference"] = reference[len(prompt) :] + return extracted + + +@dataclass +class DataCollatorForTriplePreference(DataCollatorMixin): + """ + Data collator used for triple-preference data. Inputs are dynamically padded to the maximum length of a batch. + + This collator expects each example in the input list to be a dictionary containing the keys `"prompt_ids"`, + `"chosen_ids"` and `"rejected_ids"`. When `include_reference=True` (the default) each example must additionally + contain `"reference_ids"`. The collator returns a dictionary containing the following keys: + - `"input_ids"`: Tensor of input IDs, padded to the maximum length of the batch. When + `include_reference=True`, the first third of the batch corresponds to the `"chosen_ids"`, the second third to + the `"rejected_ids"` and the last third to the `"reference_ids"`. When `include_reference=False`, the first + half corresponds to the `"chosen_ids"` and the second half to the `"rejected_ids"` (matching the layout of + [`~trl.trainer.dpo_trainer.DataCollatorForPreference`]). + - `"attention_mask"`: Tensor of attention mask, padded to the maximum length of the batch. + - `"completion_mask"`: Tensor indicating the positions of the completion tokens, padded to the maximum length of + the batch. + + Args: + pad_token_id (`int`): + Token ID to use for padding. + max_length (`int`, *optional*): + Maximum length of the sequences after concatenation. Sequences longer than `max_length` are truncated + before padding, which avoids allocating oversized tensors for batches containing very long sequences. + truncation_mode (`str`, *optional*, defaults to `"keep_start"`): + Truncation mode when a concatenated sequence exceeds `max_length`. Possible values are `"keep_end"` and + `"keep_start"`. + pad_to_multiple_of (`int`, *optional*): + If set, the sequences will be padded to a multiple of this value. + return_tensors (`str`, *optional*, defaults to `"pt"`): + Type of Tensor to return. Only `"pt"` is currently supported. + include_reference (`bool`, *optional*, defaults to `True`): + Whether to include the `"reference_ids"` branch in the collated batch. When `False`, the collator emits + only the chosen/rejected halves and skips the gold-response sequences entirely, which matches the behavior + expected when `tpo_alpha=0.0` (no NLL term). + + Examples: + ```python + >>> from trl.experimental.tpo.tpo_trainer import DataCollatorForTriplePreference + + >>> collator = DataCollatorForTriplePreference(pad_token_id=0) + >>> examples = [ + ... {"prompt_ids": [1, 2, 3], "chosen_ids": [4, 5], "rejected_ids": [6], "reference_ids": [7, 8]}, + ... {"prompt_ids": [9, 10], "chosen_ids": [11], "rejected_ids": [12, 13], "reference_ids": [14]}, + ... ] + >>> collator(examples) + {'input_ids': tensor([[ 1, 2, 3, 4, 5], + [ 9, 10, 11, 0, 0], + [ 1, 2, 3, 6, 0], + [ 9, 10, 12, 13, 0], + [ 1, 2, 3, 7, 8], + [ 9, 10, 14, 0, 0]]), + 'attention_mask': tensor([[1, 1, 1, 1, 1], + [1, 1, 1, 0, 0], + [1, 1, 1, 1, 0], + [1, 1, 1, 1, 0], + [1, 1, 1, 1, 1], + [1, 1, 1, 0, 0]]), + 'completion_mask': tensor([[0, 0, 0, 1, 1], + [0, 0, 1, 0, 0], + [0, 0, 0, 1, 0], + [0, 0, 1, 1, 0], + [0, 0, 0, 1, 1], + [0, 0, 1, 0, 0]])} + ``` + """ + + pad_token_id: int + max_length: int | None = None + truncation_mode: str = "keep_start" + pad_to_multiple_of: int | None = None + return_tensors: str = "pt" + include_reference: bool = True + + def torch_call(self, examples: list[dict[str, Any]]) -> dict[str, Any]: + prompt_chosen_ids = [example["prompt_ids"] + example["chosen_ids"] for example in examples] + prompt_rejected_ids = [example["prompt_ids"] + example["rejected_ids"] for example in examples] + chosen_mask = [[0] * len(example["prompt_ids"]) + [1] * len(example["chosen_ids"]) for example in examples] + rejected_mask = [[0] * len(example["prompt_ids"]) + [1] * len(example["rejected_ids"]) for example in examples] + if self.include_reference: + prompt_reference_ids = [example["prompt_ids"] + example["reference_ids"] for example in examples] + reference_mask = [ + [0] * len(example["prompt_ids"]) + [1] * len(example["reference_ids"]) for example in examples + ] + + if self.max_length is not None: + if self.truncation_mode == "keep_start": + sl = slice(None, self.max_length) + elif self.truncation_mode == "keep_end": + sl = slice(-self.max_length, None) + else: + raise ValueError( + f"Unsupported truncation mode: {self.truncation_mode}, expected 'keep_start' or 'keep_end'" + ) + prompt_chosen_ids = [ids[sl] for ids in prompt_chosen_ids] + prompt_rejected_ids = [ids[sl] for ids in prompt_rejected_ids] + chosen_mask = [m[sl] for m in chosen_mask] + rejected_mask = [m[sl] for m in rejected_mask] + if self.include_reference: + prompt_reference_ids = [ids[sl] for ids in prompt_reference_ids] + reference_mask = [m[sl] for m in reference_mask] + + chosen_attention_mask = [[1] * len(ids) for ids in prompt_chosen_ids] + rejected_attention_mask = [[1] * len(ids) for ids in prompt_rejected_ids] + input_ids = prompt_chosen_ids + prompt_rejected_ids + attention_mask = chosen_attention_mask + rejected_attention_mask + completion_mask = chosen_mask + rejected_mask + if self.include_reference: + reference_attention_mask = [[1] * len(ids) for ids in prompt_reference_ids] + input_ids = input_ids + prompt_reference_ids + attention_mask = attention_mask + reference_attention_mask + completion_mask = completion_mask + reference_mask + + # Convert to tensor + input_ids = [torch.tensor(ids) for ids in input_ids] + attention_mask = [torch.tensor(m, dtype=torch.long) for m in attention_mask] + completion_mask = [torch.tensor(m, dtype=torch.long) for m in completion_mask] + + # Pad + output = {} + output["input_ids"] = pad( + input_ids, + padding_value=self.pad_token_id, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ) + output["attention_mask"] = pad( + attention_mask, + padding_value=0, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ) + output["completion_mask"] = pad( + completion_mask, + padding_value=0, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ) + return output + + +class TPOTrainer(_BaseTrainer): + """ + Trainer for Triple Preference Optimization (TPO) method. This algorithm was initially proposed in the paper [Triple + Preference Optimization: Achieving Better Alignment using a Single Step + Optimization](https://huggingface.co/papers/2405.16681). This class is a wrapper around the + [`~transformers.Trainer`] class and inherits all of its attributes and methods. + + Args: + model (`str` or [`~transformers.PreTrainedModel`] or [`~peft.PeftModel`]): + Model to be trained. Can be either: + + - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a + path to a *directory* containing model weights saved using + [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded + using `.from_pretrained` (where `` is derived from the model + config) with the keyword arguments in `args.model_init_kwargs`. + - A [`~transformers.PreTrainedModel`] object. Only causal language models are supported. + - A [`~peft.PeftModel`] object. Only causal language models are supported. + args ([`experimental.tpo.TPOConfig`], *optional*): + Configuration for this trainer. If `None`, a default configuration is used. + data_collator ([`~transformers.DataCollator`], *optional*): + Function to use to form a batch from a list of elements of the processed `train_dataset` or `eval_dataset`. + Will default to [`~trl.experimental.tpo.tpo_trainer.DataCollatorForTriplePreference`]. Custom collators + must truncate sequences before padding; the trainer does not apply post-collation truncation. + train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]): + Dataset to use for training. TPO requires a *triple-preference* dataset: each sample must contain a + `"chosen"`, a `"rejected"` and a `"reference"` (gold) completion. The format of the samples can be either: + + - [Standard](dataset_formats#standard): Each sample contains plain text. + - [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role + and content). + eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Dataset | IterableDataset]`): + Dataset to use for evaluation. It must meet the same requirements as `train_dataset`. + processing_class ([`~transformers.PreTrainedTokenizerBase`], *optional*): + Processing class used to process the data. If `None`, the processing class is loaded from the model's name + with [`~transformers.AutoProcessor.from_pretrained`]. A padding token, `tokenizer.pad_token`, must be set. + If the processing class has not set a padding token, `tokenizer.eos_token` will be used as the default. + compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*): + The function that will be used to compute metrics at evaluation. Must take a + [`~transformers.EvalPrediction`] and return a dictionary string to metric values. + callbacks (list of [`~transformers.TrainerCallback`], *optional*): + List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed + in [here](https://huggingface.co/docs/transformers/main_classes/callback). + + If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`] + method. + optimizers (`tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None]`, *optional*, defaults to `(None, None)`): + A tuple containing the optimizer and the scheduler to use. Will default to an instance of `AdamW` on your + model and a scheduler given by [`~transformers.get_linear_schedule_with_warmup`] controlled by `args`. + peft_config ([`~peft.PeftConfig`], *optional*): + PEFT configuration used to wrap the model. If `None`, the model is not wrapped. + """ + + _tag_names = ["trl", "tpo"] + _name = "TPO" + _paper = { + "title": "Triple Preference Optimization: Achieving Better Alignment using a Single Step Optimization", + "id": "2405.16681", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @misc{saeidi2025triplepreferenceoptimizationachieving, + title = {{Triple Preference Optimization: Achieving Better Alignment using a Single Step Optimization}}, + author = {Amir Saeidi and Shivanshu Verma and Aswin RRV and Kashif Rasul and Chitta Baral}, + year = 2025, + eprint = {2405.16681}, + archivePrefix= {arXiv}, + primaryClass = {cs.CL}, + url = {https://arxiv.org/abs/2405.16681}, + }"""), + } + + def __init__( + self, + model: "str | PreTrainedModel | PeftModel", + args: TPOConfig | None = None, + data_collator: DataCollator | None = None, + train_dataset: Dataset | IterableDataset | None = None, + eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None, + processing_class: PreTrainedTokenizerBase | None = None, + compute_metrics: Callable[[EvalPrediction], dict] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None), + peft_config: "PeftConfig | None" = None, + ): + # Args + if args is None: + model_name = model if isinstance(model, str) else get_config_model_id(model.config) + model_name = model_name.split("/")[-1] + args = TPOConfig(f"{model_name}-TPO") + + if train_dataset is None: + raise ValueError("`train_dataset` is required") + elif isinstance(train_dataset, IterableDataset): + # IterableDataset requires dispatch_batches=False because Accelerate's dispatch mode may try to concatenate + # batches from multiple processes, leading to mismatch errors. + if args.accelerator_config.dispatch_batches is True: + logger.warning( + "You are using an `IterableDataset` for training with `dispatch_batches=True`. `dispatch_batches` " + "is forced to `False` when using an `IterableDataset`. To remove this warning, unset " + "`dispatch_batches` in `TPOConfig` or set it to `False`." + ) + args.accelerator_config.dispatch_batches = False + + # Model + if isinstance(model, str): + model_init_kwargs = args.model_init_kwargs or {} + # Distributed training requires device_map=None ("auto" fails) + if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + model_init_kwargs["device_map"] = None + model = create_model_from_path(model, **model_init_kwargs) + else: + if args.model_init_kwargs is not None: + logger.warning( + "You passed `model_init_kwargs` to the `TPOConfig`, but your model is already instantiated. " + "The `model_init_kwargs` will be ignored." + ) + + # Processing class + if processing_class is None: + processing_class = AutoProcessor.from_pretrained(get_config_model_id(model.config)) + if not isinstance(processing_class, PreTrainedTokenizerBase): + raise TypeError( + "The `processing_class` must be a `PreTrainedTokenizerBase`. `TPOTrainer` does not currently " + "support vision-language models." + ) + self._tokenizer = processing_class + + if self._tokenizer.pad_token is None: + self._tokenizer.pad_token = self._tokenizer.eos_token + + # PEFT + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + if is_peft_model(model): + raise ValueError( + "You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first merge " + "and unload the existing adapter, save the resulting base model, and then pass that base model along " + "with the new `peft_config` to the trainer." + ) + # Create PEFT model + model = get_peft_model(model, peft_config) + + # When using gradient checkpointing with PEFT, we need to enable input gradients. transformers.Trainer normally + # handles this, but a bug currently prevents it; see https://github.com/huggingface/transformers/issues/42489 + if is_peft_model(model) and args.gradient_checkpointing: + model.enable_input_require_grads() + + # Data collator. When `tpo_alpha=0.0`, the NLL term on the gold response is disabled, so we can drop the + # reference branch from the batch entirely — this spares the model from computing logits for a third of + # each step. + if data_collator is None: + data_collator = DataCollatorForTriplePreference( + pad_token_id=self._tokenizer.pad_token_id, + max_length=args.max_length, + truncation_mode=args.truncation_mode, + pad_to_multiple_of=args.pad_to_multiple_of, + include_reference=args.tpo_alpha != 0.0, + ) + + # Training arguments + self.beta = args.beta + self.loss_type = args.loss_type + self.label_smoothing = args.label_smoothing + self.tpo_alpha = args.tpo_alpha + self.tpo_l_gamma = args.tpo_l_gamma + if self.loss_type in ["hinge", "ipo"] and self.label_smoothing > 0: + logger.warning( + f"You are using the {self.loss_type} loss type that does not support label smoothing. The " + "`label_smoothing` parameter will be ignored. Set `label_smoothing` to `0.0` to remove this warning." + ) + + # Dataset + train_dataset = self._prepare_dataset(train_dataset, processing_class, args, "train") + if eval_dataset is not None: + if isinstance(eval_dataset, dict): + eval_dataset = { + key: self._prepare_dataset(dataset, processing_class, args, key) + for key, dataset in eval_dataset.items() + } + else: + eval_dataset = self._prepare_dataset(eval_dataset, processing_class, args, "eval") + + # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was + # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream + # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we + # default to the recommended non-reentrant behavior here, while preserving any user-provided value. + if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"): + args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {} + args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False) + + super().__init__( + model=model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + ) + + # Disable dropout in the model + if args.disable_dropout: + disable_dropout_in_model(model) + + # Initialize the metrics + self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)} + self._total_train_tokens = 0 + + # Add tags to the model + self.model.add_model_tags(self._tag_names) + + def _tokenize( + self, + processing_class: PreTrainedTokenizerBase, + input: str | list, + **kwargs, + ) -> dict[str, list]: + """Tokenize a single example for dataset preprocessing. + + Dispatches to `apply_chat_template` for conversational input (list of message dicts) and to `__call__` for + non-conversational input (str). + + Args: + processing_class ([`~transformers.PreTrainedTokenizerBase`]): + The tokenizer to use. + input (`str` or `list`): + A string for non-conversational input, or a list of message dicts for conversational input. + **kwargs: + Forwarded to `apply_chat_template` (e.g. `add_generation_prompt`). + + Returns: + `dict` with at least an `"input_ids"` key mapping to a flat `list[int]`. + """ + if isinstance(input, list): # conversational: list of message dicts + return processing_class.apply_chat_template(input, tokenize=True, return_dict=True, **kwargs) + # non-conversational: plain text string + return processing_class(text=input) + + def _prepare_dataset( + self, + dataset: Dataset | IterableDataset, + processing_class: PreTrainedTokenizerBase, + args: TPOConfig, + dataset_name: str, + ) -> Dataset | IterableDataset: + # Validate that the triple-preference columns are present + first_example = next(iter(dataset)) + if "chosen" not in first_example or "rejected" not in first_example: + raise ValueError( + "TPO requires a triple-preference dataset with `chosen`, `rejected` and `reference` columns, but the " + f"dataset is missing `chosen` or `rejected`. Got columns: {list(first_example.keys())}." + ) + if "reference" not in first_example: + raise ValueError( + "TPO requires a triple-preference dataset with `chosen`, `rejected` and `reference` columns, but the " + f"dataset is missing the `reference` (gold) column. Got columns: {list(first_example.keys())}." + ) + + # Build the kwargs for the `map` function + map_kwargs = {} + if isinstance(dataset, Dataset): # IterableDataset does not support num_proc + map_kwargs["num_proc"] = args.dataset_num_proc + + with PartialState().main_process_first(): + # Extract the prompt if needed. Unlike DPO, we must also strip the extracted prompt from the reference + # column (see `_extract_triple_prompt`), which assumes the reference shares the same implicit prompt. + first_example = next(iter(dataset)) + if "prompt" not in first_example: + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Extracting prompt from {dataset_name} dataset" + dataset = dataset.map(_extract_triple_prompt, **map_kwargs) + + # Add EOS to completions for non-conversational data + first_example = next(iter(dataset)) + if not is_conversational(first_example): + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Adding EOS to {dataset_name} dataset" + + def add_eos(example, eos_token): + if not example["chosen"].endswith(eos_token): + example["chosen"] = example["chosen"] + eos_token + if not example["rejected"].endswith(eos_token): + example["rejected"] = example["rejected"] + eos_token + if not example["reference"].endswith(eos_token): + example["reference"] = example["reference"] + eos_token + return example + + dataset = dataset.map(add_eos, fn_kwargs={"eos_token": processing_class.eos_token}, **map_kwargs) + + # Tokenize the dataset + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Tokenizing {dataset_name} dataset" + + def tokenize_fn(example, processing_class): + tools = example.get("tools") + tools = json.loads(tools) if isinstance(tools, str) else tools + output = {} + if is_conversational(example): + prompt_ids = self._tokenize( + processing_class, + example["prompt"], + tools=tools, + add_generation_prompt=True, + **example.get("chat_template_kwargs", {}), + )["input_ids"] + prompt_chosen_ids = self._tokenize( + processing_class, + example["prompt"] + example["chosen"], + tools=tools, + **example.get("chat_template_kwargs", {}), + )["input_ids"] + prompt_rejected_ids = self._tokenize( + processing_class, + example["prompt"] + example["rejected"], + tools=tools, + **example.get("chat_template_kwargs", {}), + )["input_ids"] + prompt_reference_ids = self._tokenize( + processing_class, + example["prompt"] + example["reference"], + tools=tools, + **example.get("chat_template_kwargs", {}), + )["input_ids"] + else: + prompt_ids = self._tokenize(processing_class, example["prompt"])["input_ids"] + prompt_chosen_ids = self._tokenize(processing_class, example["prompt"] + example["chosen"])[ + "input_ids" + ] + prompt_rejected_ids = self._tokenize(processing_class, example["prompt"] + example["rejected"])[ + "input_ids" + ] + prompt_reference_ids = self._tokenize(processing_class, example["prompt"] + example["reference"])[ + "input_ids" + ] + + # Check if the tokenized prompt starts with the tokenized prompt+completion + if not prompt_chosen_ids[: len(prompt_ids)] == prompt_ids: + logger.warning( + "Mismatch between tokenized prompt and the start of tokenized prompt+chosen. " + "This may be due to unexpected tokenizer behavior, whitespace issues, or special " + "token handling. Verify that the tokenizer is processing text consistently." + ) + if not prompt_rejected_ids[: len(prompt_ids)] == prompt_ids: + logger.warning( + "Mismatch between tokenized prompt and the start of tokenized prompt+rejected. " + "This may be due to unexpected tokenizer behavior, whitespace issues, or special " + "token handling. Verify that the tokenizer is processing text consistently." + ) + if not prompt_reference_ids[: len(prompt_ids)] == prompt_ids: + logger.warning( + "Mismatch between tokenized prompt and the start of tokenized prompt+reference. " + "This may be due to unexpected tokenizer behavior, whitespace issues, or special " + "token handling. Verify that the tokenizer is processing text consistently." + ) + + output["prompt_ids"] = prompt_ids + output["chosen_ids"] = prompt_chosen_ids[len(prompt_ids) :] + output["rejected_ids"] = prompt_rejected_ids[len(prompt_ids) :] + output["reference_ids"] = prompt_reference_ids[len(prompt_ids) :] + return output + + dataset = dataset.map(tokenize_fn, fn_kwargs={"processing_class": processing_class}, **map_kwargs) + + return dataset + + def _set_signature_columns_if_needed(self): + # If `self.args.remove_unused_columns` is True, non-signature columns are removed. + # By default, this method sets `self._signature_columns` to the model's expected inputs (usually, "input_ids" + # and "attention_mask"). + if self._signature_columns is None: + self._signature_columns = ["prompt_ids", "chosen_ids", "rejected_ids", "reference_ids"] + + def _compute_loss(self, model, inputs, return_outputs): + mode = "train" if self.model.training else "eval" + + # When `tpo_alpha=0.0` the NLL term is disabled and the collator drops the reference branch, so the batch + # is laid out as `[chosen, rejected]` (n_branches=2). Otherwise it is `[chosen, rejected, reference]` + # (n_branches=3). + n_branches = 3 if self.tpo_alpha != 0.0 else 2 + + _non_model_keys = {"completion_mask"} + model_kwargs = {k: v for k, v in inputs.items() if k not in _non_model_keys} + model_kwargs["use_cache"] = False + outputs = model(**model_kwargs) + + input_ids = inputs["input_ids"] + completion_mask = inputs["completion_mask"] + shift_logits = outputs.logits[..., :-1, :].contiguous() + shift_labels = input_ids[..., 1:].contiguous() + shift_completion_mask = completion_mask[..., 1:].contiguous() + per_token_logps = selective_log_softmax(shift_logits, shift_labels) + per_token_logps[shift_completion_mask == 0] = 0.0 # mask out non-completion tokens + + # Length-normalized for IPO and TPO-L (matches the SimPO-style implicit reward used by the TPO paper); + # summed otherwise. + if self.loss_type in ("ipo", "tpo-l"): + completion_lengths = shift_completion_mask.sum(dim=1).clamp(min=1) + logps = per_token_logps.sum(dim=1) / completion_lengths + else: + logps = per_token_logps.sum(dim=1) + logps_chunks = logps.chunk(n_branches, dim=0) + chosen_logps, rejected_logps = logps_chunks[0], logps_chunks[1] + + # Contrastive loss between chosen and rejected. Unlike DPO, TPO does not subtract reference-model log-probs: + # the "reference" in TPO is a gold response used in the NLL term below, not a separate reference policy. + delta_score = chosen_logps - rejected_logps + + if self.loss_type == "sigmoid": + per_sequence_loss = ( + -F.logsigmoid(self.beta * delta_score) * (1 - self.label_smoothing) + - F.logsigmoid(-self.beta * delta_score) * self.label_smoothing + ) + + elif self.loss_type == "hinge": + per_sequence_loss = torch.relu(1 - self.beta * delta_score) + + elif self.loss_type == "ipo": + # (Eq. 17) of the IPO paper where beta is the regularization parameter for the IPO loss, denoted by τ. + per_sequence_loss = (delta_score - 1 / (2 * self.beta)) ** 2 + + elif self.loss_type == "tpo-l": + # Length-normalized TPO-L variant: subtract a target reward margin γ/β before the sigmoid. + gamma_logratios = self.tpo_l_gamma / self.beta + shifted_delta = delta_score - gamma_logratios + per_sequence_loss = ( + -F.logsigmoid(self.beta * shifted_delta) * (1 - self.label_smoothing) + - F.logsigmoid(-self.beta * shifted_delta) * self.label_smoothing + ) + + else: + raise ValueError( + f"Unknown loss type: {self.loss_type}. Should be one of ['sigmoid', 'hinge', 'ipo', 'tpo-l']" + ) + + loss = per_sequence_loss.mean() + + # NLL loss on the gold (`reference`) response. Mirrors the `"sft"` loss branch of `DPOTrainer._compute_loss`: + # we restrict the cross-entropy to the completion tokens of the reference sequence and let `F.cross_entropy` + # average over them. The NLL contribution is folded into the main `loss` (matching DPO/SFT convention: the + # individual NLL term is not logged separately). + if n_branches == 3: + _, _, ref_logits = shift_logits.chunk(3, dim=0) + _, _, ref_labels = shift_labels.chunk(3, dim=0) + _, _, ref_mask = shift_completion_mask.chunk(3, dim=0) + ref_mask = ref_mask.bool() + nll_loss = F.cross_entropy(ref_logits[ref_mask], ref_labels[ref_mask]) + loss = loss + self.tpo_alpha * nll_loss + + # Log the metrics + # Entropy + per_token_entropy = entropy_from_logits(shift_logits.detach()) + entropy = per_token_entropy[shift_completion_mask.bool()].mean() + entropy = self.accelerator.gather_for_metrics(entropy).mean().item() + self._metrics[mode]["entropy"].append(entropy) + + # Number of tokens + if mode == "train": + num_tokens_in_batch = self.accelerator.gather_for_metrics(inputs["attention_mask"].sum()).sum().item() + self._total_train_tokens += num_tokens_in_batch + self._metrics[mode]["num_tokens"] = [self._total_train_tokens] + + # Average logits for chosen and rejected completions + logits_chunks = shift_logits.detach().chunk(n_branches, dim=0) + mask_chunks = shift_completion_mask.chunk(n_branches, dim=0) + labels_chunks = shift_labels.chunk(n_branches, dim=0) + chosen_logits, rejected_logits = logits_chunks[0], logits_chunks[1] + chosen_mask, rejected_mask = mask_chunks[0], mask_chunks[1] + chosen_labels = labels_chunks[0] + total_chosen_logits = chosen_logits[chosen_mask.bool()].mean(-1).sum() + total_chosen_tokens = chosen_mask.sum() + total_rejected_logits = rejected_logits[rejected_mask.bool()].mean(-1).sum() + total_rejected_tokens = rejected_mask.sum() + total_chosen_logits = self.accelerator.gather_for_metrics(total_chosen_logits).sum().item() + total_chosen_tokens = self.accelerator.gather_for_metrics(total_chosen_tokens).sum().item() + total_rejected_logits = self.accelerator.gather_for_metrics(total_rejected_logits).sum().item() + total_rejected_tokens = self.accelerator.gather_for_metrics(total_rejected_tokens).sum().item() + avg_chosen_logits = total_chosen_logits / total_chosen_tokens if total_chosen_tokens > 0 else 0.0 + avg_rejected_logits = total_rejected_logits / total_rejected_tokens if total_rejected_tokens > 0 else 0.0 + self._metrics[mode]["logits/chosen"].append(avg_chosen_logits) + self._metrics[mode]["logits/rejected"].append(avg_rejected_logits) + + # Token accuracy for the chosen completions + predictions = chosen_logits.argmax(dim=-1) + chosen_bool_mask = chosen_mask.bool() + correct_predictions = (predictions == chosen_labels) & chosen_bool_mask + total_tokens = chosen_bool_mask.sum() + correct_tokens = correct_predictions.sum() + correct_tokens = self.accelerator.gather_for_metrics(correct_tokens) + total_tokens = self.accelerator.gather_for_metrics(total_tokens) + total_sum = total_tokens.sum() + accuracy = (correct_tokens.sum() / total_sum).item() if total_sum > 0 else 0.0 + self._metrics[mode]["mean_token_accuracy"].append(accuracy) + + # Rewards for chosen and rejected completions (β · log π_θ as in the SimPO/TPO implicit reward) + chosen_rewards = self.beta * chosen_logps.detach() + rejected_rewards = self.beta * rejected_logps.detach() + agg_chosen_rewards = self.accelerator.gather(chosen_rewards) + agg_rejected_rewards = self.accelerator.gather(rejected_rewards) + self._metrics[mode]["rewards/chosen"].append(agg_chosen_rewards.mean().item()) + self._metrics[mode]["rewards/rejected"].append(agg_rejected_rewards.mean().item()) + + # Reward accuracy + reward_accuracies = (chosen_rewards > rejected_rewards).float() + agg_reward_accuracies = self.accelerator.gather(reward_accuracies) + self._metrics[mode]["rewards/accuracies"].append(agg_reward_accuracies.mean().item()) + + # Reward margins + margins = chosen_rewards - rejected_rewards + agg_margins = self.accelerator.gather(margins) + self._metrics[mode]["rewards/margins"].append(agg_margins.mean().item()) + + # Average log probabilities for chosen and rejected completions + self._metrics[mode]["logps/chosen"].append(self.accelerator.gather(chosen_logps).mean().item()) + self._metrics[mode]["logps/rejected"].append(self.accelerator.gather(rejected_logps).mean().item()) + + return (loss, outputs) if return_outputs else loss + + def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): + return self._compute_loss(model, inputs, return_outputs) + + def log(self, logs: dict[str, float], start_time: float | None = None) -> None: + mode = "train" if self.model.training else "eval" + metrics = {key: sum(val) / len(val) for key, val in self._metrics[mode].items()} # average the metrics + + # This method can be called both in training and evaluation. When called in evaluation, the keys in `logs` + # start with "eval_". We need to add the prefix "eval_" to the keys in `metrics` to match the format. + if mode == "eval": + metrics = {f"eval_{key}": val for key, val in metrics.items()} + + logs.update(metrics) + super().log(logs, start_time) + self._metrics[mode].clear() + + # During eval, Trainer calls prediction_step. If no labels are present in the inputs, it only runs forward and + # returns logits. We override prediction_step to force compute_loss, because this trainer doesn't involve labels. + def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys: list[str] | None = None): + inputs = self._prepare_inputs(inputs) + with torch.no_grad(), self.compute_loss_context_manager(): + if prediction_loss_only: + loss = self.compute_loss(model, inputs, return_outputs=False) + logits, labels = None, None + else: + loss, outputs = self.compute_loss(model, inputs, return_outputs=True) + logits, labels = outputs.logits, inputs["input_ids"] + return loss, logits, labels + + # Ensure the model card is saved along with the checkpoint + def _save_checkpoint(self, model, trial): + if self.args.hub_model_id is None: + model_name = Path(self.args.output_dir).name + else: + model_name = self.args.hub_model_id.split("/")[-1] + self.create_model_card(model_name=model_name) + super()._save_checkpoint(model, trial) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/utils.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2e5116a569941599ced208edafdded71bd44f946 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/utils.py @@ -0,0 +1,858 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# This file contains utility classes and functions that are used across more than one experimental trainer or feature. + +import inspect +import logging +from copy import deepcopy +from dataclasses import dataclass +from typing import Any + +import pyarrow as pa +import pyarrow.types +import torch +from accelerate.utils import is_peft_model +from packaging.version import Version +from pyarrow import compute as pc +from torch import nn +from torch.nn.utils.rnn import pad_sequence +from transformers import PreTrainedModel, PreTrainedTokenizerBase, TrainingArguments +from transformers.integrations.deepspeed import is_deepspeed_zero3_enabled +from transformers.utils import ( + is_peft_available, + is_torch_mlu_available, + is_torch_mps_available, + is_torch_npu_available, + is_torch_xpu_available, +) + +from ..data_utils import DatasetType, _get_dataset_format +from ..trainer.utils import pad + + +if is_peft_available(): + import peft + from peft import PeftConfig, PeftModel, get_peft_model + + +@dataclass +class DPODataCollatorWithPadding: + r""" + DPO DataCollator class that pads the tokenized inputs to the maximum length of the batch. + + Args: + pad_token_id (`int` defaults to 0): + The tokenizer's pad_token_id. + is_encoder_decoder (`bool` or `None`, `optional`, defaults to `None`): + Whether you model has an encoder_decoder architecture. + """ + + pad_token_id: int = 0 + is_encoder_decoder: bool | None = False + + def __call__(self, features: list[dict[str, Any]]) -> dict[str, Any]: + # first, pad everything to the same length + padded_batch = {} + for k in features[0].keys(): + if k.endswith(("_input_ids", "_attention_mask", "_labels", "_pixel_values")): + if self.is_encoder_decoder: + to_pad = [torch.LongTensor(ex[k]) for ex in features] + + if (k.startswith("prompt")) and (k.endswith("input_ids")): + if self.pad_token_id is None: + raise ValueError( + "Padding is enabled, but the tokenizer is not configured with a padding token." + " Explicitly set `tokenizer.pad_token` (e.g. `tokenizer.pad_token = tokenizer.eos_token`)" + " before calling the trainer." + ) + padding_value = self.pad_token_id + elif k.endswith("_attention_mask"): + padding_value = 0 + elif k.startswith(("chosen", "rejected", "completion")) or ("decoder" in k): + padding_value = -100 + else: + raise ValueError(f"Unexpected key in batch '{k}'") + padded_batch[k] = pad_sequence(to_pad, batch_first=True, padding_value=padding_value) + else: + # Set padding value based on the key + if k.endswith("_input_ids"): + if self.pad_token_id is None: + raise ValueError( + "Padding is enabled, but the tokenizer is not configured with a padding token." + " Explicitly set `tokenizer.pad_token` (e.g. `tokenizer.pad_token = tokenizer.eos_token`)" + " before calling the trainer." + ) + padding_value = self.pad_token_id + elif k.endswith("_labels"): + padding_value = -100 + elif k.endswith("_attention_mask"): + padding_value = 0 + elif k.endswith("_pixel_values"): + padding_value = 0 # TODO: check if this is correct + else: + raise ValueError(f"Unexpected key in batch '{k}'") + + # Set padding side based on the key + if k in ["prompt_input_ids", "prompt_attention_mask"]: + padding_side = "left" + else: + padding_side = "right" + + # Set the dtype + if k.endswith("_pixel_values"): + dtype = torch.float32 # will be downcasted if necessary by the Trainer + else: + dtype = torch.int64 + + # Convert to tensor and pad + to_pad = [torch.tensor(ex[k], dtype=dtype) for ex in features] + padded_batch[k] = pad(to_pad, padding_value=padding_value, padding_side=padding_side) + elif k.endswith("_logps"): + # the cached reference model logprobs + padded_batch[k] = torch.tensor([ex[k] for ex in features]) + else: + padded_batch[k] = [ex[k] for ex in features] + + return padded_batch + + +def pad_byte_offsets(offsets: list[tuple[int, int]], target_length: int, padding_side: str) -> torch.Tensor: + """Build a ``[target_length, 2]`` long tensor from ``(start, end)`` byte-offset tuples, + padding with ``(0, 0)`` on the requested side.""" + offs = torch.tensor(offsets, dtype=torch.long).reshape(-1, 2) + pad_len = target_length - offs.size(0) + if pad_len <= 0: + return offs + pad_block = torch.zeros(pad_len, 2, dtype=torch.long) + return torch.cat([pad_block, offs], dim=0) if padding_side == "left" else torch.cat([offs, pad_block], dim=0) + + +def is_byte_level_tokenizer(backend) -> bool: + """Whether ``backend`` is a ByteLevel BPE tokenizer (Llama-3 family, SmolLM, Qwen, \u2026) \u2014 its pieces are in + byte\u2192unicode space, one char per source byte. Detected via the pre-tokenizer / decoder repr.""" + return "ByteLevel" in repr(backend.pre_tokenizer) or "ByteLevel" in repr(backend.decoder) + + +def piece_byte_len(piece: str) -> int: + """UTF-8 byte length of a ByteLevel BPE token piece \u2014 each char maps 1:1 to one source byte. + + Cross-tokenizer ULD targets ByteLevel BPE pairs (Llama-3, Qwen, SmolLM, Phi, Mistral v0.3+, \u2026); SentencePiece + students are out of scope here and would need the loss-level projection from X-Token to align.""" + return len(piece) + + +def _bytes_to_unicode() -> dict[int, str]: + bs = list(range(ord("!"), ord("~") + 1)) + list(range(ord("\u00a1"), ord("\u00ac") + 1)) + bs += list(range(ord("\u00ae"), ord("\u00ff") + 1)) + cs = bs[:] + n = 0 + for b in range(256): + if b not in bs: + bs.append(b) + cs.append(256 + n) + n += 1 + return dict(zip(bs, [chr(n) for n in cs], strict=True)) + + +_BYTE_LEVEL_DECODER = {ch: b for b, ch in _bytes_to_unicode().items()} + + +def _byte_level_piece_len(piece: str, text_bytes: bytes, start: int) -> int | None: + piece_bytes = [] + for ch in piece: + if ch not in _BYTE_LEVEL_DECODER: + return None + piece_bytes.append(_BYTE_LEVEL_DECODER[ch]) + if piece_bytes and piece_bytes[0] == ord(" ") and text_bytes[start : start + 1] != b" ": + piece_bytes = piece_bytes[1:] + return len(piece_bytes) + + +def _split_repeated_byte_offsets(byte_offsets: list[tuple[int, int]], tokens: list[str]) -> list[tuple[int, int]]: + """Split repeated char-derived spans for byte-fallback or byte-level tokens.""" + normalized = list(byte_offsets) + i = 0 + while i < len(byte_offsets): + j = i + 1 + while j < len(byte_offsets) and byte_offsets[j] == byte_offsets[i]: + j += 1 + + if j - i > 1: + start, end = byte_offsets[i] + piece_lengths = [piece_byte_len(token) for token in tokens[i:j]] + if sum(piece_lengths) == end - start: + cursor = start + for offset_idx, length in enumerate(piece_lengths, start=i): + normalized[offset_idx] = (cursor, cursor + length) + cursor += length + + i = j + return normalized + + +def _normalize_byte_offsets( + byte_offsets: list[tuple[int, int]], tokens: list[str], text_bytes: bytes +) -> list[tuple[int, int]]: + byte_offsets = _split_repeated_byte_offsets(byte_offsets, tokens) + normalized = [] + cursor = 0 + + for idx, (start, end) in enumerate(byte_offsets): + if start == end: + normalized.append((cursor, cursor)) + continue + + piece_len = _byte_level_piece_len(tokens[idx], text_bytes, start) + next_start = byte_offsets[idx + 1][0] if idx + 1 < len(byte_offsets) else None + has_overlap = start < cursor or (next_start is not None and next_start < end) + + if piece_len is not None and (has_overlap or piece_len == end - start): + candidate_start = max(start, cursor) + candidate_end = candidate_start + piece_len + if candidate_end <= end: + start = candidate_start + end = candidate_end + + if start < cursor or end < start: + raise ValueError( + "Tokenizer produced overlapping byte offsets that could not be normalized. " + "Cross-tokenizer ULD requires monotonic byte offsets." + ) + + normalized.append((start, end)) + cursor = end + + return normalized + + +def encode_with_byte_offsets(backend, texts: list[str], add_special_tokens: bool = False): + """Encode ``texts`` and return per-text ``(ids, byte_offsets)`` pairs. + + Byte offsets are derived from the fast tokenizer's character offsets via an O(N) char-to-byte cumulative table. + Overlapping spans from byte-level and byte-fallback tokens are split across their byte pieces.""" + if not is_byte_level_tokenizer(backend): + raise NotImplementedError( + "Cross-tokenizer ULD currently supports only ByteLevel BPE tokenizers " + "(Llama-3, Qwen, SmolLM, Phi, Mistral v0.3+, …). The given tokenizer is not ByteLevel." + ) + encs = backend.encode_batch(texts, add_special_tokens=add_special_tokens) + out = [] + for text, enc in zip(texts, encs, strict=True): + char_to_byte = [0] + for ch in text: + char_to_byte.append(char_to_byte[-1] + len(ch.encode("utf-8"))) + byte_offsets = [(char_to_byte[s], char_to_byte[e]) for s, e in enc.offsets] + byte_offsets = _normalize_byte_offsets(byte_offsets, enc.tokens, text.encode("utf-8")) + out.append((list(enc.ids), byte_offsets)) + return out + + +@dataclass +class DataCollatorForChatML: + """ + Data collator for ChatML format datasets. + """ + + tokenizer: PreTrainedTokenizerBase + ignore_index: int = -100 + max_length: int = None + prompt_key: str = "prompt" + messages_key: str = "messages" + + def __post_init__(self): + if self.tokenizer.pad_token_id is None: + raise ValueError("The tokenizer does not have a pad token. Please set `pad_token_id` in the tokenizer.") + if self.max_length is None: + # set a sensible default + self.max_length = min(self.tokenizer.model_max_length, 1024) + + def __call__(self, examples: list[dict[str, Any]]) -> dict[str, torch.Tensor]: + input_ids = [] + attention_mask = [] + prompts_input_ids = [] + prompt_attention_mask = [] + labels = [] + byte_offsets: list[list[tuple[int, int]]] = [] + + for example in examples: + formatted_prompt = example.get(self.prompt_key, example.get("original_prompt_text", None)) + if formatted_prompt is None: + prompt = example[self.messages_key][:-1] + formatted_prompt = self.tokenizer.apply_chat_template( + prompt, add_generation_prompt=True, tokenize=False + ) + + if "input_ids" not in example: + message = example[self.messages_key] + formatted_message = self.tokenizer.apply_chat_template( + message, add_generation_prompt=False, tokenize=False + ) + if is_byte_level_tokenizer(self.tokenizer.backend_tokenizer): + [(message_input_ids_full, full_offs)] = encode_with_byte_offsets( + self.tokenizer.backend_tokenizer, [formatted_message], add_special_tokens=False + ) + prompt_byte_len = len(formatted_prompt.encode("utf-8")) + completion_start_idx_full = next( + (idx for idx, (start, _) in enumerate(full_offs) if start >= prompt_byte_len), + len(message_input_ids_full), + ) + else: + # Non-ByteLevel tokenizer: byte offsets are unnecessary (cross-tokenizer ULD requires ByteLevel + # anyway). Fall back to plain tokenization so GKD / non-ULD trainers with SentencePiece or + # Unigram tokenizers still work through this collator. + message_input_ids_full = self.tokenizer( + formatted_message, add_special_tokens=False, return_tensors=None + )["input_ids"] + completion_start_idx_full = len( + self.tokenizer(formatted_prompt, add_special_tokens=False, return_tensors=None)["input_ids"] + ) + full_offs = [(0, 0)] * len(message_input_ids_full) + prompt_byte_len = 0 + + # Keep the last max_length tokens — drops oldest prompt context first, + # never drops from the END (the model's recent context). + if self.max_length is not None and len(message_input_ids_full) > self.max_length: + sample_ids = message_input_ids_full[-self.max_length :] + sample_offs = full_offs[-self.max_length :] + current_prompt_len = max( + 0, completion_start_idx_full - (len(message_input_ids_full) - self.max_length) + ) + else: + sample_ids = message_input_ids_full + sample_offs = full_offs + current_prompt_len = completion_start_idx_full + + # Make completion-relative: prompt positions zeroed, completion offsets shifted. If truncation + # ate into the completion (no prompt tokens kept and the first kept token is mid-completion), + # rebase to byte 0 of the kept completion so teacher/student share the same coordinate system. + kept_completion_offs = sample_offs[current_prompt_len:] + base = ( + kept_completion_offs[0][0] if kept_completion_offs and current_prompt_len == 0 else prompt_byte_len + ) + completion_offs = [(s - base, e - base) for s, e in kept_completion_offs] + sample_offs = [(0, 0)] * current_prompt_len + completion_offs + + input_ids.append(sample_ids) + attention_mask.append([1] * len(sample_ids)) + current_prompt_ids = sample_ids[:current_prompt_len] + byte_offsets.append(sample_offs) + else: + sample_ids = example["input_ids"] + input_ids.append(sample_ids) + attention_mask.append(example.get("attention_mask", [1] * len(sample_ids))) + completion_mask = example.get("completion_mask") + if completion_mask is not None: + # Use the tracked boundary directly: no re-tokenization, survives truncation. + prompt_len = completion_mask.index(1) if 1 in completion_mask else len(sample_ids) + current_prompt_ids = sample_ids[:prompt_len] + else: + # No tracked boundary: tokenize the prompt and cap with a slice (avoid `truncation=True`, + # which would persist on the shared backend used by `encode_with_byte_offsets`). + tokenized_prompt = self.tokenizer( + formatted_prompt, + padding=False, + return_tensors=None, + add_special_tokens=False, + ) + current_prompt_ids = tokenized_prompt["input_ids"][: len(sample_ids)] + byte_offsets.append(example.get("byte_offsets", [(0, 0)] * len(sample_ids))) + + prompts_input_ids.append(current_prompt_ids) + prompt_attention_mask.append([1] * len(current_prompt_ids)) + + label = [self.ignore_index] * len(sample_ids) + label[len(current_prompt_ids) :] = sample_ids[len(current_prompt_ids) :] + labels.append(label) + + input_ids = pad( + [torch.tensor(x, dtype=torch.long) for x in input_ids], + padding_side="left", + padding_value=self.tokenizer.pad_token_id, + ) + attention_mask = pad( + [torch.tensor(x, dtype=torch.long) for x in attention_mask], padding_side="left", padding_value=0 + ) + labels = pad( + [torch.tensor(x, dtype=torch.long) for x in labels], padding_side="left", padding_value=self.ignore_index + ) + prompts_input_ids = pad( + [torch.tensor(x, dtype=torch.long) for x in prompts_input_ids], + padding_side="left", + padding_value=self.tokenizer.pad_token_id, + ) + prompt_attention_mask = pad( + [torch.tensor(x, dtype=torch.long) for x in prompt_attention_mask], padding_side="left", padding_value=0 + ) + + target_len = input_ids.size(1) + byte_offsets_tensor = torch.stack( + [pad_byte_offsets(offs, target_len, padding_side="left") for offs in byte_offsets], dim=0 + ) + + out = { + "input_ids": input_ids, + "attention_mask": attention_mask, + "labels": labels, + "prompts": prompts_input_ids, + "prompt_attention_mask": prompt_attention_mask, + "byte_offsets": byte_offsets_tensor, + } + # Forward source text for cross-tokenizer ULD, when the dataset has it. + if "original_prompt_text" in examples[0] and "original_completion_text" in examples[0]: + out["original_prompt_text"] = [ex["original_prompt_text"] for ex in examples] + out["original_completion_text"] = [ex["original_completion_text"] for ex in examples] + return out + + +def truncate_right( + input_ids: torch.Tensor, stop_token_id: int, pad_token_id: int +) -> tuple[torch.Tensor, torch.Tensor]: + """ + Truncates the input tensor from the right side after the first occurrence of the stop token. + + Args: + input_ids (`torch.Tensor`): + The tensor containing the responses to be truncated + stop_token_id (`int`): + The token ID representing the stop token where truncation occurs + pad_token_id (`int`): + The token ID representing the pad token used to fill the truncated responses + + Returns: + tuple: + - `output_ids` (`torch.Tensor`): + The truncated responses tensor with pad tokens filled after the stop token + - `mask` (`torch.Tensor`): + The mask tensor to indicate the padding tokens + """ + trunc_idxs = first_true_indices(input_ids == stop_token_id).unsqueeze(-1) + new_size = [1] * (len(input_ids.size()) - 1) + [input_ids.shape[1]] + idxs = torch.arange(input_ids.shape[1], device=input_ids.device).view(*new_size) + output_ids = torch.masked_fill(input_ids, idxs > trunc_idxs, pad_token_id) + mask = torch.masked_fill(torch.ones_like(input_ids), idxs > trunc_idxs, 0) + return output_ids, mask + + +def add_bos_token_if_needed( + bos_token_id: int | None, + prompt_len_input_ids: int, + prompt_tokens: dict[str, list[int]], + chosen_prompt_len_input_ids: int, + chosen_tokens: dict[str, list[int]], + rejected_prompt_len_input_ids: int, + rejected_tokens: dict[str, list[int]], +): + if bos_token_id is not None: + if prompt_len_input_ids == 0 or bos_token_id != prompt_tokens["prompt_input_ids"][0]: + prompt_tokens["prompt_input_ids"] = [bos_token_id] + prompt_tokens["prompt_input_ids"] + prompt_tokens["prompt_attention_mask"] = [1] + prompt_tokens["prompt_attention_mask"] + if chosen_prompt_len_input_ids == 0 or bos_token_id != chosen_tokens["prompt_input_ids"][0]: + chosen_tokens["prompt_input_ids"] = [bos_token_id] + chosen_tokens["prompt_input_ids"] + chosen_tokens["prompt_attention_mask"] = [1] + chosen_tokens["prompt_attention_mask"] + if rejected_prompt_len_input_ids == 0 or bos_token_id != rejected_tokens["prompt_input_ids"][0]: + rejected_tokens["prompt_input_ids"] = [bos_token_id] + rejected_tokens["prompt_input_ids"] + rejected_tokens["prompt_attention_mask"] = [1] + rejected_tokens["prompt_attention_mask"] + return prompt_tokens, chosen_tokens, rejected_tokens + + +def add_eos_token_if_needed( + eos_token_id: int, chosen_tokens: dict[str, list[int]], rejected_tokens: dict[str, list[int]] +): + if len(chosen_tokens["input_ids"]) == 0 or eos_token_id != chosen_tokens["input_ids"][-1]: + chosen_tokens["input_ids"].append(eos_token_id) + chosen_tokens["attention_mask"].append(1) + if len(rejected_tokens["input_ids"]) == 0 or eos_token_id != rejected_tokens["input_ids"][-1]: + rejected_tokens["input_ids"].append(eos_token_id) + rejected_tokens["attention_mask"].append(1) + return chosen_tokens, rejected_tokens + + +def first_true_indices(bools: torch.Tensor, dtype=torch.long) -> torch.Tensor: + """ + Takes an N-dimensional bool tensor and returns an (N-1)-dimensional tensor of integers giving the position of the + first True in each "row". + + Returns the length of the rows (bools.size(-1)) if no element is True in a given row. + + Args: + bools (`torch.Tensor`): + An N-dimensional boolean tensor. + dtype (`torch.dtype`, optional): + The desired data type of the output tensor. Defaults to `torch.long`. + + Returns: + `torch.Tensor`: + An (N-1)-dimensional tensor of integers indicating the position of the first True in each row. If no True + value is found in a row, returns the length of the row. + """ + row_len = bools.size(-1) + zero_or_index = row_len * (~bools).type(dtype) + torch.arange(row_len, dtype=dtype, device=bools.device) + return torch.min(zero_or_index, dim=-1).values + + +def get_reward( + model: torch.nn.Module, query_responses: torch.Tensor, pad_token_id: int, context_length: int +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Computes the reward logits and the rewards for a given model and query responses. + + Args: + model (`torch.nn.Module`): + The model used to compute the reward logits. + query_responses (`torch.Tensor`): + The tensor containing the query responses. + pad_token_id (`int`): + The token ID representing the pad token. + context_length (`int`): + The length of the context in the query responses. + + Returns: + tuple: + - `reward_logits` (`torch.Tensor`): + The logits for the reward model. + - `final_rewards` (`torch.Tensor`): + The final rewards for each query response. + - `sequence_lengths` (`torch.Tensor`): + The lengths of the sequences in the query responses. + """ + attention_mask = query_responses != pad_token_id + position_ids = attention_mask.cumsum(1) - attention_mask.long() # exclusive cumsum + lm_backbone = getattr(model, model.base_model_prefix) + input_ids = torch.masked_fill(query_responses, ~attention_mask, 0) + output = lm_backbone( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + return_dict=True, + output_hidden_states=True, + use_cache=False, # otherwise mistral-based RM would error out + ) + reward_logits = model.score(output.hidden_states[-1]) + sequence_lengths = first_true_indices(query_responses[:, context_length:] == pad_token_id) - 1 + context_length + # https://github.com/huggingface/transformers/blob/dc68a39c8111217683bf49a4912d0c9018bab33d/src/transformers/models/gpt2/modeling_gpt2.py#L1454 + return ( + reward_logits, + reward_logits[ + torch.arange(reward_logits.size(0), device=reward_logits.device), + sequence_lengths, + ].squeeze(-1), + sequence_lengths, + ) + + +def prepare_model_for_kbit_training(model, use_gradient_checkpointing=True, gradient_checkpointing_kwargs=None): + r""" + Prepare a k-bit quantized transformers model for training (PEFT/QLoRA). + """ + loaded_in_kbit = getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False) + quant_methods = ["gptq", "aqlm", "eetq", "torchao", "hqq"] + is_quantized = getattr(model, "quantization_method", None) in quant_methods or getattr( + model, "hqq_quantized", False + ) + + if gradient_checkpointing_kwargs is None: + gradient_checkpointing_kwargs = {} + + for _, param in model.named_parameters(): + # freeze all parameters + param.requires_grad = False + + # Enable gradient checkpointing if needed + if (loaded_in_kbit or is_quantized) and use_gradient_checkpointing: + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + # backward-compatible hook + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + supports_gc_kwargs = "gradient_checkpointing_kwargs" in list( + inspect.signature(model.gradient_checkpointing_enable).parameters + ) + gc_kwargs = {"gradient_checkpointing_kwargs": gradient_checkpointing_kwargs} if supports_gc_kwargs else {} + model.gradient_checkpointing_enable(**gc_kwargs) + + return model + + +def enable_gradient_checkpointing( + model: PreTrainedModel, gradient_checkpointing_kwargs: dict | None +) -> PreTrainedModel: + """Enables gradient checkpointing for the model.""" + # Enable gradient checkpointing on the base model for PEFT + if is_peft_model(model): + model.base_model.gradient_checkpointing_enable() + # Enable gradient checkpointing for non-PEFT models + else: + model.gradient_checkpointing_enable() + + gradient_checkpointing_kwargs = gradient_checkpointing_kwargs or {} + use_reentrant = ( + "use_reentrant" not in gradient_checkpointing_kwargs or gradient_checkpointing_kwargs["use_reentrant"] + ) + + if use_reentrant: + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + return model + + +def prepare_peft_model( + model: PreTrainedModel, peft_config: "PeftConfig | None", args: TrainingArguments +) -> PreTrainedModel: + """Prepares a model for PEFT training.""" + if not is_peft_available(): + raise ImportError("PEFT is required to use a peft model. Run `pip install peft`.") + + if isinstance(model, PeftModel) and peft_config is not None: + raise ValueError( + "You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first merge and " + "unload the existing adapter, save the resulting base model, and then pass that base model along with the " + "new `peft_config` to the trainer." + ) + + # Handle quantized models (QLoRA) + is_qlora = getattr(model, "is_loaded_in_4bit", False) or getattr(model, "is_loaded_in_8bit", False) + + is_sharded_qlora = False + if getattr(model, "is_loaded_in_4bit", False): + # Check if model is sharded (FSDP/DS-Zero3) + for _, param in model.named_parameters(): + if param.__class__.__name__ == "Params4bit": + is_sharded_qlora = param.data.device.type in {"cpu", "meta"} + break + + # Prepare model for kbit training if needed + if is_qlora and not is_sharded_qlora and not isinstance(model, PeftModel): + model = prepare_model_for_kbit_training( + model, + use_gradient_checkpointing=args.gradient_checkpointing, + gradient_checkpointing_kwargs=args.gradient_checkpointing_kwargs or {}, + ) + # Disable gradient checkpointing as it's handled by prepare_model_for_kbit_training + args.gradient_checkpointing = False + elif args.gradient_checkpointing: + model = enable_gradient_checkpointing(model, args.gradient_checkpointing_kwargs) + + # Create PEFT model + if peft_config is not None: + if ( + Version(peft.__version__) >= Version("0.12") # autocast_adapter_dtype introduced in 0.12 + and getattr(model, "is_loaded_in_4bit", False) + and is_sharded_qlora + ): + model = get_peft_model(model, peft_config, autocast_adapter_dtype=False) + else: + model = get_peft_model(model, peft_config) + + # Handle bf16 casting for 4-bit models + if args.bf16 and getattr(model, "is_loaded_in_4bit", False) and not is_sharded_qlora: + peft_module_casting_to_bf16(model) + + return model + + +def pad_to_length(tensor: torch.Tensor, length: int, pad_value: int | float, dim: int = -1) -> torch.Tensor: + if tensor.size(dim) >= length: + return tensor + else: + pad_size = list(tensor.shape) + pad_size[dim] = length - tensor.size(dim) + return torch.cat( + [ + tensor, + pad_value * torch.ones(*pad_size, dtype=tensor.dtype, device=tensor.device), + ], + dim=dim, + ) + + +def empty_cache() -> None: + """Empties the cache of the available torch device. + + This function checks for the availability of different torch devices (CUDA, MLU, MPS, NPU, XPU) and empties the + cache of the first available device it finds. + + If none of the specific devices are available, it defaults to emptying the CUDA cache. + """ + if is_torch_mlu_available(): + torch.mlu.empty_cache() + elif is_torch_mps_available(): + torch.mps.empty_cache() + elif is_torch_npu_available(): + torch.npu.empty_cache() + elif is_torch_xpu_available(): + torch.xpu.empty_cache() + else: + torch.cuda.empty_cache() + + +def peft_module_casting_to_bf16(model): + for name, module in model.named_modules(): + if isinstance(module, torch.nn.LayerNorm) or "norm" in name: + module = module.to(torch.float32) + elif any(x in name for x in ["lm_head", "embed_tokens", "wte", "wpe"]): + if hasattr(module, "weight"): + if module.weight.dtype == torch.float32: + module = module.to(torch.bfloat16) + + +LAYER_PATTERNS = [ + "transformer.h.{layer}", + "model.decoder.layers.{layer}", + "gpt_neox.layers.{layer}", + "model.layers.{layer}", +] + + +def create_reference_model( + model: nn.Module, num_shared_layers: int | None = None, pattern: str | None = None +) -> nn.Module: + """ + Creates a static reference copy of a model. Note that model will be in `.eval()` mode. + + Args: + model ([`nn.Module`]): The model to be copied. + num_shared_layers (`int`, *optional*): + The number of initial layers that are shared between both models and kept frozen. Shared layers reference + the same storage as the source model, so they are not duplicated in memory. + pattern (`str`, *optional*): The shared layers are selected with a string pattern + (e.g. "transformer.h.{layer}" for GPT2) and if a custom pattern is necessary it can be passed here. + + Returns: + [`nn.Module`] + """ + if is_deepspeed_zero3_enabled(): + raise ValueError( + "DeepSpeed ZeRO-3 is enabled and is not compatible with `create_reference_model()`. Please instantiate your reference model directly with `AutoModelForCausalLM.from_pretrained()`." + ) + + parameter_names = [n for n, _ in model.named_parameters()] + ref_model = deepcopy(model) + + # if no layers are shared, return copy of model + if num_shared_layers is None: + for param_name in parameter_names: + param = ref_model.get_parameter(param_name) + param.requires_grad = False + return ref_model.eval() + + # identify layer name pattern + if pattern is not None: + pattern = pattern.format(layer=num_shared_layers) + else: + for pattern_candidate in LAYER_PATTERNS: + pattern_candidate = pattern_candidate.format(layer=num_shared_layers) + if any(pattern_candidate in name for name in parameter_names): + pattern = pattern_candidate + break + + if pattern is None: + raise ValueError("Layer pattern could not be matched.") + + # divide parameters in shared and unshared parameter lists + shared_param_list = [] + unshared_param_list = [] + + shared_parameter = True + for name, _param in model.named_parameters(): + if pattern in name: + shared_parameter = False + if shared_parameter: + shared_param_list.append(name) + else: + unshared_param_list.append(name) + + # Freeze the shared layers in the source model, then point the reference parameter at the same + # storage instead of keeping the `deepcopy` duplicate. The shared (frozen) layers are thus held in + # memory only once; because they are frozen in the model, the reference stays static during training. + for param_name in shared_param_list: + param = model.get_parameter(param_name) + param.requires_grad = False + + ref_param = ref_model.get_parameter(param_name) + ref_param.data = param.data + ref_param.requires_grad = False + + # for all other parameters just make sure they don't use gradients + for param_name in unshared_param_list: + param = ref_model.get_parameter(param_name) + param.requires_grad = False + + if pattern is not None and len(unshared_param_list) == 0: + logging.warning("Pattern passed or found, but no layers matched in the model. Check for a typo.") + + return ref_model.eval() + + +def truncate_dataset( + dataset: DatasetType, + max_length: int, + map_kwargs: dict[str, Any] | None = None, +) -> DatasetType: + r""" + Truncate sequences in a dataset to a specified `max_length`. + + Args: + dataset ([`~datasets.Dataset`] or [`~datasets.DatasetDict`]): + Dataset to truncate. + max_length (`int`): + Maximum sequence length to truncate to. + map_kwargs (`dict`, *optional*): + Additional keyword arguments to pass to the dataset's map method when truncating examples. + + Returns: + [`~datasets.Dataset`] or [`~datasets.DatasetDict`]: The dataset with truncated sequences. + + Example: + ```python + >>> from datasets import Dataset + + >>> examples = { + ... "input_ids": [[1, 2, 3], [4, 5, 6, 7], [8]], + ... "attention_mask": [[0, 1, 1], [0, 0, 1, 1], [1]], + ... } + >>> dataset = Dataset.from_dict(examples) + >>> truncated_dataset = truncate_dataset(dataset, max_length=2) + >>> truncated_dataset[:] + {'input_ids': [[1, 2], [4, 5], [8]], + 'attention_mask': [[0, 1], [0, 0], [1]]} + ``` + """ + if map_kwargs is None: + map_kwargs = {} + + def truncate(examples): + truncated_columns = [] + for column in examples.columns: + if pyarrow.types.is_list(column.type) or pyarrow.types.is_large_list(column.type): + column = pc.list_slice(column, 0, max_length) + truncated_columns.append(column) + return pa.Table.from_arrays(truncated_columns, names=examples.column_names) + + format = _get_dataset_format(dataset) + dataset = dataset.with_format("arrow") + dataset = dataset.map(truncate, batched=True, **map_kwargs) + dataset = dataset.with_format(**format) + return dataset diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/xpo/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/xpo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2fc35384cd4246001ac14d1bd126430cce00b122 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/xpo/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .xpo_config import XPOConfig +from .xpo_trainer import XPOTrainer + + +__all__ = ["XPOConfig", "XPOTrainer"] diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/xpo/xpo_config.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/xpo/xpo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..243545084617bdc8f384289cb76883d22fcfaf54 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/xpo/xpo_config.py @@ -0,0 +1,44 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field + +from ..online_dpo import OnlineDPOConfig + + +@dataclass +class XPOConfig(OnlineDPOConfig): + r""" + Configuration class for the [`experimental.xpo.XPOTrainer`]. + + Subclass of [`experimental.online_dpo.OnlineDPOConfig`] we can use all its arguments and add the following: + + Parameters: + alpha (`float` or `list[float]`, *optional*, defaults to `1e-5`): + Weight of the XPO loss term. If a list of floats is provided then the alpha is selected for each new epoch + and the last alpha is used for the rest of the epochs. + """ + + alpha: list[float] = field( + default_factory=lambda: [1e-5], + metadata={ + "help": "Weight of the XPO loss term. If a list of floats is provided then the alpha is selected for each " + "new epoch and the last alpha is used for the rest of the epochs." + }, + ) + + def __post_init__(self): + super().__post_init__() + if hasattr(self.alpha, "__len__") and len(self.alpha) == 1: + self.alpha = self.alpha[0] diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/xpo/xpo_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/xpo/xpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..5edbbc3dc2022802816fba8ea8b52f486745d3a1 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/experimental/xpo/xpo_trainer.py @@ -0,0 +1,506 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import textwrap +from collections.abc import Callable +from typing import Any + +import torch +import torch.nn as nn +import torch.nn.functional as F +from datasets import Dataset, IterableDataset +from transformers import ( + BaseImageProcessor, + FeatureExtractionMixin, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, +) +from transformers.trainer_utils import EvalPrediction +from transformers.training_args import OptimizerNames +from transformers.utils import is_peft_available + +from ...data_utils import maybe_apply_chat_template +from ...models.utils import unwrap_model_for_generation +from ...trainer.utils import selective_log_softmax +from ..online_dpo import OnlineDPOTrainer +from ..utils import empty_cache, get_reward, truncate_right +from .xpo_config import XPOConfig + + +if is_peft_available(): + from peft import PeftConfig, PeftModel + + +class XPOTrainer(OnlineDPOTrainer): + """ + Trainer for Exploratory Preference Optimization (XPO). + + It is implemented as a subclass of [`experimental.online_dpo.OnlineDPOTrainer`]. + + Args: + model ([`~transformers.PreTrainedModel`]): + The model to train, preferably an `AutoModelForCausalLM`. + ref_model ([`~transformers.PreTrainedModel`]): + Hugging Face transformer model with a casual language modelling head. Used for implicit reward computation + and loss. If no reference model is provided, the trainer will create a reference model with the same + architecture as the model to be optimized. + reward_funcs ([`~transformers.PreTrainedModel`]): + The reward model to score completions with, preferably an + [`~transformers.AutoModelForSequenceClassification`]. + args ([`experimental.xpo.XPOConfig`]): + The XPO config arguments to use for training. + data_collator ([`~transformers.DataCollator`]): + The data collator to use for training. If None is specified, the default data collator + ([`experimental.utils.DPODataCollatorWithPadding`]) will be used which will pad the sequences to the + maximum length of the sequences in the batch, given a dataset of paired sequences. + train_dataset ([`~datasets.Dataset`]): + The dataset to use for training. + eval_dataset ([`~datasets.Dataset`]): + The dataset to use for evaluation. + processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*): + Processing class used to process the data. If provided, will be used to automatically process the inputs + for the model, and it will be saved along the model to make it easier to rerun an interrupted training or + reuse the fine-tuned model. + reward_processing_classes ([`~transformers.PreTrainedTokenizerBase`] or `list[PreTrainedTokenizerBase]`, *optional*): + Processing classes corresponding to the reward functions specified in `reward_funcs`. Can be either: + + - A single processing class: Used when `reward_funcs` contains only one reward function. + - A list of processing classes: Must match the order and length of the reward functions in `reward_funcs`. + + If set to `None`, the tokenizer for each model-based reward function is automatically loaded using + [`~transformers.AutoTokenizer.from_pretrained`]. + peft_config ([`~peft.PeftConfig`], *optional*): + The peft config to use for training. + compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*): + The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to + metric values. + callbacks (`list[transformers.TrainerCallback]`): + The callbacks to use for training. + optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`): + The optimizer and scheduler to use for training. + preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`): + The function to use to preprocess the logits before computing the metrics. + """ + + _tag_names = ["trl", "xpo"] + _name = "XPO" + _paper = { + "title": "Exploratory Preference Optimization: Harnessing Implicit Q*-Approximation for Sample-Efficient RLHF", + "id": "2405.21046", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @article{jung2024binary, + title = {{Exploratory Preference Optimization: Harnessing Implicit Q*-Approximation for Sample-Efficient RLHF}}, + author = {Tengyang Xie and Dylan J. Foster and Akshay Krishnamurthy and Corby Rosset and Ahmed Awadallah and Alexander Rakhlin}, + year = 2024, + eprint = {arXiv:2405.21046} + }"""), + } + + def __init__( + self, + model: PreTrainedModel | nn.Module = None, + ref_model: PreTrainedModel | nn.Module = None, + reward_funcs: nn.Module | None = None, + args: XPOConfig | None = None, + data_collator: Callable | None = None, + train_dataset: Dataset | IterableDataset | None = None, + eval_dataset: Dataset | dict[str, Dataset] | None = None, + processing_class: PreTrainedTokenizerBase + | BaseImageProcessor + | FeatureExtractionMixin + | ProcessorMixin + | None = None, + reward_processing_classes: PreTrainedTokenizerBase | list[PreTrainedTokenizerBase] | None = None, + peft_config: "PeftConfig | None" = None, + compute_metrics: Callable[[EvalPrediction], dict] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None, + ) -> None: + super().__init__( + model=model, + ref_model=ref_model, + reward_funcs=reward_funcs, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + reward_processing_classes=reward_processing_classes, + peft_config=peft_config, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + ) + + self._alpha = self.args.alpha + + # Overwrite the stats dictionary to include XPO specific statistics + self.stats = { + # Remove "non_score_reward", "rlhf_reward", "scores" + # Add "loss/dpo", "loss/xpo" + "loss/dpo": [], + "loss/xpo": [], + "objective/kl": [], + "objective/entropy": [], + "rewards/chosen": [], + "rewards/rejected": [], + "rewards/accuracies": [], + "rewards/margins": [], + "logps/chosen": [], + "logps/rejected": [], + # Replace "contain_eos_token" by "model_contain_eos_token" and "ref_contain_eos_token" + "val/model_contain_eos_token": [], + "val/ref_contain_eos_token": [], + "objective/model_scores": [], + "objective/ref_scores": [], + "objective/scores_margin": [], + "alpha": [], + "beta": [], + } + if len(self.reward_funcs) != 1: + raise ValueError("XPOTrainer only supports one reward function/model.") + self.reward_funcs = self.reward_funcs[0] + + @property + def alpha(self): + if isinstance(self._alpha, list): + epoch = self.state.epoch + return self._alpha[epoch] if epoch < len(self._alpha) else self._alpha[-1] + else: + return self._alpha + + def _generate_completions(self, prompts, model): + with ( + unwrap_model_for_generation( + model, + self.accelerator, + generation_kwargs=self.generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762 + ) as unwrapped_policy_model_for_gen, + ): + model_output = unwrapped_policy_model_for_gen.generate( + input_ids=prompts["input_ids"], + attention_mask=prompts["attention_mask"], + generation_config=self.generation_config, + ) + + actual_model_for_ref_generation: torch.nn.Module + if self.ref_model is None: + unwrapped_main_model_for_ref_logic = self.accelerator.unwrap_model(model) + + if is_peft_available() and isinstance(unwrapped_main_model_for_ref_logic, PeftModel): + actual_model_for_ref_generation = unwrapped_main_model_for_ref_logic.get_base_model() + else: + actual_model_for_ref_generation = unwrapped_main_model_for_ref_logic + else: + actual_model_for_ref_generation = self.accelerator.unwrap_model(self.ref_model) + + with ( + unwrap_model_for_generation( + actual_model_for_ref_generation, + self.accelerator, + generation_kwargs=self.generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762 + ) as final_ref_model_for_gen, + ): + ref_output = final_ref_model_for_gen.generate( + input_ids=prompts["input_ids"], + attention_mask=prompts["attention_mask"], + generation_config=self.generation_config, + ) + + return model_output, ref_output + + def _process_completions(self, model_output, ref_output, prompts): + context_length = prompts["input_ids"].shape[1] + + # Process model completions + model_completion_ids = model_output[:, context_length:] + model_completion_ids, model_completion_mask = truncate_right( + model_completion_ids, self.processing_class.eos_token_id, self.processing_class.pad_token_id + ) + model_data = { + "input_ids": torch.cat((prompts["input_ids"], model_completion_ids), dim=1), + "attention_mask": torch.cat((prompts["attention_mask"], model_completion_mask), dim=1), + "raw": prompts["raw"], + } + + # Process reference model completions + ref_completion_ids = ref_output[:, context_length:] + ref_completion_ids, ref_completion_mask = truncate_right( + ref_completion_ids, self.processing_class.eos_token_id, self.processing_class.pad_token_id + ) + ref_data = { + "input_ids": torch.cat((prompts["input_ids"], ref_completion_ids), dim=1), + "attention_mask": torch.cat((prompts["attention_mask"], ref_completion_mask), dim=1), + "raw": prompts["raw"], + } + + return model_data, ref_data + + def _compute_rewards(self, model_data, ref_data, context_length): + with torch.no_grad(): + _, model_scores, _ = get_reward( + self.reward_funcs, model_data["input_ids"], self.processing_class.pad_token_id, context_length + ) + _, ref_scores, _ = get_reward( + self.reward_funcs, ref_data["input_ids"], self.processing_class.pad_token_id, context_length + ) + + # Apply EOS penalty if needed + if self.args.missing_eos_penalty is not None: + model_contain_eos = torch.any(model_data["input_ids"] == self.processing_class.eos_token_id, dim=-1) + ref_contain_eos = torch.any(ref_data["input_ids"] == self.processing_class.eos_token_id, dim=-1) + model_scores[~model_contain_eos] -= self.args.missing_eos_penalty + ref_scores[~ref_contain_eos] -= self.args.missing_eos_penalty + + return model_scores, ref_scores + + def _compute_logprobs(self, model, model_data, ref_data, context_length): + def compute_logprobs_for_data(m, data): + output = m(data["input_ids"], attention_mask=data["attention_mask"]) + logits = output.logits[:, context_length - 1 : -1] + token_logprobs = selective_log_softmax(logits, data["input_ids"][:, context_length:]) + return token_logprobs + + # Compute logprobs for model completions + model_logprobs_model_data = compute_logprobs_for_data(model, model_data) + # Compute logprobs for model on reference completions (for XPO loss) + model_logprobs_ref_data = compute_logprobs_for_data(model, ref_data) + + # Compute logprobs for reference model completions + with torch.no_grad(): + if self.ref_model is None: + with model.disable_adapter(): + ref_logprobs_model_data = compute_logprobs_for_data(model, model_data) + ref_logprobs_ref_data = compute_logprobs_for_data(model, ref_data) + else: + ref_logprobs_model_data = compute_logprobs_for_data(self.ref_model, model_data) + ref_logprobs_ref_data = compute_logprobs_for_data(self.ref_model, ref_data) + + # Mask padding tokens + model_padding_mask = model_data["attention_mask"][:, context_length:] == 0 + ref_padding_mask = ref_data["attention_mask"][:, context_length:] == 0 + model_logprobs_model_data = model_logprobs_model_data.masked_fill(model_padding_mask, 0.0) + model_logprobs_ref_data = model_logprobs_ref_data.masked_fill(ref_padding_mask, 0.0) + ref_logprobs_ref_data = ref_logprobs_ref_data.masked_fill(ref_padding_mask, 0.0) + ref_logprobs_model_data = ref_logprobs_model_data.masked_fill(model_padding_mask, 0.0) + + return model_logprobs_model_data, model_logprobs_ref_data, ref_logprobs_ref_data, ref_logprobs_model_data + + def _compute_losses( + self, + model_logprobs_model_data, + model_logprobs_ref_data, + ref_logprobs_ref_data, + ref_logprobs_model_data, + chosen_mask, + ): + # Compute log probs + model_logprobs_model_data_sum = model_logprobs_model_data.sum(1) + model_logprobs_ref_data_sum = model_logprobs_ref_data.sum(1) + ref_logprobs_ref_data_sum = ref_logprobs_ref_data.sum(1) + ref_logprobs_model_data_sum = ref_logprobs_model_data.sum(1) + + chosen_model_logprobs = torch.where(chosen_mask, model_logprobs_model_data_sum, model_logprobs_ref_data_sum) + chosen_ref_logprobs = torch.where(chosen_mask, ref_logprobs_model_data_sum, ref_logprobs_ref_data_sum) + chosen_log_ratios = chosen_model_logprobs - chosen_ref_logprobs + + rejected_model_logprobs = torch.where(~chosen_mask, model_logprobs_model_data_sum, model_logprobs_ref_data_sum) + rejected_ref_logprobs = torch.where(~chosen_mask, ref_logprobs_model_data_sum, ref_logprobs_ref_data_sum) + rejected_log_ratios = rejected_model_logprobs - rejected_ref_logprobs + + # Compute logits as the difference between chosen and rejected log ratios + logits = chosen_log_ratios - rejected_log_ratios + + if self.args.loss_type == "sigmoid": + dpo_losses = -F.logsigmoid(self.beta * logits) + elif self.args.loss_type == "ipo": + dpo_losses = (logits - 1 / (2 * self.beta)) ** 2 + else: + raise NotImplementedError(f"invalid loss type {self.args.loss_type}") + + # Compute XPO specific loss + xpo_losses = self.alpha * model_logprobs_ref_data_sum + + # Total loss + loss = (dpo_losses + xpo_losses).mean() + + return loss, dpo_losses, xpo_losses + + def _log_statistics( + self, + model_data, + ref_data, + model_logprobs_model_data, + model_logprobs_ref_data, + ref_logprobs_ref_data, + ref_logprobs_model_data, + chosen_mask, + dpo_losses, + xpo_losses, + context_length, + model_scores, + ref_scores, + ): + # Helper function to gather and compute mean + def gather_mean(tensor): + return self.accelerator.gather_for_metrics(tensor).mean().item() + + # Log losses + self.stats["loss/dpo"].append(gather_mean(dpo_losses)) + self.stats["loss/xpo"].append(gather_mean(xpo_losses)) + + # Log scores + self.stats["objective/model_scores"].append(gather_mean(model_scores)) + self.stats["objective/ref_scores"].append(gather_mean(ref_scores)) + self.stats["objective/scores_margin"].append(gather_mean(model_scores - ref_scores)) + + # Log logprobs + model_logprobs_model_data_sum = model_logprobs_model_data.sum(1) + model_logprobs_ref_data_sum = model_logprobs_ref_data.sum(1) + ref_logprobs_ref_data_sum = ref_logprobs_ref_data.sum(1) + ref_logprobs_model_data_sum = ref_logprobs_model_data.sum(1) + + chosen_model_logprobs = torch.where(chosen_mask, model_logprobs_model_data_sum, model_logprobs_ref_data_sum) + chosen_ref_logprobs = torch.where(chosen_mask, ref_logprobs_model_data_sum, ref_logprobs_ref_data_sum) + chosen_log_ratios = chosen_model_logprobs - chosen_ref_logprobs + + rejected_model_logprobs = torch.where(~chosen_mask, model_logprobs_model_data_sum, model_logprobs_ref_data_sum) + rejected_ref_logprobs = torch.where(~chosen_mask, ref_logprobs_model_data_sum, ref_logprobs_ref_data_sum) + rejected_log_ratios = rejected_model_logprobs - rejected_ref_logprobs + + self.stats["logps/chosen"].append(gather_mean(chosen_model_logprobs.mean() + chosen_ref_logprobs.mean())) + self.stats["logps/rejected"].append(gather_mean(rejected_model_logprobs.mean() + rejected_ref_logprobs.mean())) + + # Log rewards + # Compute various statistics + chosen_rewards = chosen_log_ratios * self.beta + rejected_rewards = rejected_log_ratios * self.beta + self.stats["rewards/chosen"].append(gather_mean(chosen_rewards.mean())) + self.stats["rewards/rejected"].append(gather_mean(rejected_rewards.mean())) + + # Calculate KL divergence for model and ref data + kl_model_data = model_logprobs_model_data - ref_logprobs_model_data + kl_ref_data = model_logprobs_ref_data - ref_logprobs_ref_data + mean_kl = (kl_model_data.sum(1) + kl_ref_data.sum(1)).mean() / 2 + self.stats["objective/kl"].append(gather_mean(mean_kl)) + + # Calculate entropy for model and ref data + entropy_model_data = -model_logprobs_model_data.sum(1) + entropy_ref_data = -model_logprobs_ref_data.sum(1) + mean_entropy = (entropy_model_data.mean() + entropy_ref_data.mean()) / 2 + self.stats["objective/entropy"].append(gather_mean(mean_entropy)) + + # Calculate margins + margin = chosen_rewards - rejected_rewards + self.stats["rewards/margins"].append(gather_mean(margin.mean())) + + # Calculate accuracy + accuracy = (margin > 0).float() + self.stats["rewards/accuracies"].append(gather_mean(accuracy.mean())) + + # Log EOS token statistics + model_eos = (model_data["input_ids"][:, context_length:] == self.processing_class.eos_token_id).any(dim=1) + ref_eos = (ref_data["input_ids"][:, context_length:] == self.processing_class.eos_token_id).any(dim=1) + self.stats["val/model_contain_eos_token"].append(gather_mean(model_eos.float())) + self.stats["val/ref_contain_eos_token"].append(gather_mean(ref_eos.float())) + + # Log alpha and beta + self.stats["alpha"].append(self.alpha) + self.stats["beta"].append(self.beta) + + def training_step( + self, model: nn.Module, inputs: dict[str, torch.Tensor | Any], num_items_in_batch: int | None = None + ) -> torch.Tensor: + model.train() + + # Apply chat template and tokenize the input + batch_size = len(next(iter(inputs.values()))) + prompts = inputs["prompt"] + inputs = [{k: v[i] for k, v in inputs.items()} for i in range(batch_size)] + inputs = [maybe_apply_chat_template(x, self.processing_class) for x in inputs] + inputs = [self.tokenize_row(x, self.model.config.is_encoder_decoder, self.processing_class) for x in inputs] + inputs = self.data_collator(inputs) + + # need the prompt_ only + inputs = self._prepare_inputs(inputs) + context_length = inputs["prompt_input_ids"].shape[1] + prompts = { + "input_ids": inputs["prompt_input_ids"], + "attention_mask": inputs["prompt_attention_mask"], + "raw": prompts, + } + del inputs + + # Sample completions from both the model and the reference model + model_output, ref_output = self._generate_completions(prompts, model) + + # Process model completions + model_data, ref_data = self._process_completions(model_output, ref_output, prompts) + + # Compute rewards + model_scores, ref_scores = self._compute_rewards(model_data, ref_data, context_length) + chosen_mask = model_scores >= ref_scores + + # Compute logprobs + model_logprobs_model_data, model_logprobs_ref_data, ref_logprobs_ref_data, ref_logprobs_model_data = ( + self._compute_logprobs(model, model_data, ref_data, context_length) + ) + + # Compute loss + loss, dpo_losses, xpo_losses = self._compute_losses( + model_logprobs_model_data, + model_logprobs_ref_data, + ref_logprobs_ref_data, + ref_logprobs_model_data, + chosen_mask, + ) + + # Log everything + self._log_statistics( + model_data, + ref_data, + model_logprobs_model_data.detach(), + model_logprobs_ref_data.detach(), + ref_logprobs_ref_data, + ref_logprobs_model_data, + chosen_mask, + dpo_losses.detach(), + xpo_losses.detach(), + context_length, + model_scores, + ref_scores, + ) + + if ( + self.args.torch_empty_cache_steps is not None + and self.state.global_step % self.args.torch_empty_cache_steps == 0 + ): + empty_cache() + + kwargs = {} + # For LOMO optimizers you need to explicitly use the learning rate + if self.args.optim in [OptimizerNames.LOMO, OptimizerNames.ADALOMO]: + kwargs["learning_rate"] = self._get_learning_rate() + + if self.args.n_gpu > 1: + loss = loss.mean() # mean() to average on multi-gpu parallel training + + self.accelerator.backward(loss, **kwargs) + + return loss.detach() / self.args.gradient_accumulation_steps diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/extras/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/extras/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d2777dd0eb21a0ea67dce8775337a27ea8499da2 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/extras/__init__.py @@ -0,0 +1,13 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/extras/dataset_formatting.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/extras/dataset_formatting.py new file mode 100644 index 0000000000000000000000000000000000000000..6dd89493a33263bda1506f67f661947ac69a3690 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/extras/dataset_formatting.py @@ -0,0 +1,32 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import datasets +from datasets import Value +from packaging.version import Version + + +if Version(datasets.__version__) >= Version("4.0.0"): + from datasets import List + + FORMAT_MAPPING = { + "chatml": List({"content": Value(dtype="string", id=None), "role": Value(dtype="string", id=None)}), + "instruction": {"completion": Value(dtype="string", id=None), "prompt": Value(dtype="string", id=None)}, + } +else: + FORMAT_MAPPING = { + "chatml": [{"content": Value(dtype="string", id=None), "role": Value(dtype="string", id=None)}], + "instruction": {"completion": Value(dtype="string", id=None), "prompt": Value(dtype="string", id=None)}, + } diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/extras/profiling.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/extras/profiling.py new file mode 100644 index 0000000000000000000000000000000000000000..01a7b62212cfa141ebccd145e722430ce5590c61 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/extras/profiling.py @@ -0,0 +1,224 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import functools +import time +from collections.abc import Callable + +from transformers import Trainer +from transformers.integrations import is_mlflow_available, is_trackio_available, is_wandb_available + + +if is_wandb_available(): + import wandb + +if is_mlflow_available(): + import mlflow + +if is_trackio_available(): + import trackio + + +class ProfilingContext: + """ + Context manager for profiling code blocks with configurable logging. + + This class handles timing of code execution and logging metrics to various backends (Weights & Biases, MLflow, + Trackio) without being coupled to the Trainer class. + + Args: + name (`str`): + Name of the profiling context. Used in the metric name. + report_to (`list` of `str`): + List of integrations to report metrics to (e.g., ["wandb", "mlflow", "trackio"]). + is_main_process (`bool`, *optional*, defaults to `True`): + Whether this is the main process in distributed training. Metrics are only logged from the main process. + step (`int` or `None`, *optional*): + Training step to associate with the logged metrics. + metric_prefix (`str`, *optional*, defaults to `"profiling/Time taken"`): + Prefix for the metric name in logs. + + Example: + ```python + # Direct usage + from trl.extras.profiling import ProfilingContext + + with ProfilingContext( + name="MyClass.expensive_operation", + report_to=["wandb"], + is_main_process=True, + step=100, + ): + # Code to profile + result = expensive_computation() + + # With Trainer (backwards compatible via profiling_context function) + from transformers import Trainer + from trl.extras.profiling import profiling_context + + + class MyTrainer(Trainer): + def some_method(self): + with profiling_context(self, "matrix_multiplication"): + result = matrix_multiply() + ``` + """ + + def __init__( + self, + name: str, + report_to: list[str], + is_main_process: bool = True, + step: int | None = None, + metric_prefix: str = "profiling/Time taken", + ): + self.name = name + self.report_to = report_to + self.is_main_process = is_main_process + self.step = step + self.metric_prefix = metric_prefix + self._start_time = None + + def __enter__(self): + """Start timing when entering the context.""" + self._start_time = time.perf_counter() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + """Stop timing and log metrics when exiting the context.""" + if self._start_time is not None: + duration = time.perf_counter() - self._start_time + self._log_metrics(duration) + return False + + def _log_metrics(self, duration: float) -> None: + """ + Log profiling metrics to configured backends. + + Args: + duration (`float`): + Execution time in seconds. + """ + if not self.is_main_process: + return + + metric_name = f"{self.metric_prefix}: {self.name}" + metrics = {metric_name: duration} + + # Log to Weights & Biases if configured + if "wandb" in self.report_to and is_wandb_available() and wandb.run is not None: + wandb.log(metrics) + + # Log to MLflow if configured + if "mlflow" in self.report_to and is_mlflow_available() and mlflow.active_run() is not None: + mlflow.log_metrics(metrics, step=self.step) + + # Log to Trackio if configured + if "trackio" in self.report_to and is_trackio_available(): + trackio.log(metrics, step=self.step) + + +def profiling_context(trainer: Trainer, name: str) -> ProfilingContext: + """ + Factory function to create a ProfilingContext from a Trainer instance. + + This function maintains backwards compatibility with existing code while using the decoupled ProfilingContext class + internally. + + Args: + trainer (`~transformers.Trainer`): + Trainer object containing configuration for logging. + name (`str`): + Name of the block to be profiled. Will be prefixed with the trainer class name. + + Returns: + `ProfilingContext`: A configured profiling context manager. + + Example: + ```python + from transformers import Trainer + from trl.extras.profiling import profiling_context + + + class MyTrainer(Trainer): + def some_method(self): + A = np.random.rand(1000, 1000) + B = np.random.rand(1000, 1000) + with profiling_context(self, "matrix_multiplication"): + # Code to profile: simulate a computationally expensive operation + result = A @ B # Matrix multiplication + ``` + """ + context_name = f"{trainer.__class__.__name__}.{name}" + step = trainer.state.global_step + + return ProfilingContext( + name=context_name, + report_to=trainer.args.report_to, + is_main_process=trainer.accelerator.is_main_process, + step=step, + ) + + +def profiling_decorator(func: Callable) -> Callable: + """ + Decorator to profile a function and log execution time using [`extras.profiling.profiling_context`]. + + This decorator works with methods that have access to a trainer instance (typically as `self`). For non-Trainer + objects that have an `accelerator` attribute, it will use that for logging configuration. + + Args: + func (`Callable`): + Function to be profiled. + + Returns: + `Callable`: Wrapped function that profiles execution time. + + Example: + ```python + from transformers import Trainer + from trl.extras.profiling import profiling_decorator + + + class MyTrainer(Trainer): + @profiling_decorator + def some_method(self): + A = np.random.rand(1000, 1000) + B = np.random.rand(1000, 1000) + # Code to profile: simulate a computationally expensive operation + result = A @ B + ``` + """ + + @functools.wraps(func) + def wrapper(self, *args, **kwargs): + # Check if self is a Trainer-like object with required attributes + if hasattr(self, "state") and hasattr(self, "args"): + with profiling_context(self, func.__name__): + return func(self, *args, **kwargs) + # For non-Trainer objects (e.g., VLLMGeneration), use ProfilingContext directly + elif hasattr(self, "accelerator"): + context_name = f"{self.__class__.__name__}.{func.__name__}" + with ProfilingContext( + name=context_name, + report_to=[], # No reporting for non-Trainer objects without args + is_main_process=self.accelerator.is_main_process, + step=None, + ): + return func(self, *args, **kwargs) + else: + # No profiling available, just run the function + return func(self, *args, **kwargs) + + return wrapper diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/generation/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/generation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..22e7cf6d88463c5b6774725e2b66ee1496bddd22 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/generation/__init__.py @@ -0,0 +1,25 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Generation backends for TRL trainers.""" + +from ..import_utils import is_vllm_available + + +__all__ = [] + +if is_vllm_available(): + from .vllm_generation import VLLMGeneration + + __all__.append("VLLMGeneration") diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/generation/vllm_client.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/generation/vllm_client.py new file mode 100644 index 0000000000000000000000000000000000000000..cb05ae5a551365f76b97f0edd54337bc976c57a3 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/generation/vllm_client.py @@ -0,0 +1,764 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import atexit +import base64 +import copy +import logging +import socket +import time +from io import BytesIO +from urllib.parse import urlparse + +import torch +import torch.distributed.distributed_c10d as c10d +from requests.adapters import HTTPAdapter +from torch import nn +from transformers import is_torch_xpu_available +from transformers.utils import get_json_schema +from urllib3.util.retry import Retry + +from ..import_utils import is_requests_available, is_vllm_ascend_available, is_vllm_available + + +if is_requests_available(): + import requests + from requests import ConnectionError + + +if is_vllm_available(): + from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator + from vllm.distributed.utils import StatelessProcessGroup + + if is_vllm_ascend_available(): + from vllm_ascend.distributed.device_communicators.pyhccl import PyHcclCommunicator as PyNcclCommunicator + + +logger = logging.getLogger(__name__) + + +def pil_to_base64(image): + buffer = BytesIO() + image.save(buffer, format="PNG") + img_bytes = buffer.getvalue() + return base64.b64encode(img_bytes).decode("utf-8") + + +class VLLMClient: + """ + A client class to interact with a vLLM server. + + This class provides methods to generate completions, initialize and manage weight update groups, and update model + weights in a distributed setting. Before using it, start the vLLM server with `trl vllm-serve`. + + Args: + base_url (`str`, *optional*): + Base URL for the vLLM server (e.g., `"http://localhost:8000"`). If provided, `host` and `server_port` are + ignored. + host (`str`, *optional*, defaults to `"0.0.0.0"`): + IP address of the vLLM server. Ignored if `base_url` is provided. + server_port (`int`, *optional*, defaults to `8000`): + Port number of the vLLM server. Ignored if `base_url` is provided. + group_port (`int`, *optional*, defaults to `51216`): + Port number for the weight update group. + connection_timeout (`float`, *optional*, defaults to `0.0`): + Total timeout duration in seconds to wait for the server to be up. If the server is not up after the + timeout, a `ConnectionError` is raised. + + Examples: + Run the vLLM server with the model `Qwen/Qwen2.5-7B`: + + ``` + $ trl vllm-serve --model Qwen/Qwen2.5-7B + ... + INFO: Application startup complete. + INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit) + ``` + + Use the client to generate completions and update model weights: + + ```python + >>> from trl.generation.vllm_client import VLLMClient + + >>> client = VLLMClient() + >>> client.generate(["Hello, AI!", "Tell me a joke"]) + {'prompt_ids': [[9707, 11, 15235, 0], + [40451, 752, 264, 21646]], + 'completion_ids': [[2980, 498, 1492, 752, 448, 264, 13027, 8645, 30, 358, 2776, 4460, 311, 3270, 264, 2025], + [911, 98072, 2142, 624, 45, 51426, 2142, 374, 279, 16396, 429, 4302, 702, 36988, 7290, 476]], + 'logprobs': [[[-1.6612], [-0.0081], [-1.5189], [-0.0123], [-1.2045], [-0.6227], [-2.9791], [-2.8387], [-0.1267], [-0.0366], [-2.6528], [-0.3197], [-0.0001], [-1.8174], [-0.0251], [-1.473]], + [[-0.018], [-10.7331], [-0.1605], [-0.891], [-3.7945], [-0.0127], [-0.3073], [-1.1648], [-1.8025], [-0.409], [-0.0256], [-1.6127], [-2.2935], [-4.1785], [-0.6531], [-0.2629]]], + 'logprob_token_ids': [[[2980], [498], [1492], [752], [448], [264], [13027], [8645], [30], [358], [2776], [4460], [311], [3270], [264], [2025]], + [[911], [98072], [2142], [624], [45], [51426], [2142], [374], [279], [16396], [429], [4302], [702], [36988], [7290], [476]]]} + + >>> from transformers import AutoModelForCausalLM + + >>> model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-7B", device_map="cuda") + >>> client.init_communicator(device="cuda") + >>> client.update_model_params(model) + ``` + + There are several ways to initialize the client: + + ```python + VLLMClient(base_url="http://localhost:8000") + VLLMClient(base_url="http://192.168.1.100:8000") + VLLMClient(host="localhost", server_port=8000) + VLLMClient(host="192.168.1.100", server_port=8000) + ``` + """ + + def __init__( + self, + base_url: str | None = None, + host: str = "0.0.0.0", + server_port: int = 8000, + group_port: int = 51216, + connection_timeout: float = 0.0, + ): + if not is_requests_available(): + raise ImportError("requests is not installed. Please install it with `pip install requests`.") + if not is_vllm_available(): + raise ImportError("vLLM is not installed. Please install it with `pip install trl[vllm]`.") + + self.session = requests.Session() + + # Configure retries for HTTP requests made through this session. + # This is not strictly required for correctness, but it helps make training more robust to rare, transient + # failures (network hiccups, temporary 5xx errors, overloaded servers). Without this, such failures could cause + # an otherwise healthy training run to fail. + retry_strategy = Retry( + total=5, # global cap on the total number of retries across all failure types + connect=5, # retry connection-level failures (DNS issues, refused connections, etc) + read=5, # retry failures while reading the response after the connection was successfully established + status=3, # retry a limited number of times when we receive certain HTTP error responses from the server + status_forcelist=[500, 502, 503], # only retry on server-side errors that are usually temporary + backoff_factor=2, # exponential backoff between retries (2s, 4s, 8s, ...) + allowed_methods=["POST", "GET"], # allow POST as well, even though we're not sure it's safe here + ) + + adapter = HTTPAdapter(max_retries=retry_strategy) + self.session.mount("http://", adapter) + self.session.mount("https://", adapter) + + if base_url is not None: + # Parse the base_url to extract host and port + parsed_url = urlparse(base_url) + self.host = socket.gethostbyname(parsed_url.hostname) + scheme = parsed_url.scheme or "http" + self.base_url = f"{scheme}://{parsed_url.netloc}{parsed_url.path}" + else: + self.host = host + self.server_port = server_port + self.base_url = f"http://{self.host}:{self.server_port}" + self.group_port = group_port + self.check_server(connection_timeout) # check server and fail after timeout + + def check_server(self, total_timeout: float = 0.0, retry_interval: float = 2.0): + """ + Check server availability with retries on failure, within a total timeout duration. If the server is not up + after the total timeout duration, raise a `ConnectionError`. + + Args: + retry_interval (`float`, *optional*, defaults to `2.0`): + Interval in seconds between retries. + total_timeout (`float`, *optional*, defaults to `0.0`): + Total timeout duration in seconds. + """ + url = f"{self.base_url}/health/" + start_time = time.time() # Record the start time + + while True: + try: + response = requests.get(url) + except requests.exceptions.RequestException as exc: + # Check if the total timeout duration has passed + elapsed_time = time.time() - start_time + if elapsed_time >= total_timeout: + raise ConnectionError( + f"The vLLM server can't be reached at {self.base_url} after {total_timeout} seconds. Make " + "sure the server is running by running `trl vllm-serve`." + ) from exc + else: + if response.status_code == 200: + if "X-Forwarded-For" in response.headers: + self.host = response.headers["X-Forwarded-For"] + logger.info("Server is up!") + return None + + # Retry logic: wait before trying again + logger.info(f"Server is not up yet. Retrying in {retry_interval} seconds...") + time.sleep(retry_interval) + + def generate( + self, + prompts: list[str] | list[list[int]], + images: list | None = None, + n: int = 1, + repetition_penalty: float = 1.0, + temperature: float = 1.0, + top_p: float = 1.0, + top_k: int = 0, + min_p: float = 0.0, + max_tokens: int = 16, + logprobs: int | None = 0, + structured_outputs_regex: str | None = None, + generation_kwargs: dict | None = None, + ) -> dict[str, list[list[int]]]: + """ + Generates model completions for the provided prompts. + + Args: + prompts (`list[str]` or `list[list[int]]`): + List of text prompts or list of token ID lists for which the model will generate completions. + images (`list[list[PIL.Image] | None]`, *optional*): + List of image lists for VLM support. Each element is a list of PIL images for the corresponding prompt, + or `None` if no images for that prompt. + n (`int`, *optional*, defaults to `1`): + Number of completions to generate for each prompt. + repetition_penalty (`float`, *optional*, defaults to `1.0`): + Parameter for repetition penalty. 1.0 means no penalty. + temperature (`float`, *optional*, defaults to `1.0`): + Temperature parameter for sampling. Higher values increase diversity. + top_p (`float`, *optional*, defaults to `1.0`): + Top-p sampling parameter.`1.0` means no truncation. + top_k (`int`, *optional*, defaults to `0`): + Top-k sampling parameter. `0` means no truncation. + min_p (`float`, *optional*, defaults to `0.0`): + Minimum probability for sampling. + max_tokens (`int`, *optional*, defaults to `16`): + Maximum number of tokens to generate for each prompt. + logprobs (`int` or `None`, *optional*, defaults to `0`): + Number of top logprobs to return per token. When 0, only the sampled token's logprob is returned. When + N>0, returns up to N+1 logprobs sorted by descending probability, because vLLM always includes the + sampled token's logprob (which may fall outside the top-N). + structured_outputs_regex (`str`, *optional*): + Regular expression to guide the decoding process. + generation_kwargs (`dict`, *optional*): + Additional generation parameters to pass to the vLLM `SamplingParams`. This can include parameters like + `seed`, `frequency_penalty`, etc. If it contains keys that conflict with the other parameters, they + will override them. + + Returns: + `dict` with keys: + - `prompt_ids` (`list[list[int]]`): + List of lists of token IDs representing the tokenized input prompts. + - `completion_ids` (`list[list[int]]`): + List of lists of token IDs representing the model-generated completions for each prompt. + - `logprobs` (`list[list[list[float]]]`): + Per-token logprobs of shape (num_sequences, seq_len, num_logprobs), sorted by descending + probability. + - `logprob_token_ids` (`list[list[list[int]]]`): + Token IDs corresponding to each logprob, same shape as `logprobs`. + """ + url = f"{self.base_url}/generate/" + + # Convert PIL images to base64 strings. Each element is a list of images for the corresponding prompt, + # or None if no images for that prompt. + if images: + images = [ + [pil_to_base64(img) for img in img_list] if img_list is not None else None for img_list in images + ] + + response = self.session.post( + url, + json={ + "prompts": prompts, + "images": images, + "n": n, + "repetition_penalty": repetition_penalty, + "temperature": temperature, + "top_p": top_p, + "top_k": top_k, + "min_p": min_p, + "max_tokens": max_tokens, + "logprobs": logprobs, + "structured_outputs_regex": structured_outputs_regex, + "generation_kwargs": generation_kwargs or {}, + }, + ) + if response.status_code == 200: + json_response = response.json() + return { + "prompt_ids": json_response["prompt_ids"], + "completion_ids": json_response["completion_ids"], + "logprobs": json_response["logprobs"], + "logprob_token_ids": json_response["logprob_token_ids"], + } + else: + raise Exception(f"Request failed: {response.status_code}, {response.text}") + + def chat( + self, + messages: list[list[dict]], + n: int = 1, + repetition_penalty: float = 1.0, + temperature: float = 1.0, + top_p: float = 1.0, + top_k: int = 0, + min_p: float = 0.0, + max_tokens: int = 16, + logprobs: int | None = 0, + structured_outputs_regex: str | None = None, + generation_kwargs: dict | None = None, + chat_template_kwargs: dict | None = None, + tools: list | None = None, + chat_template: str | None = None, + ) -> dict[str, list[list[int]]]: + """ + Generates model completions for the provided chat messages. + + Args: + messages (`list[list[dict]]`): + List of message lists for which the model will generate completions. Each message is a dictionary with + keys like "role" and "content". + n (`int`, *optional*, defaults to `1`): + Number of completions to generate for each message list. + repetition_penalty (`float`, *optional*, defaults to `1.0`): + Parameter for repetition penalty. 1.0 means no penalty. + temperature (`float`, *optional*, defaults to `1.0`): + Temperature parameter for sampling. Higher values increase diversity. + top_p (`float`, *optional*, defaults to `1.0`): + Top-p sampling parameter.`1.0` means no truncation. + top_k (`int`, *optional*, defaults to `0`): + Top-k sampling parameter. `0` means no truncation. + min_p (`float`, *optional*, defaults to `0.0`): + Minimum probability for sampling. + max_tokens (`int`, *optional*, defaults to `16`): + Maximum number of tokens to generate for each message list. + logprobs (`int` or `None`, *optional*, defaults to `0`): + Number of top logprobs to return per token. When 0, only the sampled token's logprob is returned. When + N>0, returns up to N+1 logprobs sorted by descending probability, because vLLM always includes the + sampled token's logprob (which may fall outside the top-N). + structured_outputs_regex (`str`, *optional*): + Regular expression to guide the decoding process. + generation_kwargs (`dict`, *optional*): + Additional generation parameters to pass to the vLLM `SamplingParams`. This can include parameters like + `seed`, `frequency_penalty`, etc. If it contains keys that conflict with the other parameters, they + will override them. + chat_template_kwargs (`dict`, *optional*): + Additional keyword arguments to customize the chat template used by the model. + tools (`list[dict | Callable]`, *optional*): + List of tool functions available for tool calling during chat generation. + chat_template (`str`, *optional*): + Template to use for structuring the chat. If not provided, the model's default chat template will be + used. + + Returns: + `dict` with keys: + - `prompt_ids` (`list[list[int]]`): + List of lists of token IDs representing the tokenized input messages. + - `completion_ids` (`list[list[int]]`): + List of lists of token IDs representing the model-generated completions for each message list. + - `logprobs` (`list[list[list[float]]]`): + Per-token logprobs of shape (num_sequences, seq_len, num_logprobs), sorted by descending + probability. + - `logprob_token_ids` (`list[list[list[int]]]`): + Token IDs corresponding to each logprob, same shape as `logprobs`. + """ + if chat_template is not None: + raise NotImplementedError("Custom chat templates are not yet implemented in VLLMClient.chat().") + + url = f"{self.base_url}/chat/" + + # Convert PIL images to base64 strings + messages = copy.deepcopy(messages) # avoid modifying the original messages + for message_list in messages: + for message in message_list: + if isinstance(message["content"], list): + for part in message["content"]: + if part["type"] == "image_pil": + part["image_pil"] = pil_to_base64(part["image_pil"]) + + if isinstance(tools, list) and len(tools) > 0: + tools = [get_json_schema(tool) if callable(tool) else tool for tool in tools] + + response = self.session.post( + url, + json={ + "messages": messages, + "n": n, + "repetition_penalty": repetition_penalty, + "temperature": temperature, + "top_p": top_p, + "top_k": top_k, + "min_p": min_p, + "max_tokens": max_tokens, + "logprobs": logprobs, + "structured_outputs_regex": structured_outputs_regex, + "generation_kwargs": generation_kwargs or {}, + "chat_template_kwargs": chat_template_kwargs or {}, + "tools": tools, + }, + ) + if response.status_code == 200: + json_response = response.json() + return { + "prompt_ids": json_response["prompt_ids"], + "completion_ids": json_response["completion_ids"], + "logprobs": json_response["logprobs"], + "logprob_token_ids": json_response["logprob_token_ids"], + } + else: + raise Exception(f"Request failed: {response.status_code}, {response.text}") + + def init_communicator(self, device: torch.device | str | int = 0): + """ + Initializes the weight update group in a distributed setup for model synchronization. + + Args: + device (`torch.device`, `str`, or `int`, *optional*, defaults to `0`): + Device of trainer main process. It's the device that will be used for the weights synchronization. Can + be a `torch.device` object, a string like `'cuda:0'`, or an integer device index. + """ + # Get the world size from the server + url = f"{self.base_url}/get_world_size/" + response = requests.get(url) + if response.status_code == 200: + vllm_world_size = response.json()["world_size"] + else: + raise Exception(f"Request failed: {response.status_code}, {response.text}") + + world_size = vllm_world_size + 1 # add the client to the world + self.rank = vllm_world_size # the client's rank is the last process + + # Initialize weight update group + url = f"{self.base_url}/init_communicator/" + # Will simplify it after torch xpu 2.9 support get uuid. + if is_torch_xpu_available(): + if hasattr(torch.xpu.get_device_properties(device), "uuid"): + client_device_uuid = str(torch.xpu.get_device_properties(device).uuid) + else: + client_device_uuid = "42" + else: + client_device_uuid = str(torch.cuda.get_device_properties(device).uuid) + + # Set the weight update group's host to "0.0.0.0" so that + # clients from different IPs can send updated weights + response = self.session.post( + url, + json={ + "host": "0.0.0.0", + "port": self.group_port, + "world_size": world_size, + "client_device_uuid": client_device_uuid, + }, + ) + if response.status_code != 200: + raise Exception(f"Request failed: {response.status_code}, {response.text}") + + # Brief delay to allow server initialization. While not strictly required (client socket will retry on + # connection failure), this prevents log warnings like: + # [W416 23:24:57.460001114 socket.cpp:204] [c10d] The hostname of the client socket cannot be retrieved. err=-3 + time.sleep(0.1) + + # Set up the communication group for weight broadcasting + if is_torch_xpu_available(): + store = torch.distributed.TCPStore( + host_name=self.host, port=self.group_port, world_size=world_size, is_master=(self.rank == 0) + ) + prefixed_store = c10d.PrefixStore("client2server", store) + xccl_options = c10d.ProcessGroupXCCL.Options() + pg = c10d.ProcessGroupXCCL( + store=prefixed_store, + rank=self.rank, + size=world_size, + options=xccl_options, + ) + self.communicator = pg + else: + pg = StatelessProcessGroup.create( + host=self.host, port=self.group_port, rank=self.rank, world_size=world_size + ) + self.communicator = PyNcclCommunicator(pg, device=device) + + # When the client object is deleted, close the weight update group + atexit.register(self.close_communicator) + + def update_named_param(self, name: str, weights: torch.Tensor): + """ + Updates a specific named parameter in the model and broadcasts it to other processes. + + Args: + name (`str`): + Name of the layer whose weights are being updated. + weights (`torch.Tensor`): + Tensor containing the updated weights. + """ + dtype, shape = str(weights.dtype), tuple(weights.shape) + url = f"{self.base_url}/update_named_param/" + response = self.session.post(url, json={"name": name, "dtype": dtype, "shape": shape}) + if response.status_code != 200: + raise Exception(f"Request failed: {response.status_code}, {response.text}") + + if is_torch_xpu_available(): + # Use XCCL to broadcast the updated weights from the client (src) to all workers. + self.communicator.broadcast(weights, root=self.rank) + self.communicator.barrier() + else: + # Use NCCL to broadcast the updated weights from the client (src) to all workers. + self.communicator.broadcast(weights, src=self.rank) + self.communicator.group.barrier() + + def update_model_params(self, model: nn.Module): + """ + Updates all parameters of the given model by calling `update_named_param` for each parameter in the model. + + Args: + model (`nn.Module`): + Model whose parameters (weights/biases) are to be updated. + """ + for name, param in model.named_parameters(): + # Update each parameter individually + self.update_named_param(name, param.data) + + def get_sequence_logprobs( + self, + sequences: list[list[int]], + prompt_lengths: list[int], + top_logprobs: int = 100, + temperature: float = 1.0, + use_binary: bool = True, + chunk_size: int = 0, + max_concurrent_requests: int = 4, + ) -> dict[str, list]: + """ + Computes teacher logprobs for existing token sequences without generating new tokens. + + Sends full sequences (prompt + completion) to the vLLM server and retrieves per-token top-k logprobs for the + completion region only. This is used for knowledge distillation where the teacher model evaluates existing + sequences rather than generating new ones. + + When `chunk_size > 0`, splits the batch into chunks and dispatches them concurrently via a thread pool, keeping + the server's data-parallel workers busy. + + When `use_binary=True`, uses base64-encoded numpy arrays for fast serialization instead of nested JSON lists. + + Args: + sequences (`list[list[int]]`): + List of full token ID sequences (prompt + completion). + prompt_lengths (`list[int]`): + Number of prompt tokens in each sequence. Logprobs are returned starting from this position. + top_logprobs (`int`, *optional*, defaults to `100`): + Number of top logprobs to return per token position. + temperature (`float`, *optional*, defaults to `1.0`): + Temperature used when scoring the teacher distribution. + use_binary (`bool`, *optional*, defaults to `True`): + Use binary (base64 numpy) response format for faster serialization. + chunk_size (`int`, *optional*, defaults to `0`): + If > 0, split batch into chunks of this size and dispatch concurrently. If 0, send the entire batch in + a single request. + max_concurrent_requests (`int`, *optional*, defaults to `4`): + Maximum number of concurrent requests when using chunked dispatch. + + Returns: + `dict` with keys: + - `logprobs` (`list[list[list[float]]]`): + Per-token logprobs of shape (batch, completion_len, top_logprobs), sorted by descending + probability. + - `logprob_token_ids` (`list[list[list[int]]]`): + Token IDs corresponding to each logprob, same shape as `logprobs`. + """ + from concurrent.futures import ThreadPoolExecutor, as_completed + + if temperature <= 0: + raise ValueError(f"temperature must be positive, got {temperature}") + + url = f"{self.base_url}/get_sequence_logprobs/" + response_format = "binary" if use_binary else "json" + + if chunk_size > 0 and len(sequences) > chunk_size: + # Chunked concurrent dispatch + n = len(sequences) + chunks = [] + for i in range(0, n, chunk_size): + chunks.append((sequences[i : i + chunk_size], prompt_lengths[i : i + chunk_size])) + + responses = [None] * len(chunks) + + def _send_chunk(idx, seqs, plens): + resp = self.session.post( + url, + json={ + "sequences": seqs, + "prompt_lengths": plens, + "top_logprobs": top_logprobs, + "temperature": temperature, + "response_format": response_format, + }, + ) + if resp.status_code != 200: + raise Exception(f"Request failed: {resp.status_code}, {resp.text}") + return idx, resp.json() + + with ThreadPoolExecutor(max_workers=min(max_concurrent_requests, len(chunks))) as executor: + futures = { + executor.submit(_send_chunk, idx, seqs, plens): idx for idx, (seqs, plens) in enumerate(chunks) + } + for future in as_completed(futures): + idx, result = future.result() + responses[idx] = result + + # Merge results + if use_binary: + return self._merge_binary_responses(responses, top_logprobs) + else: + all_logprobs = [] + all_token_ids = [] + for resp in responses: + all_logprobs.extend(resp["logprobs"]) + all_token_ids.extend(resp["logprob_token_ids"]) + return {"logprobs": all_logprobs, "logprob_token_ids": all_token_ids} + else: + # Single request + response = self.session.post( + url, + json={ + "sequences": sequences, + "prompt_lengths": prompt_lengths, + "top_logprobs": top_logprobs, + "temperature": temperature, + "response_format": response_format, + }, + ) + if response.status_code != 200: + raise Exception(f"Request failed: {response.status_code}, {response.text}") + + json_response = response.json() + if use_binary: + return self._decode_binary_logprobs(json_response) + else: + return { + "logprobs": json_response["logprobs"], + "logprob_token_ids": json_response["logprob_token_ids"], + } + + @staticmethod + def _decode_binary_logprobs(response: dict) -> dict[str, list]: + """Decode base64-encoded numpy arrays back to nested lists. + + Returns a dict with: + ``logprobs`` / ``logprob_token_ids`` — teacher's sorted top-k logprobs and + token IDs (shape per sequence: ``(comp_len, top_k)``). Used for the forward KL term. + ``actual_logprobs`` / ``actual_token_ids`` — teacher logprob for the actual + token at each position (shape per sequence: ``(comp_len, 1)``). Used for the reverse KL term. + """ + import numpy as np + + shape = response["shape"] # [batch, max_comp_len, top_k] + comp_lengths = response["completion_lengths"] + + logprobs_arr = np.frombuffer(base64.b64decode(response["logprobs_b64"]), dtype=np.float32).reshape(shape) + token_ids_arr = np.frombuffer(base64.b64decode(response["token_ids_b64"]), dtype=np.int32).reshape(shape) + + # Convert back to nested lists, trimming padding + all_logprobs = [] + all_token_ids = [] + for i, comp_len in enumerate(comp_lengths): + all_logprobs.append(logprobs_arr[i, :comp_len, :].tolist()) + all_token_ids.append(token_ids_arr[i, :comp_len, :].tolist()) + + result = {"logprobs": all_logprobs, "logprob_token_ids": all_token_ids} + + # Decode actual-token logprobs (for reverse KL) + if "actual_logprobs_b64" in response: + actual_shape = [shape[0], shape[1], 1] + actual_lp = np.frombuffer(base64.b64decode(response["actual_logprobs_b64"]), dtype=np.float32).reshape( + actual_shape + ) + actual_ids = np.frombuffer(base64.b64decode(response["actual_token_ids_b64"]), dtype=np.int32).reshape( + actual_shape + ) + all_actual_lps = [] + all_actual_ids = [] + for i, comp_len in enumerate(comp_lengths): + all_actual_lps.append(actual_lp[i, :comp_len, :].tolist()) + all_actual_ids.append(actual_ids[i, :comp_len, :].tolist()) + result["actual_logprobs"] = all_actual_lps + result["actual_token_ids"] = all_actual_ids + + return result + + @staticmethod + def _merge_binary_responses(responses: list[dict], top_logprobs: int) -> dict[str, list]: + """Merge binary responses from multiple chunks into a single result.""" + + all_logprobs = [] + all_token_ids = [] + all_actual_lps = [] + all_actual_ids = [] + for resp in responses: + decoded = VLLMClient._decode_binary_logprobs(resp) + all_logprobs.extend(decoded["logprobs"]) + all_token_ids.extend(decoded["logprob_token_ids"]) + if "actual_logprobs" in decoded: + all_actual_lps.extend(decoded["actual_logprobs"]) + all_actual_ids.extend(decoded["actual_token_ids"]) + + result = {"logprobs": all_logprobs, "logprob_token_ids": all_token_ids} + if all_actual_lps: + if len(all_actual_lps) != len(all_logprobs): + raise ValueError( + f"Inconsistent chunks: {len(all_actual_lps)} actual_logprobs entries " + f"but {len(all_logprobs)} logprobs entries." + ) + result["actual_logprobs"] = all_actual_lps + result["actual_token_ids"] = all_actual_ids + return result + + def reset_prefix_cache(self): + """ + Resets the prefix cache for the model. + """ + url = f"{self.base_url}/reset_prefix_cache/" + response = self.session.post(url) + if response.status_code != 200: + raise Exception(f"Request failed: {response.status_code}, {response.text}") + + def close_communicator(self): + """ + Closes the weight update group and cleans up the communication group. + """ + url = f"{self.base_url}/close_communicator/" + + try: + response = self.session.post(url) + except ConnectionError: + # The server might be already down, so we don't need to close the communicator + pass + else: + if response.status_code != 200: + raise Exception(f"Request failed: {response.status_code}, {response.text}") + + if self.communicator is not None: + self.communicator = None + + +# Example usage +if __name__ == "__main__": + from vllm import SamplingParams + + device = "xpu" if is_torch_xpu_available() else "cuda" + client = VLLMClient() + client.init_communicator(device=device) + + # Generate completions + responses = client.generate(["Hello, AI!", "Tell me a joke"], n=4, max_tokens=32, sampling_params=SamplingParams()) + print("Responses:", responses) # noqa + + # Update model weights + from transformers import AutoModelForCausalLM + + model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-7B").to(device) + client.update_model_params(model) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/generation/vllm_generation.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/generation/vllm_generation.py new file mode 100644 index 0000000000000000000000000000000000000000..0c9cea9b586449e4a39471b3f766bc9bc2069b3f --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/generation/vllm_generation.py @@ -0,0 +1,689 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""vLLM-based generation backend for TRL trainers.""" + +import logging +import math +import os +from contextlib import nullcontext +from typing import TYPE_CHECKING + +import torch +from accelerate.utils import broadcast_object_list, gather_object, is_peft_model +from torch import nn +from torch.distributed.fsdp import FullyShardedDataParallel as FSDP +from transformers import PreTrainedModel, PreTrainedTokenizerBase, ProcessorMixin, is_bitsandbytes_available +from transformers.utils import ( + is_torch_mlu_available, + is_torch_mps_available, + is_torch_npu_available, + is_torch_xpu_available, +) + +from ..distributed import DistributedBackend +from ..extras.profiling import ProfilingContext +from ..import_utils import is_vllm_available +from ..trainer.utils import ensure_master_addr_port +from .vllm_client import VLLMClient + + +if is_vllm_available(): + from vllm import LLM, RequestOutput, SamplingParams + from vllm.sampling_params import StructuredOutputsParams + + +logger = logging.getLogger(__name__) + + +def empty_cache() -> None: + """Empties the cache of the available torch device. + + This function checks for the availability of different torch devices (CUDA, MLU, MPS, NPU, XPU) and empties the + cache of the first available device it finds. + + If none of the specific devices are available, it defaults to emptying the CUDA cache. + """ + if is_torch_mlu_available(): + torch.mlu.empty_cache() + elif is_torch_mps_available(): + torch.mps.empty_cache() + elif is_torch_npu_available(): + torch.npu.empty_cache() + elif is_torch_xpu_available(): + torch.xpu.empty_cache() + else: + torch.cuda.empty_cache() + + +def extract_logprobs(all_outputs: list["RequestOutput"]): + """ + Extract logprobs and token IDs from vLLM generation outputs. + + Returns logprobs and token IDs sorted by rank (most probable first). Each returned list has shape (num_sequences, + seq_len, num_logprobs), where num_logprobs is determined by the `logprobs` parameter passed to vLLM (1 when + `logprobs=0`, up to N+1 when `logprobs=N`). NaN logprob values are replaced with `None`. + + Args: + all_outputs (list of `RequestOutput`): + List of vLLM `RequestOutput` objects from generation. + + Returns: + Tuple of (logprobs, logprob_token_ids), each of shape (num_sequences, seq_len, num_logprobs). + """ + all_logprobs = [] + all_token_ids = [] + for outputs in all_outputs: + for output in outputs.outputs: + if output.logprobs is None: + return None, None + seq_logprobs = [] + seq_token_ids = [] + for lp in output.logprobs: + sorted_items = sorted(lp.items(), key=lambda x: x[1].rank) + seq_token_ids.append([token_id for token_id, _ in sorted_items]) + seq_logprobs.append([None if math.isnan(item.logprob) else item.logprob for _, item in sorted_items]) + all_logprobs.append(seq_logprobs) + all_token_ids.append(seq_token_ids) + return all_logprobs, all_token_ids + + +if TYPE_CHECKING: + from accelerate import Accelerator + from peft import PeftModel + + +if is_bitsandbytes_available(): + import bitsandbytes as bnb + + +class VLLMGeneration: + """Handles vLLM-based generation for trainers. + + Extracts all vLLM-specific logic (initialization, generation, weight sync) from trainers into a separate, testable + class. + + Args: + model ([`~transformers.PreTrainedModel`] or [`~peft.PeftModel`]): + Model to use for generation. + accelerator ([`~accelerate.Accelerator`]): + Accelerator for distributed training. + processing_class ([`~transformers.PreTrainedTokenizerBase`] or [`~transformers.ProcessorMixin`]): + Tokenizer or processor for the model. + + > Parameters for vLLM: + + mode (`str`, *optional*, defaults to `"colocate"`): + vLLM mode. Must be one of `"colocate"` or `"server"`. + + - `"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. + - `"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`). + + structured_outputs_regex (`str`, *optional*): + Regex for vLLM structured outputs. If `None` (default), structured outputs is disabled. + + > Parameters for "server" vLLM mode: + + server_base_url (`str`, *optional*): + Base URL for the vLLM server (e.g., `"http://localhost:8000"`). If provided, `server_host` and + `server_port` are ignored. + server_host (`str`, *optional*, defaults to `"0.0.0.0"`): + Host of the vLLM server to connect to. Ignored if `server_base_url` is provided. + server_port (`int`, *optional*, defaults to `8000`): + Port of the vLLM server to connect to. Ignored if `server_base_url` is provided. + 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. + group_port (`int`, *optional*, defaults to `51216`): + Port number for the weight update group. This is used to communicate with the vLLM server. Unless the port + is occupied, there is no need to change it. + + > Parameters for "colocate" vLLM mode: + + tensor_parallel_size (`int`, *optional*, defaults to `1`): + The number of GPUs to use for distributed execution with tensor parallelism. This setting only applies when + `mode` is set to `"colocate"`. If you are using `mode="server"`, this parameter must be passed separately + when launching the vLLM server via the `--vllm_tensor_parallel_size` flag. + gpu_memory_utilization (`float`, *optional*, defaults to `0.9`): + Ratio (between 0 and 1) of GPU memory to reserve for the model weights, activations, and KV cache. Higher + values will increase the KV cache size and thus improve the model's throughput. However, if the value is + too high, it may cause out-of- memory (OOM) errors. This setting only applies when `mode` is set to + `"colocate"`. If you are using `mode="server"`, this parameter must be passed separately when launching the + vLLM server via the `--vllm_gpu_memory_utilization` flag. + max_model_length (`int`, *optional*): + Model context length (prompt and completion). Set it to at least the maximum prompt length in the dataset + plus `max_completion_length`; if omitted, it is inferred from the model config. + max_num_seqs (`int`, *optional*): + Maximum number of sequences to process in parallel, effectively capping the batch size. + enable_sleep_mode (`bool`, *optional*, defaults to `False`): + Whether to enable sleep mode for the engine to offload weights/cache during the optimizer step. Keeps GPU + memory usage low, but waking the engine adds host–device transfer latency. + model_impl (`str`, *optional*, defaults to `"auto"`): + Model implementation to use for vLLM. + - "auto" will try to use the vLLM implementation, if it exists, and fall back to the Transformers + implementation if no vLLM implementation is available. + - "vllm" will use the vLLM model implementation. + - "transformers" will use the Transformers model implementation. + - "terratorch" will use the TerraTorch model implementation. + + > Parameters for generation: + + repetition_penalty (`float`, *optional*, defaults to `1.0`): + Parameter for repetition penalty. It penalizes new tokens based on whether they appear in the prompt and + the generated text so far. Values > 1 encourage the model to use new tokens, while values < 1 encourage the + model to repeat tokens. Default `1.0` means no penalty. + temperature (`float`, *optional*, defaults to `1.0`): + Sampling temperature. It controls the randomness of the sampling. Lower values make the model more + deterministic, while higher values make the model more random and increase diversity. + top_p (`float`, *optional*, defaults to `1.0`): + Top-p sampling parameter. It controls the cumulative probability of the top tokens to consider. Defaults to + `1.0` to consider all tokens. + top_k (`int`, *optional*, defaults to `0`): + Top-k sampling parameter. It controls the number of top tokens to consider. Defaults to `0` to consider all + tokens. + min_p (`float`, *optional*, defaults to `0.0`): + Min-p sampling parameter. It represents the minimum probability for a token to be considered, relative to + the probability of the most likely token. Default `0.0` means min-p is disabled. + max_completion_length (`int`, *optional*, defaults to `16`): + Maximum number of tokens to generate for each prompt. + logprobs (`int` or `None`, *optional*, defaults to `0`): + Number of top logprobs to return per token. When 0 (default), only the sampled token's logprob is returned + (inner dimension = 1). When N>0, returns up to N+1 logprobs sorted by descending probability, because vLLM + always includes the sampled token's logprob alongside the top-N (the sampled token may or may not already + be in the top-N). + generation_kwargs (`dict`, *optional*): + Additional generation parameters to pass to the vLLM `SamplingParams`. This can include parameters like + `seed`, `frequency_penalty`, etc. If it contains keys that conflict with the other parameters, they will + override them. + + > Parameters for chat/tools: + + chat_template (`str`, *optional*): + Template to use for structuring the chat. If not provided, the model's default chat template will be used. + chat_template_kwargs (`dict`, *optional*): + Additional keyword arguments to customize the chat template used by the model. + tools (`list`, *optional*): + Tools available for tool calling during chat generation. + """ + + def __init__( + self, + model: "PreTrainedModel | PeftModel", + accelerator: "Accelerator", + processing_class: PreTrainedTokenizerBase | ProcessorMixin, + # vLLM configuration + mode: str = "colocate", + structured_outputs_regex: str | None = None, + # Server mode configuration + server_base_url: str | None = None, + server_host: str = "0.0.0.0", + server_port: int = 8000, + server_timeout: float = 240.0, + group_port: int = 51216, + # Colocate mode configuration + tensor_parallel_size: int = 1, + gpu_memory_utilization: float = 0.9, + max_model_length: int | None = None, + max_num_seqs: int | None = None, + enable_sleep_mode: bool = False, + model_impl: str = "auto", + # Generation configuration + repetition_penalty: float = 1.0, + temperature: float = 1.0, + top_p: float = 1.0, + top_k: int = 0, + min_p: float = 0.0, + max_completion_length: int = 16, + logprobs: int | None = 0, + generation_kwargs: dict | None = None, + ): + self.model = model + self.accelerator = accelerator + self._dist = DistributedBackend(accelerator) + self.processing_class = processing_class + + # vLLM configuration + self.mode = mode + self.structured_outputs_regex = structured_outputs_regex + + # Server mode configuration + self.server_base_url = server_base_url + self.server_host = server_host + self.server_port = server_port + self.group_port = group_port + self.server_timeout = server_timeout + + # Colocate mode configuration + self.tensor_parallel_size = tensor_parallel_size + self.gpu_memory_utilization = gpu_memory_utilization + self.max_model_length = max_model_length + self.max_num_seqs = max_num_seqs + self.enable_sleep_mode = enable_sleep_mode + self.model_impl = model_impl + + # Generation configuration + self.repetition_penalty = repetition_penalty + self.temperature = temperature + self.top_p = top_p + self.top_k = top_k + self.min_p = min_p + self.max_completion_length = max_completion_length + self.logprobs = logprobs + self.generation_kwargs = generation_kwargs or {} + + self._init_vllm() + + def _init_vllm(self): + """Initialize vLLM in server or colocate mode.""" + model = self.model + accelerator = self.accelerator + + if not is_vllm_available(): + raise ImportError( + "vLLM is not available and `use_vllm` is set to True. Please install vLLM with " + "`pip install trl[vllm]` to use it." + ) + + if self.mode == "server": + if accelerator.is_main_process: + if self.server_base_url is not None: + base_url = self.server_base_url + else: + base_url = f"http://{self.server_host}:{self.server_port}" + self.vllm_client = VLLMClient( + base_url=base_url, group_port=self.group_port, connection_timeout=self.server_timeout + ) + self.vllm_client.init_communicator(device=torch.cuda.current_device()) + + elif self.mode == "colocate": + # Make sure tensor_parallel_size group size evenly divides the world size - each group should have + # the same number of ranks + if not accelerator.num_processes % self.tensor_parallel_size == 0: + raise ValueError( + f"tensor_parallel_size ({self.tensor_parallel_size}) must divide world size " + f"({accelerator.num_processes}) evenly." + ) + + if self.tensor_parallel_size > 1: + # Create subgroups of ranks for TP, each group with `tensor_parallel_size` ranks. + # For example, if world_size=8 and tensor_parallel_size=2 → groups: [0,1], [2,3], [4,5], [6,7] + self.tp_group, _ = torch.distributed.new_subgroups_by_enumeration( + [ + list(range(i * self.tensor_parallel_size, (i + 1) * self.tensor_parallel_size)) + for i in range(accelerator.num_processes // self.tensor_parallel_size) + ] + ) + + # vLLM requires the environment variables to be set for distributed training. + os.environ["RANK"] = str(accelerator.process_index) + os.environ["LOCAL_RANK"] = str(accelerator.local_process_index) + os.environ["WORLD_SIZE"] = str(accelerator.num_processes) + # Ensure distributed rendezvous variables are set without colliding across concurrent runs + ensure_master_addr_port() + + quantization = None + if is_bitsandbytes_available(): + for _, module in model.named_modules(): + if isinstance(module, bnb.nn.Linear4bit): + quantization = "bitsandbytes" + break + elif isinstance(module, bnb.nn.Linear8bitLt): + raise ValueError("vLLM does not support in-flight 8-bit quantization.") + + # Build LLM initialization kwargs + self.llm = LLM( + model=model.name_or_path, + tensor_parallel_size=self.tensor_parallel_size, + gpu_memory_utilization=self.gpu_memory_utilization, + max_model_len=self.max_model_length, + max_num_seqs=self.max_num_seqs, + enable_sleep_mode=self.enable_sleep_mode, + model_impl=self.model_impl, + distributed_executor_backend="external_launcher", + # Feed identical seed for tp groups to ensure sampling results are the same across workers + seed=accelerator.process_index // self.tensor_parallel_size, + # Latest vLLM v1 memory profiler is misled by the high default value (i.e., 32768) - thinking there's not enough memory + max_num_batched_tokens=4096, + # Important so temperature scaling/logit tweaking affects the TIS log probs + logprobs_mode="processed_logprobs", + quantization=quantization, + ) + if self.enable_sleep_mode: + self.llm.sleep(level=2) + else: + raise ValueError(f"vllm_mode must be either 'server' or 'colocate', got '{self.mode}'.") + + # When using vLLM, the main process is responsible for loading the model weights. This can cause process + # desynchronization and seems to lead to DeepSpeed hanging during initialization. To prevent this, we + # synchronize all processes after vLLM has been fully initialized. + accelerator.wait_for_everyone() + + def _fix_param_name_to_vllm(self, name: str, extra_prefixes: list[str] | None = None) -> str: + """Fix parameter name for vLLM compatibility.""" + extra_prefixes = extra_prefixes or [] + prefixes = ["_checkpoint_wrapped_module."] + extra_prefixes + for prefix in prefixes: + name = name.replace(prefix, "") + return name + + def _push_param_to_vllm(self, name: str, param) -> None: + """Push a single parameter tensor to the vLLM engine (server or colocate mode).""" + if self.mode == "server" and self.accelerator.is_main_process: + self.vllm_client.update_named_param(name, param) + elif self.mode == "colocate": + self.llm.llm_engine.model_executor.driver_worker.model_runner.model.load_weights([(name, param)]) + + def _sync_fsdp1_params_to_vllm(self, module: nn.Module, prefix: str = "", visited: set[str] | None = None): + """Memory-efficient post-order traversal of FSDP modules to extract full parameters and sync with vLLM.""" + # For FSDP1, we need to recurse into children and also use summon_full_params + if visited is None: + visited = set() + for child_name, child_module in module.named_children(): + child_prefix = f"{prefix}.{child_name}" if prefix else child_name + self._sync_fsdp1_params_to_vllm( + child_module, prefix=child_prefix, visited=visited + ) # recurse into the child + + if isinstance(module, FSDP): + with FSDP.summon_full_params(module, recurse=False, writeback=False): + for param_name, param in module.named_parameters(): + full_name = f"{prefix}.{param_name}" if prefix else param_name + full_name = self._fix_param_name_to_vllm(full_name, extra_prefixes=["_fsdp_wrapped_module."]) + + if full_name in visited: + continue # skip FSDP subtrees already traversed + visited.add(full_name) + + self._push_param_to_vllm(full_name, param.data) + + def _sync_fsdp2_params_to_vllm(self, module: nn.Module): + """FSDP2-specific parameter synchronization.""" + # For FSDP2, module.state_dict() already covers all parameters, so no need for recursion + for name, param in module.state_dict().items(): + # When using PEFT, we need to recover the original parameter name + name = name.removeprefix("base_model.model.").replace(".base_layer", "") + # Skip PEFT layers: they don't exist in vLLM, and they are merged already. + if is_peft_model(module) and module.prefix in name: + continue + # When module to save, remove its prefix and discard the original module + if "original_module" in name: + continue + name = self._fix_param_name_to_vllm(name, extra_prefixes=["modules_to_save.default."]) + + if param.is_cpu: + param = param.to(torch.device("cuda")) + param = param.full_tensor() + + self._push_param_to_vllm(name, param) + + def _sync_fsdp_params_to_vllm(self, model: nn.Module): + """Dispatch FSDP weight sync to the version-appropriate method.""" + if self._dist.fsdp_version == 1: + self._sync_fsdp1_params_to_vllm(model) + elif self._dist.fsdp_version == 2: + self._sync_fsdp2_params_to_vllm(model) + + def sync_weights(self): + """Synchronize model weights to vLLM. + + Handles FSDP, DeepSpeed, PEFT weight synchronization. + """ + # Wake up vLLM weights before loading to ensure device memory is mapped. Without this, load_weights() writes to + # freed/unmapped memory when sleep mode is active, which crashes on backends with strict physical memory + # management (e.g., Ascend NPU). See https://github.com/huggingface/trl/issues/5142 + if self.mode == "colocate" and self.enable_sleep_mode: + empty_cache() # required to avoid OOM in some cases + self.llm.wake_up(tags=["weights"]) + + model = self.model + accelerator = self.accelerator + + if is_peft_model(model): + # With PEFT and FSDP/DeepSpeed ZeRO Stage 3, we must gather the full model at once before merging, as + # merging adapters in a sharded manner is not supported. + # TODO: does this work with FSDP? + with self._dist.gather_params(list(model.parameters())): + model.merge_adapter() + + # Update vLLM weights while parameters are gathered + if self._dist.is_fsdp: # note if using FSDP, gather_params is a no-op + # For PEFT with FSDP we need to use the memory efficient post-order traversal + self._sync_fsdp_params_to_vllm(model) + else: + # DeepSpeed ZeRO-3 with PEFT + for name, param in model.named_parameters(): + # When using PEFT, we need to recover the original parameter name + name = name.removeprefix("base_model.model.").replace(".base_layer", "") + # Skip PEFT layers: they don't exist in vLLM, and they are merged already. + if model.prefix in name: + continue + # When module to save, remove its prefix and discard the original module + if "original_module" in name: + continue + name = self._fix_param_name_to_vllm(name, extra_prefixes=["modules_to_save.default."]) + + self._push_param_to_vllm(name, param.data) + # Unmerge adapters while parameters are still gathered + model.unmerge_adapter() + # Parameters will automatically be repartitioned when exiting the context + else: + # For non-PEFT models, simply gather (if needed) and update each parameter individually. + if self._dist.is_fsdp: + self._sync_fsdp_params_to_vllm(model) + else: + for name, param in model.named_parameters(): + name = self._fix_param_name_to_vllm(name) + with self._dist.gather_params([param]): + self._push_param_to_vllm(name, param.data) + + # Reset cache on vLLM + if self.mode == "server" and accelerator.is_main_process: + self.vllm_client.reset_prefix_cache() + elif self.mode == "colocate": + self.llm.reset_prefix_cache() + + def generate( + self, + prompts: list[list[int]], + images: list[list | None] | None, + num_generations: int, + profiler: ProfilingContext | None = None, + ) -> tuple: + """Generate completions using vLLM. + + Args: + prompts: List of token ID lists, one per prompt (already tokenized). + images: Optional list of image lists for VLM support. Each element is a list of PIL images for the + corresponding prompt, or `None` if no images for that prompt. `None` if no images at all. + num_generations: Number of generations per prompt. + profiler: Optional profiler for performance tracking. + + Returns: + Tuple of (prompt_ids, completion_ids, logprobs, logprob_token_ids). + + - `prompt_ids`: `list[list[int]]` of shape `(batch_size, prompt_len)`. + - `completion_ids`: `list[list[int]]` of shape `(batch_size, completion_len)`. + - `logprobs`: `list[list[list[float | None]]]` of shape `(batch_size, completion_len, num_logprobs)`. + - `logprob_token_ids`: `list[list[list[int]]]` of shape `(batch_size, completion_len, num_logprobs)`. + + `num_logprobs` is 1 when `logprobs=0`, or up to N+1 when `logprobs=N` (the sampled token is always included + and may fall outside the top-N). + """ + profiler = profiler or nullcontext() + accelerator = self.accelerator + temperature = self.temperature + top_p = self.top_p + top_k = self.top_k + min_p = self.min_p + repetition_penalty = self.repetition_penalty + max_completion_length = self.max_completion_length + + # Wake up colocated vLLM weights if needed (idempotent if already awake from sync_weights) + if self.mode == "colocate" and self.enable_sleep_mode: + empty_cache() # required to avoid OOM in some cases + self.llm.wake_up(tags=["weights"]) + # Work around for https://github.com/vllm-project/vllm/issues/29341 + try: + self.llm.collective_rpc("reload_weights") + except NotImplementedError: + # Non-CUDA vLLM backends (e.g., vllm-ascend's NPUWorkerV1), don't implement reload_weights + pass + + # Generate completions using vLLM: gather all prompts and use them in a single call in the main process + if self.mode == "server": + all_prompts = gather_object(prompts) + # Always gather images (even when None) to avoid deadlock: images may be None on some ranks + # and non-None on others in mixed datasets, and gather_object is a collective operation. + all_images = gather_object(images if images is not None else [None] * len(prompts)) + if all(img is None for img in all_images): + all_images = None + + if accelerator.is_main_process: + # Since 'prompts' contains 'num_generations' duplicates, we first take unique prompts, and + # generate num_generations outputs for each one. This is faster than generating outputs for each + # duplicate prompt individually. + ordered_set_of_prompt_ids = all_prompts[::num_generations] + ordered_set_of_images = all_images[::num_generations] if all_images is not None else None + + sampling_params = { + "n": num_generations, + "repetition_penalty": repetition_penalty, + "temperature": temperature, + "top_p": top_p, + "top_k": top_k, + "min_p": 0.0 if min_p is None else min_p, + "max_tokens": max_completion_length, + "logprobs": self.logprobs, + "structured_outputs_regex": self.structured_outputs_regex, + "generation_kwargs": self.generation_kwargs, + } + with profiler: + output = self.vllm_client.generate( + prompts=ordered_set_of_prompt_ids, + images=ordered_set_of_images, + **sampling_params, + ) + payload = ( + output["prompt_ids"], + output["completion_ids"], + output["logprobs"], + output.get("logprob_token_ids"), + ) + else: + payload = None + + # Broadcast the completions from the main process to all processes, ensuring each process receives its corresponding slice. + obj_list = [payload] + broadcast_object_list(obj_list, from_process=0) + all_prompt_ids, all_completion_ids, all_logprobs, all_logprob_token_ids = obj_list[0] + + # vllm_client.generate(n=num_generations) returns num_generations completions per prompt. + # Duplicate prompt_ids to align with per-completion entries. + all_prompt_ids = [ids for ids in all_prompt_ids for _ in range(num_generations)] + + process_slice = slice( + accelerator.process_index * len(prompts), + (accelerator.process_index + 1) * len(prompts), + ) + prompt_ids = all_prompt_ids[process_slice] + completion_ids = all_completion_ids[process_slice] + logprobs = all_logprobs[process_slice] if all_logprobs is not None else None + logprob_token_ids = all_logprob_token_ids[process_slice] if all_logprob_token_ids is not None else None + + # Generate completions using colocated vLLM instances: each device holds vLLM copy and work on their own batch of prompts + elif self.mode == "colocate": + generation_kwargs = { + "n": 1, # vLLM on each GPU generates only 1 in colocate mode + "repetition_penalty": repetition_penalty, + "temperature": temperature, + "top_p": top_p, + "top_k": top_k, + "min_p": 0.0 if min_p is None else min_p, + "max_tokens": max_completion_length, + "logprobs": self.logprobs, + } + generation_kwargs.update(self.generation_kwargs) + + if self.structured_outputs_regex is not None: + if generation_kwargs.get("structured_outputs") is not None: + logger.warning( + "Both `structured_outputs_regex` and `generation_kwargs['structured_outputs']` are set; " + "`structured_outputs_regex` takes precedence." + ) + generation_kwargs["structured_outputs"] = StructuredOutputsParams(regex=self.structured_outputs_regex) + elif isinstance(structured_outputs_kwargs := generation_kwargs.get("structured_outputs"), dict): + generation_kwargs["structured_outputs"] = StructuredOutputsParams(**structured_outputs_kwargs) + sampling_params = SamplingParams(**generation_kwargs) + + if self.tensor_parallel_size > 1: + # Gather prompts from all ranks in the TP group and flatten. + # Each rank starts with its own prompts; after gathering, all ranks see the full group set. + orig_size = len(prompts) + gathered_prompts = [None for _ in range(self.tensor_parallel_size)] + torch.distributed.all_gather_object(gathered_prompts, prompts, group=self.tp_group) + all_prompts = [p for sublist in gathered_prompts for p in sublist] + # Always gather images (even when None) to avoid deadlock: images may be None on some + # ranks and non-None on others in mixed datasets, and all_gather_object is collective. + local_images = images if images is not None else [None] * len(prompts) + gathered_images = [None for _ in range(self.tensor_parallel_size)] + torch.distributed.all_gather_object(gathered_images, local_images, group=self.tp_group) + all_images = [img for sublist in gathered_images for img in sublist] + if all(img is None for img in all_images): + all_images = None + else: + all_prompts = prompts + all_images = images + + if self.enable_sleep_mode: + self.llm.wake_up(tags=["kv_cache"]) + + # Build vLLM-compatible prompt inputs with token IDs and optional multi-modal data + vllm_prompts = [] + if all_images is not None: + for ids, img_list in zip(all_prompts, all_images, strict=True): + row = {"prompt_token_ids": ids} + if img_list is not None: + row["multi_modal_data"] = {"image": img_list if len(img_list) > 1 else img_list[0]} + vllm_prompts.append(row) + else: + vllm_prompts = [{"prompt_token_ids": ids} for ids in all_prompts] + + with profiler: + all_outputs = self.llm.generate(vllm_prompts, sampling_params=sampling_params, use_tqdm=False) + + all_prompt_ids = [output.prompt_token_ids for output in all_outputs] + all_completion_ids = [output.token_ids for outputs in all_outputs for output in outputs.outputs] + all_logprobs, all_logprob_token_ids = extract_logprobs(all_outputs) + + if self.tensor_parallel_size > 1: + # Slice completions for this rank within its TP group. + # Each rank generates all outputs — we keep only our share. + local_rank_in_group = torch.distributed.get_rank(group=self.tp_group) + tp_slice = slice(local_rank_in_group * orig_size, (local_rank_in_group + 1) * orig_size) + prompt_ids = all_prompt_ids[tp_slice] + completion_ids = all_completion_ids[tp_slice] + logprobs = all_logprobs[tp_slice] if all_logprobs is not None else None + logprob_token_ids = all_logprob_token_ids[tp_slice] if all_logprob_token_ids is not None else None + else: + prompt_ids = all_prompt_ids + completion_ids = all_completion_ids + logprobs = all_logprobs + logprob_token_ids = all_logprob_token_ids + + if self.enable_sleep_mode: + self.llm.sleep(level=2) + + return prompt_ids, completion_ids, logprobs, logprob_token_ids diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/import_utils.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/import_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6eb80325cf5bf97b4d562ffef8f9cbc3b1d63f72 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/import_utils.py @@ -0,0 +1,145 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import importlib +import importlib.metadata +import importlib.util +import warnings +from contextlib import contextmanager + +from packaging.version import Version + + +LIGER_KERNEL_MIN_VERSION = "0.8.0" +PACKAGE_DISTRIBUTION_MAPPING = importlib.metadata.packages_distributions() + + +# From transformers: https://github.com/huggingface/transformers/blob/556312cd45a5e619c41b0f8adf680eab0d334324/src/transformers/utils/import_utils.py#L48-L77 +def _is_package_available(pkg_name: str, return_version: bool = False) -> tuple[bool, str] | bool: + """Check if `pkg_name` exist, and optionally try to get its version""" + spec = importlib.util.find_spec(pkg_name) + package_exists = spec is not None + package_version = "N/A" + if package_exists and return_version: + try: + # importlib.metadata works with the distribution package, which may be different from the import + # name (e.g. `PIL` is the import name, but `pillow` is the distribution name) + distributions = PACKAGE_DISTRIBUTION_MAPPING[pkg_name] + # Per PEP 503, underscores and hyphens are equivalent in package names. + # Prefer the distribution that matches the (normalized) package name. + normalized_pkg_name = pkg_name.replace("_", "-") + if normalized_pkg_name in distributions: + distribution_name = normalized_pkg_name + elif pkg_name in distributions: + distribution_name = pkg_name + else: + distribution_name = distributions[0] + package_version = importlib.metadata.version(distribution_name) + except (importlib.metadata.PackageNotFoundError, KeyError): + # If we cannot find the metadata (because of editable install for example), try to import directly. + # Note that this branch will almost never be run, so we do not import packages for nothing here + package = importlib.import_module(pkg_name) + package_version = getattr(package, "__version__", "N/A") + if return_version: + return package_exists, package_version + else: + return package_exists + + +def is_deepspeed_available() -> bool: + return _is_package_available("deepspeed") + + +def is_fastapi_available() -> bool: + return _is_package_available("fastapi") + + +def is_jmespath_available() -> bool: + return _is_package_available("jmespath") + + +def is_joblib_available() -> bool: + return _is_package_available("joblib") + + +def is_liger_kernel_available(min_version: str = LIGER_KERNEL_MIN_VERSION) -> bool: + _liger_kernel_available, _liger_kernel_version = _is_package_available("liger_kernel", return_version=True) + return _liger_kernel_available and Version(_liger_kernel_version) >= Version(min_version) + + +def is_math_verify_available() -> bool: + return _is_package_available("math_verify") + + +def is_mergekit_available() -> bool: + return _is_package_available("mergekit") + + +def is_openreward_available() -> bool: + return _is_package_available("openreward") + + +def is_pydantic_available() -> bool: + return _is_package_available("pydantic") + + +def is_requests_available() -> bool: + return _is_package_available("requests") + + +def is_unsloth_available() -> bool: + return _is_package_available("unsloth") + + +def is_uvicorn_available() -> bool: + return _is_package_available("uvicorn") + + +def is_vllm_available(min_version: str | None = None) -> bool: + _vllm_available, _vllm_version = _is_package_available("vllm", return_version=True) + if _vllm_available: + if not (Version("0.12.0") <= Version(_vllm_version) <= Version("0.19.0")): + warnings.warn( + f"TRL currently supports vLLM versions from 0.12.0 to 0.19.0. You have version {_vllm_version} " + "installed. We recommend installing a supported version to avoid compatibility issues.", + stacklevel=2, + ) + if min_version is not None and Version(_vllm_version) < Version(min_version): + return False + return _vllm_available + + +def is_vllm_ascend_available() -> bool: + return _is_package_available("vllm_ascend") + + +def is_weave_available() -> bool: + return _is_package_available("weave") + + +class TRLExperimentalWarning(UserWarning): + """Warning for using the 'trl.experimental' submodule.""" + + pass + + +@contextmanager +def suppress_warning(category): + with warnings.catch_warnings(): + warnings.simplefilter("ignore", category=category) + yield + + +def suppress_experimental_warning(): + return suppress_warning(TRLExperimentalWarning) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/models/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f84d989c2825020b0b69c4b31f0285fdcdf54b41 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/models/__init__.py @@ -0,0 +1,32 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import TYPE_CHECKING + +from .._lazy_module import _LazyModule + + +_import_structure = { + "activation_offloading": ["get_act_offloading_ctx_manager"], + "utils": ["create_reference_model", "prepare_deepspeed", "prepare_fsdp", "unwrap_model_for_generation"], +} + + +if TYPE_CHECKING: + from .activation_offloading import get_act_offloading_ctx_manager + from .utils import create_reference_model, prepare_deepspeed, prepare_fsdp, unwrap_model_for_generation +else: + import sys + + sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/models/activation_offloading.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/models/activation_offloading.py new file mode 100644 index 0000000000000000000000000000000000000000..b6cff43f7a34db1d492a8aa7600005a42433d0b8 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/models/activation_offloading.py @@ -0,0 +1,762 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of https://github.com/pytorch/torchtune. + + +import sys + +import psutil +import torch +from accelerate import logging +from accelerate.utils.versions import is_torch_version +from torch import nn +from torch.autograd.graph import saved_tensors_hooks +from transformers import is_torch_npu_available + + +if is_torch_npu_available(): + import torch_npu # noqa: F401 + +# Import DTensor for FSDP v2 support with version-aware import path +DTensor = None +if torch.distributed.is_available(): + try: + if is_torch_version(">=", "2.5.0"): + from torch.distributed.tensor import DTensor + else: + # from torch 2.0.0 (oldest supported accelerate torch version), DTensor is in torch.distributed._tensor + from torch.distributed._tensor import DTensor + except (ImportError, AttributeError): + DTensor = None + +logger = logging.get_logger(__name__) + + +def _get_unique_tensor_key(tensor: torch.Tensor) -> tuple: + """ + Get a unique key for a tensor based on its storage pointer and dtype. This allows deduplication of tensors that + share the same underlying storage. From: + https://github.com/volcengine/verl/blob/main/verl/utils/activation_offload.py + + Args: + tensor: The tensor to get the key for + + Returns: + A tuple of (storage_pointer, dtype) that uniquely identifies the tensor's storage + """ + # Handle special tensor types - primarily for FSDP v2 DTensor + actual_tensor = tensor + + # For DTensor (FSDP v2), extract the local tensor + if DTensor is not None and isinstance(tensor, DTensor) and hasattr(tensor, "_local_tensor"): + actual_tensor = tensor._local_tensor + + # Try to get storage pointer, but fall back to tensor id if not accessible + try: + storage_ptr = actual_tensor.untyped_storage().data_ptr() + actual_tensor.storage_offset() + except (RuntimeError, AttributeError): + # For tensors with invalid storage, use tensor id + # This won't enable deduplication for these tensors, but allows offloading to work + storage_ptr = id(actual_tensor) + + return (storage_ptr, actual_tensor.dtype) + + +class OffloadActivations(saved_tensors_hooks): + """ + Context manager under which activation tensors created in the forward pass will be offloaded. + + Enable the memory efficiency technique of activation offloading, where activations bigger than `min_offload_size` + bytes will be offloaded to CPU in the forward and brought back in the backward. This is in contrast to maintaining + the activation on GPU VRAM throughout the program. + + This manager contains the option of using one additional CUDA stream to handle the communication between CUDA and + CPU, which is intended to overlap with the default computation stream to improve runtime. We designed + synchronization with a few heuristics for optimizing the tradeoff between runtime vs memory usage. + + Args: + use_pin_memory (`bool`, *optional*, defaults to `True`): + Whether to offloaded Tensor will be placed in pinned memory on the CPU. Pinned memory allows the Tensor to + be moved back onto GPU more quickly but is a limited resource. + use_streams (`bool`, *optional*, defaults to `True`): + Whether to use streams for performance optimization where the communications get overlapped with the + computation. Requires a torch build after torch-2.5.0. + min_offload_size (`int`, *optional*, defaults to `1024`): + Minimum number of bytes a Tensor must be in order to qualify for offloading. If the tensor is too small, we + do not want to waste bandwidth and resources moving it to CPU and back. + max_fwd_stash_size (`int`, *optional*, defaults to `5`): + Maximum size of the forward stash, or the maximum number of consecutive activations to keep alive during + the forward pass. This number must be at least 1. Keeping alive more activations will potentially allow + more overlap between the communication and compute streams at the cost of increasing memory usage. Keeping + alive fewer activations will conserve memory, but may cause poor overlap between the streams, increasing + runtime. + + Raises: + ValueError: if `max_fwd_stash_size` is not at least `1`. + + Example: + ```python + >>> with OffloadActivations(): + ... outputs = model(inputs, labels=labels) + >>> loss = outputs.loss + >>> loss.backward() + ``` + """ + + def __init__( + self, + use_pin_memory: bool = True, + use_streams: bool = True, + min_offload_size: int = 1024, + max_fwd_stash_size: int = 5, + ) -> None: + self.use_streams = use_streams + + self.min_tensor_size_bytes = min_offload_size # we don't want to bother with small tensors + self.tracker = {} # tensor_id => (new_tensor, if_modified) ---> track what saved/offloaded tensors are where + self.tensor_id = 0 + self.is_first_forward_call = True + self.is_first_backward_call = True + self.is_first_forward_pass = True + + # Storage deduplication: maps storage key to tensor_id to avoid offloading same storage multiple times + self.storage_to_tensor_id = {} + + # Parameter filtering: track parameter storage pointers to skip them during offloading + self.param_storages = set() + + # Managing cpu memory + self.use_pin_memory = use_pin_memory + self.virtual_memory_safe_pct = 60 # we should not exceed this percentage of memory + + self.accelerator_type = ( + torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda" + ) + # NOTE: xpu doesn't have `default_stream` API, use `current_stream` instead + if self.accelerator_type == "xpu": # comp stream + self.s0 = torch.xpu.current_stream() + elif is_torch_npu_available() and self.accelerator_type == "npu": + self.s0 = torch.npu.current_stream() + else: + self.s0 = torch.cuda.default_stream() + + # For streaming + if self.use_streams: + if self.accelerator_type == "xpu": # comms stream + self.s1 = torch.xpu.Stream() + elif self.accelerator_type == "npu": + self.s1 = torch.npu.Stream() + else: + self.s1 = torch.cuda.Stream() + self.fwd_stash = {} # tensor_id => (activation, ev1) + if max_fwd_stash_size < 1: + raise ValueError(f"max_fwd_stash_size should be at least 1 but is {max_fwd_stash_size}") + self.max_fwd_stash_size = max_fwd_stash_size + self.bwd_tensor_stash = {} # tensor_id => activation + self.bwd_ev_stash = {} # tensor_id => ev0 + self.curr_graph_id = None + self.curr_autograd_node = None + + # -------- platform util functions -------- # + def verify_sufficient_virtual_memory(): + curr_pct = get_cpu_ram_pct() + if curr_pct > self.virtual_memory_safe_pct: + logger.warning(f"{curr_pct=}% > {self.virtual_memory_safe_pct=}% of virtual memory used") + + def get_cpu_ram_pct() -> float: + # get the percentage of memory used by the system + return psutil.virtual_memory().percent + + def get_tensor_id() -> int: + # create a unique id for each tensor we are managing + self.tensor_id += 1 + return self.tensor_id + + def get_num_bytes_tensor(x: torch.Tensor) -> int: + # get the number of bytes in a tensor, for memory management purposes + return x.element_size() * x.nelement() # x.element_size() * x._base_storage().nbytes() + + # -------- core pack / unpack work -------- # + def pack_tensor(activation: torch.Tensor) -> int: + # activations are passed in during forward pass - from here we take over and return a unique id + if self.is_first_forward_call: + if len(self.tracker) != 0: + raise ValueError("Backward pass should have cleared tracker of all tensors") + + # set training phase trackers + self.is_first_forward_call = False + self.is_first_backward_call = True + # Reset deduplication map for new forward pass + self.storage_to_tensor_id = {} + + # query for basic tensor info + num_bytes = get_num_bytes_tensor(activation) + tensor_id = get_tensor_id() + + # Check for tensor deduplication using storage pointer + # If this storage is already being tracked, we still create a new tensor_id + # but don't offload again (just keep the tensor in GPU) + storage_key = _get_unique_tensor_key(activation) + if storage_key in self.storage_to_tensor_id: + # Storage already offloaded - don't offload again, just track the reference + self.tracker[tensor_id] = (activation, False, None, None, None) # Keep on GPU, don't offload + return tensor_id + + # Check if tensor is on CPU (skip offloading) + if activation.device.type not in ["cuda", "xpu", "npu"]: + self.tracker[tensor_id] = (activation, False, None, None, None) + return tensor_id + + # Check if tensor is too small + if num_bytes < self.min_tensor_size_bytes: + self.tracker[tensor_id] = (activation, False, None, None, None) + return tensor_id + + # Check if tensor is a parameter or buffer + if isinstance(activation, torch.nn.Parameter) or ( + hasattr(torch.nn, "Buffer") and isinstance(activation, torch.nn.Buffer) + ): + self.tracker[tensor_id] = (activation, False, None, None, None) + return tensor_id + + # Check if tensor is an FP8 tensor (TorchAO) - skip offloading as they're already compressed + tensor_class_name = type(activation).__name__ + if tensor_class_name in ["Float8TrainingTensor", "ScaledMMConfig", "LinearMMConfig"]: + self.tracker[tensor_id] = (activation, False, None, None, None) + return tensor_id + + # Check if tensor storage is a model parameter (for FSDP compatibility) + try: + # Extract actual tensor for DTensor + check_tensor = activation + if DTensor is not None and isinstance(activation, DTensor) and hasattr(activation, "_local_tensor"): + check_tensor = activation._local_tensor + + if check_tensor.untyped_storage().data_ptr() in self.param_storages: + self.tracker[tensor_id] = (activation, False, None, None, None) + return tensor_id + except (RuntimeError, AttributeError): + # If we can't get data_ptr, skip this check + pass + + # Tensor qualifies for offloading + if self.use_streams: + # First, sync back and dereference previously offloaded tensors + # as the offloading should be done sufficiently long ago. + for id in list(self.fwd_stash.keys()): + if id <= tensor_id - self.max_fwd_stash_size: + _, ev = self.fwd_stash[id] + self.s0.wait_event(ev) + del self.fwd_stash[id] + else: + break + + # Sync in, offload, and add an event to sync back later + self.s1.wait_stream(self.s0) + + stream = self.s1 if self.use_streams else self.s0 + if self.accelerator_type == "xpu": + stream_ctx = torch.xpu.stream(stream) + elif self.accelerator_type == "npu": + stream_ctx = torch.npu.stream(stream) + else: + stream_ctx = torch.cuda.stream(stream) + with stream_ctx: + # Save original stride and shape information + original_stride = activation.stride() + original_storage_offset = activation.storage_offset() + original_shape = activation.size() + + # Check if tensor has broadcast dimensions (stride == 0) + # If so, copy the underlying storage directly instead of materializing the broadcast + has_broadcast = 0 in original_stride + + if has_broadcast: + # Copy only the actual underlying storage, not the materialized broadcast + # Create CPU tensor with same storage size as original + storage_size = activation.untyped_storage().size() + cpu_storage = torch.empty( + storage_size // activation.element_size(), + dtype=activation.dtype, + pin_memory=self.use_pin_memory, + device="cpu", + ) + # Copy the raw storage + cpu_storage_view = torch.as_strided( + activation, size=(storage_size // activation.element_size(),), stride=(1,), storage_offset=0 + ) + cpu_storage.copy_(cpu_storage_view, non_blocking=True) + cpu_tensor = cpu_storage + else: + # No broadcast - use normal contiguous copy + # .contiguous() can be a no-op for contiguous views with + # non-zero storage_offset. Force a clone for those views + # so later as_strided reconstruction stays in bounds. + if not activation.is_contiguous() or activation.storage_offset() != 0: + if activation.storage_offset() != 0: + activation = activation.clone(memory_format=torch.contiguous_format) + else: + activation = activation.contiguous() + original_stride = activation.stride() + original_storage_offset = activation.storage_offset() + cpu_tensor = torch.empty_like(activation, pin_memory=self.use_pin_memory, device="cpu") + cpu_tensor.copy_(activation, non_blocking=True) + + # Store CPU tensor along with stride information + self.tracker[tensor_id] = ( + cpu_tensor, + True, # True = (in future) modified + original_stride, # Save original GPU stride + original_storage_offset, # Save original storage offset + original_shape, # Save original shape for broadcast restoration + ) + + if self.use_streams: + event = self.s1.record_event() + + # Stash to keep activation alive til s1 is done + self.fwd_stash[tensor_id] = (activation, event) + + # Track this storage for deduplication + self.storage_to_tensor_id[storage_key] = tensor_id + + return tensor_id + + def unpack_tensor_single_stream(unpack_tensor_id: int) -> torch.Tensor: + # backward pass - we are called with the tensor_id, which + # we will use to retrieve the saved/offloaded tensor + if self.is_first_backward_call: + if self.is_first_forward_pass: + self.is_first_forward_pass = False + if self.use_pin_memory: + verify_sufficient_virtual_memory() + + self.is_first_backward_call = False + + if unpack_tensor_id not in self.tracker: + raise ValueError(f"Untracked tensor with id {unpack_tensor_id}") + + ( + maybe_accelerator_tensor, + modified, + original_stride, + original_storage_offset, + original_shape, + ) = self.tracker[unpack_tensor_id] + + if modified: + # Restore tensor to GPU + accelerator_tensor = maybe_accelerator_tensor.to(self.accelerator_type, non_blocking=True) + # Restore original stride if we saved it (handles both broadcast and non-broadcast cases) + if original_stride is not None: + accelerator_tensor = torch.as_strided( + accelerator_tensor, + size=original_shape, + stride=original_stride, + storage_offset=original_storage_offset, + ) + maybe_accelerator_tensor = accelerator_tensor + + # clear tensor from tracking + del self.tracker[unpack_tensor_id] + # Only set is_first_forward_call to True when all tensors have been unpacked + if len(self.tracker) == 0: + self.is_first_forward_call = True + return maybe_accelerator_tensor + + def unpack_tensor_with_streams(unpack_tensor_id: int) -> torch.Tensor: + # backward pass - we are called with the tensor_id, which + # we will use to retrieve the saved/offloaded tensor + if self.is_first_backward_call: + self.curr_graph_id = torch._C._current_graph_task_id() + + def wait_and_del_remaining_references() -> None: + for id in list(self.bwd_tensor_stash.keys()): + if id in self.bwd_ev_stash: + event = self.bwd_ev_stash[id] + self.s1.wait_event(event) + del self.bwd_tensor_stash[id] + + # Register a callback to the end of autograd to clean everything up + torch.autograd.variable.Variable._execution_engine.queue_callback(wait_and_del_remaining_references) + + if self.is_first_forward_pass: + self.is_first_forward_pass = False + if self.use_pin_memory: + verify_sufficient_virtual_memory() + + self.is_first_backward_call = False + + if unpack_tensor_id not in self.tracker: + raise ValueError(f"untracked tensor with id {unpack_tensor_id}") + + ( + maybe_accelerator_tensor, + modified, + original_stride, + original_storage_offset, + original_shape, + ) = self.tracker[unpack_tensor_id] + + if modified: + # Get data on the current autograd node + graph_id = torch._C._current_graph_task_id() + node = torch._C._current_autograd_node() + prev_node_ids = [] + + # If we're on a new node, mark prev node's tensors to be freed later + if graph_id == self.curr_graph_id and self.curr_autograd_node != node: + self.curr_autograd_node = node + prev_node_ids = list(self.bwd_tensor_stash.keys()) + + brought_back_from_cpu = True + if unpack_tensor_id in self.fwd_stash: + maybe_accelerator_tensor = self.fwd_stash[unpack_tensor_id][0] + brought_back_from_cpu = False + else: + # Kick off the process to bring tensors back + if self.accelerator_type == "xpu": + stream_ctx = torch.xpu.stream(self.s1) + elif self.accelerator_type == "npu": + stream_ctx = torch.npu.stream(self.s1) + else: + stream_ctx = torch.cuda.stream(self.s1) + with stream_ctx: + # Restore tensor to GPU + accelerator_tensor = maybe_accelerator_tensor.to(self.accelerator_type, non_blocking=True) + # Restore original stride if we saved it (handles both broadcast and non-broadcast cases) + if original_stride is not None: + accelerator_tensor = torch.as_strided( + accelerator_tensor, + size=original_shape, + stride=original_stride, + storage_offset=original_storage_offset, + ) + maybe_accelerator_tensor = accelerator_tensor + + # Tell comp stream to wait for the info to be loaded before executing + self.s0.wait_stream(self.s1) + + # Stash the tensor to keep memory alive until compute stream is complete + self.bwd_tensor_stash[unpack_tensor_id] = maybe_accelerator_tensor + + # Note: [Track views of the unpacked] + # Why do we get the use count of the unpacked tensor here? We want an + # initial count to compare to later, during the post-hook of the + # backward node, when we need to decide whether we're allowed to free + # the tensor yet. In what obscure cases must we delay freeing the + # tensor (and thus call record_stream)? + # 1. Any of the outputs of the backward node is a view of the unpacked + # tensor. + # 2. In the case that this unpacked tensor will be used in a + # checkpointed region, if one of the recomputed saved tensors ends + # up as a view of the unpacked tensor. + # 3. The user abuses the system somehow and manually relies on the + # unpacked tensor to exist after the backward node has executed. + if self.accelerator_type == "npu": + storage_refcount = torch_npu._C._storage_Use_Count( + maybe_accelerator_tensor.untyped_storage()._cdata + ) + else: + storage_refcount = torch._C._storage_Use_Count( + maybe_accelerator_tensor.untyped_storage()._cdata + ) + + def hook(outputs, inputs): + # create events for the current node inputs/outputs if they were streamed in + if brought_back_from_cpu: + # See Note: [Track views of the unpacked] + # IF any of the outputs is a view of the tensor, OR if a view of + # the tensor has been saved as a part of checkpoint's recompute + # process, OR the user has abusedly incurred a reference on the + # unpacked tensor, THEN the tensor might be used later and we + # cannot presume to delete it after only the current node is + # done! So we use our frenemy, record_stream, to ensure the + # Tensor stays unmessed with until it's done getting used in the + # compute stream (s0 here). Note that the con here is we introduce + # non-deterministic (thus higher) memory usage, but this case + # should not happen often. + # Check if tensor still exists (might have been cleaned up by a previous node) + if unpack_tensor_id in self.bwd_tensor_stash: + unpacked_tensor = self.bwd_tensor_stash[unpack_tensor_id] + if self.accelerator_type == "npu": + storage_count = torch_npu._C._storage_Use_Count( + unpacked_tensor.untyped_storage()._cdata + ) + else: + storage_count = torch._C._storage_Use_Count(unpacked_tensor.untyped_storage()._cdata) + if storage_count > storage_refcount: + unpacked_tensor.record_stream(self.s0) + del self.bwd_tensor_stash[unpack_tensor_id] + else: + event = self.s0.record_event() + self.bwd_ev_stash[unpack_tensor_id] = event + + # if there are still things in the fwd_stash, get rid of them as we're in bwd now + for id in list(self.fwd_stash.keys()): + _, ev = self.fwd_stash[id] + self.s0.wait_event(ev) + del self.fwd_stash[id] + + # wait on prev node's events and del those + for id in prev_node_ids: + # Only wait on events that exist (some tensors may have used record_stream instead) + if id in self.bwd_ev_stash: + event = self.bwd_ev_stash[id] + self.s1.wait_event(event) + del self.bwd_ev_stash[id] + if id in self.bwd_tensor_stash: + del self.bwd_tensor_stash[id] + + return outputs + + node.register_hook(hook) + + # clear tensor from tracking + del self.tracker[unpack_tensor_id] + # Only set is_first_forward_call to True when all tensors have been unpacked + if len(self.tracker) == 0: + self.is_first_forward_call = True + return maybe_accelerator_tensor + + unpack_tensor = unpack_tensor_with_streams if self.use_streams else unpack_tensor_single_stream + super().__init__(pack_tensor, unpack_tensor) + + def update_model_params(self, model: nn.Module): + """ + Update the set of parameter storage pointers from the model. This allows filtering out model parameters during + offloading, which is especially important for FSDP models where parameters may not be detected by isinstance + checks. + + For FSDP v2, this method handles DTensor parameters which may be sharded across ranks and not have valid local + storage on all ranks. We extract the local tensor from DTensors using _local_tensor when available. + + Args: + model: The model whose parameters should be tracked + """ + param_storages = set() + + for p in model.parameters(): + # For FSDP v2: extract local tensor from DTensor + actual_tensor = p + if DTensor is not None and isinstance(p, DTensor) and hasattr(p, "_local_tensor"): + actual_tensor = p._local_tensor + + # Try to get storage pointer + try: + storage_ptr = actual_tensor.untyped_storage().data_ptr() + if storage_ptr != 0: + param_storages.add(storage_ptr) + except RuntimeError: + # Parameter doesn't have accessible storage (e.g., FSDP v2 sharded without local shard, FP8 parameters) + # These will be caught by other checks (isinstance for Parameter, class name for FP8) + continue + + self.param_storages = param_storages + + def __enter__(self): + """Clear stale state and release BNB buffers before entering. + + By the time __enter__ is called, the previous forward/backward has already completed, so anything still in + tracker, storage_to_tensor_id, or the stashes is leaked and safe to drop. + + Two leak paths are handled: + 1. MoE + sample_packing + torch.compile: dynamic expert routing may leave saved tensors on subgraphs whose + backward nodes never execute, so the unpack-then-delete logic never fires. tracker/stashes from the previous + step survive into the next. + 2. QLoRA BNB dequantization buffers: tracker retains references to tensors sharing allocator blocks with BNB + buffers, and the allocator cache is never flushed between steps (~0.6 GiB/step, OOM after 30-40). + + Returns super().__enter__() to register pack/unpack hooks via saved_tensors_hooks (PyTorch autograd engine). + """ + self.tracker.clear() + self.storage_to_tensor_id.clear() + self.tensor_id = 0 + self.is_first_forward_call = True + self.is_first_backward_call = True + if self.use_streams: + self.bwd_tensor_stash.clear() + self.bwd_ev_stash.clear() + self.fwd_stash.clear() + if "bitsandbytes" in sys.modules: + if self.accelerator_type == "xpu": + torch.xpu.empty_cache() + elif is_torch_npu_available() and self.accelerator_type == "npu": + torch.npu.empty_cache() + else: + torch.cuda.empty_cache() + return super().__enter__() + + def __exit__(self, *args, **kwargs): + """Sync streams and clear stashes before parent cleanup. + + try/finally ensures the saved_tensors_hooks parent cleanup runs even if stream sync raises — otherwise hooks + stay permanently installed, creating a silent memory leak. + """ + try: + if self.use_streams: + self.s0.synchronize() + self.s1.synchronize() + self.bwd_tensor_stash.clear() + self.bwd_ev_stash.clear() + self.fwd_stash.clear() + finally: + result = super().__exit__(*args, **kwargs) + return result + + +class NoOpManager(saved_tensors_hooks): + """ + A `saved_tensors_hook` manager used to disable any other `saved_tensors_hook` manager applied before. This relies + on the behavior that only the most recently registered `saved_tensors_hook` will run. + + One example usage is to opt a local region of code out of activations offloading, which is usually applied globally + to best track state. + """ + + def __init__(self) -> None: + def noop(tensor): + return tensor + + super().__init__(noop, noop) + + +def get_act_offloading_ctx_manager( + model: nn.Module, + use_pin_memory: bool = True, + use_streams: bool = True, + min_offload_size: int = 1024, + max_fwd_stash_size: int = 5, + warn_if_no_head: bool = True, +) -> OffloadActivations: + """ + Returns the activation offloading context manager for the model. All but the last output Linear in every step will + be offloaded. + + If activation offloading is enabled, we return the OffloadActivations context manager. If activation offloading is + disabled, we return a NoOpManager context manager. + + Args: + model (`nn.Module`): + Model to wrap with the activation offloading context manager. + use_pin_memory (`bool`, *optional*, defaults to `True`): + Whether to offloaded Tensor will be placed in pinned memory on the CPU. Pinned memory allows the Tensor to + be moved back onto GPU more quickly but is a limited resource. + use_streams (`bool`, *optional*, defaults to `True`): + Whether to use streams for performance optimization where the communications get overlapped with the + computation. Requires a torch build after torch-2.5.0. + min_offload_size (`int`, *optional*, defaults to `1024`): + Minimum number of bytes a Tensor must be in order to qualify for offloading. If the tensor is too small, we + do not want to waste bandwidth and resources moving it to CPU and back. + max_fwd_stash_size (`int`, *optional*, defaults to `5`): + Maximum size of the forward stash, or the maximum number of consecutive activations to keep alive during + the forward pass. This number must be at least 1. Keeping alive more activations will potentially allow + more overlap between the communication and compute streams at the cost of increasing memory usage. Keeping + alive fewer activations will conserve memory, but may cause poor overlap between the streams, increasing + runtime. + warn_if_no_head (`bool`, *optional*, defaults to `True`): + Whether to warn if no output head is detected. If set to `False`, no warning will be raised if no output + head is detected. + + Returns: + `contextlib.ContextDecorator`: + Activation offloading context manager for the model. + """ + activations_handling_ctx = OffloadActivations( + use_pin_memory=use_pin_memory, + use_streams=use_streams, + min_offload_size=min_offload_size, + max_fwd_stash_size=max_fwd_stash_size, + ) + + # Update parameter storages to filter them during offloading (important for FSDP) + activations_handling_ctx.update_model_params(model) + + # Below is our hack to disable offloading the last output Linear in every + # step, as the cost for offloading the activation and then soon after bringing + # it back is expensive. + output_head_detected = False + noop_ctx = NoOpManager() + + # Try to get the actual model if it's wrapped + unwrapped_model = model + if hasattr(unwrapped_model, "module"): + unwrapped_model = unwrapped_model.module + # check for PEFT models + if hasattr(unwrapped_model, "base_model") and hasattr(unwrapped_model, "peft_config"): + unwrapped_model = unwrapped_model.base_model + + # Check for different types of output heads + if hasattr(unwrapped_model, "output"): + if isinstance(unwrapped_model.output, nn.Module): + unwrapped_model.output.register_forward_pre_hook(lambda *args: noop_ctx.__enter__()) + unwrapped_model.output.register_forward_hook(lambda *args: noop_ctx.__exit__(), always_call=True) + output_head_detected = True + elif hasattr(unwrapped_model.output, "linear") and isinstance(unwrapped_model.output.linear, nn.Module): + unwrapped_model.output.linear.register_forward_pre_hook(lambda *args: noop_ctx.__enter__()) + unwrapped_model.output.linear.register_forward_hook(lambda *args: noop_ctx.__exit__(), always_call=True) + output_head_detected = True + + # Check for HuggingFace model output heads + elif hasattr(unwrapped_model, "lm_head"): + unwrapped_model.lm_head.register_forward_pre_hook(lambda *args: noop_ctx.__enter__()) + unwrapped_model.lm_head.register_forward_hook(lambda *args: noop_ctx.__exit__(), always_call=True) + output_head_detected = True + + # Check for decoder-based models + elif hasattr(unwrapped_model, "decoder"): + decoder = unwrapped_model.decoder + if hasattr(decoder, "output"): + decoder.output.register_forward_pre_hook(lambda *args: noop_ctx.__enter__()) + decoder.output.register_forward_hook(lambda *args: noop_ctx.__exit__(), always_call=True) + output_head_detected = True + # Some models have lm_head in the decoder + elif hasattr(decoder, "lm_head"): + decoder.lm_head.register_forward_pre_hook(lambda *args: noop_ctx.__enter__()) + decoder.lm_head.register_forward_hook(lambda *args: noop_ctx.__exit__(), always_call=True) + output_head_detected = True + + # Check for transformer models with final layer norm + elif hasattr(unwrapped_model, "final_layer_norm") or hasattr(unwrapped_model, "ln_f"): + final_norm = getattr(unwrapped_model, "final_layer_norm", None) or unwrapped_model.ln_f + final_norm.register_forward_pre_hook(lambda *args: noop_ctx.__enter__()) + final_norm.register_forward_hook(lambda *args: noop_ctx.__exit__(), always_call=True) + output_head_detected = True + + # Check for models with head module + elif hasattr(unwrapped_model, "head") and isinstance(unwrapped_model.head, nn.Module): + unwrapped_model.head.register_forward_pre_hook(lambda *args: noop_ctx.__enter__()) + unwrapped_model.head.register_forward_hook(lambda *args: noop_ctx.__exit__(), always_call=True) + output_head_detected = True + + if not output_head_detected and warn_if_no_head: + logger.warning( + "During activation offloading, no output head was detected. If your model has an output head, it will be " + "offloaded. This usually greatly slows training, given the large vocabulary size. To change this " + "behavior, set your output head as model.output and make it an nn.Module. You can disable this warning by " + "passing `warn_if_no_head=False`." + ) + + # Disable offloading for any Liger modules + for name, module in unwrapped_model.named_modules(): + if "liger" in name.lower(): + module.register_forward_pre_hook(lambda *args: noop_ctx.__enter__()) + module.register_forward_hook(lambda *args: noop_ctx.__exit__(), always_call=True) + + return activations_handling_ctx diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/models/utils.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/models/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..52badde5ed6a278595bc968d081ec83b2ad52b2d --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/models/utils.py @@ -0,0 +1,406 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import itertools +import warnings +from collections.abc import Callable +from contextlib import contextmanager +from copy import deepcopy +from typing import TYPE_CHECKING, Any + +import accelerate +import torch.nn as nn +import transformers +from accelerate import Accelerator +from packaging.version import Version +from torch.distributed.fsdp import FSDPModule +from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP +from transformers import GenerationConfig, PreTrainedModel + +from ..import_utils import suppress_experimental_warning + + +with suppress_experimental_warning(): + from ..experimental.utils import create_reference_model as _create_reference_model + + +if Version(accelerate.__version__) >= Version("1.11.0"): + from accelerate.utils.fsdp_utils import get_parameters_from_modules + +if TYPE_CHECKING: + from deepspeed.runtime.engine import DeepSpeedEngine + from torch.nn import Module + from torch.nn.parallel.distributed import DistributedDataParallel + + +def remove_hooks(model: "DeepSpeedEngine") -> None: + """Removes the optimizer hooks from a DeepSpeed ZeRO-3 model.""" + if not hasattr(model, "optimizer"): # before the first training step, the model has no optimizer + return + if model.optimizer is not None and hasattr(model.optimizer, "parameter_offload"): + optimizer_offload = model.optimizer.parameter_offload + elif model.optimizer is not None: + optimizer_offload = model.optimizer + else: + raise RuntimeError("The model optimizer is None, which is not yet supported.") + + for param in iter_params(optimizer_offload.module, recurse=True): + param.ds_active_sub_modules.clear() + + for hook in optimizer_offload.forward_hooks: + hook.remove() + for hook in optimizer_offload.backward_hooks: + hook.remove() + + optimizer_offload.forward_hooks = [] + optimizer_offload.backward_hooks = [] + + +def get_all_parameters(sub_module, recurse=False): + return itertools.chain(sub_module.named_parameters(recurse=recurse), sub_module.ds_external_parameters()) + + +def iter_params(module, recurse=False): + return [param for _, param in get_all_parameters(module, recurse)] + + +def add_hooks(model: "DeepSpeedEngine") -> None: + """Adds the optimizer hooks from a DeepSpeed ZeRO-3 model.""" + import deepspeed + + if not hasattr(model, "optimizer"): # before the first training step, the model has no optimizer + return + if model.optimizer is not None and hasattr(model.optimizer, "parameter_offload"): + optimizer_offload = model.optimizer.parameter_offload + elif model.optimizer is not None: + optimizer_offload = model.optimizer + else: + raise RuntimeError("The model optimizer is None, which is not yet supported.") + + # Invalidate parameter coordinator trace to prevent stale state + # after generation forward passes (fixes ZeRO-3 + GKD compatibility) + if hasattr(optimizer_offload, "param_coordinator"): # param_coordinator only exists in ZeRO stage 3 + coordinator = optimizer_offload.param_coordinator + # Only invalidate if trace is not already invalid + if not coordinator.is_invalid_trace(): + coordinator._invalidate_trace() + + if Version(deepspeed.__version__) >= Version("0.16.4"): + # Account for renaming in https://github.com/deepspeedai/DeepSpeed/pull/6847 + optimizer_offload._register_deepspeed_module(optimizer_offload.module) + else: + optimizer_offload._register_hooks_recursively(optimizer_offload.module) + + +@contextmanager +def _unwrap_model_for_generation( + model: "DistributedDataParallel | DeepSpeedEngine", + accelerator: "Accelerator", + gather_deepspeed3_params: bool = True, +): + """ + Context manager to unwrap distributed or accelerated models for generation tasks. + + Args: + model (`DistributedDataParallel | DeepSpeedEngine`): + Model to be unwrapped. + accelerator ([`~accelerate.Accelerator`]): + Accelerator instance managing the model. + gather_deepspeed3_params (`bool`, *optional*, defaults to `True`): + Whether to gather weights for DeepSpeed ZeRO Stage 3 models. If `False`, skips parameter gathering, which + can be more memory-efficient but may lead to slower generation times. + + Yields: + Unwrapped model. + + Example: + ```python + with _unwrap_model_for_generation(model, accelerator) as unwrapped_model: + generated_outputs = unwrapped_model.generate(input_ids) + ``` + """ + unwrapped_model = accelerator.unwrap_model(model) + is_gradient_checkpointing = unwrapped_model.is_gradient_checkpointing + if is_gradient_checkpointing: + unwrapped_model.gradient_checkpointing_disable() + from ..distributed import DistributedBackend + + if DistributedBackend(accelerator).is_zero3: + if not gather_deepspeed3_params: + yield accelerator.unwrap_model(model) + else: + import deepspeed + + with deepspeed.zero.GatheredParameters(model.parameters()): + remove_hooks(model) + yield accelerator.unwrap_model(model) + add_hooks(model) + else: + yield unwrapped_model + if is_gradient_checkpointing: + unwrapped_model.gradient_checkpointing_enable() + + +@contextmanager +def _override_model_generation_config(model, generation_kwargs=None): + """ + Context manager to temporarily override a model's generation_config with training config. + + This works around transformers' config merging logic that would otherwise overwrite values matching global defaults + with model-specific values (see upstream issue transformers#42762; fixed in transformers v5 by PR + `transformers#42702`). + + By temporarily setting the model's generation_config to match the passed generation_config, we avoid the conflict. + + The model's original generation_config is preserved outside this context, ensuring that saved/pushed models retain + their intended inference behavior. + + Args: + model: The model (typically unwrapped_model) whose generation_config to temporarily override. + generation_kwargs (dict): Generation kwargs to be used to override model's generation config. + """ + if ( + # Issue fixed in transformers v5 by PR transformers#42702 + Version(transformers.__version__) >= Version("5.0.0") + or generation_kwargs is None + or not hasattr(model, "generation_config") + ): + yield model + return + # If it is a PEFT model, override the underlying base model + if hasattr(model, "get_base_model"): + model = model.get_base_model() + # Keep original model generation_config + original_config = model.generation_config + # Create training-specific generation config from the model's original generation config + # Then overwrite it with the training-specific generation kwargs + generation_config = GenerationConfig.from_dict(model.generation_config.to_dict()) + generation_config.update(**generation_kwargs) + model.generation_config = generation_config + try: + yield + finally: + model.generation_config = original_config + + +@contextmanager +def unwrap_model_for_generation( + model: "DistributedDataParallel | DeepSpeedEngine", + accelerator: "Accelerator", + gather_deepspeed3_params: bool = True, + generation_kwargs: dict | None = None, +): + """ + Context manager to unwrap distributed or accelerated models for generation tasks. + + This function unwraps distributed models (FSDP, DeepSpeed) and optionally overrides the model's generation_config + temporarily during generation. This is useful for applying training-specific generation parameters without + permanently modifying the model's original generation_config. + + Args: + model (`DistributedDataParallel | DeepSpeedEngine`): + Model to be unwrapped. + accelerator ([`~accelerate.Accelerator`]): + Accelerator instance managing the model. + gather_deepspeed3_params (`bool`, *optional*, defaults to `True`): + Whether to gather weights for DeepSpeed ZeRO Stage 3 models. If `False`, skips parameter gathering, which + can be more memory-efficient but may lead to slower generation times. + generation_kwargs (dict, *optional*): + If provided, temporarily overrides the model's generation_config during generation. The original config is + automatically restored when exiting the context. This is useful for using different generation parameters + during training vs. inference. + + Yields: + Unwrapped model with optionally overridden generation_config. + """ + with ( + _unwrap_model_for_generation( + model, accelerator, gather_deepspeed3_params=gather_deepspeed3_params + ) as unwrapped_model, + _override_model_generation_config(unwrapped_model, generation_kwargs=generation_kwargs), + ): + yield unwrapped_model + + +def prepare_deepspeed(model: "Module", accelerator: "Accelerator"): + """Prepares the model for DeepSpeed inference or evaluation by initializing it with the appropriate configuration. + + Adapted from accelerate: + https://github.com/huggingface/accelerate/blob/739b135f8367becb67ffaada12fe76e3aa60fefd/src/accelerate/accelerator.py#L1473 + """ + import deepspeed # local import (instead of top-level) to avoid DS init interfering with other backends (like vllm): https://github.com/deepspeedai/DeepSpeed/issues/7252 + + deepspeed_plugin = accelerator.state.deepspeed_plugin + config_kwargs = deepcopy(deepspeed_plugin.deepspeed_config) + stage = config_kwargs["zero_optimization"]["stage"] + + if model is not None: + hidden_size = ( + max(model.config.hidden_sizes) + if getattr(model.config, "hidden_sizes", None) + else getattr(model.config, "hidden_size", None) + ) + if hidden_size is not None and stage == 3: + # Note that `stage3_prefetch_bucket_size` can produce DeepSpeed messages like: `Invalidate trace cache + # @ step 0: expected module 1, but got module 0` + # This is expected and is not an error, see: https://github.com/microsoft/DeepSpeed/discussions/4081 + config_kwargs.update( + { + "zero_optimization.reduce_bucket_size": hidden_size * hidden_size, + "zero_optimization.stage3_param_persistence_threshold": 10 * hidden_size, + "zero_optimization.stage3_prefetch_bucket_size": 0.9 * hidden_size * hidden_size, + } + ) + + # If ZeRO-3 is used, we shard both the active and reference model. + # Otherwise, we assume the reference model fits in memory and is initialized on each device with ZeRO + # disabled (stage 0) + if stage != 3: + config_kwargs["zero_optimization"]["stage"] = 0 + model, *_ = deepspeed.initialize(model=model, config=config_kwargs) + model.eval() + return model + + +def prepare_fsdp(model, accelerator: Accelerator) -> FSDP | FSDPModule: + # Check if the model is already a FSDP model due to `Manual Wrapping` and if so, don't wrap it again + if not isinstance(model, (FSDP, FSDPModule)): + fsdp_plugin = accelerator.state.fsdp_plugin + if fsdp_plugin.fsdp_version == 1: + accelerator.state.fsdp_plugin.set_auto_wrap_policy(model) + kwargs = { + "sharding_strategy": fsdp_plugin.sharding_strategy or fsdp_plugin.reshard_after_forward, + "cpu_offload": fsdp_plugin.cpu_offload, + "auto_wrap_policy": fsdp_plugin.auto_wrap_policy, + "mixed_precision": fsdp_plugin.mixed_precision_policy, + "sync_module_states": fsdp_plugin.sync_module_states, + "backward_prefetch": fsdp_plugin.backward_prefetch, + "forward_prefetch": fsdp_plugin.forward_prefetch, + "use_orig_params": fsdp_plugin.use_orig_params, + "param_init_fn": fsdp_plugin.param_init_fn, + "ignored_modules": fsdp_plugin.ignored_modules, + "limit_all_gathers": fsdp_plugin.limit_all_gathers, + "device_id": accelerator.device, + } + model = FSDP(model, **kwargs) + elif fsdp_plugin.fsdp_version == 2: + from torch.distributed.fsdp import MixedPrecisionPolicy, fully_shard + + mesh = getattr(accelerator, "torch_device_mesh", None) + if Version(accelerate.__version__) >= Version("1.11.0"): + ignored_params = get_parameters_from_modules(fsdp_plugin.ignored_modules, model, accelerator.device) + else: + warnings.warn( + "FSDP version 2 is being used with accelerate version < 1.11.0, which may lead to incorrect " + "handling of ignored modules. Please upgrade accelerate to v1.11.0 or later for proper support." + ) + ignored_params = None + fully_shard( + model, + reshard_after_forward=fsdp_plugin.reshard_after_forward, + offload_policy=fsdp_plugin.cpu_offload, + # `fully_shard` doesn't accept `None` in case of `MixedPrecisionPolicy` + mp_policy=fsdp_plugin.mixed_precision_policy or MixedPrecisionPolicy(), + mesh=mesh[tuple(accelerator.parallelism_config.fsdp_dim_names)] if mesh is not None else None, + ignored_params=ignored_params, + ) + else: + raise ValueError(f"FSDP version {fsdp_plugin.fsdp_version} is not supported.") + model.eval() + return model + + +class _ForwardRedirection: + """Implements the `forward-redirection`. + + Taken from Pytorch-lightning: + https://github.com/Lightning-AI/pytorch-lightning/blob/02311d03fb982560246eead7c08104481fac9579/src/lightning/pytorch/strategies/strategy.py#L602 + + A method call to a wrapped module gets rerouted through the wrapper's `forward` method instead. + + """ + + def __call__( + self, wrapper_module: nn.Module, original_module: nn.Module, method: Callable, *args: Any, **kwargs: Any + ): + """Reroutes a method call through the `wrapper_module`'s `forward` method. + + Args: + wrapper_module: The module that has `original_module` wrapped. + original_module: The module that was wrapped inside `wrapper_module`. + method: The method that should be called on the `original_module` after inputs get + redirected through the `wrapper_module`'s `forward` method. + *args: The positional arguments to the `method`. They will get passed to a patched + `forward` method instead. + **kwargs: The keyword arguments to the `method`. They will get passed to a patched + `forward` method instead. + + """ + original_forward = original_module.forward + + def wrapped_forward(*_args: Any, **_kwargs: Any) -> Any: + # Unpatch ourselves immediately before calling the method `method_name` + # because itself may want to call the real `forward` + original_module.forward = original_forward # type: ignore[method-assign] + # Call the actual method e.g. `.training_step(...)` + out = method(*_args, **_kwargs) + self.on_after_inner_forward(wrapper_module, original_module) + return out + + # Patch the original_module's forward so we can redirect the arguments back to the real method + original_module.forward = wrapped_forward # type: ignore[method-assign] + + wrapper_output = wrapper_module(*args, **kwargs) + self.on_after_outer_forward(wrapper_module, original_module) + return wrapper_output + + def on_after_inner_forward(self, wrapper_module: nn.Module, original_module: nn.Module) -> None: + pass + + def on_after_outer_forward(self, wrapper_module: nn.Module, original_module: nn.Module) -> None: + pass + + +@contextmanager +def disable_gradient_checkpointing(model: PreTrainedModel, gradient_checkpointing_kwargs: dict | None = None): + """ + Temporarily disable gradient checkpointing, restoring the previous state afterward. + + Args: + model (`PreTrainedModel`): + Model for which to temporarily disable gradient checkpointing. + gradient_checkpointing_kwargs (`dict` or `None`, *optional*): + Additional kwargs for gradient checkpointing enabling. + """ + was_enabled = model.is_gradient_checkpointing + if was_enabled: + model.gradient_checkpointing_disable() + try: + yield + finally: + if was_enabled: + model.gradient_checkpointing_enable(gradient_checkpointing_kwargs) + + +def create_reference_model( + model: nn.Module, num_shared_layers: int | None = None, pattern: str | None = None +) -> nn.Module: + warnings.warn( + "The `create_reference_model` function is now located in `trl.experimental.utils`. Please update your " + "imports to `from trl.experimental.utils import create_reference_model`. This import path will be removed in " + "TRL 1.0.0.", + FutureWarning, + stacklevel=2, + ) + return _create_reference_model(model, num_shared_layers=num_shared_layers, pattern=pattern) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/py.typed b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/rewards/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/rewards/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..aeec677314023b0a2221d98872304a4f631530cf --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/rewards/__init__.py @@ -0,0 +1,35 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import sys +from typing import TYPE_CHECKING + +from .._lazy_module import _LazyModule + + +_import_structure = { + "accuracy_rewards": ["accuracy_reward", "reasoning_accuracy_reward"], + "format_rewards": ["think_format_reward"], + "other_rewards": ["get_soft_overlong_punishment"], +} + + +if TYPE_CHECKING: + from .accuracy_rewards import accuracy_reward, reasoning_accuracy_reward + from .format_rewards import think_format_reward + from .other_rewards import get_soft_overlong_punishment + + +else: + sys.modules[__name__] = _LazyModule(__name__, __file__, _import_structure, module_spec=__spec__) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/rewards/accuracy_rewards.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/rewards/accuracy_rewards.py new file mode 100644 index 0000000000000000000000000000000000000000..45b061d846b6823d234d3e6e9d360f8af00755b9 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/rewards/accuracy_rewards.py @@ -0,0 +1,244 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging +import threading +from collections.abc import Callable + +from ..import_utils import is_math_verify_available + + +if is_math_verify_available(): + from latex2sympy2_extended import NormalizationConfig + from math_verify import LatexExtractionConfig, parse, verify + + +def accuracy_reward( + completions: list[list[dict[str, str]]], + solution: list[str], + log_extra: Callable[[str, list], None] | None = None, + **kwargs, +) -> list[float | None]: + r""" + Reward function that checks if the completion matches the ground truth. + - If both gold and prediction are parseable → use math verification. + - If gold is not parseable → return `None` to skip the example. + + Args: + completions (`list[list[dict[str, str]]]`): + List of completions to be evaluated. Each completion must be a list of one message, i.e. a dictionary + containing the key `"content"` with the value being the text of the completion. + solution (`list[str]`): + List of the raw-text solutions to the questions/problems/prompts. + log_extra (`callable`, *optional*): + Callable to log extra columns to the completions table, provided automatically by the trainer. Defaults to + `None` to allow calling the function directly outside of a trainer (e.g., for testing). + **kwargs: + Additional keyword arguments. This function does not use them, but they are required in the function + signature to ensure compatibility with trainers like [`GRPOTrainer`]. + Example: + ```python + >>> from trl.rewards import accuracy_reward + + >>> solutions = [r"\frac{1}{3}", r"\frac{1}{3}"] + >>> completions = [ + ... [{"role": "assistant", "content": r"My answer is \boxed{\frac{1}{3}}"}], + ... [{"role": "assistant", "content": r"My answer is \boxed{\frac{1}{2}}"}], + ... ] + >>> accuracy_reward(completions, solutions) + [1.0, 0.0] + ``` + """ + if not is_math_verify_available(): + raise ImportError("Please install the `math_verify` package to use accuracy_reward") + + contents = [completion[0]["content"] for completion in completions] + rewards = [] + gold_parsed_strs = [] + answer_parsed_strs = [] + + # math_verify uses signal.alarm() for timeouts, which only works in the main thread. + # Disable timeouts when running in a non-main thread to avoid ValueError. + is_main_thread = threading.current_thread() is threading.main_thread() + parsing_timeout = None if not is_main_thread else 10 + verify_timeout = None if not is_main_thread else 5 + + # Suppress the "Timeout is disabled" warnings from math_verify when we intentionally disable timeouts + if not is_main_thread: + logging.getLogger("math_verify.parser").setLevel(logging.ERROR) + logging.getLogger("math_verify.grader").setLevel(logging.ERROR) + + for content, sol in zip(contents, solution, strict=True): + gold_parsed = parse(sol, parsing_timeout=parsing_timeout) + if len(gold_parsed) != 0: + # We require the answer to be provided in correct latex (no malformed operators) + answer_parsed = parse( + content, + extraction_config=[ + LatexExtractionConfig( + normalization_config=NormalizationConfig(units=True), + # Ensures that boxed is tried first + boxed_match_priority=0, + try_extract_without_anchor=False, + ) + ], + extraction_mode="first_match", + parsing_timeout=parsing_timeout, + ) + reward = float(verify(gold_parsed, answer_parsed, timeout_seconds=verify_timeout)) + gold_parsed_strs.append(str(gold_parsed)) + answer_parsed_strs.append(str(answer_parsed) if answer_parsed else "[unparseable]") + else: + # If the gold solution cannot be parsed, we assign `None` to skip this example + reward = None + gold_parsed_strs.append("[unparseable]") + answer_parsed_strs.append("[skipped]") + rewards.append(reward) + + if log_extra is not None: + log_extra("solution", list(solution)) + log_extra("gold_parsed", gold_parsed_strs) + log_extra("answer_parsed", answer_parsed_strs) + + return rewards + + +def reasoning_accuracy_reward( + completions: list[list[dict[str, str]]], + solution: list[str], + reasoning_delimiters: list[str] | None = None, + log_extra: Callable[[str, list], None] | None = None, + **kwargs, +) -> list[float | None]: + r""" + Reward function that removes the reasoning content and checks if the final answer matches the ground truth. + - If both gold and prediction are parseable → use math verification. + - If gold is not parseable → return `None` to skip the example. + + Args: + completions (`list[list[dict[str, str]]]`): + List of completions to be evaluated. Each completion must be a list of one message, i.e. a dictionary + containing the key `"content"` with the value being the text of the completion. + solution (`list[str]`): + List of the raw-text solutions to the questions/problems/prompts. + reasoning_delimiters (`list[str]]`, *optional*): + List of strings indicating where the reasoning content ends. The final answer is assumed to be after the + last occurrence of any of these delimiters. If `None`, defaults to `[""]`. + log_extra (`callable`, *optional*): + Callable to log extra columns to the completions table, provided automatically by the trainer. Defaults to + `None` to allow calling the function directly outside of a trainer (e.g., for testing). + **kwargs: + Additional keyword arguments. This function does not use them, but they are required in the function + signature to ensure compatibility with trainers like [`GRPOTrainer`]. + Example: + ```python + >>> from trl.rewards import reasoning_accuracy_reward + + >>> reasoning_delimiters = [""] + >>> solutions = [r"\frac{1}{3}", r"\frac{1}{3}", r"\frac{1}{3}"] + >>> completions = [ + ... [ + ... { + ... "role": "assistant", + ... "content": r" Reasoning content The final answer is \boxed{\frac{1}{3}}", + ... } + ... ], + ... [ + ... { + ... "role": "assistant", + ... "content": r" Reasoning content The final answer is \boxed{\frac{1}{2}}", + ... } + ... ], + ... [ + ... { + ... "role": "assistant", + ... "content": r" Reasoning content with partial answers \boxed{\frac{1}{3}} but no final answer", + ... } + ... ], + ... ] + >>> reasoning_accuracy_reward(completions, solutions, reasoning_delimiters=reasoning_delimiters) + [1.0, 0.0, 0.0] + ``` + """ + if not is_math_verify_available(): + raise ImportError("Please install the `math_verify` package to use reasoning_accuracy_reward") + + if reasoning_delimiters is None: + # Use sensible defaults for majority of reasoning models + reasoning_delimiters = [""] + + rewards = [] + contents = [completion[0]["content"] for completion in completions] + gold_parsed_strs = [] + answer_parsed_strs = [] + + # math_verify uses signal.alarm() for timeouts, which only works in the main thread. + # Disable timeouts when running in a non-main thread to avoid ValueError. + is_main_thread = threading.current_thread() is threading.main_thread() + parsing_timeout = None if not is_main_thread else 10 + verify_timeout = None if not is_main_thread else 5 + + # Suppress the "Timeout is disabled" warnings from math_verify when we intentionally disable timeouts + if not is_main_thread: + logging.getLogger("math_verify.parser").setLevel(logging.ERROR) + logging.getLogger("math_verify.grader").setLevel(logging.ERROR) + + for content, sol in zip(contents, solution, strict=True): + # Split final answer from reasoning content + is_reasoning_complete = False + for delim in reasoning_delimiters: + if delim in content: + content = content.split(delim)[-1] + is_reasoning_complete = True + break + if not is_reasoning_complete: + # We assign zero reward instead of `None` to penalize incomplete reasoning + rewards.append(0.0) + gold_parsed_strs.append("[incomplete reasoning]") + answer_parsed_strs.append("[incomplete reasoning]") + continue + + gold_parsed = parse(sol, parsing_timeout=parsing_timeout) + if len(gold_parsed) != 0: + # We require the answer to be provided in correct latex (no malformed operators) + answer_parsed = parse( + content, + extraction_config=[ + LatexExtractionConfig( + boxed_match_priority=0, + normalization_config=NormalizationConfig( + units=True, + ), + try_extract_without_anchor=False, + ) + ], + extraction_mode="first_match", + parsing_timeout=parsing_timeout, + ) + reward = float(verify(gold_parsed, answer_parsed, timeout_seconds=verify_timeout)) + gold_parsed_strs.append(str(gold_parsed)) + answer_parsed_strs.append(str(answer_parsed) if answer_parsed else "[unparseable]") + else: + # If the gold solution cannot be parsed, we assign `None` to skip this example + reward = None + gold_parsed_strs.append("[unparseable]") + answer_parsed_strs.append("[skipped]") + rewards.append(reward) + + if log_extra is not None: + log_extra("solution", list(solution)) + log_extra("gold_parsed", gold_parsed_strs) + log_extra("answer_parsed", answer_parsed_strs) + + return rewards diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/rewards/format_rewards.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/rewards/format_rewards.py new file mode 100644 index 0000000000000000000000000000000000000000..c737d0036b165ebf4a15e2c2558f82187e87038d --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/rewards/format_rewards.py @@ -0,0 +1,50 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import re + + +def think_format_reward(completions: list[list[dict[str, str]]], **kwargs) -> list[float]: + r""" + Reward function that checks if the reasoning process is enclosed within `""` and `""` tags. The + function returns a reward of 1.0 if the format is correct, otherwise 0.0. + + Args: + completions (`list[list[dict[str, str]]]`): + List of completions to be evaluated. Each completion must be a list of one message, i.e. a dictionary + containing the key `"content"` with the value being the text of the completion. + **kwargs: + Additional keyword arguments. This function does not use them, but they are required in the function + signature to ensure compatibility with trainers like [`GRPOTrainer`]. + + Returns: + `list[float]`: + A list of rewards, where each reward is 1.0 if the completion matches the expected format, otherwise 0.0. + + Example: + ```python + >>> from trl.rewards import think_format_reward + + >>> completions = [ + ... [{"content": "\nThis is my reasoning.\n\nThis is my answer."}], + ... [{"content": "\nThis is my reasoning.\nThis is my answer."}], + ... ] + >>> think_format_reward(completions) + [1.0, 0.0] + ``` + """ + pattern = r"^(?!.*)(.*?).*$" + completion_contents = [completion[0]["content"] for completion in completions] + matches = [re.match(pattern, content, re.DOTALL | re.MULTILINE) for content in completion_contents] + return [1.0 if match else 0.0 for match in matches] diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/rewards/other_rewards.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/rewards/other_rewards.py new file mode 100644 index 0000000000000000000000000000000000000000..9e6fb05fc942b358720cded0e718c987fadae350 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/rewards/other_rewards.py @@ -0,0 +1,73 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from collections.abc import Callable + + +def get_soft_overlong_punishment(max_completion_len: int, soft_punish_cache: int) -> Callable: + # docstyle-ignore + r""" + Reward function that penalizes overlong completions. It is used to penalize overlong completions, but not to reward + shorter completions. Reference: Eq. (13) from the DAPO paper (https://huggingface.co/papers/2503.14476) + + $$ + R_{\text{length}}(y) = \begin{cases} + 0, & |y| \le L_{\max} - L_{\text{cache}} \\ + \dfrac{(L_{\max} - L_{\text{cache}}) - |y|}{L_{\text{cache}}}, & L_{\max} - L_{\text{cache}} < |y| \le L_{\max} \\ + -1, & L_{\max} < |y| + \end{cases} + $$ + + Args: + max_completion_len (`int`): + Maximum length of the completion, \( L_{\max} \). + soft_punish_cache (`int`): + Minimum length of the completion, \( L_{\text{cache}} \). If set to `0`, no minimum length is applied. + + Example: + ```python + from trl.rewards import get_soft_overlong_punishment + + soft_overlong_punishment = get_soft_overlong_punishment(max_completion_len=100, soft_punish_cache=20) + completion_ids = [[1] * 90] # simulating a completion with 90 tokens. 90 is between 80 and 100. + rewards = soft_overlong_punishment(completion_ids) + print(rewards) # [-0.5] + ``` + """ + return _SoftOverlongPunishment(max_completion_len, soft_punish_cache) + + +class _SoftOverlongPunishment: + # Callable class rather than a closure so the reward stays picklable: the async GRPO rollout + # worker forwards reward funcs to a spawned child process, and closures can't be pickled. + # `__name__` mirrors the old inner-function name so metric logging keys are unchanged. + __name__ = "soft_overlong_punishment_reward" + + def __init__(self, max_completion_len: int, soft_punish_cache: int): + self.max_completion_len = max_completion_len + self.soft_punish_cache = soft_punish_cache + + def __call__(self, completion_ids: list[list[int]], **kwargs) -> list[float]: + rewards = [] + for ids in completion_ids: + completion_length = len(ids) + if completion_length <= self.max_completion_len - self.soft_punish_cache: + rewards.append(0.0) + elif self.max_completion_len - self.soft_punish_cache < completion_length <= self.max_completion_len: + rewards.append( + (self.max_completion_len - self.soft_punish_cache - completion_length) / self.soft_punish_cache + ) + else: + rewards.append(-1.0) + return rewards diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/scripts/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/scripts/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cb15e6cdfe5446affd20a72cd22a8c74c6f15e1e --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/scripts/__init__.py @@ -0,0 +1,29 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import TYPE_CHECKING + +from .._lazy_module import _LazyModule + + +_import_structure = { + "utils": ["DatasetMixtureConfig", "ScriptArguments", "TrlParser", "get_dataset", "init_zero_verbose"], +} + +if TYPE_CHECKING: + from .utils import DatasetMixtureConfig, ScriptArguments, TrlParser, get_dataset, init_zero_verbose +else: + import sys + + sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/scripts/_hf_argparser.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/scripts/_hf_argparser.py new file mode 100644 index 0000000000000000000000000000000000000000..8e795b96fcdd0dd1a9ea5e1db037ee85f3e268d5 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/scripts/_hf_argparser.py @@ -0,0 +1,453 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +# Copied from: https://github.com/huggingface/transformers/blob/3a275d3581c0ecf962f7412aa764c2047331fd6b/src/transformers/hf_argparser.py +# This avoids an upstream latency issue: https://github.com/huggingface/transformers/issues/44273 +# - Moved yaml import inside function + + +import dataclasses +import json +import os +import sys +import types +from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError +from collections.abc import Callable, Iterable +from copy import copy +from enum import Enum +from inspect import isclass +from pathlib import Path +from typing import Any, Literal, NewType, Union, get_type_hints + + +DataClass = NewType("DataClass", Any) +DataClassType = NewType("DataClassType", Any) + + +# From https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse +def string_to_bool(v): + if isinstance(v, bool): + return v + if v.lower() in ("yes", "true", "t", "y", "1"): + return True + elif v.lower() in ("no", "false", "f", "n", "0"): + return False + else: + raise ArgumentTypeError( + f"Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive)." + ) + + +def _accept_none(inner: Callable[[str], Any]) -> Callable[[str], Any]: + """Wrap a type converter so `'none'` and `'null'` (case-insensitive) parse to Python `None`. + + Used for `T | None` fields so they can be set to `None` from the CLI (argparse's `type=int` rejects `'None'`). + Mirrors the case-insensitive convention of [`string_to_bool`]. + """ + + def parse(v: str) -> Any: + if v.lower() in ("none", "null"): + return None + return inner(v) + + parse.__name__ = getattr(inner, "__name__", "value") # so argparse error messages keep the inner type name + return parse + + +def make_choice_type_function(choices: list) -> Callable[[str], Any]: + """ + Creates a mapping function from each choices string representation to the actual value. Used to support multiple + value types for a single argument. + + Args: + choices (list): List of choices. + + Returns: + Callable[[str], Any]: Mapping function from string representation to actual value for each choice. + """ + str_to_choice = {str(choice): choice for choice in choices} + return lambda arg: str_to_choice.get(arg, arg) + + +def HfArg( + *, + aliases: str | list[str] | None = None, + help: str | None = None, + default: Any = dataclasses.MISSING, + default_factory: Callable[[], Any] = dataclasses.MISSING, + metadata: dict | None = None, + **kwargs, +) -> dataclasses.Field: + """Argument helper enabling a concise syntax to create dataclass fields for parsing with `HfArgumentParser`. + + Example comparing the use of `HfArg` and `dataclasses.field`: + ``` + @dataclass + class Args: + regular_arg: str = dataclasses.field(default="Huggingface", metadata={"aliases": ["--example", "-e"], "help": "This syntax could be better!"}) + hf_arg: str = HfArg(default="Huggingface", aliases=["--example", "-e"], help="What a nice syntax!") + ``` + + Args: + aliases (Union[str, list[str]], optional): + Single string or list of strings of aliases to pass on to argparse, e.g. `aliases=["--example", "-e"]`. + Defaults to None. + help (str, optional): Help string to pass on to argparse that can be displayed with --help. Defaults to None. + default (Any, optional): + Default value for the argument. If not default or default_factory is specified, the argument is required. + Defaults to dataclasses.MISSING. + default_factory (Callable[[], Any], optional): + The default_factory is a 0-argument function called to initialize a field's value. It is useful to provide + default values for mutable types, e.g. lists: `default_factory=list`. Mutually exclusive with `default=`. + Defaults to dataclasses.MISSING. + metadata (dict, optional): Further metadata to pass on to `dataclasses.field`. Defaults to None. + + Returns: + Field: A `dataclasses.Field` with the desired properties. + """ + if metadata is None: + # Important, don't use as default param in function signature because dict is mutable and shared across function calls + metadata = {} + if aliases is not None: + metadata["aliases"] = aliases + if help is not None: + metadata["help"] = help + + return dataclasses.field(metadata=metadata, default=default, default_factory=default_factory, **kwargs) + + +class HfArgumentParser(ArgumentParser): + """ + This subclass of `argparse.ArgumentParser` uses type hints on dataclasses to generate arguments. + + The class is designed to play well with the native argparse. In particular, you can add more (non-dataclass backed) + arguments to the parser after initialization and you'll get the output back after parsing as an additional + namespace. Optional: To create sub argument groups use the `_argument_group_name` attribute in the dataclass. + + Args: + dataclass_types (`DataClassType` or `Iterable[DataClassType]`, *optional*): + Dataclass type, or list of dataclass types for which we will "fill" instances with the parsed args. + kwargs (`dict[str, Any]`, *optional*): + Passed to `argparse.ArgumentParser()` in the regular way. + """ + + dataclass_types: Iterable[DataClassType] + + def __init__(self, dataclass_types: DataClassType | Iterable[DataClassType] | None = None, **kwargs): + # Make sure dataclass_types is an iterable + if dataclass_types is None: + dataclass_types = [] + elif not isinstance(dataclass_types, Iterable): + dataclass_types = [dataclass_types] + + # To make the default appear when using --help + if "formatter_class" not in kwargs: + kwargs["formatter_class"] = ArgumentDefaultsHelpFormatter + super().__init__(**kwargs) + if dataclasses.is_dataclass(dataclass_types): + dataclass_types = [dataclass_types] + self.dataclass_types = list(dataclass_types) + for dtype in self.dataclass_types: + self._add_dataclass_arguments(dtype) + + @staticmethod + def _parse_dataclass_field(parser: ArgumentParser, field: dataclasses.Field): + # Long-option strings are conventionlly separated by hyphens rather + # than underscores, e.g., "--long-format" rather than "--long_format". + # Argparse converts hyphens to underscores so that the destination + # string is a valid attribute name. Hf_argparser should do the same. + long_options = [f"--{field.name}"] + if "_" in field.name: + long_options.append(f"--{field.name.replace('_', '-')}") + + kwargs = field.metadata.copy() + # field.metadata is not used at all by Data Classes, + # it is provided as a third-party extension mechanism. + if isinstance(field.type, str): + raise RuntimeError( + "Unresolved type detected, which should have been done with the help of " + "`typing.get_type_hints` method by default" + ) + + aliases = kwargs.pop("aliases", []) + if isinstance(aliases, str): + aliases = [aliases] + + origin_type = getattr(field.type, "__origin__", field.type) + accepts_none = False + if origin_type is Union or (hasattr(types, "UnionType") and isinstance(origin_type, types.UnionType)): + if str not in field.type.__args__ and ( + len(field.type.__args__) != 2 or type(None) not in field.type.__args__ + ): + raise ValueError( + "Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because" + " the argument parser only supports one type per argument." + f" Problem encountered in field '{field.name}'." + ) + if type(None) not in field.type.__args__: + # filter `str` in Union + field.type = field.type.__args__[0] if field.type.__args__[1] is str else field.type.__args__[1] + origin_type = getattr(field.type, "__origin__", field.type) + elif bool not in field.type.__args__: + # filter `NoneType` in Union (except for `Union[bool, NoneType]`) + field.type = ( + field.type.__args__[0] if isinstance(None, field.type.__args__[1]) else field.type.__args__[1] + ) + origin_type = getattr(field.type, "__origin__", field.type) + # Enable the `'none'`/`'null'` sentinel only when the inner type can't possibly accept those as + # legitimate string values (i.e. anything non-str). For str-typed fields, `'none'` may be a real + # value — e.g. `report_to`, whose CLI string `'none'` means "no integrations" downstream. + accepts_none = field.type is not str + + # A variable to store kwargs for a boolean field, if needed + # so that we can init a `no_*` complement argument (see below) + bool_kwargs = {} + if origin_type is Literal or (isinstance(field.type, type) and issubclass(field.type, Enum)): + if origin_type is Literal: + kwargs["choices"] = field.type.__args__ + else: + kwargs["choices"] = [x.value for x in field.type] + + kwargs["type"] = make_choice_type_function(kwargs["choices"]) + + if field.default is not dataclasses.MISSING: + kwargs["default"] = field.default + else: + kwargs["required"] = True + elif field.type is bool or field.type == bool | None: + # Copy the correct kwargs to use to instantiate a `no_*` complement argument below. + # We do not initialize it here because the `no_*` alternative must be instantiated after the real argument + bool_kwargs = copy(kwargs) + + # Hack because type=bool in argparse does not behave as we want. + kwargs["type"] = string_to_bool + if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING): + # Default value is False if we have no default when of type bool. + default = False if field.default is dataclasses.MISSING else field.default + # This is the value that will get picked if we don't include --{field.name} in any way + kwargs["default"] = default + # This tells argparse we accept 0 or 1 value after --{field.name} + kwargs["nargs"] = "?" + # This is the value that will get picked if we do --{field.name} (without value) + kwargs["const"] = True + elif isclass(origin_type) and issubclass(origin_type, list): + kwargs["type"] = field.type.__args__[0] + kwargs["nargs"] = "+" + if field.default_factory is not dataclasses.MISSING: + kwargs["default"] = field.default_factory() + elif field.default is dataclasses.MISSING: + kwargs["required"] = True + else: + kwargs["type"] = _accept_none(field.type) if accepts_none else field.type + if field.default is not dataclasses.MISSING: + kwargs["default"] = field.default + elif field.default_factory is not dataclasses.MISSING: + kwargs["default"] = field.default_factory() + else: + kwargs["required"] = True + parser.add_argument(*long_options, *aliases, **kwargs) + + # Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added. + # Order is important for arguments with the same destination! + # We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down + # here and we do not need those changes/additional keys. + if field.default is True and (field.type is bool or field.type == bool | None): + bool_kwargs["default"] = False + parser.add_argument( + f"--no_{field.name}", + f"--no-{field.name.replace('_', '-')}", + action="store_false", + dest=field.name, + **bool_kwargs, + ) + + def _add_dataclass_arguments(self, dtype: DataClassType): + if hasattr(dtype, "_argument_group_name"): + parser = self.add_argument_group(dtype._argument_group_name) + else: + parser = self + + try: + type_hints: dict[str, type] = get_type_hints(dtype) + except NameError: + raise RuntimeError( + f"Type resolution failed for {dtype}. Try declaring the class in global scope or " + "removing line of `from __future__ import annotations` which opts in Postponed " + "Evaluation of Annotations (PEP 563)" + ) from None + + for field in dataclasses.fields(dtype): + if not field.init: + continue + field.type = type_hints[field.name] + self._parse_dataclass_field(parser, field) + + def parse_args_into_dataclasses( + self, + args=None, + return_remaining_strings=False, + look_for_args_file=True, + args_filename=None, + args_file_flag=None, + ) -> tuple[DataClass, ...]: + """ + Parse command-line args into instances of the specified dataclass types. + + This relies on argparse's `ArgumentParser.parse_known_args`. See the doc at: + docs.python.org/3/library/argparse.html#argparse.ArgumentParser.parse_args + + Args: + args: + List of strings to parse. The default is taken from sys.argv. (same as argparse.ArgumentParser) + return_remaining_strings: + If true, also return a list of remaining argument strings. + look_for_args_file: + If true, will look for a ".args" file with the same base name as the entry point script for this + process, and will append its potential content to the command line args. + args_filename: + If not None, will uses this file instead of the ".args" file specified in the previous argument. + args_file_flag: + If not None, will look for a file in the command-line args specified with this flag. The flag can be + specified multiple times and precedence is determined by the order (last one wins). + + Returns: + Tuple consisting of: + + - the dataclass instances in the same order as they were passed to the initializer.abspath + - if applicable, an additional namespace for more (non-dataclass backed) arguments added to the parser + after initialization. + - The potential list of remaining argument strings. (same as argparse.ArgumentParser.parse_known_args) + """ + + if args_file_flag or args_filename or (look_for_args_file and len(sys.argv)): + args_files = [] + + if args_filename: + args_files.append(Path(args_filename)) + elif look_for_args_file and len(sys.argv): + args_files.append(Path(sys.argv[0]).with_suffix(".args")) + + # args files specified via command line flag should overwrite default args files so we add them last + if args_file_flag: + # Create special parser just to extract the args_file_flag values + args_file_parser = ArgumentParser() + args_file_parser.add_argument(args_file_flag, type=str, action="append") + + # Use only remaining args for further parsing (remove the args_file_flag) + cfg, args = args_file_parser.parse_known_args(args=args) + cmd_args_file_paths = vars(cfg).get(args_file_flag.lstrip("-"), None) + + if cmd_args_file_paths: + args_files.extend([Path(p) for p in cmd_args_file_paths]) + + file_args = [] + for args_file in args_files: + if args_file.exists(): + file_args += args_file.read_text().split() + + # in case of duplicate arguments the last one has precedence + # args specified via the command line should overwrite args from files, so we add them last + args = file_args + args if args is not None else file_args + sys.argv[1:] + namespace, remaining_args = self.parse_known_args(args=args) + outputs = [] + for dtype in self.dataclass_types: + keys = {f.name for f in dataclasses.fields(dtype) if f.init} + inputs = {k: v for k, v in vars(namespace).items() if k in keys} + for k in keys: + delattr(namespace, k) + obj = dtype(**inputs) + outputs.append(obj) + if len(namespace.__dict__) > 0: + # additional namespace. + outputs.append(namespace) + if return_remaining_strings: + return (*outputs, remaining_args) + else: + if remaining_args: + raise ValueError(f"Some specified arguments are not used by the HfArgumentParser: {remaining_args}") + + return (*outputs,) + + def parse_dict(self, args: dict[str, Any], allow_extra_keys: bool = False) -> tuple[DataClass, ...]: + """ + Alternative helper method that does not use `argparse` at all, instead uses a dict and populating the dataclass + types. + + Args: + args (`dict`): + dict containing config values + allow_extra_keys (`bool`, *optional*, defaults to `False`): + Defaults to False. If False, will raise an exception if the dict contains keys that are not parsed. + + Returns: + Tuple consisting of: + + - the dataclass instances in the same order as they were passed to the initializer. + """ + unused_keys = set(args.keys()) + outputs = [] + for dtype in self.dataclass_types: + keys = {f.name for f in dataclasses.fields(dtype) if f.init} + inputs = {k: v for k, v in args.items() if k in keys} + unused_keys.difference_update(inputs.keys()) + obj = dtype(**inputs) + outputs.append(obj) + if not allow_extra_keys and unused_keys: + raise ValueError(f"Some keys are not used by the HfArgumentParser: {sorted(unused_keys)}") + return tuple(outputs) + + def parse_json_file(self, json_file: str | os.PathLike, allow_extra_keys: bool = False) -> tuple[DataClass, ...]: + """ + Alternative helper method that does not use `argparse` at all, instead loading a json file and populating the + dataclass types. + + Args: + json_file (`str` or `os.PathLike`): + File name of the json file to parse + allow_extra_keys (`bool`, *optional*, defaults to `False`): + Defaults to False. If False, will raise an exception if the json file contains keys that are not + parsed. + + Returns: + Tuple consisting of: + + - the dataclass instances in the same order as they were passed to the initializer. + """ + with open(Path(json_file), encoding="utf-8") as open_json_file: + data = json.loads(open_json_file.read()) + outputs = self.parse_dict(data, allow_extra_keys=allow_extra_keys) + return tuple(outputs) + + def parse_yaml_file(self, yaml_file: str | os.PathLike, allow_extra_keys: bool = False) -> tuple[DataClass, ...]: + """ + Alternative helper method that does not use `argparse` at all, instead loading a yaml file and populating the + dataclass types. + + Args: + yaml_file (`str` or `os.PathLike`): + File name of the yaml file to parse + allow_extra_keys (`bool`, *optional*, defaults to `False`): + Defaults to False. If False, will raise an exception if the json file contains keys that are not + parsed. + + Returns: + Tuple consisting of: + + - the dataclass instances in the same order as they were passed to the initializer. + """ + import yaml + + outputs = self.parse_dict(yaml.safe_load(Path(yaml_file).read_text()), allow_extra_keys=allow_extra_keys) + return tuple(outputs) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/scripts/dpo.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/scripts/dpo.py new file mode 100644 index 0000000000000000000000000000000000000000..4d2dc899d351f673610ec8c3ea367a826fbdf9ba --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/scripts/dpo.py @@ -0,0 +1,146 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# /// script +# dependencies = [ +# "trl", +# "peft", +# "trackio", +# "kernels", +# ] +# /// + +""" +# Full training +```bash +python trl/scripts/dpo.py \ + --dataset_name trl-lib/ultrafeedback_binarized \ + --model_name_or_path Qwen/Qwen2-0.5B-Instruct \ + --learning_rate 5.0e-7 \ + --num_train_epochs 1 \ + --per_device_train_batch_size 2 \ + --max_steps 1000 \ + --gradient_accumulation_steps 8 \ + --eval_strategy steps \ + --eval_steps 50 \ + --output_dir Qwen2-0.5B-DPO \ + --no_remove_unused_columns +``` + +# LoRA: +```bash +python trl/scripts/dpo.py \ + --dataset_name trl-lib/ultrafeedback_binarized \ + --model_name_or_path Qwen/Qwen2-0.5B-Instruct \ + --learning_rate 5.0e-6 \ + --num_train_epochs 1 \ + --per_device_train_batch_size 2 \ + --max_steps 1000 \ + --gradient_accumulation_steps 8 \ + --eval_strategy steps \ + --eval_steps 50 \ + --output_dir Qwen2-0.5B-DPO \ + --no_remove_unused_columns \ + --use_peft \ + --lora_r 32 \ + --lora_alpha 16 +``` +""" + +import argparse + + +def main(script_args, training_args, model_args, dataset_args): + from accelerate import logging + from datasets import load_dataset + + from trl import DPOTrainer, get_dataset, get_kbit_device_map, get_peft_config, get_quantization_config + + logger = logging.get_logger(__name__) + + training_args.model_init_kwargs = dict( + revision=model_args.model_revision, + trust_remote_code=model_args.trust_remote_code, + attn_implementation=model_args.attn_implementation, + dtype=model_args.dtype, + ) + quantization_config = get_quantization_config(model_args) + if quantization_config is not None: + # Passing None would not be treated the same as omitting the argument, so we include it only when valid. + training_args.model_init_kwargs["device_map"] = get_kbit_device_map() + training_args.model_init_kwargs["quantization_config"] = quantization_config + + # Load the dataset + if dataset_args.datasets and script_args.dataset_name: + logger.warning( + "Both `datasets` and `dataset_name` are provided. The `datasets` argument will be used to load the " + "dataset and `dataset_name` will be ignored." + ) + dataset = get_dataset(dataset_args) + elif dataset_args.datasets and not script_args.dataset_name: + dataset = get_dataset(dataset_args) + elif not dataset_args.datasets and script_args.dataset_name: + dataset = load_dataset( + script_args.dataset_name, name=script_args.dataset_config, streaming=script_args.dataset_streaming + ) + else: + raise ValueError("Either `datasets` or `dataset_name` must be provided.") + + # Initialize the DPO trainer + trainer = DPOTrainer( + model=model_args.model_name_or_path, + args=training_args, + train_dataset=dataset[script_args.dataset_train_split], + eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None, + peft_config=get_peft_config(model_args), + ) + + if script_args.ignore_bias_buffers: + import torch + + # torch distributed hack + trainer.model._ddp_params_and_buffers_to_ignore = [ + name for name, buffer in trainer.model.named_buffers() if buffer.dtype == torch.bool + ] + + # Train the model + trainer.train() + + # Log training complete + trainer.accelerator.print("✅ Training completed.") + + # Save and push to Hub + trainer.save_model(training_args.output_dir) + trainer.accelerator.print(f"💾 Model saved to {training_args.output_dir}.") + + if training_args.push_to_hub: + trainer.push_to_hub(dataset_name=script_args.dataset_name) + trainer.accelerator.print(f"🤗 Model pushed to the Hub in https://huggingface.co/{trainer.hub_model_id}.") + + +def make_parser(subparsers: argparse._SubParsersAction | None = None, prog: str | None = None): + from trl import DatasetMixtureConfig, DPOConfig, ModelConfig, ScriptArguments, TrlParser + + dataclass_types = (ScriptArguments, DPOConfig, ModelConfig, DatasetMixtureConfig) + if subparsers is not None: + parser = subparsers.add_parser("dpo", help="Run the DPO training script", dataclass_types=dataclass_types) + else: + parser = TrlParser(dataclass_types, prog=prog) + return parser + + +if __name__ == "__main__": + parser = make_parser() + script_args, training_args, model_args, dataset_args = parser.parse_args_and_config(fail_with_unknown_args=False) + main(script_args, training_args, model_args, dataset_args) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/scripts/env.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/scripts/env.py new file mode 100644 index 0000000000000000000000000000000000000000..830bbee0a9ab39e1426f011bcdf06df3a9b85f9e --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/scripts/env.py @@ -0,0 +1,81 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# /// script +# dependencies = [ +# "trl", +# ] +# /// + +import os +import platform +from importlib.metadata import version + + +def print_env(): + import torch + from accelerate.commands.config import default_config_file, load_config_from_file + from transformers import is_bitsandbytes_available + from transformers.utils import is_peft_available + + from trl import __version__ + from trl.import_utils import is_deepspeed_available, is_liger_kernel_available, is_vllm_available + from trl.scripts.utils import get_git_commit_hash + + devices = None + if torch.cuda.is_available(): + devices = [torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())] + elif torch.backends.mps.is_available(): + devices = ["MPS"] + elif torch.xpu.is_available(): + devices = [torch.xpu.get_device_name(i) for i in range(torch.xpu.device_count())] + + accelerate_config = accelerate_config_str = "not found" + + # Get the default from the config file. + if os.path.isfile(default_config_file): + accelerate_config = load_config_from_file(default_config_file).to_dict() + + accelerate_config_str = ( + "\n" + "\n".join([f" - {prop}: {val}" for prop, val in accelerate_config.items()]) + if isinstance(accelerate_config, dict) + else accelerate_config + ) + + commit_hash = get_git_commit_hash("trl") + + info = { + "Platform": platform.platform(), + "Python version": platform.python_version(), + "TRL version": f"{__version__}+{commit_hash[:7]}" if commit_hash else __version__, + "PyTorch version": version("torch"), + "accelerator(s)": ", ".join(devices) if devices is not None else "cpu", + "Transformers version": version("transformers"), + "Accelerate version": version("accelerate"), + "Accelerate config": accelerate_config_str, + "Datasets version": version("datasets"), + "HF Hub version": version("huggingface_hub"), + "bitsandbytes version": version("bitsandbytes") if is_bitsandbytes_available() else "not installed", + "DeepSpeed version": version("deepspeed") if is_deepspeed_available() else "not installed", + "Liger-Kernel version": version("liger_kernel") if is_liger_kernel_available() else "not installed", + "PEFT version": version("peft") if is_peft_available() else "not installed", + "vLLM version": version("vllm") if is_vllm_available() else "not installed", + } + + info_str = "\n".join([f"- {prop}: {val}" for prop, val in info.items()]) + print(f"\nCopy-paste the following information when reporting an issue:\n\n{info_str}\n") # noqa + + +if __name__ == "__main__": + print_env() diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/scripts/grpo.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/scripts/grpo.py new file mode 100644 index 0000000000000000000000000000000000000000..355a6eb9ce4d7f0c2fcd72a25430983438c06b36 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/scripts/grpo.py @@ -0,0 +1,177 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# /// script +# dependencies = [ +# "trl", +# "peft", +# "trackio", +# "kernels", +# ] +# /// + +import argparse +import importlib +import os +import sys +from dataclasses import dataclass, field + +from trl import ScriptArguments + + +@dataclass +class GRPOScriptArguments(ScriptArguments): + """ + Script arguments for the GRPO training script. + + Args: + reward_model_name_or_path (`str`, *optional*): + Reward model id of a pretrained model hosted inside a model repo on huggingface.co or local path to a + directory containing model weights saved using [`~transformers.PreTrainedModel.save_pretrained`]. + reward_funcs (`list[str]`, *optional*): + Reward functions to use. Supported values are: + - `"accuracy_reward"` + - `"reasoning_accuracy_reward"` + - `"think_format_reward"` + - `"get_soft_overlong_punishment"` (used value are `max_completion_len=1280`, `soft_punish_cache=256`) + - any dotted import path " (e.g., `'my_lib.rewards.custom_reward'`). + """ + + reward_model_name_or_path: str | None = field( + default=None, + metadata={ + "help": "Reward model id of a pretrained model hosted inside a model repo on huggingface.co or " + "local path to a directory containing model weights saved using `PreTrainedModel.save_pretrained`." + }, + ) + reward_funcs: list[str] | None = field( + default=None, + metadata={ + "help": "Reward functions to use. Supported values are: `accuracy_reward`, `reasoning_accuracy_reward`, `think_format_reward`, " + "`get_soft_overlong_punishment` (used values are `max_completion_len=1280`, `soft_punish_cache=256`), or " + "any dotted import path (e.g., `'my_lib.rewards.custom_reward'`)." + }, + ) + + +def main(script_args, training_args, model_args, dataset_args): + from accelerate import logging + from datasets import load_dataset + + from trl import GRPOTrainer, get_dataset, get_kbit_device_map, get_peft_config, get_quantization_config + from trl.rewards import ( + accuracy_reward, + get_soft_overlong_punishment, + reasoning_accuracy_reward, + think_format_reward, + ) + + logger = logging.get_logger(__name__) + + reward_funcs_registry = { + "accuracy_reward": accuracy_reward, + "reasoning_accuracy_reward": reasoning_accuracy_reward, + "think_format_reward": think_format_reward, + "get_soft_overlong_punishment": get_soft_overlong_punishment(max_completion_len=1280, soft_punish_cache=256), + } + + # Get the reward models and functions + reward_funcs = [] + if script_args.reward_model_name_or_path: + reward_funcs.append(script_args.reward_model_name_or_path) + + if script_args.reward_funcs: + for func_name in script_args.reward_funcs: + if func_name in reward_funcs_registry: + reward_funcs.append(reward_funcs_registry[func_name]) + elif "." in func_name: + module_path, func_name = func_name.rsplit(".", 1) + sys.path.insert(0, os.getcwd()) + module = importlib.import_module(module_path) + reward_func = getattr(module, func_name) + reward_funcs.append(reward_func) + else: + raise ValueError( + f"Could not load reward function '{func_name}'. Expected one of " + f"{list(reward_funcs_registry.keys())} or a valid import path." + ) + + training_args.model_init_kwargs = dict( + revision=model_args.model_revision, + trust_remote_code=model_args.trust_remote_code, + attn_implementation=model_args.attn_implementation, + dtype=model_args.dtype, + ) + quantization_config = get_quantization_config(model_args) + if quantization_config is not None: + # Passing None would not be treated the same as omitting the argument, so we include it only when valid. + training_args.model_init_kwargs["device_map"] = get_kbit_device_map() + training_args.model_init_kwargs["quantization_config"] = quantization_config + + # Load the dataset + if dataset_args.datasets and script_args.dataset_name: + logger.warning( + "Both `datasets` and `dataset_name` are provided. The `datasets` argument will be used to load the " + "dataset and `dataset_name` will be ignored." + ) + dataset = get_dataset(dataset_args) + elif dataset_args.datasets and not script_args.dataset_name: + dataset = get_dataset(dataset_args) + elif not dataset_args.datasets and script_args.dataset_name: + dataset = load_dataset( + script_args.dataset_name, name=script_args.dataset_config, streaming=script_args.dataset_streaming + ) + else: + raise ValueError("Either `datasets` or `dataset_name` must be provided.") + + # Initialize the GRPO trainer + trainer = GRPOTrainer( + model=model_args.model_name_or_path, + reward_funcs=reward_funcs, + args=training_args, + train_dataset=dataset[script_args.dataset_train_split], + eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None, + peft_config=get_peft_config(model_args), + ) + + # Train the model + trainer.train() + + # Log training complete + trainer.accelerator.print("✅ Training completed.") + + # Save and push to Hub + trainer.save_model(training_args.output_dir) + trainer.accelerator.print(f"💾 Model saved to {training_args.output_dir}.") + + if training_args.push_to_hub: + trainer.push_to_hub(dataset_name=script_args.dataset_name) + trainer.accelerator.print(f"🤗 Model pushed to the Hub in https://huggingface.co/{trainer.hub_model_id}.") + + +def make_parser(subparsers: argparse._SubParsersAction | None = None, prog: str | None = None): + from trl import DatasetMixtureConfig, GRPOConfig, ModelConfig, TrlParser + + dataclass_types = (GRPOScriptArguments, GRPOConfig, ModelConfig, DatasetMixtureConfig) + if subparsers is not None: + parser = subparsers.add_parser("grpo", help="Run the GRPO training script", dataclass_types=dataclass_types) + else: + parser = TrlParser(dataclass_types, prog=prog) + return parser + + +if __name__ == "__main__": + parser = make_parser() + script_args, training_args, model_args, dataset_args = parser.parse_args_and_config(fail_with_unknown_args=False) + main(script_args, training_args, model_args, dataset_args) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/scripts/kto.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/scripts/kto.py new file mode 100644 index 0000000000000000000000000000000000000000..ad0bb3e9c6059bfc6f78a706994932c8409900b4 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/scripts/kto.py @@ -0,0 +1,151 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# /// script +# dependencies = [ +# "trl", +# "peft", +# "trackio", +# "kernels", +# ] +# /// + +""" +Run the KTO training script with the commands below. In general, the optimal configuration for KTO will be similar to +that of DPO. + +# Full training: +```bash +python trl/scripts/kto.py \ + --dataset_name trl-lib/kto-mix-14k \ + --model_name_or_path=trl-lib/qwen1.5-1.8b-sft \ + --per_device_train_batch_size 16 \ + --num_train_epochs 1 \ + --learning_rate 5e-7 \ + --lr_scheduler_type=cosine \ + --gradient_accumulation_steps 1 \ + --eval_steps 500 \ + --output_dir=kto-aligned-model \ + --warmup_steps 0.1 \ + --logging_first_step +``` + +# QLoRA: +```bash +# QLoRA: +python trl/scripts/kto.py \ + --dataset_name trl-lib/kto-mix-14k \ + --model_name_or_path=trl-lib/qwen1.5-1.8b-sft \ + --per_device_train_batch_size 8 \ + --num_train_epochs 1 \ + --learning_rate 5e-7 \ + --lr_scheduler_type=cosine \ + --gradient_accumulation_steps 1 \ + --eval_steps 500 \ + --output_dir=kto-aligned-model-lora \ + --warmup_steps 0.1 \ + --logging_first_step \ + --use_peft \ + --load_in_4bit \ + --lora_target_modules=all-linear \ + --lora_r=16 \ + --lora_alpha=16 +``` +""" + +import argparse + + +def main(script_args, training_args, model_args, dataset_args): + from accelerate import logging + from datasets import load_dataset + from transformers import AutoModelForCausalLM, AutoTokenizer + + from trl import get_dataset, get_peft_config + from trl.experimental.kto import KTOTrainer + + logger = logging.get_logger(__name__) + + # Load a pretrained model + model = AutoModelForCausalLM.from_pretrained( + model_args.model_name_or_path, trust_remote_code=model_args.trust_remote_code + ) + ref_model = AutoModelForCausalLM.from_pretrained( + model_args.model_name_or_path, trust_remote_code=model_args.trust_remote_code + ) + + tokenizer = AutoTokenizer.from_pretrained( + model_args.model_name_or_path, trust_remote_code=model_args.trust_remote_code + ) + if tokenizer.pad_token is None: + tokenizer.pad_token = tokenizer.eos_token + + # Load the dataset + if dataset_args.datasets and script_args.dataset_name: + logger.warning( + "Both `datasets` and `dataset_name` are provided. The `datasets` argument will be used to load the " + "dataset and `dataset_name` will be ignored." + ) + dataset = get_dataset(dataset_args) + elif dataset_args.datasets and not script_args.dataset_name: + dataset = get_dataset(dataset_args) + elif not dataset_args.datasets and script_args.dataset_name: + dataset = load_dataset( + script_args.dataset_name, name=script_args.dataset_config, streaming=script_args.dataset_streaming + ) + else: + raise ValueError("Either `datasets` or `dataset_name` must be provided.") + + # Initialize the KTO trainer + trainer = KTOTrainer( + model, + ref_model, + args=training_args, + train_dataset=dataset[script_args.dataset_train_split], + eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None, + processing_class=tokenizer, + peft_config=get_peft_config(model_args), + ) + + # Train the model + trainer.train() + + # Log training complete + trainer.accelerator.print("✅ Training completed.") + + # Save and push to Hub + trainer.save_model(training_args.output_dir) + trainer.accelerator.print(f"💾 Model saved to {training_args.output_dir}.") + + if training_args.push_to_hub: + trainer.push_to_hub(dataset_name=script_args.dataset_name) + trainer.accelerator.print(f"🤗 Model pushed to the Hub in https://huggingface.co/{trainer.hub_model_id}.") + + +def make_parser(subparsers: argparse._SubParsersAction | None = None, prog: str | None = None): + from trl import DatasetMixtureConfig, ModelConfig, ScriptArguments, TrlParser + from trl.experimental.kto import KTOConfig + + dataclass_types = (ScriptArguments, KTOConfig, ModelConfig, DatasetMixtureConfig) + if subparsers is not None: + parser = subparsers.add_parser("kto", help="Run the KTO training script", dataclass_types=dataclass_types) + else: + parser = TrlParser(dataclass_types, prog=prog) + return parser + + +if __name__ == "__main__": + parser = make_parser() + script_args, training_args, model_args, dataset_args = parser.parse_args_and_config(fail_with_unknown_args=False) + main(script_args, training_args, model_args, dataset_args) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/scripts/reward.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/scripts/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..3b83502b41e434645fa230bcd38f5cf4bfffebca --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/scripts/reward.py @@ -0,0 +1,103 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# /// script +# dependencies = [ +# "trl", +# "peft", +# "trackio", +# "kernels", +# ] +# /// + +import argparse + + +def main(script_args, training_args, model_args, dataset_args): + from accelerate import logging + from datasets import load_dataset + + from trl import RewardTrainer, get_dataset, get_kbit_device_map, get_peft_config, get_quantization_config + + logger = logging.get_logger(__name__) + + training_args.model_init_kwargs = dict( + revision=model_args.model_revision, + trust_remote_code=model_args.trust_remote_code, + attn_implementation=model_args.attn_implementation, + dtype=model_args.dtype, + ) + quantization_config = get_quantization_config(model_args) + if quantization_config is not None: + # Passing None would not be treated the same as omitting the argument, so we include it only when valid. + training_args.model_init_kwargs["device_map"] = get_kbit_device_map() + training_args.model_init_kwargs["quantization_config"] = quantization_config + + # Load the dataset + if dataset_args.datasets and script_args.dataset_name: + logger.warning( + "Both `datasets` and `dataset_name` are provided. The `datasets` argument will be used to load the " + "dataset and `dataset_name` will be ignored." + ) + dataset = get_dataset(dataset_args) + elif dataset_args.datasets and not script_args.dataset_name: + dataset = get_dataset(dataset_args) + elif not dataset_args.datasets and script_args.dataset_name: + dataset = load_dataset( + script_args.dataset_name, name=script_args.dataset_config, streaming=script_args.dataset_streaming + ) + else: + raise ValueError("Either `datasets` or `dataset_name` must be provided.") + + # Initialize the reward trainer + trainer = RewardTrainer( + model=model_args.model_name_or_path, + args=training_args, + train_dataset=dataset[script_args.dataset_train_split], + eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None, + peft_config=get_peft_config(model_args), + ) + + # Train the model + trainer.train() + + # Log training complete + trainer.accelerator.print("✅ Training completed.") + + # Save and push to Hub + trainer.save_model(training_args.output_dir) + trainer.accelerator.print(f"💾 Model saved to {training_args.output_dir}.") + + if training_args.push_to_hub: + trainer.push_to_hub(dataset_name=script_args.dataset_name) + trainer.accelerator.print(f"🤗 Model pushed to the Hub in https://huggingface.co/{trainer.hub_model_id}.") + + +def make_parser(subparsers: argparse._SubParsersAction | None = None, prog: str | None = None): + from trl import DatasetMixtureConfig, ModelConfig, RewardConfig, ScriptArguments, TrlParser + + dataclass_types = (ScriptArguments, RewardConfig, ModelConfig, DatasetMixtureConfig) + if subparsers is not None: + parser = subparsers.add_parser( + "reward", help="Run the reward training script", dataclass_types=dataclass_types + ) + else: + parser = TrlParser(dataclass_types, prog=prog) + return parser + + +if __name__ == "__main__": + parser = make_parser() + script_args, training_args, model_args, dataset_args = parser.parse_args_and_config(fail_with_unknown_args=False) + main(script_args, training_args, model_args, dataset_args) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/scripts/rloo.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/scripts/rloo.py new file mode 100644 index 0000000000000000000000000000000000000000..140693f8d02ef25cb3ff34a1650fcbe6748f164f --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/scripts/rloo.py @@ -0,0 +1,177 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# /// script +# dependencies = [ +# "trl", +# "peft", +# "trackio", +# "kernels", +# ] +# /// + +import argparse +import importlib +import os +import sys +from dataclasses import dataclass, field + +from trl import ScriptArguments + + +@dataclass +class RLOOScriptArguments(ScriptArguments): + """ + Script arguments for the RLOO training script. + + Args: + reward_model_name_or_path (`str`, *optional*): + Reward model id of a pretrained model hosted inside a model repo on huggingface.co or local path to a + directory containing model weights saved using [`~transformers.PreTrainedModel.save_pretrained`]. + reward_funcs (`list[str]`, *optional*): + Reward functions to use. Supported values are: + - `"accuracy_reward"` + - `"reasoning_accuracy_reward"` + - `"think_format_reward"` + - `"get_soft_overlong_punishment"` (used value are `max_completion_len=1280`, `soft_punish_cache=256`) + - any dotted import path " (e.g., `'my_lib.rewards.custom_reward'`). + """ + + reward_model_name_or_path: str | None = field( + default=None, + metadata={ + "help": "Reward model id of a pretrained model hosted inside a model repo on huggingface.co or " + "local path to a directory containing model weights saved using `PreTrainedModel.save_pretrained`." + }, + ) + reward_funcs: list[str] | None = field( + default=None, + metadata={ + "help": "Reward functions to use. Supported values are: `accuracy_reward`, `reasoning_accuracy_reward`, `think_format_reward`, " + "`get_soft_overlong_punishment` (used values are `max_completion_len=1280`, `soft_punish_cache=256`), or " + "any dotted import path (e.g., `'my_lib.rewards.custom_reward'`)." + }, + ) + + +def main(script_args, training_args, model_args, dataset_args): + from accelerate import logging + from datasets import load_dataset + + from trl import RLOOTrainer, get_dataset, get_kbit_device_map, get_peft_config, get_quantization_config + from trl.rewards import ( + accuracy_reward, + get_soft_overlong_punishment, + reasoning_accuracy_reward, + think_format_reward, + ) + + logger = logging.get_logger(__name__) + + reward_funcs_registry = { + "accuracy_reward": accuracy_reward, + "reasoning_accuracy_reward": reasoning_accuracy_reward, + "think_format_reward": think_format_reward, + "get_soft_overlong_punishment": get_soft_overlong_punishment(max_completion_len=1280, soft_punish_cache=256), + } + + # Get the reward models and functions + reward_funcs = [] + if script_args.reward_model_name_or_path: + reward_funcs.append(script_args.reward_model_name_or_path) + + if script_args.reward_funcs: + for func_name in script_args.reward_funcs: + if func_name in reward_funcs_registry: + reward_funcs.append(reward_funcs_registry[func_name]) + elif "." in func_name: + module_path, func_name = func_name.rsplit(".", 1) + sys.path.insert(0, os.getcwd()) + module = importlib.import_module(module_path) + reward_func = getattr(module, func_name) + reward_funcs.append(reward_func) + else: + raise ValueError( + f"Could not load reward function '{func_name}'. Expected one of " + f"{list(reward_funcs_registry.keys())} or a valid import path." + ) + + training_args.model_init_kwargs = dict( + revision=model_args.model_revision, + trust_remote_code=model_args.trust_remote_code, + attn_implementation=model_args.attn_implementation, + dtype=model_args.dtype, + ) + quantization_config = get_quantization_config(model_args) + if quantization_config is not None: + # Passing None would not be treated the same as omitting the argument, so we include it only when valid. + training_args.model_init_kwargs["device_map"] = get_kbit_device_map() + training_args.model_init_kwargs["quantization_config"] = quantization_config + + # Load the dataset + if dataset_args.datasets and script_args.dataset_name: + logger.warning( + "Both `datasets` and `dataset_name` are provided. The `datasets` argument will be used to load the " + "dataset and `dataset_name` will be ignored." + ) + dataset = get_dataset(dataset_args) + elif dataset_args.datasets and not script_args.dataset_name: + dataset = get_dataset(dataset_args) + elif not dataset_args.datasets and script_args.dataset_name: + dataset = load_dataset( + script_args.dataset_name, name=script_args.dataset_config, streaming=script_args.dataset_streaming + ) + else: + raise ValueError("Either `datasets` or `dataset_name` must be provided.") + + # Initialize the RLOO trainer + trainer = RLOOTrainer( + model=model_args.model_name_or_path, + reward_funcs=reward_funcs, + args=training_args, + train_dataset=dataset[script_args.dataset_train_split], + eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None, + peft_config=get_peft_config(model_args), + ) + + # Train the model + trainer.train() + + # Log training complete + trainer.accelerator.print("✅ Training completed.") + + # Save and push to Hub + trainer.save_model(training_args.output_dir) + trainer.accelerator.print(f"💾 Model saved to {training_args.output_dir}.") + + if training_args.push_to_hub: + trainer.push_to_hub(dataset_name=script_args.dataset_name) + trainer.accelerator.print(f"🤗 Model pushed to the Hub in https://huggingface.co/{trainer.hub_model_id}.") + + +def make_parser(subparsers: argparse._SubParsersAction | None = None, prog: str | None = None): + from trl import DatasetMixtureConfig, ModelConfig, RLOOConfig, TrlParser + + dataclass_types = (RLOOScriptArguments, RLOOConfig, ModelConfig, DatasetMixtureConfig) + if subparsers is not None: + parser = subparsers.add_parser("rloo", help="Run the RLOO training script", dataclass_types=dataclass_types) + else: + parser = TrlParser(dataclass_types, prog=prog) + return parser + + +if __name__ == "__main__": + parser = make_parser() + script_args, training_args, model_args, dataset_args = parser.parse_args_and_config(fail_with_unknown_args=False) + main(script_args, training_args, model_args, dataset_args) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/scripts/sft.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/scripts/sft.py new file mode 100644 index 0000000000000000000000000000000000000000..385fe3fa88b511273a52fb11a73e34b0a07909d5 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/scripts/sft.py @@ -0,0 +1,140 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# /// script +# dependencies = [ +# "trl", +# "peft", +# "trackio", +# "kernels", +# ] +# /// + +""" +# Full training +``` +python trl/scripts/sft.py \ + --model_name_or_path Qwen/Qwen2-0.5B \ + --dataset_name trl-lib/Capybara \ + --learning_rate 2.0e-5 \ + --num_train_epochs 1 \ + --packing \ + --per_device_train_batch_size 2 \ + --gradient_accumulation_steps 8 \ + --eos_token '<|im_end|>' \ + --eval_strategy steps \ + --eval_steps 100 \ + --output_dir Qwen2-0.5B-SFT \ + --push_to_hub +``` + +# LoRA +``` +python trl/scripts/sft.py \ + --model_name_or_path Qwen/Qwen2-0.5B \ + --dataset_name trl-lib/Capybara \ + --learning_rate 2.0e-4 \ + --num_train_epochs 1 \ + --packing \ + --per_device_train_batch_size 2 \ + --gradient_accumulation_steps 8 \ + --eos_token '<|im_end|>' \ + --eval_strategy steps \ + --eval_steps 100 \ + --use_peft \ + --lora_r 32 \ + --lora_alpha 16 \ + --output_dir Qwen2-0.5B-SFT \ + --push_to_hub +``` +""" + +import argparse + + +def main(script_args, training_args, model_args, dataset_args): + from accelerate import logging + from datasets import load_dataset + + from trl import SFTTrainer, get_dataset, get_kbit_device_map, get_peft_config, get_quantization_config + + logger = logging.get_logger(__name__) + + training_args.model_init_kwargs = dict( + revision=model_args.model_revision, + trust_remote_code=model_args.trust_remote_code, + attn_implementation=model_args.attn_implementation, + dtype=model_args.dtype, + ) + quantization_config = get_quantization_config(model_args) + if quantization_config is not None: + # Passing None would not be treated the same as omitting the argument, so we include it only when valid. + training_args.model_init_kwargs["device_map"] = get_kbit_device_map() + training_args.model_init_kwargs["quantization_config"] = quantization_config + + # Load the dataset + if dataset_args.datasets and script_args.dataset_name: + logger.warning( + "Both `datasets` and `dataset_name` are provided. The `datasets` argument will be used to load the " + "dataset and `dataset_name` will be ignored." + ) + dataset = get_dataset(dataset_args) + elif dataset_args.datasets and not script_args.dataset_name: + dataset = get_dataset(dataset_args) + elif not dataset_args.datasets and script_args.dataset_name: + dataset = load_dataset( + script_args.dataset_name, name=script_args.dataset_config, streaming=script_args.dataset_streaming + ) + else: + raise ValueError("Either `datasets` or `dataset_name` must be provided.") + + # Initialize the SFT trainer + trainer = SFTTrainer( + model=model_args.model_name_or_path, + args=training_args, + train_dataset=dataset[script_args.dataset_train_split], + eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None, + peft_config=get_peft_config(model_args), + ) + + # Train the model + trainer.train() + + # Log training complete + trainer.accelerator.print("✅ Training completed.") + + # Save and push to Hub + trainer.save_model(training_args.output_dir) + trainer.accelerator.print(f"💾 Model saved to {training_args.output_dir}.") + + if training_args.push_to_hub: + trainer.push_to_hub(dataset_name=script_args.dataset_name) + trainer.accelerator.print(f"🤗 Model pushed to the Hub in https://huggingface.co/{trainer.hub_model_id}.") + + +def make_parser(subparsers: argparse._SubParsersAction | None = None, prog: str | None = None): + from trl import DatasetMixtureConfig, ModelConfig, ScriptArguments, SFTConfig, TrlParser + + dataclass_types = (ScriptArguments, SFTConfig, ModelConfig, DatasetMixtureConfig) + if subparsers is not None: + parser = subparsers.add_parser("sft", help="Run the SFT training script", dataclass_types=dataclass_types) + else: + parser = TrlParser(dataclass_types, prog=prog) + return parser + + +if __name__ == "__main__": + parser = make_parser() + script_args, training_args, model_args, dataset_args = parser.parse_args_and_config(fail_with_unknown_args=False) + main(script_args, training_args, model_args, dataset_args) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/scripts/utils.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/scripts/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..165fec49fc32ed3c00cb3001f64f35ab5d690a6f --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/scripts/utils.py @@ -0,0 +1,466 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import importlib +import inspect +import logging +import os +import subprocess +import sys +from collections.abc import Iterable +from dataclasses import dataclass, field +from typing import TYPE_CHECKING + +# Temporarily import from the local module instead of transformers to avoid an upstream latency issue +# See: https://github.com/huggingface/transformers/issues/44273 +# This workaround can be reverted once the fix is included in the minimum required transformers version +from trl.scripts._hf_argparser import DataClass, DataClassType, HfArgumentParser + + +if TYPE_CHECKING: + from datasets import DatasetDict + + +logger = logging.getLogger(__name__) + + +@dataclass +class DatasetConfig: + """ + Configuration for a dataset. + + This class matches the signature of [`~datasets.load_dataset`] and the arguments are used directly in the + [`~datasets.load_dataset`] function. You can refer to the [`~datasets.load_dataset`] documentation for more + details. + + Parameters: + path (`str`): + Path or name of the dataset. + name (`str`, *optional*): + Defining the name of the dataset configuration. + data_dir (`str`, *optional*): + Defining the `data_dir` of the dataset configuration. If specified for the generic builders(csv, text etc.) + or the Hub datasets and `data_files` is `None`, the behavior is equal to passing `os.path.join(data_dir, + **)` as `data_files` to reference all the files in a directory. + data_files (`str` or `Sequence` or `Mapping`, *optional*): + Path(s) to source data file(s). + split (`str`, *optional*, defaults to `"train"`): + Which split of the data to load. + columns (`list[str]`, *optional*): + List of column names to select from the dataset. If `None`, all columns are selected. + """ + + path: str + name: str | None = None + data_dir: str | None = None + data_files: str | list[str] | dict[str, str] | None = None + split: str = "train" + columns: list[str] | None = None + + +@dataclass +class DatasetMixtureConfig: + """ + Configuration class for a mixture of datasets. + + 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: + datasets (`list[DatasetConfig]`): + List of dataset configurations to include in the mixture. + streaming (`bool`, *optional*, defaults to `False`): + Whether to stream the datasets. If `True`, the datasets will be loaded in streaming mode. + test_split_size (`float`, *optional*): + Size of the test split. Refer to the `test_size` parameter in the [`~datasets.train_test_split`] function + for more details. If `None`, the dataset will not be split into train and test sets. + + Usage: + When using the CLI, you can add the following section to your YAML config file: + + ```yaml + datasets: + - path: ... + name: ... + data_dir: ... + data_files: ... + split: ... + columns: ... + - path: ... + name: ... + data_dir: ... + data_files: ... + split: ... + columns: ... + streaming: ... + test_split_size: ... + ``` + """ + + datasets: list[DatasetConfig] = field( + default_factory=list, + metadata={"help": "List of dataset configurations to include in the mixture."}, + ) + streaming: bool = field( + default=False, + metadata={"help": "Whether to stream the datasets. If True, the datasets will be loaded in streaming mode."}, + ) + test_split_size: float | None = field( + default=None, + metadata={ + "help": "Size of the test split. Refer to the `test_size` parameter in the `datasets.train_test_split` " + "function for more details. If None, the dataset will not be split into train and test sets." + }, + ) + + def __post_init__(self): + # Convert any dataset dicts (from CLI/config parsing) into DatasetConfig objects + for idx, dataset in enumerate(self.datasets): + if isinstance(dataset, dict): + # If it's a dict, convert it to DatasetConfig + self.datasets[idx] = DatasetConfig(**dataset) + + +@dataclass +class ScriptArguments: + """ + Arguments common to all scripts. + + Args: + dataset_name (`str`,, *optional*): + Path or name of the dataset to load. If `datasets` is provided, this will be ignored. + dataset_config (`str`, *optional*): + Dataset configuration name. Corresponds to the `name` argument of the [`~datasets.load_dataset`] function. + If `datasets` is provided, this will be ignored. + dataset_train_split (`str`, *optional*, defaults to `"train"`): + Dataset split to use for training. If `datasets` is provided, this will be ignored. + dataset_test_split (`str`, *optional*, defaults to `"test"`): + Dataset split to use for evaluation. If `datasets` is provided, this will be ignored. + dataset_streaming (`bool`, *optional*, defaults to `False`): + Whether to stream the dataset. If True, the dataset will be loaded in streaming mode. If `datasets` is + provided, this will be ignored. + ignore_bias_buffers (`bool`, *optional*, defaults to `False`): + Debug argument for distributed training. Fix for DDP issues with LM bias/mask buffers - invalid scalar + type, inplace operation. See + https://github.com/huggingface/transformers/issues/22482#issuecomment-1595790992. + """ + + dataset_name: str | None = field( + default=None, + metadata={"help": "Path or name of the dataset to load. If `datasets` is provided, this will be ignored."}, + ) + dataset_config: str | None = field( + default=None, + metadata={ + "help": "Dataset configuration name. Corresponds to the `name` argument of the `datasets.load_dataset` " + "function. If `datasets` is provided, this will be ignored." + }, + ) + dataset_train_split: str = field( + default="train", + metadata={"help": "Dataset split to use for training. If `datasets` is provided, this will be ignored."}, + ) + dataset_test_split: str = field( + default="test", + metadata={"help": "Dataset split to use for evaluation. If `datasets` is provided, this will be ignored."}, + ) + dataset_streaming: bool = field( + default=False, + metadata={ + "help": "Whether to stream the dataset. If True, the dataset will be loaded in streaming mode. If " + "`datasets` is provided, this will be ignored." + }, + ) + ignore_bias_buffers: bool = field( + default=False, + metadata={ + "help": "Debug argument for distributed training. Fix for DDP issues with LM bias/mask buffers - invalid " + "scalar type, inplace operation. See " + "https://github.com/huggingface/transformers/issues/22482#issuecomment-1595790992." + }, + ) + + +def init_zero_verbose(): + """ + Perform zero verbose init - use this method on top of the CLI modules to make logging and warning output cleaner. + Uses Rich if available, falls back otherwise. + """ + import logging + import warnings + + from transformers.utils import is_rich_available + + FORMAT = "%(message)s" + + if is_rich_available(): + from rich.logging import RichHandler + + handler = RichHandler() + else: + handler = logging.StreamHandler() + + logging.basicConfig(format=FORMAT, datefmt="[%X]", handlers=[handler], level=logging.ERROR) + + # Custom warning handler to redirect warnings to the logging system + def warning_handler(message, category, filename, lineno, file=None, line=None): + logging.warning(f"{filename}:{lineno}: {category.__name__}: {message}") + + # Add the custom warning handler - we need to do that before importing anything to make sure the loggers work well + warnings.showwarning = warning_handler + + +class TrlParser(HfArgumentParser): + """ + A subclass of [`transformers.HfArgumentParser`] designed for parsing command-line arguments with dataclass-backed + configurations, while also supporting configuration file loading and environment variable management. + + Args: + dataclass_types (`DataClassType | Iterable[DataClassType]`, *optional*): + Dataclass types to use for argument parsing. + **kwargs: + Additional keyword arguments passed to the [`transformers.HfArgumentParser`] constructor. + + Examples: + + ```yaml + # config.yaml + env: + VAR1: value1 + arg1: 23 + ``` + + ```python + # main.py + import os + from dataclasses import dataclass + from trl import TrlParser + + + @dataclass + class MyArguments: + arg1: int + arg2: str = "alpha" + + + parser = TrlParser(dataclass_types=[MyArguments]) + training_args = parser.parse_args_and_config() + + print(training_args, os.environ.get("VAR1")) + ``` + + ```bash + $ python main.py --config config.yaml + (MyArguments(arg1=23, arg2='alpha'),) value1 + + $ python main.py --arg1 5 --arg2 beta + (MyArguments(arg1=5, arg2='beta'),) None + ``` + """ + + def __init__( + self, + dataclass_types: DataClassType | Iterable[DataClassType] | None = None, + **kwargs, + ): + # Make sure dataclass_types is an iterable + if dataclass_types is None: + dataclass_types = [] + elif not isinstance(dataclass_types, Iterable): + dataclass_types = [dataclass_types] + + # Check that none of the dataclasses have the "config" field + for dataclass_type in dataclass_types: + if "config" in dataclass_type.__dataclass_fields__: + raise ValueError( + f"Dataclass {dataclass_type.__name__} has a field named 'config'. This field is reserved for the " + f"config file path and should not be used in the dataclass." + ) + + super().__init__(dataclass_types=dataclass_types, **kwargs) + + def parse_args_and_config( + self, + args: Iterable[str] | None = None, + return_remaining_strings: bool = False, + fail_with_unknown_args: bool = True, + separate_remaining_strings: bool = False, + ) -> tuple[DataClass, ...]: + """ + Parse command-line args and config file into instances of the specified dataclass types. + + This method wraps [`transformers.HfArgumentParser.parse_args_into_dataclasses`] and also parses the config file + specified with the `--config` flag. The config file (in YAML format) provides argument values that replace the + default values in the dataclasses. Command line arguments can override values set by the config file. The + method also sets any environment variables specified in the `env` field of the config file. + """ + import yaml + + args = list(args) if args is not None else sys.argv[1:] + if "--config" in args: + # Get the config file path from + config_index = args.index("--config") + args.pop(config_index) # remove the --config flag + config_path = args.pop(config_index) # get the path to the config file + with open(config_path) as yaml_file: + config = yaml.safe_load(yaml_file) + + # Set the environment variables specified in the config file + if "env" in config: + env_vars = config.pop("env", {}) + if not isinstance(env_vars, dict): + raise ValueError("`env` field should be a dict in the YAML file.") + for key, value in env_vars.items(): + os.environ[key] = str(value) + + # Set the defaults from the config values + config_remaining_strings = self.set_defaults_with_config(**config) + else: + config_remaining_strings = [] + + # Parse the arguments from the command line + output = self.parse_args_into_dataclasses(args=args, return_remaining_strings=return_remaining_strings) + + # Merge remaining strings from the config file with the remaining strings from the command line + if return_remaining_strings: + args_remaining_strings = output[-1] + if separate_remaining_strings: + return output[:-1] + (config_remaining_strings, args_remaining_strings) + return output[:-1] + (config_remaining_strings + args_remaining_strings,) + elif fail_with_unknown_args and config_remaining_strings: + raise ValueError( + f"Unknown arguments from config file: {config_remaining_strings}. Please remove them, add them to the " + "dataclass, or set `fail_with_unknown_args=False`." + ) + else: + return output + + def set_defaults_with_config(self, **kwargs) -> list[str]: + """ + Overrides the parser's default values with those provided via keyword arguments, including for subparsers. + + Any argument with an updated default will also be marked as not required if it was previously required. + + Returns a list of strings that were not consumed by the parser. + """ + + def apply_defaults(parser, kw): + used_keys = set() + for action in parser._actions: + # Handle subparsers recursively + if isinstance(action, argparse._SubParsersAction): + for subparser in action.choices.values(): + used_keys.update(apply_defaults(subparser, kw)) + elif action.dest in kw: + action.default = kw[action.dest] + action.required = False + used_keys.add(action.dest) + return used_keys + + used_keys = apply_defaults(self, kwargs) + # Remaining args not consumed by the parser + remaining = [ + item for key, value in kwargs.items() if key not in used_keys for item in (f"--{key}", str(value)) + ] + return remaining + + +def get_git_commit_hash(package_name): + try: + # Import the package to locate its path + package = importlib.import_module(package_name) + # Get the path to the package using inspect + package_path = os.path.dirname(inspect.getfile(package)) + + # Navigate up to the Git repository root if the package is inside a subdirectory + git_repo_path = os.path.abspath(os.path.join(package_path, "..")) + git_dir = os.path.join(git_repo_path, ".git") + + if os.path.isdir(git_dir): + # Run the git command to get the current commit hash + commit_hash = ( + subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=git_repo_path).strip().decode("utf-8") + ) + return commit_hash + else: + return None + except Exception as e: + return f"Error: {str(e)}" + + +def get_dataset(mixture_config: DatasetMixtureConfig) -> "DatasetDict": + """ + Load a mixture of datasets based on the configuration. + + Args: + mixture_config ([`DatasetMixtureConfig`]): + Script arguments containing dataset configuration. + + Returns: + [`~datasets.DatasetDict`]: + Combined dataset(s) from the mixture configuration, with optional train/test split if `test_split_size` is + set. + + Example: + ```python + from trl import DatasetMixtureConfig, get_dataset + from trl.scripts.utils import DatasetConfig + + mixture_config = DatasetMixtureConfig(datasets=[DatasetConfig(path="trl-lib/tldr")]) + dataset = get_dataset(mixture_config) + print(dataset) + ``` + + ``` + DatasetDict({ + train: Dataset({ + features: ['prompt', 'completion'], + num_rows: 116722 + }) + }) + ``` + """ + import datasets + + logger.info(f"Creating dataset mixture with {len(mixture_config.datasets)} datasets") + datasets_list = [] + for dataset_config in mixture_config.datasets: + logger.info(f"Loading dataset for mixture: {dataset_config.path} (config name: {dataset_config.name})") + dataset = datasets.load_dataset( + path=dataset_config.path, + name=dataset_config.name, + data_dir=dataset_config.data_dir, + data_files=dataset_config.data_files, + split=dataset_config.split, + streaming=mixture_config.streaming, + ) + if dataset_config.columns is not None: + dataset = dataset.select_columns(dataset_config.columns) + datasets_list.append(dataset) + + if datasets_list: + combined_dataset = datasets.concatenate_datasets(datasets_list) + if isinstance(combined_dataset, datasets.Dataset): # IterableDataset does not have a length + logger.info(f"Created dataset mixture with {len(combined_dataset)} examples") + + if mixture_config.test_split_size is not None: + logger.info(f"Splitting dataset into train and test sets with test size: {mixture_config.test_split_size}") + combined_dataset = combined_dataset.train_test_split(test_size=mixture_config.test_split_size) + return combined_dataset + else: + return datasets.DatasetDict({"train": combined_dataset}) + else: + raise ValueError("No datasets were loaded from the mixture configuration") diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/scripts/vllm_serve.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/scripts/vllm_serve.py new file mode 100644 index 0000000000000000000000000000000000000000..ccf182eeaacfbc498b3fbcd5c455a3e93be16536 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/scripts/vllm_serve.py @@ -0,0 +1,1220 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import base64 +import json +import logging +import math +import os +from collections.abc import Sequence +from contextlib import asynccontextmanager +from dataclasses import dataclass, field +from io import BytesIO +from itertools import chain +from multiprocessing import Pipe, Process +from multiprocessing.connection import Connection + + +# We use CUDA with multiprocessing, so we must use the 'spawn' start method. Otherwise, we will get the following +# error: RuntimeError: Cannot re-initialize CUDA in forked subprocess. To use CUDA with multiprocessing, you must use +# the 'spawn' start method +os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn" + + +class WeightSyncWorkerExtension: + """ + A vLLM worker extension that enables weight synchronization between a client and multiple server workers. + + This worker uses a `StatelessProcessGroup` to establish communication and a `PyNcclCommunicator` or + `ProcessGroupXCCL` to handle efficient GPU-based communication using NCCL. The primary purpose of this class is to + receive updated model weights from a client process and distribute them to all worker processes participating in + model inference. + """ + + # The following attributes are initialized when `init_communicator` method is called. + communicator = None # Communicator for weight updates + client_rank = None # Source rank for broadcasting updated weights + + def init_communicator(self, host: str, port: int, world_size: int, client_device_uuid: str) -> None: + """ + Initializes the weight update communicator using a stateless process group. + + This method creates a `StatelessProcessGroup` that allows external training processes to communicate with vLLM + workers without interfering with the global torch distributed group. + + Args: + host (`str`): + Hostname or IP address of the master node. + port (`int`): + Port number to be used for communication. + world_size (`int`): + Total number of participating processes in the update group. + client_device_uuid (`str`): + UUID of the device of client main process. Used to assert that devices are different from vllm workers + devices. + """ + import torch + import torch.distributed.distributed_c10d as c10d + from transformers import is_torch_xpu_available + from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator + from vllm.distributed.parallel_state import get_world_group + from vllm.distributed.utils import StatelessProcessGroup + + from trl.import_utils import is_vllm_ascend_available + + if is_vllm_ascend_available(): + from vllm_ascend.distributed.device_communicators.pyhccl import PyHcclCommunicator as PyNcclCommunicator + + if self.communicator is not None: + raise RuntimeError("Weight update group already initialized. Call close_communicator first.") + + # TODO: will remove after torch xpu 2.9 support uuid in get_device_properties + if torch.cuda.is_available() or ( + is_torch_xpu_available() and hasattr(torch.xpu.get_device_properties(self.device), "uuid") + ): + accelerator_module = torch.xpu if is_torch_xpu_available() else torch.cuda + if client_device_uuid == str(accelerator_module.get_device_properties(self.device).uuid): + raise RuntimeError( + f"Attempting to use the same CUDA device (UUID: {client_device_uuid}) for multiple distinct " + "roles/ranks within the same communicator. This setup is unsupported and will likely lead to program " + "hangs or incorrect behavior. Ensure that trainer is using different devices than vLLM server." + ) + # Get the rank of the current worker in the global world group. + rank = get_world_group().rank + + if is_torch_xpu_available(): + store = torch.distributed.TCPStore(host_name=host, port=port, world_size=world_size, is_master=(rank == 0)) + prefixed_store = c10d.PrefixStore("client2server", store) + xccl_options = c10d.ProcessGroupXCCL.Options() + pg = c10d.ProcessGroupXCCL( + store=prefixed_store, + rank=rank, + size=world_size, + options=xccl_options, + ) + self.communicator = pg + else: + # Create a stateless process group to manage communication between training processes and vLLM workers. + # Initialize the NCCL-based communicator for weight synchronization. + pg = StatelessProcessGroup.create(host=host, port=port, rank=rank, world_size=world_size) + self.communicator = PyNcclCommunicator(pg, device=self.device) + + # The client process that sends updated weights has the highest rank (world_size - 1). + self.client_rank = world_size - 1 + + def update_named_param(self, name: str, dtype: str, shape: Sequence[int]) -> None: + """ + Receives updated weights from the client process and updates the named parameter in the model. + + Args: + name (`str`): + Name of the weight tensor being updated. + dtype (`str`): + Data type of the weight tensor as a string (e.g., `"torch.float32"`). + shape (`Sequence[int]`): + Shape of the weight tensor. + """ + import torch + from transformers import is_torch_xpu_available + + if self.communicator is None: + raise RuntimeError("Communicator not initialized. Call `init_communicator` first.") + + dtype = getattr(torch, dtype.split(".")[-1]) + # Allocate memory for the incoming weight tensor on the correct device. + weight = torch.empty(shape, dtype=dtype, device=self.device) + + if is_torch_xpu_available(): + # Use XCCL to broadcast the updated weights from the client (src) to all workers. + self.communicator.broadcast(weight, root=self.client_rank) + self.communicator.barrier() + else: + # Use NCCL to broadcast the updated weights from the client (src) to all workers. + self.communicator.broadcast(weight, src=self.client_rank) + self.communicator.group.barrier() + + # Load the received weights into the model. + self.model_runner.model.load_weights(weights=[(name, weight)]) + + def close_communicator(self) -> None: + """ + Closes the communicator when weight synchronization is no longer needed. + + This method deletes the NCCL communicator to release associated resources. + """ + + if self.communicator is not None: + del self.communicator + self.communicator = None # Ensure attribute is reset to None + self.client_rank = None # Ensure attribute is reset to None + + +@dataclass +class ScriptArguments: + r""" + Arguments for the script. + + Args: + model (`str`): + Model name or path to load the model from. + revision (`str`, *optional*): + Revision to use for the model. If not specified, the default branch will be used. + tensor_parallel_size (`int`, *optional*, defaults to `1`): + Number of tensor parallel workers to use. + data_parallel_size (`int`, *optional*, defaults to `1`): + Number of data parallel workers to use. For dense models, keep this at 1. Starting from vLLM `0.14.0`, + setting this above `1` for dense models is no longer supported/useful and will error out (see vLLM PR + #30739). + host (`str`, *optional*, defaults to `"0.0.0.0"`): + Host address to run the server on. + port (`int`, *optional*, defaults to `8000`): + Port to run the server on. + gpu_memory_utilization (`float`, *optional*, defaults to `0.9`): + Ratio (between 0 and 1) of GPU memory to reserve for the model weights, activations, and KV cache on the + device dedicated to generation powered by vLLM. Higher values will increase the KV cache size and thus + improve the model's throughput. However, if the value is too high, it may cause out-of-memory (OOM) errors + during initialization. + dtype (`str`, *optional*, defaults to `"auto"`): + Data type to use for vLLM generation. If set to `"auto"`, the data type will be automatically determined + based on the model configuration. Find the supported values in the vLLM documentation. + max_model_len (`int`, *optional*): + If set, the `max_model_len` to use for vLLM. This can be useful when running with reduced + `vllm_gpu_memory_utilization`, leading to a reduced KV cache size. If not set, vLLM will use the model + context size, which might be much larger than the KV cache, leading to inefficiencies. + enable_prefix_caching (`bool`, *optional*): + Whether to enable prefix caching in vLLM. If set to `True`, ensure that the model and the hardware support + this feature. + enforce_eager (`bool`, *optional*, defaults to `False`): + Whether to enforce eager execution. If set to `True`, we will disable CUDA graph and always execute the + model in eager mode. If `False` (default behavior), we will use CUDA graph and eager execution in hybrid. + 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. + kv_cache_dtype (`str`, *optional*, defaults to `"auto"`): + Data type to use for KV cache. If set to `"auto"`, the dtype will default to the model data type. + trust_remote_code (`bool`, *optional*, defaults to `False`): + Whether to trust remote code when loading models. Set to `True` to allow executing code from model + repositories. This is required for some custom models but introduces security risks. + log_level (`str`, *optional*, defaults to `"info"`): + Log level for uvicorn. Possible choices: `"critical"`, `"error"`, `"warning"`, `"info"`, `"debug"`, + `"trace"`. + distributed_executor_backend (`str` or `None`, *optional*): + Distributed executor backend for vLLM. Set to `"ray"` to distribute tensor parallel workers across multiple + nodes via a Ray cluster. Required when `tensor_parallel_size` exceeds the number of local GPUs. If not set, + vLLM defaults to the multiproc backend (single-node only). + speculative_config (`str`, *optional*): + JSON string for vLLM speculative decoding config, forwarded to `LLM(speculative_config=...)`. When unset, + speculative decoding is disabled. Example: `'{"method": "qwen3_next_mtp", "num_speculative_tokens": 5}'`. + """ + + model: str = field( + metadata={"help": "Model name or path to load the model from."}, + ) + revision: str | None = field( + default=None, + metadata={"help": "Revision to use for the model. If not specified, the default branch will be used."}, + ) + tensor_parallel_size: int = field( + default=1, + metadata={"help": "Number of tensor parallel workers to use."}, + ) + data_parallel_size: int = field( + default=1, + metadata={ + "help": "Number of data parallel workers to use. For dense models, keep this at 1. Starting from vLLM " + "`0.14.0`, setting this above `1` for dense models is no longer supported/useful and will error out (see " + "vLLM PR #30739)." + }, + ) + host: str = field( + default="0.0.0.0", + metadata={"help": "Host address to run the server on."}, + ) + port: int = field( + default=8000, + metadata={"help": "Port to run the server on."}, + ) + gpu_memory_utilization: float = field( + default=0.9, + metadata={ + "help": "Ratio (between 0 and 1) of GPU memory to reserve for the model weights, activations, and KV " + "cache on the device dedicated to generation powered by vLLM. Higher values will increase the KV cache " + "size and thus improve the model's throughput. However, if the value is too high, it may cause " + "out-of-memory (OOM) errors during initialization." + }, + ) + dtype: str = field( + default="auto", + metadata={ + "help": "Data type to use for vLLM generation. If set to 'auto', the data type will be automatically " + "determined based on the model configuration. Find the supported values in the vLLM documentation." + }, + ) + max_model_len: int | None = field( + default=None, + metadata={ + "help": "If set, the `max_model_len` to use for vLLM. This can be useful when running with reduced " + "`vllm_gpu_memory_utilization`, leading to a reduced KV cache size. If not set, vLLM will use the model " + "context size, which might be much larger than the KV cache, leading to inefficiencies." + }, + ) + enable_prefix_caching: bool | None = field( + default=None, + metadata={ + "help": "Whether to enable prefix caching in vLLM. If set to `True`, ensure that the model and the " + "hardware support this feature." + }, + ) + enforce_eager: bool | None = field( + default=False, + metadata={ + "help": "Whether to enforce eager execution. If set to `True`, we will disable CUDA graph and always " + "execute the model in eager mode. If `False` (default behavior), we will use CUDA graph and eager " + "execution in hybrid." + }, + ) + kv_cache_dtype: str = field( + default="auto", + metadata={ + "help": "Data type to use for KV cache. If set to 'auto', the dtype will default to the model data type." + }, + ) + trust_remote_code: bool = field( + default=False, + metadata={ + "help": "Whether to trust remote code when loading models. Set to True to allow executing code from model " + "repositories. This is required for some custom models but introduces security risks." + }, + ) + log_level: str = field( + default="info", + metadata={ + "help": "Log level for uvicorn. Possible choices: 'critical', 'error', 'warning', 'info', 'debug', " + "'trace'." + }, + ) + vllm_model_impl: str = field( + default="vllm", + metadata={ + "help": "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." + }, + ) + distributed_executor_backend: str | None = field( + default=None, + metadata={ + "help": "Distributed executor backend for vLLM. When set to 'ray', vLLM uses Ray to distribute tensor " + "parallel workers across multiple nodes. Required when tensor_parallel_size exceeds the number of local " + "GPUs. If not set, vLLM defaults to the multiproc backend (single-node only)." + }, + ) + speculative_config: str | None = field( + default=None, + metadata={ + "help": "JSON string for vLLM speculative decoding config. " + 'Example: \'{"method": "qwen3_next_mtp", "num_speculative_tokens": 5}\'' + }, + ) + + +def llm_worker( + script_args: ScriptArguments, data_parallel_rank: int, master_port: int, connection: Connection +) -> None: + from vllm import LLM + + # Set required environment variables for DP to work with vLLM + os.environ["VLLM_DP_RANK"] = str(data_parallel_rank) + os.environ["VLLM_DP_RANK_LOCAL"] = str(data_parallel_rank) + os.environ["VLLM_DP_SIZE"] = str(script_args.data_parallel_size) + os.environ["VLLM_DP_MASTER_PORT"] = str(master_port) + + llm = LLM( + model=script_args.model, + revision=script_args.revision, + tensor_parallel_size=script_args.tensor_parallel_size, + gpu_memory_utilization=script_args.gpu_memory_utilization, + enforce_eager=script_args.enforce_eager, + dtype=script_args.dtype, + # Automatic Prefix Caching caches the KV cache of existing queries, so that a new query can + # directly reuse the KV cache if it shares the same prefix with one of the existing queries. + # This is particularly useful here because we generate completions from the same prompts. + enable_prefix_caching=script_args.enable_prefix_caching, + kv_cache_dtype=script_args.kv_cache_dtype, + max_model_len=script_args.max_model_len, + worker_extension_cls="trl.scripts.vllm_serve.WeightSyncWorkerExtension", + trust_remote_code=script_args.trust_remote_code, + model_impl=script_args.vllm_model_impl, + distributed_executor_backend=script_args.distributed_executor_backend, + # Important so temperature scaling/logit tweaking affects the TIS log probs + logprobs_mode="processed_logprobs", + speculative_config=json.loads(script_args.speculative_config) if script_args.speculative_config else None, + ) + + # Send ready signal to parent process + connection.send({"status": "ready"}) + + while True: + # Wait for commands from the parent process + try: + command = connection.recv() + except KeyboardInterrupt: + llm.collective_rpc(method="close_communicator") + break + + # Handle commands + if command["type"] in ["call", "fire_and_forget"]: + method_name = command["method"] + args, kwargs = command.get("args", ()), command.get("kwargs", {}) + method = getattr(llm, method_name) + result = method(*args, **kwargs) + if command["type"] == "call": + connection.send(result) + elif command["type"] == "shutdown": + break + + +def chunk_list(lst: list, n: int) -> list[list]: + """ + Split list `lst` into `n` evenly distributed sublists. + + Example: + ```python + >>> chunk_list([1, 2, 3, 4, 5, 6], 2) + [[1, 2, 3], [4, 5, 6]] + + >>> chunk_list([1, 2, 3, 4, 5, 6], 4) + [[1, 2], [3, 4], [5], [6]] + + >>> chunk_list([1, 2, 3, 4, 5, 6], 8) + [[1], [2], [3], [4], [5], [6], [], []] + ``` + """ + k, r = divmod(len(lst), n) + return [lst[i * k + min(i, r) : (i + 1) * k + min(i + 1, r)] for i in range(n)] + + +def main(script_args: ScriptArguments): + import asyncio + + from transformers import is_vision_available + + from trl.generation.vllm_generation import extract_logprobs + from trl.import_utils import ( + is_fastapi_available, + is_pydantic_available, + is_uvicorn_available, + is_vllm_available, + ) + + if not is_fastapi_available(): + raise ImportError( + "FastAPI is required to run the vLLM serve script. Please install it using `pip install fastapi`." + ) + + if not is_pydantic_available(): + raise ImportError( + "Pydantic is required to run the vLLM serve script. Please install it using `pip install pydantic`." + ) + + if not is_uvicorn_available(): + raise ImportError( + "Uvicorn is required to run the vLLM serve script. Please install it using `pip install uvicorn`." + ) + + if not is_vllm_available(): + raise ImportError("vLLM is required to run the vLLM serve script. Please install it using `pip install vllm`.") + + import uvicorn + from fastapi import FastAPI + from pydantic import BaseModel + from vllm import SamplingParams + from vllm.sampling_params import StructuredOutputsParams + from vllm.utils.network_utils import get_open_port + + if is_vision_available(): + from PIL import Image + + logger = logging.getLogger(__name__) + + # Spawn dp workers, and setup pipes for communication + master_port = get_open_port() + connections = [] + processes = [] + for data_parallel_rank in range(script_args.data_parallel_size): + parent_connection, child_connection = Pipe() + process = Process(target=llm_worker, args=(script_args, data_parallel_rank, master_port, child_connection)) + process.start() + connections.append(parent_connection) + processes.append(process) + + @asynccontextmanager + async def lifespan(app: FastAPI): + # Wait for all workers to send "ready" + ready_connections = set() + while len(ready_connections) < script_args.data_parallel_size: + for connection in connections: + msg = connection.recv() + if isinstance(msg, dict) and msg.get("status") == "ready": + ready_connections.add(connection) + + # Start the logprob request batcher background task + batcher_task = asyncio.create_task(_logprob_batcher()) + + yield + + batcher_task.cancel() + + # Wait for processes to terminate + for process in processes: + process.join(timeout=10) # Wait for 10 seconds for the process to terminate + if process.is_alive(): + logger.warning(f"Process {process} is still alive after 10 seconds, attempting to terminate...") + process.terminate() + process.join() # ensure process termination after calling terminate() + + app = FastAPI(lifespan=lifespan) + + # Define the endpoints for the model server + @app.get("/health/") + async def health(): + """ + Health check endpoint to verify that the server is running. + """ + return {"status": "ok"} + + @app.get("/get_world_size/") + async def get_world_size(): + """ + Retrieves the world size of the LLM engine, which is `tensor_parallel_size * data_parallel_size`. + + Returns: + `dict`: + A dictionary containing the world size. + + Example response: + ```json + {"world_size": 8} + ``` + """ + return {"world_size": script_args.tensor_parallel_size * script_args.data_parallel_size} + + class GenerateRequest(BaseModel): + prompts: list[str] | list[list[int]] + images: list[list[str] | None] | None = None + n: int = 1 + repetition_penalty: float = 1.0 + temperature: float = 1.0 + top_p: float = 1.0 + top_k: int = -1 + min_p: float = 0.0 + max_tokens: int = 16 + logprobs: int | None = 0 + structured_outputs_regex: str | None = None + generation_kwargs: dict = field(default_factory=dict) + + class GenerateResponse(BaseModel): + prompt_ids: list[list[int]] + completion_ids: list[list[int]] + logprobs: list[list[list[float | None]]] | None + logprob_token_ids: list[list[list[int]]] | None + + @app.post("/generate/", response_model=GenerateResponse) + async def generate(request: GenerateRequest): + """ + Generates completions for the provided prompts. + + Args: + request (`GenerateRequest`): + - `prompts` (list of `str` or list of list of `int`): A list of prompts. It accepts either text strings + or pre-tokenized token ID lists. When text strings are provided, `images` can optionally be included. + - `images` (list of list of `str` or `None`, *optional*): A list of image lists. Each element is a list + of base64-encoded images for the corresponding prompt, or `None` if no images for that prompt. + - `n` (`int`, *optional*, defaults to `1`): Number of completions to generate for each prompt. + - `repetition_penalty` (`float`, *optional*, defaults to `1.0`): Repetition penalty to apply during + generation. + - `temperature` (`float`, *optional*, defaults to `1.0`): Temperature for sampling. Higher values lead + to more random outputs. + - `top_p` (`float`, *optional*, defaults to `1.0`): Top-p (nucleus) sampling parameter. It controls the + diversity of the generated text. + - `top_k` (`int`, *optional*, defaults to `-1`): Top-k sampling parameter. If set to `-1`, it disables + top-k sampling. + - `min_p` (`float`, *optional*, defaults to `0.0`): Minimum probability threshold for sampling. + - `max_tokens` (`int`, *optional*, defaults to `16`): Maximum number of tokens to generate for each + completion. + - `logprobs` (`int`, *optional*, defaults to `0`): Number of top logprobs to return per token. When 0, + only the sampled token's logprob is returned. When N>0, returns up to N+1 logprobs sorted by + descending probability, because vLLM always includes the sampled token's logprob (which may fall + outside the top-N). + - `structured_outputs_regex` (`str`, *optional*): A regex pattern for structured outputs. If provided, + the model will only generate tokens that match this regex pattern. + - `generation_kwargs` (`dict`, *optional*): Additional generation parameters to pass to the vLLM + `SamplingParams`. This can include parameters like `seed`, `frequency_penalty`, etc. If it contains + keys that conflict with the other parameters, they will override them. + + Returns: + `GenerateResponse`: + - `prompt_ids` (list of list of `int`): A list of lists of token IDs for each input prompt. + - `completion_ids` (list of list of `int`): A list of lists of token IDs for each generated completion. + - `logprobs` (list of list of list of `float`): Per-token logprobs of shape (num_sequences, seq_len, + num_logprobs), sorted by descending probability. + - `logprob_token_ids` (list of list of list of `int`): Token IDs corresponding to each logprob, same + shape as `logprobs`. + + Example request (text prompts): + ```json + {"prompts": ["Hello world", "What is AI?"]} + ``` + + Example request (token IDs): + ```json + {"prompts": [[101, 102], [201, 202]]} + ``` + + Example response: + ```json + { + "prompt_ids": [[101, 102], [201, 202]], + "completion_ids": [[103, 104, 105], [203, 204, 205]], + "logprobs": [[[-0.1], [-0.2], [-0.3]], [[-0.4], [-0.5], [-0.6]]], + "logprob_token_ids": [[[103], [104], [105]], [[203], [204], [205]]] + } + ``` + """ + # Build vLLM-compatible prompt inputs + is_token_ids = request.prompts and isinstance(request.prompts[0], list) + request.images = request.images or [None] * len(request.prompts) + + prompts = [] + for prompt, image_list in zip(request.prompts, request.images, strict=True): + row = {"prompt_token_ids": prompt} if is_token_ids else {"prompt": prompt} + if image_list is not None: + row["multi_modal_data"] = {"image": [Image.open(BytesIO(base64.b64decode(img))) for img in image_list]} + prompts.append(row) + + generation_kwargs = { + "n": request.n, + "repetition_penalty": request.repetition_penalty, + "temperature": request.temperature, + "top_p": request.top_p, + "top_k": request.top_k, + "min_p": request.min_p, + "max_tokens": request.max_tokens, + "logprobs": request.logprobs, + } + generation_kwargs.update(request.generation_kwargs) + + # Structured outputs, if enabled + if request.structured_outputs_regex is not None: + if generation_kwargs.get("structured_outputs") is not None: + logger.warning( + "Both `structured_outputs_regex` and `generation_kwargs['structured_outputs']` are set; " + "`structured_outputs_regex` takes precedence." + ) + generation_kwargs["structured_outputs"] = StructuredOutputsParams(regex=request.structured_outputs_regex) + elif isinstance(structured_outputs_kwargs := generation_kwargs.get("structured_outputs"), dict): + generation_kwargs["structured_outputs"] = StructuredOutputsParams(**structured_outputs_kwargs) + sampling_params = SamplingParams(**generation_kwargs) + + # Evenly distribute prompts across DP ranks + chunked_prompts = chunk_list(prompts, script_args.data_parallel_size) + + # Send the prompts to each worker + for connection, prompts in zip(connections, chunked_prompts, strict=True): + # When the number of prompts is less than data_parallel_size, some workers will receive empty prompts. + # However, vLLM requires that we always send at least one prompt. So we send a placeholder prompt to comply + # with vLLM's requirement, and we later ignore the result. + if not prompts: + prompts = [""] + kwargs = {"prompts": prompts, "sampling_params": sampling_params} + connection.send({"type": "call", "method": "generate", "kwargs": kwargs}) + + # Receive results + all_outputs = [connection.recv() for connection in connections] + + # Handle empty prompts (see above) + all_outputs = [output for output, prompts in zip(all_outputs, chunked_prompts, strict=True) if prompts] + + # Flatten and combine all results + all_outputs = list(chain.from_iterable(all_outputs)) # from list of list to single list + prompt_ids = [output.prompt_token_ids for output in all_outputs] + completion_ids = [list(output.token_ids) for outputs in all_outputs for output in outputs.outputs] + logprobs, logprob_token_ids = extract_logprobs(all_outputs) + + return { + "prompt_ids": prompt_ids, + "completion_ids": completion_ids, + "logprobs": logprobs, + "logprob_token_ids": logprob_token_ids, + } + + class SequenceLogprobsRequest(BaseModel): + sequences: list[list[int]] + prompt_lengths: list[int] + top_logprobs: int = 100 + temperature: float = 1.0 + response_format: str = "json" # "json" (legacy) or "binary" (base64 numpy arrays) + + class SequenceLogprobsResponse(BaseModel): + logprobs: list[list[list[float | None]]] | None = None + logprob_token_ids: list[list[list[int]]] | None = None + # Binary format fields (base64-encoded numpy arrays) + logprobs_b64: str | None = None + token_ids_b64: str | None = None + actual_logprobs_b64: str | None = None + actual_token_ids_b64: str | None = None + shape: list[int] | None = None # [batch_size, max_completion_len, top_logprobs] + completion_lengths: list[int] | None = None # actual completion length per sample + + def _run_prompt_logprobs(prompts, sampling_params): + """Send prompts to DP workers and collect outputs.""" + chunked_prompts = chunk_list(prompts, script_args.data_parallel_size) + for connection, chunk in zip(connections, chunked_prompts, strict=True): + if not chunk: + chunk = [{"prompt_token_ids": [0]}] + kwargs = {"prompts": chunk, "sampling_params": sampling_params} + connection.send({"type": "call", "method": "generate", "kwargs": kwargs}) + all_outputs = [connection.recv() for connection in connections] + all_outputs = [output for output, chunk in zip(all_outputs, chunked_prompts, strict=True) if chunk] + return list(chain.from_iterable(all_outputs)) + + # ── Request batching for get_sequence_logprobs ── + # Collects concurrent requests into batches and dispatches them together so that + # all DP workers stay busy. Without this, async endpoint handlers block the event + # loop during pipe I/O, serializing requests and leaving DP workers idle. + _logprob_queue: asyncio.Queue = asyncio.Queue() + + # Maximum time (seconds) to wait for more requests before dispatching a batch. + _BATCH_WAIT_S = 0.005 # 5ms - short enough to not add much latency when lightly loaded + # Maximum number of HTTP requests to collect per batcher cycle + _MAX_BATCH_REQUESTS = max(script_args.data_parallel_size * 4, 16) + # Maximum total tokens per batch. prompt_logprobs materializes full-vocab logits + # during the forward pass, so each worker can safely handle ~1 max-length sequence. + # Budget = max_model_len * dp_size gives ~1 sequence per worker at max length. + _max_model_len = script_args.max_model_len or 8192 + _MAX_BATCH_TOKENS = _max_model_len * script_args.data_parallel_size + + async def _logprob_batcher(): + """Background task that continuously drains the queue, batches requests, and dispatches.""" + loop = asyncio.get_running_loop() + + while True: + batch = [] + try: + # Wait for the first request + batch_tokens = 0 + item = await _logprob_queue.get() + batch.append(item) + # Count tokens in this item's sequences + for prompt in item[0]: + batch_tokens += len(prompt.get("prompt_token_ids", [])) + + # Collect more requests up to batch limit, timeout, or token budget + deadline = loop.time() + _BATCH_WAIT_S + while len(batch) < _MAX_BATCH_REQUESTS and batch_tokens < _MAX_BATCH_TOKENS: + remaining = deadline - loop.time() + if remaining <= 0: + break + try: + item = await asyncio.wait_for(_logprob_queue.get(), timeout=remaining) + # Check if adding this item would exceed the token budget + item_tokens = sum(len(p.get("prompt_token_ids", [])) for p in item[0]) + if batch_tokens + item_tokens > _MAX_BATCH_TOKENS and len(batch) > 0: + # Put it back and dispatch current batch + await _logprob_queue.put(item) + break + batch.append(item) + batch_tokens += item_tokens + except asyncio.TimeoutError: + break + + # batch is a list of (prompts, prompt_lengths, top_logprobs, temperature, response_format, future) + # All items in a batch must share the same (top_logprobs, temperature) pair. + # Group by those execution parameters to handle mixed requests. + groups = {} + for prompts, prompt_lengths, top_logprobs, temperature, response_format, future in batch: + key = (top_logprobs, temperature) + if key not in groups: + groups[key] = [] + groups[key].append((prompts, prompt_lengths, response_format, future)) + + for (top_logprobs, temperature), items in groups.items(): + # Merge all sequences into a single batch + all_prompts = [] + all_prompt_lengths = [] + offsets = [] # (start_idx, count) per original request + for prompts, prompt_lengths, _response_format, _future in items: + start = len(all_prompts) + all_prompts.extend(prompts) + all_prompt_lengths.extend(prompt_lengths) + offsets.append((start, len(prompts))) + + sampling_params = SamplingParams( + max_tokens=1, + temperature=temperature, + prompt_logprobs=top_logprobs, + ) + + # Dispatch to workers in a thread to avoid blocking the event loop + try: + all_outputs = await loop.run_in_executor( + None, _run_prompt_logprobs, all_prompts, sampling_params + ) + + # Split results back to individual requests + for (start, count), (_, prompt_lengths, response_format, future) in zip( + offsets, items, strict=True + ): + outputs_slice = all_outputs[start : start + count] + if not future.done(): + future.set_result((outputs_slice, prompt_lengths, top_logprobs, response_format)) + except Exception as e: + # Signal error to all waiting requests in this execution-parameter group + for *_, future in items: + if not future.done(): + future.set_exception(e) + except Exception as e: + # Prevent killing the batcher task — signal error to all unfulfilled futures + for *_, future in batch: + if not future.done(): + future.set_exception(e) + + def _format_logprob_response(all_outputs, prompt_lengths, top_k, response_format): + """Format vLLM outputs into the response dict (runs in any thread).""" + import numpy as np + + batch_size = len(all_outputs) + use_binary = response_format == "binary" + + if use_binary: + from starlette.responses import Response + + comp_lengths = [] + for output, prompt_length in zip(all_outputs, prompt_lengths, strict=True): + prompt_lps = output.prompt_logprobs + if prompt_lps is None: + raise ValueError("prompt_logprobs is None.") + comp_lengths.append(len(prompt_lps) - prompt_length) + + max_comp_len = max(comp_lengths) if comp_lengths else 0 + + # logprobs_arr / token_ids_arr: teacher's sorted top-k logprobs + token ids (for forward KL). + # actual_logprobs_arr / actual_token_ids_arr: actual token's teacher logprob (for reverse KL). + logprobs_arr = np.full((batch_size, max_comp_len, top_k), float("-inf"), dtype=np.float32) + token_ids_arr = np.zeros((batch_size, max_comp_len, top_k), dtype=np.int32) + actual_logprobs_arr = np.full((batch_size, max_comp_len, 1), float("-inf"), dtype=np.float32) + actual_token_ids_arr = np.zeros((batch_size, max_comp_len, 1), dtype=np.int32) + + for i, (output, prompt_length) in enumerate(zip(all_outputs, prompt_lengths, strict=True)): + prompt_lps = output.prompt_logprobs + seq_tokens = output.prompt_token_ids + if comp_lengths[i] == 0: + continue + + for pos in range(prompt_length, len(prompt_lps)): + lp = prompt_lps[pos] + if lp is None: + continue + t = pos - prompt_length + actual_token = seq_tokens[pos] + + # Actual token's logprob (for reverse KL) + if actual_token in lp: + val = lp[actual_token].logprob + if not math.isnan(val): + actual_logprobs_arr[i, t, 0] = val + actual_token_ids_arr[i, t, 0] = actual_token + + # Teacher's top-k logprobs (for forward KL) + if top_k == 1: + # Fast path: find rank-1 directly instead of sorting + for token_id, logprob_obj in lp.items(): + if logprob_obj.rank == 1: + val = logprob_obj.logprob + if not math.isnan(val): + logprobs_arr[i, t, 0] = val + token_ids_arr[i, t, 0] = token_id + break + else: + sorted_items = sorted(lp.items(), key=lambda x: x[1].rank) + for k_idx, (token_id, logprob_obj) in enumerate(sorted_items[:top_k]): + val = logprob_obj.logprob + if not math.isnan(val): + logprobs_arr[i, t, k_idx] = val + token_ids_arr[i, t, k_idx] = token_id + + payload = { + "logprobs_b64": base64.b64encode(logprobs_arr.tobytes()).decode("ascii"), + "token_ids_b64": base64.b64encode(token_ids_arr.tobytes()).decode("ascii"), + "actual_logprobs_b64": base64.b64encode(actual_logprobs_arr.tobytes()).decode("ascii"), + "actual_token_ids_b64": base64.b64encode(actual_token_ids_arr.tobytes()).decode("ascii"), + "shape": [batch_size, max_comp_len, top_k], + "completion_lengths": comp_lengths, + } + + try: + import orjson + + return Response(content=orjson.dumps(payload), media_type="application/json") + except ImportError: + return payload + else: + all_logprobs = [] + all_token_ids = [] + for output, prompt_length in zip(all_outputs, prompt_lengths, strict=True): + prompt_lps = output.prompt_logprobs + if prompt_lps is None: + raise ValueError("prompt_logprobs is None.") + seq_logprobs = [] + seq_token_ids = [] + for pos in range(prompt_length, len(prompt_lps)): + lp = prompt_lps[pos] + if lp is None: + seq_logprobs.append([]) + seq_token_ids.append([]) + continue + sorted_items = sorted(lp.items(), key=lambda x: x[1].rank) + seq_token_ids.append([token_id for token_id, _ in sorted_items]) + seq_logprobs.append( + [None if math.isnan(item.logprob) else item.logprob for _, item in sorted_items] + ) + all_logprobs.append(seq_logprobs) + all_token_ids.append(seq_token_ids) + return {"logprobs": all_logprobs, "logprob_token_ids": all_token_ids} + + @app.post("/get_sequence_logprobs/", response_model=SequenceLogprobsResponse) + async def get_sequence_logprobs(request: SequenceLogprobsRequest): + """ + Computes teacher logprobs for existing token sequences without generating new tokens. + + Concurrent requests are automatically batched and dispatched together to maximize GPU utilization across DP + workers. This avoids the event-loop-blocking problem where synchronous pipe I/O serializes requests despite + having multiple DP workers. + + Args: + request (`SequenceLogprobsRequest`): + - `sequences` (list of list of `int`): Full token sequences (prompt + completion) per sample. + - `prompt_lengths` (list of `int`): Number of prompt tokens per sequence; completion logprobs start + after each prompt. + - `top_logprobs` (`int`, *optional*, defaults to `100`): Number of top teacher logprobs to return per + completion position (sorted by vLLM rank). + - `temperature` (`float`, *optional*, defaults to `1.0`): Sampling temperature passed to vLLM for + logprob computation. + - `response_format` (`str`, *optional*, defaults to `"json"`): Either `"json"` (nested lists, + backward-compatible) or `"binary"` (base64-encoded numpy arrays for fast serialization). + + Returns: + `SequenceLogprobsResponse` or Starlette `Response`: + When `response_format` is `"json"`, a JSON object with: + - `logprobs` (list of list of list of `float` or `None`): Top-k teacher logprobs per completion token. + - `logprob_token_ids` (list of list of list of `int`): Token IDs aligned with `logprobs`. + When `response_format` is `"binary"`, a JSON response (Starlette `Response` if `orjson` is installed) + whose body is a JSON object with base64-encoded float32/int32 arrays: `logprobs_b64`, `token_ids_b64`, + `actual_logprobs_b64`, `actual_token_ids_b64`, plus `shape` (`list[int]`, `[batch_size, + max_completion_len, top_k]`) and `completion_lengths` (`list[int]`). + """ + if len(request.sequences) != len(request.prompt_lengths): + raise ValueError("sequences and prompt_lengths must have the same length.") + + for i, (seq, pl) in enumerate(zip(request.sequences, request.prompt_lengths, strict=True)): + if pl < 0 or pl > len(seq): + raise ValueError( + f"Sequence {i} has prompt_length={pl} which is out of range [0, {len(seq)}]. " + f"prompt_length must be between 0 and the sequence length inclusive." + ) + + # Validate sequence lengths against max_model_len to prevent worker OOM crashes + if _max_model_len: + for i, seq in enumerate(request.sequences): + if len(seq) > _max_model_len: + raise ValueError( + f"Sequence {i} has length {len(seq)} which exceeds max_model_len={_max_model_len}. " + f"Truncate sequences or increase --max-model-len." + ) + + prompts = [{"prompt_token_ids": seq} for seq in request.sequences] + + # Submit to the batching queue and await result + loop = asyncio.get_running_loop() + future = loop.create_future() + await _logprob_queue.put( + ( + prompts, + list(request.prompt_lengths), + request.top_logprobs, + request.temperature, + request.response_format, + future, + ) + ) + + # Wait for the batcher to process our request + all_outputs, prompt_lengths, top_k, response_format = await future + + return await loop.run_in_executor( + None, _format_logprob_response, all_outputs, prompt_lengths, top_k, response_format + ) + + class ChatRequest(BaseModel): + messages: list[list[dict]] + n: int = 1 + repetition_penalty: float = 1.0 + temperature: float = 1.0 + top_p: float = 1.0 + top_k: int = -1 + min_p: float = 0.0 + max_tokens: int = 16 + logprobs: int | None = 0 + structured_outputs_regex: str | None = None + generation_kwargs: dict = field(default_factory=dict) + chat_template_kwargs: dict = field(default_factory=dict) + tools: list | None = None + + class ChatResponse(BaseModel): + prompt_ids: list[list[int]] + completion_ids: list[list[int]] + logprobs: list[list[list[float | None]]] | None + logprob_token_ids: list[list[list[int]]] | None + + @app.post("/chat/", response_model=ChatResponse) + async def chat(request: ChatRequest): + """ + Generates completions for the provided chat messages. + + Args: + request (`ChatRequest`): + - `messages` (list of `dict`): A list of messages (dicts with "role" and "content" keys) for the model + to generate completions. + - `n` (`int`, *optional*, defaults to `1`): Number of completions to generate for each prompt. + - `repetition_penalty` (`float`, *optional*, defaults to `1.0`): Repetition penalty to apply during + generation. + - `temperature` (`float`, *optional*, defaults to `1.0`): Temperature for sampling. Higher values lead + to more random outputs. + - `top_p` (`float`, *optional*, defaults to `1.0`): Top-p (nucleus) sampling parameter. It controls the + diversity of the generated text. + - `top_k` (`int`, *optional*, defaults to `-1`): Top-k sampling parameter. If set to `-1`, it disables + top-k sampling. + - `min_p` (`float`, *optional*, defaults to `0.0`): Minimum probability threshold for sampling. + - `max_tokens` (`int`, *optional*, defaults to `16`): Maximum number of tokens to generate for each + completion. + - `logprobs` (`int`, *optional*, defaults to `0`): Number of top logprobs to return per token. When 0, + only the sampled token's logprob is returned. When N>0, returns up to N+1 logprobs sorted by + descending probability, because vLLM always includes the sampled token's logprob (which may fall + outside the top-N). + - `structured_outputs_regex` (`str`, *optional*): A regex pattern for structured outputs. If provided, + the model will only generate tokens that match this regex pattern. + - `generation_kwargs` (`dict`, *optional*): Additional generation parameters to pass to the vLLM + `SamplingParams`. This can include parameters like `seed`, `frequency_penalty`, etc. If it contains + keys that conflict with the other parameters, they will override them. + - `chat_template_kwargs` (`dict`, *optional*): Additional keyword arguments to pass to the chat + template. + + Returns: + `ChatResponse`: + - `prompt_ids` (list of list of `int`): A list of lists of token IDs for each input prompt. + - `completion_ids` (list of list of `int`): A list of lists of token IDs for each generated completion. + - `logprobs` (list of list of list of `float`): Per-token logprobs of shape (num_sequences, seq_len, + num_logprobs), sorted by descending probability. + - `logprob_token_ids` (list of list of list of `int`): Token IDs corresponding to each logprob, same + shape as `logprobs`. + + Example request: + ```bash + curl -X POST 'http://0.0.0.0:8000/chat/' \ + -H 'Content-Type: application/json' \ + -d '{"messages": [[{ "role": "user", "content": "Hello!" }]]}' + ``` + + Example response: + ```json + { + "prompt_ids": [[151644, 872, 198, 9707, 0, 151645, 198, 151644, 77091, 198]], + "completion_ids": [[151667, 198, 32313, 11, 279]], + "logprobs": [[[-0.0003], [-3.58e-07], [-0.0902], [-6.39e-05], [-0.0387]]], + "logprob_token_ids": [[[151667], [198], [32313], [11], [279]]] + } + ``` + """ + # Convert PIL images to base64 strings + for message_list in request.messages: + for message in message_list: + if isinstance(message["content"], list): + for part in message["content"]: + if part["type"] == "image_pil": + part["image_pil"] = Image.open(BytesIO(base64.b64decode(part["image_pil"]))) + + generation_kwargs = { + "n": request.n, + "repetition_penalty": request.repetition_penalty, + "temperature": request.temperature, + "top_p": request.top_p, + "top_k": request.top_k, + "min_p": request.min_p, + "max_tokens": request.max_tokens, + "logprobs": request.logprobs, + } + generation_kwargs.update(request.generation_kwargs) + + # Structured outputs, if enabled + if request.structured_outputs_regex is not None: + if generation_kwargs.get("structured_outputs") is not None: + logger.warning( + "Both `structured_outputs_regex` and `generation_kwargs['structured_outputs']` are set; " + "`structured_outputs_regex` takes precedence." + ) + generation_kwargs["structured_outputs"] = StructuredOutputsParams(regex=request.structured_outputs_regex) + elif isinstance(structured_outputs_kwargs := generation_kwargs.get("structured_outputs"), dict): + generation_kwargs["structured_outputs"] = StructuredOutputsParams(**structured_outputs_kwargs) + sampling_params = SamplingParams(**generation_kwargs) + + # Evenly distribute prompts across DP ranks + chunked_messages = chunk_list(request.messages, script_args.data_parallel_size) + + # Send the messages to each worker + for connection, messages in zip(connections, chunked_messages, strict=True): + # When the number of messages is less than data_parallel_size, some workers will receive empty messages. + # However, vLLM requires that we always send at least one prompt. So we send a placeholder prompt to comply + # with vLLM's requirement, and we later ignore the result. + if not messages: + messages = [[{"role": "user", "content": ""}]] + kwargs = { + "messages": messages, + "sampling_params": sampling_params, + "chat_template_kwargs": request.chat_template_kwargs, + "tools": request.tools, + } + connection.send({"type": "call", "method": "chat", "kwargs": kwargs}) + + # Receive results + all_outputs = [connection.recv() for connection in connections] + + # Handle empty prompts (see above) + all_outputs = [output for output, prompts in zip(all_outputs, chunked_messages, strict=True) if prompts] + + # Flatten and combine all results + all_outputs = list(chain.from_iterable(all_outputs)) # from list of list to single list + prompt_ids = [output.prompt_token_ids for output in all_outputs] + completion_ids = [list(output.token_ids) for outputs in all_outputs for output in outputs.outputs] + logprobs, logprob_token_ids = extract_logprobs(all_outputs) + + return { + "prompt_ids": prompt_ids, + "completion_ids": completion_ids, + "logprobs": logprobs, + "logprob_token_ids": logprob_token_ids, + } + + class InitCommunicatorRequest(BaseModel): + host: str + port: int + world_size: int + client_device_uuid: str + + @app.post("/init_communicator/") + async def init_communicator(request: InitCommunicatorRequest): + """ + Initializes the communicator for synchronizing model weights between a client and multiple server workers. + + Args: + request (`InitCommunicatorRequest`): + - `host` (`str`): Hostname or IP address of the master node. + - `port` (`int`): Port number to be used for communication. + - `world_size` (`int`): Total number of participating processes in the group. + - `client_device_uuid` (`str`): UUID of the device of client main process. Used to assert that devices + are different from vLLM workers devices. + """ + world_size = script_args.tensor_parallel_size * script_args.data_parallel_size + 1 + + # The function init_communicator is called this way: init_communicator(host, port, world_size) + # So with collective_rpc we need to call it this way: + # llm.collective_rpc(method="init_communicator", args=(host, port, world_size)) + kwargs = { + "method": "init_communicator", + "args": (request.host, request.port, world_size, request.client_device_uuid), + } + for connection in connections: + connection.send({"type": "fire_and_forget", "method": "collective_rpc", "kwargs": kwargs}) + + return {"message": "Request received, initializing communicator"} + + class UpdateWeightsRequest(BaseModel): + name: str + dtype: str + shape: list[int] + + @app.post("/update_named_param/") + async def update_named_param(request: UpdateWeightsRequest): + """ + Updates the model weights with the provided tensor. + + Once this endpoint is called, the client process should broadcast the updated weights to all server workers. + + Args: + request (`UpdateWeightsRequest`): + - `name` (`str`): Name of the weight tensor being updated. + - `dtype` (`str`): Data type of the weight tensor (e.g., `"torch.float32"`). + - `shape` (list of `int`): Shape of the weight + + """ + # The function update_named_param is called this way: update_named_param("name", "torch.float32", (10, 10)) + # So with collective_rpc we need to call it this way: + # llm.collective_rpc("update_named_param", args=("name", "torch.float32", (10, 10))) + kwargs = {"method": "update_named_param", "args": (request.name, request.dtype, tuple(request.shape))} + for connection in connections: + connection.send({"type": "fire_and_forget", "method": "collective_rpc", "kwargs": kwargs}) + + return {"message": "Request received, updating named parameter"} + + @app.post("/reset_prefix_cache/") + async def reset_prefix_cache(): + """ + Resets the prefix cache for the model. + """ + for connection in connections: + connection.send({"type": "call", "method": "reset_prefix_cache"}) + # Wait for and collect all results + all_outputs = [connection.recv() for connection in connections] + success = all(output for output in all_outputs) + return {"message": "Request received, resetting prefix cache status: " + str(success)} + + @app.post("/close_communicator/") + async def close_communicator(): + """ + Closes the weight update group and cleans up associated resources. + """ + kwargs = {"method": "close_communicator"} + for connection in connections: + connection.send({"type": "fire_and_forget", "method": "collective_rpc", "kwargs": kwargs}) + return {"message": "Request received, closing communicator"} + + # Start the server + uvicorn.run(app, host=script_args.host, port=script_args.port, log_level=script_args.log_level) + + +def make_parser(subparsers: argparse._SubParsersAction | None = None, prog: str | None = None): + from trl import TrlParser + + if subparsers is not None: + parser = subparsers.add_parser("vllm-serve", help="Run the vLLM serve script", dataclass_types=ScriptArguments) + else: + parser = TrlParser(ScriptArguments, prog=prog) + return parser + + +if __name__ == "__main__": + parser = make_parser() + (script_args,) = parser.parse_args_and_config() + main(script_args) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/skills/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/skills/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..29603ebfd06c6042f7892ccff7426cf38a2936b7 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/skills/__init__.py @@ -0,0 +1,21 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .skills import ( + install_skill, + list_agent_names, + list_skills, + resolve_target_path, + uninstall_skill, +) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/skills/cli.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/skills/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..712f50d1b0b61d751a547dc99224d71b934785fc --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/skills/cli.py @@ -0,0 +1,199 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +CLI commands for TRL skills installation and management. + +This module provides command-line interface for installing TRL skills to various AI agent directories. +""" + +import argparse + +from .skills import install_skill, list_agent_names, list_skills, resolve_target_path, uninstall_skill + + +def add_skills_subcommands(subparsers: argparse._SubParsersAction) -> None: + """ + Add skills subcommands to the parser. + + This creates nested subcommands under 'trl skills' for managing skill installations. + + Args: + subparsers: Subparsers from 'trl skills' command + """ + # Parent parser for common target options + target_parser = argparse.ArgumentParser(add_help=False) + target_parser.add_argument( + "--target", + default="agents", + help=f"Installation target: agent name ({', '.join(list_agent_names())}) or directory path", + ) + target_parser.add_argument( + "--scope", + choices=["project", "global"], + default="project", + help="Scope when using --target with agent name: project (./agents/skills/) or global (user-level like ~/.agents/skills/)", + ) + + # trl skills list (no target required - lists TRL's built-in skills by default) + list_parser = subparsers.add_parser( + "list", + help="List available TRL skills or installed skills in a target", + description="Show TRL skills available for installation, or if --target is specified, show installed skills", + ) + list_parser.add_argument( + "--target", + help="Optional: show installed skills in target (agent name or directory path)", + ) + list_parser.add_argument( + "--scope", + choices=["project", "global"], + default="project", + help="Scope when using --target with agent name: project (./agents/skills/) or global (user-level like ~/.agents/skills/)", + ) + list_parser.set_defaults(func=cmd_list) + + # trl skills install + install_parser = subparsers.add_parser( + "install", + parents=[target_parser], + help="Install skill", + description="Install TRL skill to target", + ) + install_parser.add_argument("skill", nargs="?", help="Skill name to install (omit to use --all)") + install_parser.add_argument("--all", action="store_true", help="Install all available TRL skills") + install_parser.add_argument("--force", action="store_true", help="Overwrite if skill already exists") + install_parser.set_defaults(func=cmd_install) + + # trl skills uninstall + uninstall_parser = subparsers.add_parser( + "uninstall", + parents=[target_parser], + help="Uninstall skill from target", + description="Remove a TRL skill from an AI agent's skills directory", + ) + uninstall_parser.add_argument("skill", help="Skill name to uninstall") + uninstall_parser.set_defaults(func=cmd_uninstall) + + +def cmd_install(args): + """Handle 'trl skills install' command.""" + # Validate arguments + if not args.skill and not args.all: + print("Error: Either provide a skill name or use --all to install all skills") + print("Usage: trl skills install --target ") + print(" or: trl skills install --all --target ") + return 1 + + if args.skill and args.all: + print("Error: Cannot specify both a skill name and --all") + return 1 + + # Determine skills to install + if args.all: + skills_to_install = list_skills() + if not skills_to_install: + print("No skills available to install") + return 1 + print(f"Installing {len(skills_to_install)} skills to {args.target}") + else: + skills_to_install = [args.skill] + + # Install each skill + success_count = 0 + for skill_name in skills_to_install: + try: + print(f"Installing '{skill_name}'...", end=" ") + install_skill( + skill_name=skill_name, + target=args.target, + scope=args.scope, + force=args.force, + ) + print("✓") + success_count += 1 + + except FileExistsError as e: + print("✗") + print(f" Error: {e}") + if not args.force: + print(" Use --force to overwrite") + except (FileNotFoundError, ValueError) as e: + print("✗") + print(f" Error: {e}") + + # Summary + print(f"\n{success_count}/{len(skills_to_install)} skills installed successfully") + + if success_count > 0: + target_path = resolve_target_path(args.target, args.scope) + print(f"\nSkills are now available at: {target_path}") + print("You may need to restart your AI agent to use the new skills.") + + return 0 if success_count == len(skills_to_install) else 1 + + +def cmd_uninstall(args): + """Handle 'trl skills uninstall' command.""" + try: + print(f"Uninstalling '{args.skill}' from {args.target}...", end=" ") + uninstall_skill(args.skill, target=args.target, scope=args.scope) + print("✓") + print(f"\nSkill '{args.skill}' has been removed") + return 0 + + except (FileNotFoundError, PermissionError, ValueError) as e: + print("✗") + print(f"Error: {e}") + return 1 + + +def cmd_list(args): + """Handle 'trl skills list' command.""" + try: + # List skills - if no target specified, list TRL's built-in skills + if args.target: + skills = list_skills(target=args.target, scope=args.scope) + location = args.target + else: + skills = list_skills() + location = "TRL (available for installation)" + + if not skills: + if args.target: + print(f"No skills installed in {args.target}") + else: + print("No TRL skills available") + return 0 + + print(f"\nSkills in {location}:\n") + + for skill in skills: + print(f" {skill}") + + print(f"\nTotal: {len(skills)} skill(s)") + + if not args.target: + print("\nUse 'trl skills install --target ' to install a skill") + + return 0 + + except ValueError as e: + print(f"Error: {e}") + return 1 + + +__all__ = [ + "add_skills_subcommands", +] diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/skills/skills.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/skills/skills.py new file mode 100644 index 0000000000000000000000000000000000000000..6a9b15f4e13f38e930c48dfa6b7e47e687e1ab5d --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/skills/skills.py @@ -0,0 +1,353 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Agent Skills. + +This module: +- provides utilities for discovering and accessing TRL skills that can be used by AI agents to learn how to use the TRL + CLI +- handles installation, uninstallation, and management of TRL skills +- defines where different AI agents and coding tools look for skills, enabling easy installation of TRL skills to the + appropriate directories + +Agent Skills are folders of instructions, scripts, and resources that agents can discover and use to perform tasks more +accurately and efficiently. Learn more at https://agentskills.io +""" + +import importlib.resources as resources +import shutil +from pathlib import Path + + +AGENT_PATHS = { + "agents": { + "global": Path("~/.agents/skills"), + "project": Path("./.agents/skills"), + }, + "claude": { + "global": Path("~/.claude/skills"), + "project": Path("./.claude/skills"), + }, +} + + +def list_agent_names() -> list[str]: + """ + List available predefined agent names. + + Returns: + `list[str]`: Sorted list of agent names (e.g., ['agents', 'claude']). + """ + return sorted(AGENT_PATHS.keys()) + + +def _get_trl_skills_dir() -> Path: + """ + Get the path to the TRL skills directory. + + This is the directory inside the TRL package containing skills that can be installed to AI agent directories. + + Returns: + `Path`: TRL skills directory. + """ + return Path(str(resources.files("trl.skills"))) + + +def resolve_target_path(target: str | Path, scope: str = "project") -> Path: + """ + Resolve target to a concrete directory path. + + Converts semantic agent names (e.g., 'claude') with scope to actual filesystem paths, or normalizes provided paths. + + Args: + target (`str | Path`): Agent name (e.g., 'agents', 'claude') or directory path. + scope (`str`, defaults to `"project"`): + Scope for agent names: 'global' (user-level like ~/.agents/skills/) or 'project' (./agents/skills/). + + Returns: + `Path`: Resolved absolute path. + + Raises: + `ValueError`: If `scope` is invalid for a predefined agent target. + + Example: + ```python + from trl.skills import resolve_target_path + + # Resolve agent name with scope + path = resolve_target_path("claude", "global") + print(path) # /home/user/.claude/skills + + # Resolve custom path + path = resolve_target_path("/custom/skills") + print(path) # /custom/skills + ``` + """ + if isinstance(target, Path): + return target.expanduser().resolve() + + # Check if it's a predefined agent + if target in AGENT_PATHS: + if scope not in AGENT_PATHS[target]: + valid_scopes = ", ".join(sorted(AGENT_PATHS[target])) + raise ValueError(f"Invalid scope '{scope}' for agent '{target}'. Expected one of: {valid_scopes}") + agent_path = AGENT_PATHS[target][scope] + return agent_path.expanduser().resolve() + + # Treat as custom path string + return Path(target).expanduser().resolve() + + +def _list_skills_in_dir(skills_dir: Path) -> list[str]: + """ + List skills in directory. + + A skill is a directory containing a SKILL.md file. + + Args: + skills_dir (`Path`): Skills directory to scan. + + Returns: + `list[str]`: Skill names (directory names containing SKILL.md). + """ + if not skills_dir.exists(): + return [] + skills = [] + for item in skills_dir.iterdir(): + if item.is_dir() and (item / "SKILL.md").exists(): + skills.append(item.name) + return sorted(skills) + + +def list_skills(target: str | Path | None = None, scope: str = "project") -> list[str]: + """ + List skills. + + A skill is a directory containing a SKILL.md file. + + Args: + target (`str | Path`, *optional*): + Agent name (e.g., 'claude'), directory path, or `None` for TRL's built-in skills. + scope (`str`, defaults to `"project"`): + For agent names: 'global' (user-level) or 'project' (current directory). + + Returns: + `list[str]`: Skill names (directory names containing SKILL.md). + + Example: + ```python + from trl.skills import list_skills + + # List TRL's built-in skills + skills = list_skills() + print(skills) # ['trl-training'] + + # List skills installed for Claude globally + installed = list_skills(target="claude", scope="global") + print(installed) # ['trl-training', 'custom-skill'] + + # List skills in custom directory + custom = list_skills(target="/path/to/skills") + print(custom) # [...] + ``` + """ + if target is None: + # List TRL's built-in skills + return _list_skills_in_dir(_get_trl_skills_dir()) + + target_dir = resolve_target_path(target, scope) + return _list_skills_in_dir(target_dir) + + +def _install_skill_to_dir( + skill_name: str, + target_dir: Path, + source_dir: Path, + force: bool = False, +) -> bool: + """ + Install a skill to target directory. + + Args: + skill_name (`str`): Name of skill to install. + target_dir (`Path`): Target installation directory. + source_dir (`Path`): Source directory containing skills. + force (`bool`, defaults to `False`): Whether to overwrite if exists. + + Returns: + `bool`: True if installed successfully. + + Raises: + - `FileNotFoundError`: If skill doesn't exist in source_dir. + - `FileExistsError`: If skill already installed and not force. + - `PermissionError`: If no permission to write to target_dir. + - `ValueError`: If source_dir entry exists but is not a directory. + - `OSError`: If copying the skill fails. + """ + source_skill = source_dir / skill_name + + # Check if source skill exists + if not source_skill.exists(): + available = ", ".join(list_skills(target=source_dir)) + source_msg = f"source directory {source_dir}" + if available: + raise FileNotFoundError(f"Skill '{skill_name}' not found in {source_msg}. Available skills: {available}") + raise FileNotFoundError(f"Skill '{skill_name}' not found in {source_msg}") + + if not source_skill.is_dir(): + raise ValueError(f"Skill '{skill_name}' is not a directory") + + target_skill = target_dir / skill_name + + # Check if already exists + if target_skill.exists() and not force: + raise FileExistsError(f"Skill '{skill_name}' already installed at {target_skill}. Use --force to overwrite.") + + # Create target directory + try: + target_dir.mkdir(parents=True, exist_ok=True) + except PermissionError as e: + raise PermissionError(f"Cannot create directory {target_dir}: {e}") from e + + # Remove existing if force + if target_skill.exists() and force: + if target_skill.is_symlink(): + target_skill.unlink() + else: + shutil.rmtree(target_skill) + + # Install + try: + shutil.copytree(source_skill, target_skill) + except OSError as e: + raise OSError(f"Failed to install skill: {e}") from e + + return True + + +def install_skill( + skill_name: str, + target: str | Path, + scope: str = "project", + source: str | Path | None = None, + force: bool = False, +) -> bool: + """ + Install a skill. + + Args: + skill_name (`str`): Name of skill to install. + target (`str | Path`): Agent name (e.g., 'agents', 'claude') or directory path. + scope (`str`, defaults to `"project"`): + Scope for agent names: 'global' (user-level) or 'project' (current directory). + source (`str | Path`, *optional*): + Source directory containing skills. If `None`, defaults to TRL skills directory. + force (`bool`, defaults to `False`): Whether to overwrite if skill already exists. + + Returns: + `bool`: True if installed successfully. + + Raises: + - `FileNotFoundError`: If skill doesn't exist in source. + - `FileExistsError`: If skill already installed and not force. + - `PermissionError`: If no permission to write to target. + - `ValueError`: + - If `scope` is invalid for a predefined agent target. + - If `source` entry exists but is not a directory. + - `OSError`: If copying the skill fails. + + Example: + ```python + from trl.skills import install_skill + + # Install to Claude's global skills directory + install_skill("trl-training", target="claude", scope="global") + + # Install to custom directory + install_skill("trl-training", target="/path/to/skills") + + # Overwrite existing installation + install_skill("trl-training", target="claude", force=True) + ``` + """ + target_dir = resolve_target_path(target, scope) + source_dir = Path(source).expanduser().resolve() if source else _get_trl_skills_dir() + return _install_skill_to_dir(skill_name, target_dir, source_dir, force) + + +def _uninstall_skill_from_dir(skill_name: str, target_dir: Path) -> bool: + """ + Uninstall a skill from target directory. + + Args: + skill_name (`str`): Name of skill to uninstall. + target_dir (`Path`): Directory skill is installed in. + + Returns: + `bool`: True if uninstalled successfully. + + Raises: + - `FileNotFoundError`: If skill not installed. + - `PermissionError`: If no permission to remove. + - `OSError`: If removing the skill fails for another filesystem reason. + """ + target_skill = target_dir / skill_name + + if not target_skill.exists(): + raise FileNotFoundError(f"Skill '{skill_name}' not installed at {target_dir}") + + # Remove symlink or directory + try: + shutil.rmtree(target_skill) + except PermissionError as e: + raise PermissionError(f"Cannot remove skill: {e}") from e + except OSError as e: + raise OSError(f"Failed to remove skill: {e}") from e + + return True + + +def uninstall_skill(skill_name: str, target: str | Path, scope: str = "project") -> bool: + """ + Uninstall a skill. + + Args: + skill_name (`str`): Name of skill to uninstall. + target (`str | Path`): Agent name (e.g., 'agents', 'claude') or directory path. + scope (`str`, defaults to `"project"`): + Scope for agent names: 'global' (user-level) or 'project' (current directory). + + Returns: + `bool`: True if uninstalled successfully. + + Raises: + - `FileNotFoundError`: If skill not installed. + - `PermissionError`: If no permission to remove. + - `OSError`: If removing the skill fails for another filesystem reason. + - `ValueError`: If `scope` is invalid for a predefined agent target. + + Example: + ```python + from trl.skills import uninstall_skill + + # Uninstall from Claude's global directory + uninstall_skill("trl-training", target="claude", scope="global") + + # Uninstall from custom directory + uninstall_skill("trl-training", target="/path/to/skills") + ``` + """ + target_dir = resolve_target_path(target, scope) + return _uninstall_skill_from_dir(skill_name, target_dir) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/skills/trl-training/SKILL.md b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/skills/trl-training/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..1941385812d82abbbe1f466aa1204e0f8d775ea9 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/skills/trl-training/SKILL.md @@ -0,0 +1,333 @@ +--- +name: trl-training +description: Train and fine-tune transformer language models using TRL (Transformers Reinforcement Learning). Supports SFT, DPO, GRPO, KTO, RLOO and Reward Model training via CLI commands. +license: Apache-2.0 +metadata: + version: "1.0.0" + author: huggingface + commands: + - trl sft + - trl dpo + - trl grpo + - trl kto + - trl rloo + - trl reward + categories: + - machine-learning + - llm-training + - reinforcement-learning + tags: + - rlhf + - supervised-fine-tuning + - dpo + - grpo + - huggingface + - transformers + documentation: https://huggingface.co/docs/trl/en/clis +--- + +# TRL Training Skill + +You are an expert at using the TRL (Transformers Reinforcement Learning) library to train and fine-tune large language models. + +## Overview + +TRL provides CLI commands for post-training foundation models using state-of-the-art techniques: + +- **SFT** (Supervised Fine-Tuning): Fine-tune models on instruction-following or conversational datasets +- **DPO** (Direct Preference Optimization): Align models using preference data +- **GRPO** (Group Relative Policy Optimization): Train models by ranking multiple sampled outputs relative to each other and optimizing based on their comparative rewards. +- **RLOO** (Reinforce Leave One Out): Online RL training with generation-based rewards +- **Reward Model Training**: Train reward models for RLHF + +TRL is built on top of Hugging Face Transformers and Accelerate, providing seamless integration with the Hugging Face ecosystem. + +## Core Commands + +### trl sft - Supervised Fine-Tuning + +Fine-tune language models on instruction-following or conversational datasets. + +**Full training:** + +```bash +trl sft \ + --model_name_or_path Qwen/Qwen2-0.5B \ + --dataset_name trl-lib/Capybara \ + --learning_rate 2.0e-5 \ + --num_train_epochs 1 \ + --packing \ + --per_device_train_batch_size 2 \ + --gradient_accumulation_steps 8 \ + --eos_token '<|im_end|>' \ + --eval_strategy steps \ + --eval_steps 100 \ + --output_dir Qwen2-0.5B-SFT \ + --push_to_hub +``` + +**Train with LoRA adapters:** + +```bash +trl sft \ + --model_name_or_path Qwen/Qwen2-0.5B \ + --dataset_name trl-lib/Capybara \ + --learning_rate 2.0e-4 \ + --num_train_epochs 1 \ + --packing \ + --per_device_train_batch_size 2 \ + --gradient_accumulation_steps 8 \ + --eos_token '<|im_end|>' \ + --eval_strategy steps \ + --eval_steps 100 \ + --use_peft \ + --lora_r 32 \ + --lora_alpha 16 \ + --output_dir Qwen2-0.5B-SFT \ + --push_to_hub +``` + +### trl dpo - Direct Preference Optimization + +Align models using preference data (chosen/rejected pairs). + +**Full training:** + +```bash +trl dpo \ + --dataset_name trl-lib/ultrafeedback_binarized \ + --model_name_or_path Qwen/Qwen2-0.5B-Instruct \ + --learning_rate 5.0e-7 \ + --num_train_epochs 1 \ + --per_device_train_batch_size 2 \ + --max_steps 1000 \ + --gradient_accumulation_steps 8 \ + --eval_strategy steps \ + --eval_steps 50 \ + --output_dir Qwen2-0.5B-DPO \ + --no_remove_unused_columns +``` + +**Train with LoRA adapters:** + +```bash +trl dpo \ + --dataset_name trl-lib/ultrafeedback_binarized \ + --model_name_or_path Qwen/Qwen2-0.5B-Instruct \ + --learning_rate 5.0e-6 \ + --num_train_epochs 1 \ + --per_device_train_batch_size 2 \ + --max_steps 1000 \ + --gradient_accumulation_steps 8 \ + --eval_strategy steps \ + --eval_steps 50 \ + --output_dir Qwen2-0.5B-DPO \ + --no_remove_unused_columns \ + --use_peft \ + --lora_r 32 \ + --lora_alpha 16 +``` + +### trl grpo - Group Relative Policy Optimization + +Train models using reward functions or LLM-as-a-judge for evaluating generations and providing rewards. + +**Basic usage:** + +```bash +trl grpo \ + --model_name_or_path Qwen/Qwen2.5-0.5B \ + --dataset_name trl-lib/gsm8k \ + --reward_funcs accuracy_reward \ + --output_dir Qwen2-0.5B-GRPO \ + --push_to_hub +``` + +### trl rloo - Reinforce Leave One Out + +Online RL training where the model generates text and receives rewards based on custom criteria. + +**Basic usage:** + +```bash +trl rloo \ + --model_name_or_path Qwen/Qwen2.5-0.5B \ + --dataset_name trl-lib/tldr \ + --reward_model_name_or_path sentiment-analysis:nlptown/bert-base-multilingual-uncased-sentiment \ + --output_dir Qwen2-0.5B-RLOO \ + --push_to_hub +``` + +### trl reward - Reward Model Training + +Train a reward model to score text quality for RLHF. + +**Full training:** + +```bash +trl reward \ + --model_name_or_path Qwen/Qwen2-0.5B-Instruct \ + --dataset_name trl-lib/ultrafeedback_binarized \ + --output_dir Qwen2-0.5B-Reward \ + --per_device_train_batch_size 8 \ + --num_train_epochs 1 \ + --learning_rate 1.0e-5 \ + --eval_strategy steps \ + --eval_steps 50 \ + --max_length 2048 +``` + +**Train with LoRA adapters:** + +```bash +trl reward \ + --model_name_or_path Qwen/Qwen2-0.5B-Instruct \ + --dataset_name trl-lib/ultrafeedback_binarized \ + --output_dir Qwen2-0.5B-Reward-LoRA \ + --per_device_train_batch_size 8 \ + --num_train_epochs 1 \ + --learning_rate 1.0e-4 \ + --eval_strategy steps \ + --eval_steps 50 \ + --max_length 2048 \ + --use_peft \ + --lora_task_type SEQ_CLS \ + --lora_r 32 \ + --lora_alpha 16 +``` + +## Configuration Files + +TRL supports YAML configuration files for reproducible training. All CLI arguments can be specified in a config file. + +**Example config (sft_config.yaml):** + +```yaml +model_name_or_path: Qwen/Qwen2.5-0.5B +dataset_name: trl-lib/Capybara +learning_rate: 2.0e-5 +num_train_epochs: 1 +per_device_train_batch_size: 8 +gradient_accumulation_steps: 2 +output_dir: ./sft_output +use_peft: true +lora_r: 16 +lora_alpha: 16 +report_to: trackio +``` + +**Launch with config:** + +```bash +trl sft --config sft_config.yaml +``` + +**Override config values:** + +```bash +trl sft --config sft_config.yaml --learning_rate 1.0e-5 +``` + +## Distributed Training + +TRL integrates with Accelerate for multi-GPU and multi-node training. + +**Multi-GPU training:** + +```bash +trl sft \ + --config sft_config.yaml \ + --num_processes 4 +``` + +**Use predefined Accelerate configs:** + +TRL provides predefined configs: `single_gpu`, `multi_gpu`, `fsdp1`, `fsdp2`, `zero1`, `zero2`, `zero3` + +```bash +trl sft \ + --config sft_config.yaml \ + --accelerate_config zero2 +``` + +**Custom Accelerate config:** + +```bash +# Generate custom config +accelerate config + +# Use custom config +trl sft --config sft_config.yaml --config_file ~/.cache/huggingface/accelerate/default_config.yaml +``` + +**Fully Sharded Data Parallel (FSDP):** + +```bash +trl sft --config sft_config.yaml --accelerate_config fsdp2 +``` + +**DeepSpeed ZeRO:** + +```bash +trl sft --config sft_config.yaml --accelerate_config zero3 +``` + +## Troubleshooting + +### CUDA Out of Memory + +- Reduce `--per_device_train_batch_size` and increase `--gradient_accumulation_steps` +- Enable `--use_peft` for LoRA training +- Use `--gradient_checkpointing` to save memory +- Try smaller model or longer sequence truncation + +### Dataset Loading Issues + +- Verify dataset exists: check Hugging Face Hub or local path +- Check dataset format matches expected columns +- Use `--dataset_config` for multi-config datasets +- Inspect dataset: `from datasets import load_dataset; ds = load_dataset(name)` + +### Model Loading Issues + +- Verify model exists on Hugging Face Hub +- Check if gated model requires authentication: `hf auth login` +- For local models, provide absolute path +- Ensure sufficient disk space and memory + +### Slow Training + +- Enable dataset `--packing` for short sequences +- Use larger `--per_device_train_batch_size` if memory allows +- Enable `--tf32` for faster computation on Ampere GPUs +- Use `--bf16` on supported hardware +- Consider multi-GPU training with `--num_processes` + +### Generation Issues (GRPO/RLOO) + +- Check prompt format in dataset +- Adjust `--temperature` and `--top_p` for generation +- Verify the reward function (for GRPO/RLOO) + +## Additional Resources + +- **Documentation**: https://huggingface.co/docs/trl +- **GitHub**: https://github.com/huggingface/trl +- **Examples**: https://github.com/huggingface/trl/tree/main/examples + +## Best Practices + +1. **Start with SFT**: Always fine-tune base models with SFT before preference alignment +2. **Use LoRA for efficiency**: Enable `--use_peft` for faster training and lower memory +3. **Monitor training**: Use `--report_to trackio` (or `--report_to wandb` or `--report_to tensorboard`) for tracking +4. **Save checkpoints**: TRL automatically saves checkpoints in `--output_dir` +5. **Test on small datasets first**: Verify pipeline works before full training +6. **Use configuration files**: Create YAML configs for reproducibility +7. **Leverage Accelerate**: Use multi-GPU training for faster iteration + +When helping users with TRL: +- Always check which training method is appropriate for their use case +- Verify dataset format matches the expected schema +- Recommend starting with smaller models for testing +- Suggest LoRA for resource-constrained environments +- Point to specific documentation sections for advanced features diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/templates/completions_dataset_card.md b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/templates/completions_dataset_card.md new file mode 100644 index 0000000000000000000000000000000000000000..6246844db5738c7cc6807c9b221544f6939692c6 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/templates/completions_dataset_card.md @@ -0,0 +1,40 @@ +--- +{{ card_data }} +--- + +# TRL Completion logs + +This dataset contains the completions generated during training using `trl`. + +{% if hub_model_id %} +Find the trained model at https://huggingface.co/{{ hub_model_id }}. + +{% endif %} +The completions are stored in parquet files, and each file contains the completions for a single step of training (depending on the `logging_steps` argument). + +Each file contains the following columns: + +- `step`: the step of training +- `prompt`: the prompt used to generate the completion +- `completion`: the completion generated by the model +- ``: the reward(s) assigned to the completion by the reward function(s) used during training +- `advantage`: the computed advantage for the completion + +Having this data stored as a simple parquet file makes it easy to load and analyze using the Datasets Viewer, Polars, Pandas, etc. + +You can load the dataset using the `datasets` library: + +```python +import datasets + +dataset = datasets.load_dataset("{{ repo_id }}") +``` + +You can also load the dataset using Polars: + +```python +import polars as pl + +# Login using e.g. `hf auth login` to access this dataset if it's private +df = pl.read_parquet(f"hf://datasets/{{ repo_id }}/*.parquet") +``` diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/templates/lm_model_card.md b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/templates/lm_model_card.md new file mode 100644 index 0000000000000000000000000000000000000000..ae7e33bfb5d5e5864257fd0abf04bd78d1629c5f --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/templates/lm_model_card.md @@ -0,0 +1,55 @@ +--- +{{ card_data }} +--- + +# Model Card for {{ model_name }} + +This model is a fine-tuned version of [{{ base_model }}](https://huggingface.co/{{ base_model }}){% if dataset_name %} on the [{{ dataset_name }}](https://huggingface.co/datasets/{{ dataset_name }}) dataset{% endif %}. +It has been trained using [TRL](https://github.com/huggingface/trl). + +## Quick start + +```python +from transformers import pipeline + +question = "If you had a time machine, but could only go to the past or the future once and never return, which would you choose and why?" +generator = pipeline("text-generation", model="{{ hub_model_id }}", device="cuda") +output = generator([{"role": "user", "content": question}], max_new_tokens=128, return_full_text=False)[0] +print(output["generated_text"]) +``` + +## Training procedure + +{% if wandb_url %}[Visualize in Weights & Biases]({{ wandb_url }}){% endif %} +{% if trackio_url %}[Visualize in Trackio]({{ trackio_url }}){% endif %} +{% if comet_url %}[Visualize in Comet]({{ comet_url }}){% endif %} + +This model was trained with {{ trainer_name }}{% if paper_id %}, a method introduced in [{{ paper_title }}](https://huggingface.co/papers/{{ paper_id }}){% endif %}. + +### Framework versions + +- TRL: {{ trl_version }} +- Transformers: {{ transformers_version }} +- Pytorch: {{ pytorch_version }} +- Datasets: {{ datasets_version }} +- Tokenizers: {{ tokenizers_version }} + +## Citations + +{% if trainer_citation %}Cite {{ trainer_name }} as: + +```bibtex +{{ trainer_citation }} +```{% endif %} + +Cite TRL as: + +```bibtex +{% raw %}@software{vonwerra2020trl, + title = {{TRL: Transformers Reinforcement Learning}}, + author = {von Werra, Leandro and Belkada, Younes and Tunstall, Lewis and Beeching, Edward and Thrush, Tristan and Lambert, Nathan and Huang, Shengyi and Rasul, Kashif and Gallouédec, Quentin}, + license = {Apache-2.0}, + url = {https://github.com/huggingface/trl}, + year = {2020} +}{% endraw %} +``` diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/templates/rm_model_card.md b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/templates/rm_model_card.md new file mode 100644 index 0000000000000000000000000000000000000000..0e47e9724a6c38f262b63782507d5871bb4272c2 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/templates/rm_model_card.md @@ -0,0 +1,55 @@ +--- +{{ card_data }} +--- + +# Model Card for {{ model_name }} + +This model is a fine-tuned version of [{{ base_model }}](https://huggingface.co/{{ base_model }}){% if dataset_name %} on the [{{ dataset_name }}](https://huggingface.co/datasets/{{ dataset_name }}) dataset{% endif %}. +It has been trained using [TRL](https://github.com/huggingface/trl). + +## Quick start + +```python +from transformers import pipeline + +text = "The capital of France is Paris." +rewarder = pipeline(model="{{ hub_model_id }}", device="cuda") +output = rewarder(text)[0] +print(output["score"]) +``` + +## Training procedure + +{% if wandb_url %}[Visualize in Weights & Biases]({{ wandb_url }}){% endif %} +{% if trackio_url %}[Visualize in Trackio]({{ trackio_url }}){% endif %} +{% if comet_url %}[Visualize in Comet]({{ comet_url }}){% endif %} + +This model was trained with {{ trainer_name }}{% if paper_id %}, a method introduced in [{{ paper_title }}](https://huggingface.co/papers/{{ paper_id }}){% endif %}. + +### Framework versions + +- TRL: {{ trl_version }} +- Transformers: {{ transformers_version }} +- Pytorch: {{ pytorch_version }} +- Datasets: {{ datasets_version }} +- Tokenizers: {{ tokenizers_version }} + +## Citations + +{% if trainer_citation %}Cite {{ trainer_name }} as: + +```bibtex +{{ trainer_citation }} +```{% endif %} + +Cite TRL as: + +```bibtex +{% raw %}@software{vonwerra2020trl, + title = {{TRL: Transformers Reinforcement Learning}}, + author = {von Werra, Leandro and Belkada, Younes and Tunstall, Lewis and Beeching, Edward and Thrush, Tristan and Lambert, Nathan and Huang, Shengyi and Rasul, Kashif and Gallouédec, Quentin}, + license = {Apache-2.0}, + url = {https://github.com/huggingface/trl}, + year = {2020} +}{% endraw %} +``` diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/__init__.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1d79d365056136a5940af7d23fb964fb8db0e62c --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/__init__.py @@ -0,0 +1,83 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import TYPE_CHECKING + +from .._lazy_module import _LazyModule + + +_import_structure = { + "callbacks": [ + "BEMACallback", + "LogCompletionsCallback", + "RichProgressCallback", + "SyncRefModelCallback", + "WeaveCallback", + ], + "dpo_config": ["DPOConfig"], + "dpo_trainer": ["DPOTrainer"], + "grpo_config": ["GRPOConfig"], + "grpo_trainer": ["GRPOTrainer"], + "kto_config": ["KTOConfig"], + "kto_trainer": ["KTOTrainer"], + "model_config": ["ModelConfig"], + "reward_config": ["RewardConfig"], + "reward_trainer": ["RewardTrainer"], + "rloo_config": ["RLOOConfig"], + "rloo_trainer": ["RLOOTrainer"], + "sft_config": ["SFTConfig"], + "sft_trainer": ["SFTTrainer"], + "utils": [ + "disable_dropout_in_model", + "ensure_master_addr_port", + "get_kbit_device_map", + "get_peft_config", + "get_quantization_config", + "patch_chunked_lm_head", + ], +} + +if TYPE_CHECKING: + from .callbacks import ( + BEMACallback, + LogCompletionsCallback, + RichProgressCallback, + SyncRefModelCallback, + WeaveCallback, + ) + from .dpo_config import DPOConfig + from .dpo_trainer import DPOTrainer + from .grpo_config import GRPOConfig + from .grpo_trainer import GRPOTrainer + from .kto_config import KTOConfig + from .kto_trainer import KTOTrainer + from .model_config import ModelConfig + from .reward_config import RewardConfig + from .reward_trainer import RewardTrainer + from .rloo_config import RLOOConfig + from .rloo_trainer import RLOOTrainer + from .sft_config import SFTConfig + from .sft_trainer import SFTTrainer + from .utils import ( + disable_dropout_in_model, + ensure_master_addr_port, + get_kbit_device_map, + get_peft_config, + get_quantization_config, + patch_chunked_lm_head, + ) +else: + import sys + + sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/base_config.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/base_config.py new file mode 100644 index 0000000000000000000000000000000000000000..fd20188c74b342974ace79b863b0566c23673ec3 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/base_config.py @@ -0,0 +1,107 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field + +from transformers import TrainingArguments + + +@dataclass +class _BaseConfig(TrainingArguments): + """ + Base configuration class for all TRL trainer configurations. + + Subclasses [`~transformers.TrainingArguments`] and overrides fields that are common across TRL trainers or that + contain unescaped "%" characters which would cause argparse to raise a `TypeError` when rendering `--help` output. + + Parameters: + logging_steps (`int` or `float`, *optional*, defaults to `10`): + Number of update steps between two logs if `logging_strategy="steps"`. Should be an integer or a float in + range `[0,1)`. If smaller than 1, will be interpreted as ratio of total training steps. + gradient_checkpointing (`bool`, *optional*, defaults to `True`): + Whether to enable gradient checkpointing to trade compute for memory. Reduces memory usage by clearing + activations during forward pass and recomputing them during backward pass. Enables training larger models + or batch sizes at the cost of ~20% slower training. + bf16 (`bool`, *optional*): + Whether to use bfloat16 (BF16) mixed precision instead of 32-bit. Generally preferred over FP16 due to + better numerical stability and no loss scaling required. Requires Ampere or higher NVIDIA architecture or + Intel XPU or using CPU (use_cpu) or Ascend NPU. If not set, it defaults to `True` if `fp16` is not set. + lr_scheduler_kwargs (`dict` or `str`, *optional*): + Additional parameters for the lr_scheduler, such as `{'num_cycles': 1}` for cosine with hard restarts. See + the documentation of each scheduler for possible values. + use_liger_kernel (`bool`, *optional*, defaults to `False`): + Enable [Liger Kernel](https://github.com/linkedin/Liger-Kernel) optimizations. Increases multi-GPU + throughput by ~20% and reduces memory usage by ~60%. Works with Flash Attention, FSDP, and DeepSpeed. + Currently, supports Llama, Mistral, Mixtral, and Gemma models. + torch_empty_cache_steps (`int`, *optional*): + Number of steps to wait before calling `torch..empty_cache()`. If left unset or set to None, cache + will not be emptied. This can help avoid CUDA out-of-memory errors by lowering peak VRAM usage at a cost of + about [10% slower performance](https://github.com/huggingface/transformers/issues/31372). + """ + + # Override fields from TrainingArguments to set defaults preferred by all TRL trainers. + logging_steps: float = field( + default=10, + metadata={ + "help": "Log every X updates steps. Should be an integer or a float in range `[0,1)`. If smaller than 1, " + "will be interpreted as ratio of total training steps." + }, + ) + gradient_checkpointing: bool = field( + default=True, + metadata={ + "help": "Enable gradient checkpointing to trade compute for memory. Reduces memory at the cost of ~20%% slower training." + }, + ) + bf16: bool | None = field( + default=None, + metadata={ + "help": "Whether to use bf16 (mixed) precision instead of 32-bit. Requires Ampere or higher NVIDIA " + "architecture or Intel XPU or using CPU (use_cpu) or Ascend NPU. If not set, it defaults to `True` if " + "`fp16` is not set." + }, + ) + # Transformers 4.57.0 introduced a bug that caused the dtype of `lr_scheduler_kwargs` to be unparsable. This issue + # was fixed in https://github.com/huggingface/transformers/pull/41322 and released in 4.57.5. We add a temporary + # workaround here, which can be removed once we drop support for versions older than 4.57.5. + lr_scheduler_kwargs: dict | str | None = field( + default=None, + metadata={ + "help": "Additional parameters for the lr_scheduler, such as {'num_cycles': 1} for cosine with hard " + "restarts. See the documentation of each scheduler for possible values." + }, + ) + + # Override fields from TrainingArguments whose help strings contain unescaped "%" characters. + # argparse interprets "%" as a format specifier, raising TypeError when rendering --help output. + # Fixed upstream in transformers v5.3.0, but overridden here to support older versions. + # - Introduced in v5.2.0; fixed in v5.3.0 + use_liger_kernel: bool = field( + default=False, + metadata={ + "help": "Enable Liger Kernel optimizations. Increases throughput by ~20%% and reduces memory by ~60%%." + }, + ) + # - Introduced in v4.54.1; fixed in v5.3.0 + torch_empty_cache_steps: int | None = field( + default=None, + metadata={ + "help": "Number of steps to wait before calling `torch..empty_cache()`. Helps avoid CUDA OOM at a cost of ~10%% slower performance. If None, cache will not be emptied." + }, + ) + + def __post_init__(self): + self.bf16 = not (self.fp16) if self.bf16 is None else self.bf16 + + super().__post_init__() diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/base_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/base_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..705cdf11f236ad3bf50842c08eda4afdee69c5b4 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/base_trainer.py @@ -0,0 +1,191 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os + +import torch +from accelerate.utils import is_peft_model +from huggingface_hub.utils import send_telemetry +from transformers import CONFIG_MAPPING, Trainer, is_wandb_available + +from .. import __version__ +from .utils import generate_model_card, get_comet_experiment_url, get_config_model_id, get_trackio_space_url + + +if is_wandb_available(): + import wandb + + +# Trainer class names that may appear in telemetry topics. Any class outside this set — internal helpers, +# in-flight subclasses not yet shipped, user-defined subclasses — is reported as "other" so unreleased or +# private names never leak. Adding a new trainer requires an explicit entry here. +_TELEMETRY_TRAINERS = { + # Stable + "DPOTrainer", + "GRPOTrainer", + "KTOTrainer", + "RewardTrainer", + "RLOOTrainer", + "SFTTrainer", + # Experimental + "A2POTrainer", + "AsyncGRPOTrainer", + "BCOTrainer", + "CPOTrainer", + "DistillationTrainer", + "DPPOTrainer", + "GFPOTrainer", + "GKDTrainer", + "GOLDTrainer", + "GRPOWithReplayBufferTrainer", + "MiniLLMTrainer", + "NashMDTrainer", + "OnlineDPOTrainer", + "ORPOTrainer", + "PAPOTrainer", + "PPOTrainer", + "PRMTrainer", + "SDFTTrainer", + "SDPOTrainer", + "SSDTrainer", + "TPOTrainer", + "XPOTrainer", +} + + +class _BaseTrainer(Trainer): + _tag_names = [] + _name = "Base" + _paper = {} + _template_file = None + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._send_telemetry() + + def _send_telemetry(self): + # Only send from rank 0 to avoid multiplying pings by world size, and skip CI runs so automated tests don't + # bias the data. Honors `HF_HUB_DISABLE_TELEMETRY=1` and `HF_HUB_OFFLINE=1` (handled by `send_telemetry`). + if not self.accelerator.is_main_process or os.environ.get("CI"): + return + if self.is_deepspeed_enabled: + distributed = "deepspeed" + elif self.is_fsdp_enabled: + distributed = "fsdp" + elif self.accelerator.num_processes > 1: + distributed = "ddp" + else: + distributed = "none" + device = self.accelerator.device.type + if device == "cuda": + gpu = torch.cuda.get_device_name(0) + elif device == "xpu": + gpu = torch.xpu.get_device_name(0) + elif device == "npu": + gpu = torch.npu.get_device_name(0) + elif device == "mlu": + gpu = torch.mlu.get_device_name(0) + else: + gpu = "other" + # Bucketed to avoid fingerprinting individual deployments by their exact cluster size. + n = self.accelerator.num_processes + world_size = "1" if n == 1 else "2-8" if n <= 8 else "9-64" if n <= 64 else "65+" + # Trainer class and model arch are reported only if they come from a known upstream allowlist (TRL trainers, + # transformers `CONFIG_MAPPING`); anything else is reported as "other" so we never leak the names of internal, + # custom trainer subclasses or private model architectures. + cls = type(self) + trainer = ( + cls.__name__ if cls.__name__ in _TELEMETRY_TRAINERS and cls.__module__.startswith("trl.") else "other" + ) + model_type = self.model.config.model_type + model_arch = model_type if model_type in CONFIG_MAPPING else "other" + send_telemetry( + topic=f"trl/{trainer}", + library_name="trl", + library_version=__version__, + user_agent={ + "model_arch": model_arch, + "peft": str(is_peft_model(self.model)).lower(), + "distributed": distributed, + "world_size": world_size, + "device": device, + "gpu": gpu, + }, + ) + + def create_model_card( + self, + model_name: str | None = None, + dataset_name: str | None = None, + tags: str | list[str] | None = None, + ): + """ + Creates a draft of a model card using the information available to the `Trainer`. + + Args: + model_name (`str`, *optional*): + Name of the model. + dataset_name (`str`, *optional*): + Name of the dataset used for training. + tags (`str`, `list[str]`, *optional*): + Tags to be associated with the model card. + """ + if not self.is_world_process_zero(): + return + + model_name_or_path = get_config_model_id(self.model.config) + if model_name_or_path and not os.path.isdir(model_name_or_path): + base_model = model_name_or_path + else: + base_model = None + + # Normalize tags + if tags is None: + tags = set() + elif isinstance(tags, str): + tags = {tags} + else: + tags = set(tags) + if hasattr(self.model.config, "unsloth_version"): + tags.add("unsloth") + if "JOB_ID" in os.environ: + tags.add("hf_jobs") + tags.update(self._tag_names) + + trackio_url = get_trackio_space_url() + # Pop existing Trackio tag and re-add the one with the proper url parameters + if trackio_url is not None: + for tag in list(tags): + if tag.startswith("trackio:"): + tags.remove(tag) + tags.add(f"trackio:{trackio_url}") + + tags = list(tags) + + model_card = generate_model_card( + base_model=base_model, + model_name=model_name, + hub_model_id=self.hub_model_id, + dataset_name=dataset_name, + tags=tags, + wandb_url=wandb.run.url if is_wandb_available() and wandb.run is not None else None, + trackio_url=trackio_url, + comet_url=get_comet_experiment_url(), + trainer_name=self._name, + trainer_citation=self._paper.get("citation"), + template_file=self._template_file, + paper_title=self._paper.get("title"), + paper_id=self._paper.get("id"), + ) + model_card.save(os.path.join(self.args.output_dir, "README.md")) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/callbacks.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/callbacks.py new file mode 100644 index 0000000000000000000000000000000000000000..a530e38b0c4f39f63ca16c7c8a52fa6078316b76 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/callbacks.py @@ -0,0 +1,758 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging + +import pandas as pd +import torch +from accelerate import Accelerator +from accelerate.state import AcceleratorState +from accelerate.utils import gather_object, is_wandb_available +from transformers import ( + GenerationConfig, + PreTrainedModel, + PreTrainedTokenizerBase, + Trainer, + TrainerCallback, + TrainerControl, + TrainerState, + TrainingArguments, +) +from transformers.trainer_utils import has_length +from transformers.utils import is_rich_available + +from ..data_utils import maybe_apply_chat_template +from ..import_utils import is_weave_available +from ..models.utils import unwrap_model_for_generation +from .utils import log_table_to_comet_experiment + + +if is_rich_available(): + from rich.columns import Columns + from rich.console import Console, Group + from rich.live import Live + from rich.panel import Panel + from rich.progress import Progress + from rich.table import Table + +if is_wandb_available(): + import wandb + +if is_weave_available(): + import weave + from weave import EvaluationLogger + from weave.trace.context import weave_client_context + + +# Logger for module-level logging +logger = logging.getLogger(__name__) + + +def _generate_completions( + prompts: list[str], + model: PreTrainedModel, + tokenizer: PreTrainedTokenizerBase, + accelerator: Accelerator, + generation_config: GenerationConfig | None, + batch_size: int = 1, +) -> list[str]: + """ + Generates completions for a list of pre-formatted prompts from the given model. + + Args: + prompts (list[str]): A list of input prompts for which completions are to be generated. + model (PreTrainedModel): The pre-trained model to be used for generation. + tokenizer (PreTrainedTokenizerBase): The tokenizer to be used for encoding and decoding. + accelerator (Accelerator): The accelerator to be used for model execution. + generation_config (GenerationConfig): Configuration for text generation. + batch_size (int, optional): The number of prompts to process in each batch. Default is 1. + + Returns: + list[str]: A list of generated text completions corresponding to the input prompts. + """ + completions = [] + # TODO: Override model.generation_config with generation_kwargs + with unwrap_model_for_generation(model, accelerator) as unwrapped_model: + for idx in range(0, len(prompts), batch_size): + batch = prompts[idx : idx + batch_size] + tokenized_batch = tokenizer(batch, return_tensors="pt", padding=True, truncation=True).to(model.device) + generations = unwrapped_model.generate( + **tokenized_batch, + generation_config=generation_config, + ) + for prompt, generation in zip(tokenized_batch.input_ids, generations, strict=True): + # Remove prompt from generation + generation = generation[len(prompt) :] + completion = tokenizer.decode(generation, skip_special_tokens=True) + completions.append(completion) + return completions + + +class SyncRefModelCallback(TrainerCallback): + """ + Callback to synchronize the model with a reference model. + """ + + def __init__( + self, + ref_model: PreTrainedModel | torch.nn.Module, + accelerator: Accelerator | None, + ): + self.accelerator = accelerator + self.ref_model = ref_model + + @staticmethod + def _sync_target_model(model, target_model, alpha): + for target_param, copy_param in zip(target_model.parameters(), model.parameters(), strict=True): + target_param.data.mul_(1.0 - alpha).add_(copy_param.data, alpha=alpha) + + @staticmethod + def sync_target_model(model, target_model, alpha): + deepspeed_plugin = AcceleratorState().deepspeed_plugin + if deepspeed_plugin is not None and deepspeed_plugin.zero_stage == 3: + import deepspeed + + with deepspeed.zero.GatheredParameters( + list(model.parameters()) + list(target_model.parameters()), modifier_rank=0 + ): + if deepspeed.comm.get_rank() == 0: + SyncRefModelCallback._sync_target_model(model, target_model, alpha) + else: + SyncRefModelCallback._sync_target_model(model, target_model, alpha) + + def on_step_end(self, args, state, control, **kwargs): + model: PreTrainedModel = kwargs["model"] + + if self.ref_model is not None and state.global_step % args.ref_model_sync_steps == 0: + if self.accelerator: + model = self.accelerator.unwrap_model(model) + self.sync_target_model(model, self.ref_model, args.ref_model_mixup_alpha) + + +class RichProgressCallback(TrainerCallback): + """ + A [`TrainerCallback`] that displays the progress of training or evaluation using Rich. + """ + + def __init__(self): + if not is_rich_available(): + raise ImportError("RichProgressCallback requires the `rich` extra. To install, run `pip install rich`.") + + self.training_bar = None + self.evaluation_bar = None + self.training_task = None + self.evaluation_task = None + self.rich_group = None + self.rich_console = None + self.training_status = None + self.current_step = None + + def on_train_begin(self, args, state, control, **kwargs): + if not state.is_world_process_zero: + return + + self.training_bar = Progress() + self.evaluation_bar = Progress() + self.rich_console = Console() + self.training_status = self.rich_console.status("Nothing to log yet ...") + self.rich_group = Live(Panel(Group(self.training_bar, self.evaluation_bar, self.training_status))) + self.rich_group.start() + self.training_task = self.training_bar.add_task("[blue]Training ", total=state.max_steps) + self.current_step = 0 + + def on_step_end(self, args, state, control, **kwargs): + if not state.is_world_process_zero: + return + + self.training_bar.update(self.training_task, advance=state.global_step - self.current_step, update=True) + self.current_step = state.global_step + + def on_prediction_step(self, args, state, control, eval_dataloader=None, **kwargs): + if not state.is_world_process_zero: + return + + if has_length(eval_dataloader): + if self.evaluation_task is None: + self.evaluation_task = self.evaluation_bar.add_task("[blue]Evaluation", total=len(eval_dataloader)) + self.evaluation_bar.update(self.evaluation_task, advance=1, update=True) + + def on_evaluate(self, args, state, control, **kwargs): + if not state.is_world_process_zero: + return + + if self.evaluation_task is not None: + self.evaluation_bar.remove_task(self.evaluation_task) + self.evaluation_task = None + + def on_predict(self, args, state, control, **kwargs): + if not state.is_world_process_zero: + return + + if self.evaluation_task is not None: + self.evaluation_bar.remove_task(self.evaluation_task) + self.evaluation_task = None + + def on_log(self, args, state, control, logs=None, **kwargs): + if not (state.is_world_process_zero and self.training_bar): + return + + # Group keys by top-level prefix + grouped_logs = {} + for key, value in logs.items(): + parts = key.split("/") + group = parts[0] if len(parts) > 1 else None + subkey = "/".join(parts[1:]) if len(parts) > 1 else key + grouped_logs.setdefault(group, {})[subkey] = value + + # Create a table per group + tables = [] + for group_name, metrics in grouped_logs.items(): + table = Table( + title=f"[bold blue]{group_name}[/]" if group_name else None, header_style="bold magenta", box=None + ) + table.add_column("Metric", justify="left", no_wrap=True) + table.add_column("Value", justify="right") + + for metric, val in metrics.items(): + formatted = f"{val:.3f}" if isinstance(val, (float, int)) else str(val) + table.add_row(metric, formatted) + + tables.append(Panel(table, border_style="cyan", padding=(0, 1))) + + # Arrange tables in columns using Columns + column_layout = Columns(tables, equal=False, expand=True) + self.training_status.update( + Panel(column_layout, title=f"[bold green]Step {state.global_step}[/bold green]", border_style="green") + ) + + def on_train_end(self, args, state, control, **kwargs): + if not state.is_world_process_zero: + return + + self.rich_group.stop() + self.training_bar = None + self.evaluation_bar = None + self.training_task = None + self.evaluation_task = None + self.rich_group = None + self.rich_console = None + self.training_status = None + self.current_step = None + + +class LogCompletionsCallback(TrainerCallback): + r""" + A [`~transformers.TrainerCallback`] that logs completions to Weights & Biases and/or Comet. + + Usage: + ```python + trainer = DPOTrainer(...) + completions_callback = LogCompletionsCallback(trainer=trainer) + trainer.add_callback(completions_callback) + ``` + + Args: + trainer (`Trainer`): + Trainer to which the callback will be attached. The trainer's evaluation dataset must include a `"prompt"` + column containing the prompts for generating completions. + generation_config ([`~transformers.GenerationConfig`], *optional*): + The generation config to use for generating completions. + num_prompts (`int`, *optional*): + The number of prompts to generate completions for. If not provided, defaults to the number of examples in + the evaluation dataset. + freq (`int`, *optional*): + The frequency at which to log completions. If not provided, defaults to the trainer's `eval_steps`. + """ + + def __init__( + self, + trainer: Trainer, + generation_config: GenerationConfig | None = None, + num_prompts: int | None = None, + freq: int | None = None, + ): + self.trainer = trainer + self.generation_config = generation_config + self.freq = freq + self.table = [] + self._last_logged_step = -1 + + if self.trainer.eval_dataset is None: + raise ValueError("Trainer must have an evaluation dataset to use the LogCompletionsCallback.") + else: + self.eval_dataset = self.trainer.eval_dataset + + if num_prompts is not None: + self.eval_dataset = self.eval_dataset.select(range(num_prompts)) + + def on_step_end(self, args, state, control, **kwargs): + # Only log once per step (this method may be called multiple times) + if state.global_step == self._last_logged_step: + return + + # Only log every `freq` steps (if no `freq` is provided, log every `eval_steps` steps) + freq = self.freq or state.eval_steps + if state.global_step % freq != 0: + return + + tokenizer = kwargs["processing_class"] + tokenizer.padding_side = "left" + accelerator = self.trainer.accelerator + model = self.trainer.model_wrapped + with accelerator.split_between_processes(self.eval_dataset["prompt"]) as prompts: + prompts = [maybe_apply_chat_template({"prompt": prompt}, tokenizer)["prompt"] for prompt in prompts] + completions = _generate_completions( + prompts, + model=model, + tokenizer=tokenizer, + accelerator=accelerator, + generation_config=self.generation_config, + batch_size=args.per_device_eval_batch_size, + ) + completions = gather_object(completions) + prompts = gather_object(prompts) + + # Build the data to log + if self.trainer.accelerator.is_main_process: + global_step = [str(state.global_step)] * len(prompts) + data = list(zip(global_step, prompts, completions, strict=True)) + self.table.extend(data) + table = pd.DataFrame(columns=["step", "prompt", "completion"], data=self.table) + + if "wandb" in args.report_to: + wandb.log({"completions": table}) + + if "comet_ml" in args.report_to: + log_table_to_comet_experiment( + name="completions.csv", + table=table, + ) + + # Save the last logged step, so we don't log the same completions multiple times + self._last_logged_step = state.global_step + + +class WeaveCallback(TrainerCallback): + r""" + A [`~transformers.TrainerCallback`] that logs traces and evaluations to W&B Weave. The callback uses + https://weave-docs.wandb.ai/guides/evaluation/evaluation_logger/ to log traces and evaluations at each evaluation + step. + + Supports two modes based on the `scorers` parameter: + - **Tracing Mode** (when scorers=None): Logs predictions for data exploration and analysis + - **Evaluation Mode** (when scorers provided): Logs predictions with scoring and summary metrics + + Both modes use Weave's EvaluationLogger for structured, consistent data logging. + + The callback logs data during evaluation phases (`on_evaluate`) rather than training steps, making it more + efficient and semantically correct. It gracefully handles missing weave installation by logging warnings and + skipping weave-specific functionality. It also checks for existing weave clients before initializing new ones. + + Usage: + ```python + # Tracing mode (just log predictions) + trainer = DPOTrainer(...) + weave_callback = WeaveTraceCallback(trainer=trainer) # project_name optional + trainer.add_callback(weave_callback) + + # Or specify a project name + weave_callback = WeaveTraceCallback(trainer=trainer, project_name="my-llm-training") + trainer.add_callback(weave_callback) + + + # Evaluation mode (log predictions + scores + summary) + def accuracy_scorer(prompt: str, completion: str) -> float: + # Your scoring logic here (metadata available via eval_attributes) + return score + + + weave_callback = WeaveTraceCallback( + trainer=trainer, + project_name="my-llm-training", # optional and needed only if weave client is not initialized + scorers={"accuracy": accuracy_scorer}, + ) + trainer.add_callback(weave_callback) + ``` + + Args: + trainer (`Trainer`): + Trainer to which the callback will be attached. The trainer's evaluation dataset must include a `"prompt"` + column containing the prompts for generating completions. + project_name (`str`, *optional*): + Name of the Weave project where data will be logged. If not provided, will try to use existing weave client + or fall back to the active wandb run's project name. Raises an error if none of these are available. + scorers (`dict[str, Callable]`, *optional*): + Dictionary mapping scorer names to scorer functions. If `None`, operates in tracing mode (predictions + only). If provided, operates in evaluation mode (predictions + scores + summary). Scorer functions should + have signature: `scorer(prompt: str, completion: str) -> float | int` + generation_config ([`~transformers.GenerationConfig`], *optional*): + Generation config to use for generating completions. + num_prompts (`int` or `None`, *optional*): + Number of prompts to generate completions for. If not provided, defaults to the number of examples in the + evaluation dataset. + dataset_name (`str`, *optional*, defaults to `"eval_dataset"`): + Name for the dataset metadata in Weave. + model_name (`str`, *optional*): + Name for the model metadata in Weave. If not provided, attempts to extract from model config. + """ + + def __init__( + self, + trainer: Trainer, + project_name: str | None = None, + scorers: dict[str, callable] | None = None, + generation_config: GenerationConfig | None = None, + num_prompts: int | None = None, + dataset_name: str = "eval_dataset", + model_name: str | None = None, + ): + self.trainer = trainer + self.project_name = project_name + self.scorers = scorers or {} + self.generation_config = generation_config + self.dataset_name = dataset_name + self.model_name = model_name + self._last_logged_step = -1 + self._weave_initialized = False + self._eval_logger = None + + if self.trainer.eval_dataset is None: + raise ValueError("Trainer must have an evaluation dataset to use the WeaveCallback.") + else: + self.eval_dataset = self.trainer.eval_dataset + + if num_prompts is not None: + self.eval_dataset = self.eval_dataset.select(range(num_prompts)) + + def _initialize_weave(self): + """Initialize Weave and EvaluationLogger if not already initialized.""" + if not self._weave_initialized: + if not is_weave_available(): + logger.warning("Weave is not available. Please install weave to enable logging: `pip install weave`") + return + + if wc := weave_client_context.get_weave_client(): + self._weave_client = wc + else: + if self.project_name is None: + if is_wandb_available(): + if wandb.run is not None: + self.project_name = wandb.run.entity + "/" + wandb.run.project + logger.info(f"Using project name from active wandb run: {self.project_name}") + + if self.project_name is None: + raise ValueError( + "No existing Weave client found and no project_name provided. " + "Please either initialize weave with `weave.init('project-name')`, " + "provide a project_name to the `WeaveTraceCallback`, " + "or ensure an active wandb run exists." + ) + + self._weave_client = weave.init(self.project_name) + logger.info(f"Initialized Weave with project: {self.project_name}") + + if self.model_name is None: + self.model_name = getattr(self.trainer.model_wrapped.config, "_name_or_path", "unknown_model") + + self._EvaluationLogger = EvaluationLogger + + self._weave_initialized = True + + @property + def is_evaluation_mode(self) -> bool: + """True if scorers are provided (evaluation mode), False for tracing mode.""" + return bool(self.scorers) + + def on_train_begin(self, args, state, control, **kwargs): + """Initialize Weave when training begins.""" + self._initialize_weave() + + def on_evaluate(self, args, state, control, **kwargs): + if state.global_step == self._last_logged_step: + return + + self._initialize_weave() + + if not self._weave_initialized: + logger.debug("Weave not initialized, skipping logging") + return + + tokenizer = kwargs["processing_class"] + tokenizer.padding_side = "left" + accelerator = self.trainer.accelerator + model = self.trainer.model_wrapped + + with accelerator.split_between_processes(self.eval_dataset["prompt"]) as prompts: + prompts = [maybe_apply_chat_template({"prompt": prompt}, tokenizer)["prompt"] for prompt in prompts] + + completions = _generate_completions( + prompts=prompts, + model=model, + tokenizer=tokenizer, + accelerator=accelerator, + generation_config=self.generation_config, + batch_size=args.per_device_eval_batch_size, + ) + + all_prompts = gather_object(prompts) + all_completions = gather_object(completions) + + if self.trainer.accelerator.is_main_process: + eval_attributes = { + "training_step": state.global_step, + "model_name": self.model_name, + "generation_config": (self.generation_config.to_dict() if self.generation_config else None), + } + + eval_logger = self._EvaluationLogger( + model=self.model_name, + dataset=self.dataset_name, + eval_attributes=eval_attributes, + ) + + successful_predictions = 0 + total_score_values = {} # For summary statistics + + for prompt, completion in zip(all_prompts, all_completions, strict=True): + try: + pred_logger = eval_logger.log_prediction(inputs={"prompt": prompt}, output=completion) + + if self.is_evaluation_mode: + for scorer_name, scorer_func in self.scorers.items(): + try: + score = scorer_func(prompt, completion) + pred_logger.log_score(scorer=scorer_name, score=score) + + if scorer_name not in total_score_values: + total_score_values[scorer_name] = [] + total_score_values[scorer_name].append(score) + + except Exception as scorer_e: + logger.warning(f"Failed to apply scorer '{scorer_name}': {scorer_e}") + + pred_logger.finish() + successful_predictions += 1 + + except Exception as pred_e: + logger.warning(f"Failed to log prediction for prompt: {pred_e}") + # Continue with other predictions even if one fails + + if self.is_evaluation_mode and total_score_values: + try: + summary_stats = { + "total_predictions": len(all_prompts), + "successful_predictions": successful_predictions, + } + + for scorer_name, scores in total_score_values.items(): + if scores: # Only if we have valid scores + summary_stats[f"avg_{scorer_name}"] = sum(scores) / len(scores) + + eval_logger.log_summary(summary_stats) + + except Exception as summary_e: + logger.warning(f"Failed to log summary: {summary_e}") + else: + try: + eval_logger.finish() + except Exception as finish_e: + logger.warning(f"Failed to finish evaluation logger: {finish_e}") + + self._last_logged_step = state.global_step + + +class BEMACallback(TrainerCallback): + # docstyle-ignore + r""" + A [`~transformers.TrainerCallback`] that implements [BEMA](https://huggingface.co/papers/2508.00180) + (Bias-Corrected Exponential Moving Average) by [Adam Block](https://huggingface.co/abblock) and [Cyril + Zhang](https://huggingface.co/cyrilzhang). Code from https://github.com/abblock/bema under MIT license. + + BEMA computes model weights that scale like: + + $$ + \theta_t' = \alpha_t \cdot (\theta_t - \theta_0) + \text{EMA}_t + $$ + + where \\( \theta_t \\) is the current model weights, \\( \theta_0 \\) is a snapshot of the model weights at the + first `update_after` step, \\( \text{EMA}_t \\) is the exponential moving average of the model weights, and + \\( \alpha_t \\) is a scaling factor that decays with the number of steps \\( t \\) as + + $$ + \alpha_t = (\rho + \gamma \cdot t)^{-\eta}. + $$ + + The EMA is computed as: + + $$ + \text{EMA}_t = (1 - \beta_t) \cdot \text{EMA}_{t-1} + \beta_t \cdot \theta_t + $$ + + where \\( \beta_t \\) is a decay factor that decays with the number of steps \\( t \\) as + + $$ + \beta_t = (\rho + \gamma \cdot t)^{-\kappa}. + $$ + + Args: + update_freq (`int`, *optional*, defaults to `400`): + Update the BEMA weights every X steps. Denoted this as \\( \phi \\) in the paper. + ema_power (`float`, *optional*, defaults to `0.5`): + Power for the EMA decay factor. Denoted \\( \kappa \\) in the paper. To disable EMA, set this to `0.0`. + bias_power (`float`, *optional*, defaults to `0.2`): + Power for the BEMA scaling factor. Denoted \\( \eta \\) in the paper. To disable BEMA, set this to `0.0`. + lag (`int`, *optional*, defaults to `10`): + Initial offset in the weight decay schedule that controls early-stage smoothness by acting as a virtual + starting age for the updates. Denoted as \\( \rho \\) in the paper. + update_after (`int`, *optional*, defaults to `0`): + Burn-in time before starting to update the BEMA weights. Denoted \\( \tau \\) in the paper. + multiplier (`float`, *optional*, defaults to `1.0`): + Initial value for the EMA decay factor. Denoted as \\( \gamma \\) in the paper. + min_ema_multiplier (`float`, *optional*, defaults to `0.0`): + Minimum value for the EMA decay factor. + device (`str`, *optional*, defaults to `"cpu"`): + Device to use for the BEMA buffers, e.g. `"cpu"` or `"cuda"`. Note that in most cases, this device SHOULD + BE DIFFERENT from the device used for training in order to avoid OOM. + + Example: + + ```python + from trl import BEMACallback + + trainer = Trainer(..., callbacks=[BEMACallback()]) + ``` + """ + + def __init__( + self, + update_freq: int = 400, + ema_power: float = 0.5, + bias_power: float = 0.2, + lag: int = 10, + update_after: int = 0, + multiplier: float = 1.0, + min_ema_multiplier: float = 0.0, + device: str = "cpu", + ): + # User-provided hyperparams + self.update_freq = update_freq + self.ema_power = ema_power + self.bias_power = bias_power + self.lag = lag + self.update_after = update_after + self.multiplier = multiplier + self.min_ema_multiplier = min_ema_multiplier + self.device = device + + # Internal state + self.param_names = [] # references to training model param names + self.thetat_params = [] # references to training model params + self.theta0_params = [] # θ₀ buffers (on self.device) + self.ema_params = [] # EMA buffers (on self.device) + self.running_model = None # a copy of the model to run BEMA on + + @staticmethod + def _unwrap_model(model): + """ + Helper function to unwrap model from various wrappers including DataParallel, DistributedDataParallel, + DeepSpeed, and FSDP. + """ + # Handle DeepSpeed + if hasattr(model, "module") and hasattr(model, "engine"): + # DeepSpeed engine + return model.module + + # Handle FSDP + if hasattr(model, "_fsdp_wrapped_module"): + # FSDP wrapped model + return model._fsdp_wrapped_module + + # Handle DataParallel/DistributedDataParallel + if hasattr(model, "module"): + return model.module + + return model + + @torch.no_grad() + def on_train_begin( + self, args: TrainingArguments, state: TrainerState, control: TrainerControl, model: PreTrainedModel, **kwargs + ): + model = self._unwrap_model(model) + + # Create a new instance and load state_dict + self.running_model = type(model)(model.config).to(self.device) + self.running_model.load_state_dict(model.state_dict()) + + # Cache trainable parameters once in a fixed order + for name, param in model.named_parameters(): + if not param.requires_grad: + continue + self.param_names.append(name) + self.thetat_params.append(param) + + # Clone θ₀ and EMA on the same device as model + theta0 = param.detach().clone().to(self.device) + self.theta0_params.append(theta0) + self.ema_params.append(theta0.clone()) # initialize EMA with θ₀ + + def _ema_beta(self, step: int) -> float: + """Compute the EMA decay factor βₜ = (ρ + γ·t)⁻ᵏᵃᵖᵖᵃ.""" + beta = (self.lag + self.multiplier * step) ** (-self.ema_power) + return max(beta, self.min_ema_multiplier) + + def _bema_alpha(self, step: int) -> float: + """Compute the BEMA scaling factor αₜ = (ρ + γ·t)⁻ᵉᵗᵃ.""" + return (self.lag + self.multiplier * step) ** (-self.bias_power) + + def _update_bema_weights(self, step: int): + beta = self._ema_beta(step) + alpha = self._bema_alpha(step) + + # Compute EMA + BEMA in-place and write directly to running_model + for thetat, theta0, ema, run_param in zip( + self.thetat_params, self.theta0_params, self.ema_params, self.running_model.parameters(), strict=True + ): + thetat = thetat.detach().to(self.device) + ema.mul_(1 - beta).add_(thetat, alpha=beta) # EMA update: ema = (1 - beta) * ema + beta * θₜ + run_param.copy_(ema + alpha * (thetat - theta0)) # BEMA update: run_param = ema + alpha * (θₜ - θ₀) + + @torch.no_grad() + def on_step_end( + self, args: TrainingArguments, state: TrainerState, control: TrainerControl, model: PreTrainedModel, **kwargs + ): + step = state.global_step + + # If we haven't reached the update_after step, skip the BEMA update + if step < self.update_after: + return + + # Snapshot θ₀ and EMA at first update + if step == self.update_after: + for thetat_param, theta0_param, ema_param in zip( + self.thetat_params, self.theta0_params, self.ema_params, strict=True + ): + theta0_param.copy_(thetat_param) + ema_param.copy_(thetat_param) + + # Update BEMA weights every `update_freq` steps + elif (step - self.update_after) % self.update_freq == 0: + self._update_bema_weights(step) + logger.info(f"Updated BEMA weights at step {step}") + + @torch.no_grad() + def on_train_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): + if state.is_world_process_zero: + save_directory = f"{args.output_dir}/bema" + self.running_model.save_pretrained(save_directory) + logger.info(f"Saved BEMA model to {save_directory}") diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/dpo_config.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/dpo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..f47038433b46779bfa91c5e4cd61de7d4a40ac91 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/dpo_config.py @@ -0,0 +1,343 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from dataclasses import dataclass, field +from typing import Any + +from .base_config import _BaseConfig + + +@dataclass +class DPOConfig(_BaseConfig): + # docstyle-ignore + r""" + Configuration class for the [`DPOTrainer`]. + + This class includes only the parameters that are specific to DPO 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 + + model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments for [`~transformers.AutoModelForCausalLM.from_pretrained`], used when the `model` + argument of the [`DPOTrainer`] is provided as a string. + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the model and reference model. + + > Parameters that control the data preprocessing + + dataset_num_proc (`int`, *optional*): + Number of processes to use for processing the dataset. + max_length (`int` or `None`, *optional*, defaults to `1024`): + Maximum length of the tokenized sequence. Sequences longer than `max_length` are truncated from the left or + right depending on the `truncation_mode`. If `None`, no truncation is applied. + truncation_mode (`str`, *optional*, defaults to `"keep_start"`): + Truncation mode to use when the sequence exceeds `max_length`. The only supported value is + `"keep_start"`. The `"keep_end"` value is deprecated and will be removed in v2.0.0. + padding_free (`bool`, *optional*, defaults to `False`): + Whether to perform forward passes without padding by flattening all sequences in the batch into a single + continuous sequence. This reduces memory usage by eliminating padding overhead. Currently, this is only + supported with the FlashAttention 2 or 3, which can efficiently handle the flattened batch structure. + pad_to_multiple_of (`int`, *optional*): + If set, the sequences will be padded to a multiple of this value. + precompute_ref_log_probs (`bool`, *optional*, defaults to `False`): + Whether to precompute the reference model log probabilities for the entire training dataset before + training. This allows to save memory during training, as the reference model does not need to be kept in + memory. + precompute_ref_batch_size (`int`, *optional*): + Batch size to use when precomputing reference model log probabilities. This can be set higher than the + training batch size to speed up preprocessing. If `None`, defaults to `per_device_train_batch_size` for + training and `per_device_eval_batch_size` for evaluation. + + > Parameters that control the training + + loss_type (`list[str]`, *optional*, defaults to `["sigmoid"]`): + Type of loss to use. Possible values are: `'sigmoid'`, `'hinge'`, `'ipo'`, `'exo_pair'`, `'nca_pair'`, + `'robust'`, `'bco_pair'`, `'sppo_hard'`, `'aot'`, `'aot_unpaired'`, `'apo_zero'`, `'apo_down'`, + `'discopop'`, `'sft'`, `'sigmoid_norm'`. If multiple loss types are provided, they will be combined using + the weights specified in `loss_weights`. + loss_weights (`list[float]`, *optional*): + List of loss weights for multi-loss combinations. Used when combining multiple loss types. Example: `[0.8, + 0.2, 1.0]` for MPO. If not provided, defaults to equal weights (`1.0`) for all loss types. + ld_alpha (`float`, *optional*): + α parameter from the LD-DPO paper, which controls the weighting of the verbose token log-probabilities in + responses. If `None`, no weighting is applied to the verbose part, and the loss is equivalent to the + standard DPO loss. Must be in [0.0, 1.0]: `ld_alpha=1.0` applies no weighting, and `ld_alpha=0.0` masks + tokens beyond shared lengths. + f_divergence_type (`str`, *optional*, defaults to `"reverse_kl"`): + f-divergence regularizer between policy and reference (f-DPO paper). Possible values are: `reverse_kl` + (default), `forward_kl`, `js_divergence`, `alpha_divergence`. + f_alpha_divergence_coef (`float`, *optional*, defaults to `0.5`): + α coefficient for the α-divergence u^-α regularizer, used only when `f_divergence_type='alpha_divergence'`. + label_smoothing (`float`, *optional*, defaults to `0.0`): + Label smoothing parameter used in Robust DPO and EXO. In Robust DPO, it is interpreted as the probability + that a preference label is flipped and must lie in [0.0, 0.5); a typical value recommended by the Robust + DPO paper is 0.1. In EXO, it corresponds to the ε label smoothing parameter, for which the paper recommends + a typical value of 1e-3. + beta (`float`, *optional*, defaults to `0.1`): + Parameter controlling the deviation from the reference model. Higher β means less deviation from the + reference model. For the IPO loss (`loss_type='ipo'`), this value is the regularization parameter denoted + by τ in the [paper](https://huggingface.co/papers/2310.12036). + use_weighting (`bool`, *optional*, defaults to `False`): + Whether to apply WPO-style weighting (https://huggingface.co/papers/2406.11827) to preference pairs using + the policy's length-normalized sequence probabilities. + discopop_tau (`float`, *optional*, defaults to `0.05`): + τ/temperature parameter from the DiscoPOP paper, which controls the shape of the log-ratio modulated loss + when using `loss_type='discopop'`. The paper recommends the default value `discopop_tau=0.05`. + activation_offloading (`bool`, *optional*, defaults to `False`): + Whether to offload the activations to the CPU. + 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. `sync_ref_model=True` is not yet compatible with + PEFT or `precompute_ref_log_probs=True`. + ref_model_mixup_alpha (`float`, *optional*, defaults to `0.6`): + α parameter from the TR-DPO 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 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`. + + > Deprecated parameters + + pad_token: + + + + Parameter `pad_token` is deprecated and will be removed in version v2.0.0. Set `tokenizer.pad_token` + directly and pass it as `processing_class` to the trainer instead. + + + + > [!NOTE] + > These parameters have default values different from [`~transformers.TrainingArguments`]: + > - `logging_steps`: Defaults to `10` instead of `500`. + > - `gradient_checkpointing`: Defaults to `True` instead of `False`. + > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`. + > - `learning_rate`: Defaults to `1e-6` instead of `5e-5`. + """ + + _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"] + + # Parameters whose default values are overridden from TrainingArguments + learning_rate: float = field( + default=1e-6, + metadata={"help": "The initial learning rate for AdamW."}, + ) + + # Parameters that control the model + model_init_kwargs: dict[str, Any] | str | None = field( + default=None, + metadata={ + "help": "Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `model` argument of " + "the `DPOTrainer` is provided as a string." + }, + ) + disable_dropout: bool = field( + default=True, + metadata={"help": "Whether to disable dropout in the model and reference model."}, + ) + + # Parameters that control the data preprocessing + dataset_num_proc: int | None = field( + default=None, + metadata={"help": "Number of processes to use for processing the dataset."}, + ) + max_length: int | None = field( + default=1024, + metadata={ + "help": "Maximum length of the tokenized sequence. Sequences longer than `max_length` are truncated from " + "the left or right depending on the `truncation_mode`. If `None`, no truncation is applied." + }, + ) + truncation_mode: str = field( + default="keep_start", + metadata={ + "help": "Truncation mode to use when the sequence exceeds `max_length`. The only supported value is " + "`'keep_start'`. The `'keep_end'` value is deprecated and will be removed in v2.0.0.", + "choices": ["keep_end", "keep_start"], + }, + ) + padding_free: bool = field( + default=False, + metadata={ + "help": "Whether to perform forward passes without padding by flattening all sequences in the batch into " + "a single continuous sequence. This reduces memory usage by eliminating padding overhead. Currently, this " + "is only supported with the FlashAttention 2 or 3, which can efficiently handle the flattened batch " + "structure." + }, + ) + pad_to_multiple_of: int | None = field( + default=None, + metadata={"help": "If set, the sequences will be padded to a multiple of this value."}, + ) + precompute_ref_log_probs: bool = field( + default=False, + metadata={ + "help": "Whether to precompute the reference model log probabilities for the entire training dataset " + "before training. This allows to save memory during training, as the reference model does not need to be " + "kept in memory." + }, + ) + precompute_ref_batch_size: int | None = field( + default=None, + metadata={ + "help": "Batch size to use when precomputing reference model log probabilities. This can be set higher " + "than the training batch size to speed up preprocessing. If `None`, defaults to " + "`per_device_train_batch_size` for training and `per_device_eval_batch_size` for evaluation." + }, + ) + + # Parameters that control the training + loss_type: list[str] = field( + default_factory=lambda: ["sigmoid"], + metadata={ + "help": "Type of loss to use. Possible values are: `'sigmoid'`, `'hinge'`, `'ipo'`, `'exo_pair'`, " + "`'nca_pair'`, `'robust'`, `'bco_pair'`, `'sppo_hard'`, `'aot'`, `'aot_unpaired'`, `'apo_zero'`, " + "`'apo_down'`, `'discopop'`, `'sft'`, `'sigmoid_norm'`. If multiple loss types are provided, they will be " + "combined using the weights specified in `loss_weights`.", + }, + ) + loss_weights: list[float] | None = field( + default=None, + metadata={ + "help": "List of loss weights for multi-loss combinations. Used when combining multiple loss types. " + "Example: `[0.8, 0.2, 1.0]` for MPO. If not provided, defaults to equal weights (`1.0`) for all loss " + "types." + }, + ) + ld_alpha: float | None = field( + default=None, + metadata={ + "help": "α parameter from the LD-DPO paper, which controls the weighting of the verbose token " + "log-probabilities in responses. If `None`, no weighting is applied to the verbose part, and the loss is " + "equivalent to the standard DPO loss. Must be in [0.0, 1.0]: `ld_alpha=1.0` applies no weighting, and " + "`ld_alpha=0.0` masks tokens beyond shared lengths.", + }, + ) + f_divergence_type: str = field( + default="reverse_kl", + metadata={ + "help": "f-divergence regularizer between policy and reference (f-DPO paper). Possible values are: " + "`reverse_kl` (default), `forward_kl`, `js_divergence`, `alpha_divergence`.", + }, + ) + f_alpha_divergence_coef: float = field( + default=0.5, + metadata={ + "help": "α coefficient for the α-divergence u^-α regularizer, used only when " + "`f_divergence_type='alpha_divergence'`." + }, + ) + label_smoothing: float = field( + default=0.0, + metadata={ + "help": "Label smoothing parameter used in Robust DPO and EXO. In Robust DPO, it is interpreted as the " + "probability that a preference label is flipped and must lie in [0.0, 0.5); a typical value recommended " + "by the Robust DPO paper is 0.1. In EXO, it corresponds to the ε label smoothing parameter, for which the " + "paper recommends a typical value of 1e-3." + }, + ) + beta: float = field( + default=0.1, + metadata={ + "help": "Parameter controlling the deviation from the reference model. Higher β means less deviation from " + "the reference model. For the IPO loss (`loss_type='ipo'`), this value is the regularization parameter " + "denoted by τ in the [paper](https://huggingface.co/papers/2310.12036)." + }, + ) + use_weighting: bool = field( + default=False, + metadata={ + "help": "Whether to apply WPO-style weighting (https://huggingface.co/papers/2406.11827) to preference " + "pairs using the policy's length-normalized sequence probabilities." + }, + ) + discopop_tau: float = field( + default=0.05, + metadata={ + "help": "τ/temperature parameter from the DiscoPOP paper, which controls the shape of the log-ratio " + "modulated loss when using `loss_type='discopop'`. The paper recommends the default value " + "`discopop_tau=0.05`." + }, + ) + activation_offloading: bool = field( + default=False, + metadata={"help": "Whether to offload the activations to the CPU."}, + ) + sync_ref_model: bool = field( + default=False, + metadata={ + "help": "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. `sync_ref_model=True` is not yet compatible " + "with PEFT or `precompute_ref_log_probs=True`." + }, + ) + ref_model_mixup_alpha: float = field( + default=0.6, + metadata={ + "help": "α parameter from the TR-DPO 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 = field( + default=512, + metadata={ + "help": "τ parameter from the TR-DPO 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`." + }, + ) + + # Deprecated parameters + pad_token: str | None = field( + default=None, + metadata={ + "help": "Deprecated. Set `tokenizer.pad_token` directly and pass it as `processing_class` to the trainer instead." + }, + ) + + def __post_init__(self): + if isinstance(self.loss_type, str): + self.loss_type = [self.loss_type] + if self.loss_weights is not None and len(self.loss_weights) != len(self.loss_type): + raise ValueError( + "`loss_weights` must have the same length as `loss_type` when combining multiple losses. " + f"Got {len(self.loss_weights)} weights for {len(self.loss_type)} loss types." + ) + if self.pad_token is not None: + warnings.warn( + "`pad_token` is deprecated and will be removed in v2.0.0. " + "Set `tokenizer.pad_token` directly and pass it as `processing_class` to the trainer instead.", + FutureWarning, + stacklevel=3, + ) + if self.truncation_mode == "keep_end": + warnings.warn( + "The `'keep_end'` truncation mode is deprecated and will be removed in v2.0.0. " + "Use `truncation_mode='keep_start'` (the default) instead.", + FutureWarning, + stacklevel=3, + ) + + super().__post_init__() diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/dpo_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/dpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..c2c84ff5bc901c1081ffa09590f8b9fc70781304 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/dpo_trainer.py @@ -0,0 +1,1550 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import contextlib +import json +import os +import textwrap +from collections import defaultdict +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import torch +import torch.nn.functional as F +import transformers +from accelerate import PartialState +from accelerate.logging import get_logger +from accelerate.utils import is_peft_model, tqdm +from datasets import Dataset, IterableDataset, IterableDatasetDict, concatenate_datasets +from datasets.fingerprint import Hasher +from packaging.version import Version +from torch.utils.data import DataLoader +from transformers import ( + AutoProcessor, + DataCollator, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, +) +from transformers.data.data_collator import DataCollatorMixin +from transformers.trainer_callback import TrainerCallback +from transformers.trainer_utils import EvalPrediction +from transformers.utils import is_liger_kernel_available, is_peft_available + +from ..data_utils import apply_chat_template, extract_prompt, is_conversational, prepare_multimodal_messages +from ..models import get_act_offloading_ctx_manager, prepare_deepspeed, prepare_fsdp +from ..models.utils import disable_gradient_checkpointing +from .base_trainer import _BaseTrainer +from .callbacks import SyncRefModelCallback +from .dpo_config import DPOConfig +from .utils import ( + create_model_from_path, + disable_dropout_in_model, + entropy_from_logits, + flush_left, + get_config_model_id, + hash_module, + pad, + selective_log_softmax, + use_adapter, +) + + +if is_peft_available(): + from peft import PeftConfig, PeftModel, get_peft_model + + +if is_liger_kernel_available(): + from liger_kernel.chunked_loss import LigerFusedLinearDPOLoss + + +logger = get_logger(__name__) + + +FLASH_ATTENTION_VARIANTS = { + "flash_attention_2", + "flash_attention_3", + "kernels-community/flash-attn2", + "kernels-community/flash-attn3", + "kernels-community/vllm-flash-attn3", +} + + +def get_dataset_column_names(dataset: Dataset | IterableDataset) -> list[str]: + return list(next(iter(dataset)).keys()) if dataset.column_names is None else dataset.column_names + + +@dataclass +class DataCollatorForPreference(DataCollatorMixin): + """ + Data collator used for preference data. Inputs are dynamically padded to the maximum length of a batch. + + This collator expects each example in the input list to be a dictionary containing the keys `"prompt_ids"`, + `"chosen_ids"` and `"rejected_ids"`. The collator returns a dictionary containing the following keys: + - `"input_ids"`: Tensor of input IDs, padded to the maximum length of the batch. The first half of the batch + corresponds to the `"chosen_ids"` and the second half to the `"rejected_ids"`. + - `"attention_mask"`: Tensor of attention mask, padded to the maximum length of the batch. + - `"completion_mask"`: Tensor indicating the positions of the completion tokens, padded to the maximum length of + the batch. + + Optionally, the examples can contain a `"ref_chosen_logps"` and `"ref_rejected_logps"` keys, in which case the + returned dictionary will also contain these keys with the corresponding tensors. + + Args: + pad_token_id (`int`): + Token ID to use for padding. + max_length (`int`, *optional*): + Maximum length of the sequences after concatenation. Sequences longer than `max_length` are truncated + before padding, which avoids allocating oversized tensors for batches containing very long sequences. + truncation_mode (`str`, *optional*, defaults to `"keep_start"`): + Truncation mode when a concatenated sequence exceeds `max_length`. Possible values are `"keep_end"` and + `"keep_start"`. + pad_to_multiple_of (`int`, *optional*): + If set, the sequences will be padded to a multiple of this value. + return_tensors (`str`, *optional*, defaults to `"pt"`): + Type of Tensor to return. Only `"pt"` is currently supported. + + Examples: + ```python + >>> from trl.trainer.dpo_trainer import DataCollatorForPreference + + >>> collator = DataCollatorForPreference(pad_token_id=0) + >>> examples = [ + ... {"prompt_ids": [1, 2, 3], "chosen_ids": [4, 5], "rejected_ids": [6]}, + ... {"prompt_ids": [7, 8], "chosen_ids": [9], "rejected_ids": [10, 11]}, + ... ] + >>> collator(examples) + {'input_ids': tensor([[ 1, 2, 3, 4, 5], + [ 7, 8, 9, 0, 0], + [ 1, 2, 3, 6, 0], + [ 7, 8, 10, 11, 0]]), + 'attention_mask': tensor([[1, 1, 1, 1, 1], + [1, 1, 1, 0, 0], + [1, 1, 1, 1, 0], + [1, 1, 1, 1, 0]]), + 'completion_mask': tensor([[0, 0, 0, 1, 1], + [0, 0, 1, 0, 0], + [0, 0, 0, 1, 0], + [0, 0, 1, 1, 0]])} + ``` + """ + + pad_token_id: int + max_length: int | None = None + truncation_mode: str = "keep_start" + pad_to_multiple_of: int | None = None + return_tensors: str = "pt" + + def torch_call(self, examples: list[dict[str, Any]]) -> dict[str, Any]: + prompt_chosen_ids = [example["prompt_ids"] + example["chosen_ids"] for example in examples] + prompt_rejected_ids = [example["prompt_ids"] + example["rejected_ids"] for example in examples] + chosen_mask = [[0] * len(example["prompt_ids"]) + [1] * len(example["chosen_ids"]) for example in examples] + rejected_mask = [[0] * len(example["prompt_ids"]) + [1] * len(example["rejected_ids"]) for example in examples] + + if self.max_length is not None: + if self.truncation_mode == "keep_start": + sl = slice(None, self.max_length) + elif self.truncation_mode == "keep_end": + sl = slice(-self.max_length, None) + else: + raise ValueError( + f"Unsupported truncation mode: {self.truncation_mode}, expected 'keep_start' or 'keep_end'" + ) + prompt_chosen_ids = [ids[sl] for ids in prompt_chosen_ids] + prompt_rejected_ids = [ids[sl] for ids in prompt_rejected_ids] + chosen_mask = [m[sl] for m in chosen_mask] + rejected_mask = [m[sl] for m in rejected_mask] + + chosen_attention_mask = [[1] * len(ids) for ids in prompt_chosen_ids] + rejected_attention_mask = [[1] * len(ids) for ids in prompt_rejected_ids] + input_ids = prompt_chosen_ids + prompt_rejected_ids + attention_mask = chosen_attention_mask + rejected_attention_mask + completion_mask = chosen_mask + rejected_mask + + # Convert to tensor + input_ids = [torch.tensor(ids) for ids in input_ids] + attention_mask = [torch.tensor(m, dtype=torch.long) for m in attention_mask] + completion_mask = [torch.tensor(m, dtype=torch.long) for m in completion_mask] + if "ref_chosen_logps" in examples[0]: + ref_chosen_logps = torch.tensor([example["ref_chosen_logps"] for example in examples]) + if "ref_rejected_logps" in examples[0]: + ref_rejected_logps = torch.tensor([example["ref_rejected_logps"] for example in examples]) + + # Pad + output = {} + output["input_ids"] = pad( + input_ids, + padding_value=self.pad_token_id, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ) + output["attention_mask"] = pad( + attention_mask, + padding_value=0, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ) + output["completion_mask"] = pad( + completion_mask, + padding_value=0, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ) + if "ref_chosen_logps" in examples[0]: + output["ref_chosen_logps"] = ref_chosen_logps + if "ref_rejected_logps" in examples[0]: + output["ref_rejected_logps"] = ref_rejected_logps + return output + + +@dataclass +class DataCollatorForVisionPreference(DataCollatorMixin): + """ + Data collator for vision-preference tasks. + + Unlike text-only datasets, where the collator typically receives pre-tokenized inputs ready for batching, + vision-language data processing involves converting images into pixel values. This conversion is disk-intensive, + making upfront preprocessing of the entire dataset impractical. Therefore, this collator performs tokenization and + image processing on-the-fly to efficiently prepare batches. + + Each input example should be a dictionary containing at least: + - An `"images"` key holding a list of images, or an `"image"` key holding a single image. + - Keys `"prompt"` `"chosen"` and `"rejected"` for the prompt and preference responses. + + The collator outputs a dictionary including: + - `"input_ids"`: Tensor of token IDs. + - `"attention_mask"`: Tensor indicating attention mask. + - `"completion_mask"`: Tensor indicating which tokens correspond to completions. + - `"pixel_values"`: Tensor representing image pixel values. + + Additional keys may be present depending on the processor, such as `"image_grid_thw"` or `"image_position_ids"`. + + Args: + processor ([`~transformers.ProcessorMixin`]): + The processor used to tokenize text and process images. It must be a subclass of + [`~transformers.ProcessorMixin`] and include a `tokenizer` with a defined `pad_token_id`. + max_length (`int`, *optional*): + Maximum sequence length. Sequences longer than `max_length` are truncated before padding, which avoids + allocating oversized tensors for batches containing very long sequences. Only `"keep_start"` truncation + applies to vision datasets; `"keep_end"` is rejected upstream. + pad_to_multiple_of (`int` or `None`, optional, defaults to `None`): + If set, the sequences will be padded to a multiple of this value. + return_tensors (`str`, optional, defaults to `"pt"`): + The tensor type to return. Currently, only `"pt"` (PyTorch tensors) is supported. + + Example: + ```python + >>> from trl.trainer.dpo_trainer import DataCollatorForVisionPreference + >>> from transformers import AutoProcessor + + >>> processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct") + >>> collator = DataCollatorForVisionPreference(processor) + >>> examples = [ + ... { + ... "images": [Image.open("image_0.png")], + ... "prompt": [{"role": "user", "content": "What is this?"}], + ... "chosen": [{"role": "assistant", "content": "This is a cat."}], + ... "rejected": [{"role": "assistant", "content": "This is a dog."}], + ... }, + ... { + ... "images": [Image.open("image_1.png")], + ... "prompt": [{"role": "user", "content": "Describe this image."}], + ... "chosen": [{"role": "assistant", "content": "A beautiful landscape."}], + ... "rejected": [{"role": "assistant", "content": "An urban cityscape."}], + ... }, + ... ] + >>> collator(examples) + {'input_ids': tensor([[151644, 8948, 198, 2610, 525, 264, 10950, 17847, 13, 151645, 198, 151644, 872, 198, 151652, 151655, 151655, 151655, 151655, 151653, 3838, 374, 419, 30, 151645, 198, 151644, 77091, 198, 1986, 374, 264, 8251, 13, 151645, 198], + [151644, 8948, 198, 2610, 525, 264, 10950, 17847, 13, 151645, 198, 151644, 872, 198, 151652, 151655, 151655, 151655, 151655, 151653, 74785, 419, 2168, 13, 151645, 198, 151644, 77091, 198, 32, 6233, 18414, 13, 151645, 198, 151643], + [151644, 8948, 198, 2610, 525, 264, 10950, 17847, 13, 151645, 198, 151644, 872, 198, 151652, 151655, 151655, 151655, 151655, 151653, 3838, 374, 419, 30, 151645, 198, 151644, 77091, 198, 1986, 374, 264, 5562, 13, 151645, 198], + [151644, 8948, 198, 2610, 525, 264, 10950, 17847, 13, 151645, 198, 151644, 872, 198, 151652, 151655, 151655, 151655, 151655, 151653, 74785, 419, 2168, 13, 151645, 198, 151644, 77091, 198, 2082, 15662, 3283, 57518, 13, 151645, 198]]), + 'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]), + 'pixel_values': tensor([[-1.3251, 0.1347, -0.4784, ..., 0.4537, -0.0156, 1.2358], + [ 0.5727, 0.4997, -0.9164, ..., -0.5701, 0.7950, -0.7123], + [-0.0550, -0.8288, 1.0690, ..., -0.1293, -0.1151, 1.6055], + ..., + [ 0.2953, 0.5581, 0.1785, ..., -0.7123, -0.7977, 0.1693], + [-0.7558, 1.0398, 1.3464, ..., -0.5417, -0.5417, 0.4395], + [ 0.8063, 0.6895, 0.4267, ..., -0.4422, 1.3354, 0.1266]]), + 'image_grid_thw': tensor([[1, 4, 4], + [1, 4, 4], + [1, 4, 4], + [1, 4, 4]]), + 'completion_mask': tensor([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1]])} + ``` + """ + + processor: ProcessorMixin + max_length: int | None = None + pad_to_multiple_of: int | None = None + return_tensors: str = "pt" + + def torch_call(self, examples: list[dict[str, Any]]) -> dict[str, Any]: + if self.pad_to_multiple_of is not None: + raise NotImplementedError( + "Padding to a multiple of a value is not yet implemented for vision-language modeling and " + "prompt-completion data." + ) + if "image" in examples[0]: + for example in examples: + example["images"] = [example.pop("image")] + images = [example["images"] for example in examples] * 2 # repeat for chosen and rejected + # Transformers requires at least one image in the batch, otherwise it throws an error + if all(img_list == [] for img_list in images): + images = None + if is_conversational(examples[0]): # conversational case + for example in examples: + example["prompt"] = prepare_multimodal_messages(example["prompt"], images=example["images"]) + example["chosen"] = prepare_multimodal_messages(example["chosen"]) + example["rejected"] = prepare_multimodal_messages(example["rejected"]) + examples = [apply_chat_template(example, self.processor) for example in examples] + + prompts = [example["prompt"] for example in examples] * 2 # repeat for chosen and rejected + chosens = [example["chosen"] for example in examples] + rejecteds = [example["rejected"] for example in examples] + + processed_prompts = self.processor( + images=images, + text=prompts, + padding=True, + padding_side="left", + return_tensors=self.return_tensors, + add_special_tokens=False, # to avoid adding the BOS, twice see https://huggingface.co/blog/qgallouedec/gotchas-in-tokenizer-behavior#7-chat-template-and-tokenization-dont-compose-due-to-special-tokens + ) + processed_chosens = self.processor( + text=chosens, + padding=True, + padding_side="right", + return_tensors=self.return_tensors, + add_special_tokens=False, # to avoid adding the BOS, twice see https://huggingface.co/blog/qgallouedec/gotchas-in-tokenizer-behavior#7-chat-template-and-tokenization-dont-compose-due-to-special-tokens + ) + processed_rejecteds = self.processor( + text=rejecteds, + padding=True, + padding_side="right", + return_tensors=self.return_tensors, + add_special_tokens=False, # to avoid adding the BOS, twice see https://huggingface.co/blog/qgallouedec/gotchas-in-tokenizer-behavior#7-chat-template-and-tokenization-dont-compose-due-to-special-tokens + ) + + # Concatenate prompts and completions + prompt_ids, prompt_mask = processed_prompts["input_ids"], processed_prompts["attention_mask"] + chosen_ids, chosen_mask = processed_chosens["input_ids"], processed_chosens["attention_mask"] + rejected_ids, rejected_mask = processed_rejecteds["input_ids"], processed_rejecteds["attention_mask"] + pad_token_id = self.processor.tokenizer.pad_token_id or self.processor.tokenizer.eos_token_id + completion_ids = torch.cat(tuple(pad([chosen_ids, rejected_ids], padding_value=pad_token_id))) + completion_mask = torch.cat(tuple(pad([chosen_mask, rejected_mask], padding_value=0))) + input_ids = torch.cat((prompt_ids, completion_ids), dim=1) + attention_mask = torch.cat((prompt_mask, completion_mask), dim=1) + completion_mask = torch.cat((torch.zeros_like(prompt_mask), completion_mask), dim=1) + if "token_type_ids" in processed_prompts: # special case for Gemma + prompt_token_type_ids = processed_prompts["token_type_ids"] + chosen_type_ids = processed_chosens["token_type_ids"] + rejected_type_ids = processed_rejecteds["token_type_ids"] + completion_token_type_ids = torch.cat(tuple(pad([chosen_type_ids, rejected_type_ids], padding_value=0))) + token_type_ids = torch.cat((prompt_token_type_ids, completion_token_type_ids), dim=1) + if "mm_token_type_ids" in processed_prompts: # special case for Qwen2.5-VL + prompt_mm_token_type_ids = processed_prompts["mm_token_type_ids"] + mm_token_type_ids = torch.cat((prompt_mm_token_type_ids, torch.zeros_like(completion_ids)), dim=1) + + # Flush left to reduce padding + if "token_type_ids" in processed_prompts and "mm_token_type_ids" in processed_prompts: + attention_mask, input_ids, completion_mask, token_type_ids, mm_token_type_ids = flush_left( + attention_mask, input_ids, completion_mask, token_type_ids, mm_token_type_ids + ) + elif "token_type_ids" in processed_prompts: + attention_mask, input_ids, completion_mask, token_type_ids = flush_left( + attention_mask, input_ids, completion_mask, token_type_ids + ) + elif "mm_token_type_ids" in processed_prompts: + attention_mask, input_ids, completion_mask, mm_token_type_ids = flush_left( + attention_mask, input_ids, completion_mask, mm_token_type_ids + ) + else: + attention_mask, input_ids, completion_mask = flush_left(attention_mask, input_ids, completion_mask) + + if self.max_length is not None: + input_ids = input_ids[:, : self.max_length] + attention_mask = attention_mask[:, : self.max_length] + completion_mask = completion_mask[:, : self.max_length] + if "token_type_ids" in processed_prompts: + token_type_ids = token_type_ids[:, : self.max_length] + if "mm_token_type_ids" in processed_prompts: + mm_token_type_ids = mm_token_type_ids[:, : self.max_length] + + # Build the output dictionary + output = processed_prompts # we take processed_prompts because it contains the images + output["input_ids"] = input_ids + output["attention_mask"] = attention_mask + output["completion_mask"] = completion_mask + if "token_type_ids" in processed_prompts: + output["token_type_ids"] = token_type_ids + if "mm_token_type_ids" in processed_prompts: + output["mm_token_type_ids"] = mm_token_type_ids + return output + + +class DPOTrainer(_BaseTrainer): + """ + Trainer for Direct Preference Optimization (DPO) method. This algorithm was initially proposed in the paper [Direct + Preference Optimization: Your Language Model is Secretly a Reward Model](https://huggingface.co/papers/2305.18290). + This class is a wrapper around the [`~transformers.Trainer`] class and inherits all of its attributes and methods. + + Example: + + ```python + from trl import DPOTrainer + from datasets import load_dataset + + dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train") + + trainer = DPOTrainer( + model="Qwen/Qwen2.5-0.5B-Instruct", + train_dataset=dataset, + ) + trainer.train() + ``` + + Args: + model (`str` or [`~transformers.PreTrainedModel`] or [`~peft.PeftModel`]): + Model to be trained. Can be either: + + - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a + path to a *directory* containing model weights saved using + [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded + using `.from_pretrained` (where `` is derived from the model + config) with the keyword arguments in `args.model_init_kwargs`. + - A [`~transformers.PreTrainedModel`] object. Only causal language models are supported. + - A [`~peft.PeftModel`] object. Only causal language models are supported. + ref_model ([`~transformers.PreTrainedModel`], *optional*): + Reference model used to compute the reference log probabilities. + + - If provided, this model is used directly as the reference policy. + - If `None`, the trainer will automatically use the initial policy corresponding to `model`, i.e. the model + state before DPO training starts. + args ([`DPOConfig`], *optional*): + Configuration for this trainer. If `None`, a default configuration is used. + data_collator ([`~transformers.DataCollator`], *optional*): + Function to use to form a batch from a list of elements of the processed `train_dataset` or `eval_dataset`. + Will default to [`~trainer.dpo_trainer.DataCollatorForPreference`] if the model is a language model and + [`~trainer.dpo_trainer.DataCollatorForVisionPreference`] if the model is a vision-language model. Custom + collators must truncate sequences before padding; the trainer does not apply post-collation truncation. + train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]): + Dataset to use for training. This trainer supports both [language modeling](#language-modeling) type and + [prompt-completion](#prompt-completion) type. The format of the samples can be either: + + - [Standard](dataset_formats#standard): Each sample contains plain text. + - [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role + and content). + eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Dataset | IterableDataset]`): + Dataset to use for evaluation. It must meet the same requirements as `train_dataset`. + processing_class ([`~transformers.PreTrainedTokenizerBase`] or [`~transformers.ProcessorMixin`], *optional*): + Processing class used to process the data. The padding side must be set to "left". If `None`, the + processing class is loaded from the model's name with [`~transformers.AutoProcessor.from_pretrained`]. A + padding token, `tokenizer.pad_token`, must be set. If the processing class has not set a padding token, + `tokenizer.eos_token` will be used as the default. + compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*): + The function that will be used to compute metrics at evaluation. Must take a + [`~transformers.EvalPrediction`] and return a dictionary string to metric values. When passing + [`SFTConfig`] with `batch_eval_metrics` set to `True`, your `compute_metrics` function must take a boolean + `compute_result` argument. This will be triggered after the last eval batch to signal that the function + needs to calculate and return the global summary statistics rather than accumulating the batch-level + statistics. + callbacks (list of [`~transformers.TrainerCallback`], *optional*): + List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed + in [here](https://huggingface.co/docs/transformers/main_classes/callback). + + If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`] + method. + optimizers (`tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None]`, *optional*, defaults to `(None, None)`): + A tuple containing the optimizer and the scheduler to use. Will default to an instance of `AdamW` on your + model and a scheduler given by [`~transformers.get_linear_schedule_with_warmup`] controlled by `args`. + peft_config ([`~peft.PeftConfig`], *optional*): + PEFT configuration used to wrap the model. If `None`, the model is not wrapped. + """ + + _tag_names = ["trl", "dpo"] + _name = "DPO" + _paper = { + "title": "Direct Preference Optimization: Your Language Model is Secretly a Reward Model", + "id": "2305.18290", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @inproceedings{rafailov2023direct, + title = {{Direct Preference Optimization: Your Language Model is Secretly a Reward Model}}, + author = {Rafael Rafailov and Archit Sharma and Eric Mitchell and Christopher D. Manning and Stefano Ermon and Chelsea Finn}, + year = 2023, + booktitle = {Advances in Neural Information Processing Systems 36: Annual Conference on Neural Information Processing Systems 2023, NeurIPS 2023, New Orleans, LA, USA, December 10 - 16, 2023}, + url = {http://papers.nips.cc/paper_files/paper/2023/hash/a85b405ed65c6477a4fe8302b5e06ce7-Abstract-Conference.html}, + editor = {Alice Oh and Tristan Naumann and Amir Globerson and Kate Saenko and Moritz Hardt and Sergey Levine}, + }"""), + } + + def __init__( + self, + model: "str | PreTrainedModel | PeftModel", + ref_model: PreTrainedModel | None = None, + args: DPOConfig | None = None, + data_collator: DataCollator | None = None, + train_dataset: Dataset | IterableDataset | None = None, + eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None, + processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None, + compute_metrics: Callable[[EvalPrediction], dict] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None), + peft_config: "PeftConfig | None" = None, + ): + # Args + if args is None: + model_name = model if isinstance(model, str) else get_config_model_id(model.config) + model_name = model_name.split("/")[-1] + args = DPOConfig(f"{model_name}-DPO") + + if train_dataset is None: + raise ValueError("`train_dataset` is required") + elif isinstance(train_dataset, IterableDataset): + # IterableDataset requires dispatch_batches=False because Accelerate's dispatch mode may try to concatenate + # batches from multiple processes, leading to mismatch errors. + if args.accelerator_config.dispatch_batches is True: + logger.warning( + "You are using an `IterableDataset` for training with `dispatch_batches=True`. `dispatch_batches` " + "is forced to `False` when using an `IterableDataset`. To remove this warning, unset " + "`dispatch_batches` in `DPOConfig` or set it to `False`." + ) + args.accelerator_config.dispatch_batches = False + + # Model + if isinstance(model, str): + model_init_kwargs = args.model_init_kwargs or {} + # Distributed training requires device_map=None ("auto" fails) + if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + model_init_kwargs["device_map"] = None + model = create_model_from_path(model, **model_init_kwargs) + else: + if args.model_init_kwargs is not None: + logger.warning( + "You passed `model_init_kwargs` to the `DPOConfig`, but your model is already instantiated. " + "The `model_init_kwargs` will be ignored." + ) + if ref_model is model: + raise ValueError( + "`model` and `ref_model` cannot be the same object. In most cases you should omit `ref_model` and " + "we'll initialize it to a copy of `model` for you." + ) + + # Processing class + if processing_class is None: + processing_class = AutoProcessor.from_pretrained(get_config_model_id(model.config)) + + # Handle pad token for processors or tokenizers + if isinstance(processing_class, ProcessorMixin): + self._tokenizer = processing_class.tokenizer + self._is_vlm = True + elif isinstance(processing_class, PreTrainedTokenizerBase): + self._tokenizer = processing_class + self._is_vlm = False + else: + raise TypeError("The `processing_class` must be either a `PreTrainedTokenizerBase` or a `ProcessorMixin`") + + if self._tokenizer.pad_token is None: + self._tokenizer.pad_token = self._tokenizer.eos_token + + # PEFT + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + if is_peft_model(model): + raise ValueError( + "You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first merge " + "and unload the existing adapter, save the resulting base model, and then pass that base model along " + "with the new `peft_config` to the trainer." + ) + # Create PEFT model + model = get_peft_model(model, peft_config) + + elif is_peft_model(model) and ref_model is None: + # If the model is a PEFT model with a pretrained adapter, we need to create a "ref" adapter that is a copy + # of the "default" adapter, so that we can use it as the reference model during DPO training. + model.add_adapter("ref", model.peft_config["default"]) + for name, param in model.named_parameters(): + if ".default." in name: + ref_name = name.replace(".default.", ".ref.") + ref_param = model.get_parameter(ref_name) + ref_param.data.copy_(param.data) + + # When using gradient checkpointing with PEFT, we need to enable input gradients. transformers.Trainer normally + # handles this, but a bug currently prevents it; see https://github.com/huggingface/transformers/issues/42489 + if is_peft_model(model) and args.gradient_checkpointing: + model.enable_input_require_grads() + + # When using QLoRA, the PEFT adapter weights are converted to bf16 to follow the recommendations from the + # original paper (see https://huggingface.co/papers/2305.14314, paragraph 3). Normally, this can be done by + # passing `autocast_adapter_dtype=False` to `get_peft_model`, but this option is not yet supported for + # quantized models. See: https://github.com/huggingface/peft/issues/2889 + # Non-quantized models do not have the `is_loaded_in_{8,4}bit` attributes, whereas quantized models do + if getattr(model, "is_loaded_in_4bit", False) or getattr(model, "is_loaded_in_8bit", False): + for param in model.parameters(): + if param.requires_grad: + param.data = param.data.to(torch.bfloat16) + + # Data collator + self.padding_free = args.padding_free + if self.padding_free: + logger.warning( + "`padding_free=True` is temporarily unavailable after a refactor and is currently disabled. Falling " + "back to standard padding (`padding_free=False`). This feature is planned to return in a future " + "update; for now, please set `padding_free=False` explicitly." + ) + self.padding_free = False + dataset_sample = next(iter(train_dataset)) + self._is_vision_dataset = "image" in dataset_sample or "images" in dataset_sample + if self._is_vision_dataset and not self._is_vlm: + raise ValueError( + "The dataset appears to be vision-related (contains 'image' or 'images' keys), but the provided " + "model does not seem to be a vision-language model. Please check your model and dataset." + ) + if self._is_vision_dataset and args.max_length is not None and args.truncation_mode == "keep_end": + raise ValueError( + "truncation_mode='keep_end' is not supported for vision-language models. Image tokens reside " + "inside the prompt portion of the sequence; depending on the example, keep_end may silently " + "drop them, causing pixel_values to be forwarded to the model with no corresponding visual " + "tokens in input_ids. Use truncation_mode='keep_start' (the default) or set max_length=None." + ) + if self._is_vision_dataset and args.precompute_ref_log_probs: + raise ValueError( + "`precompute_ref_log_probs=True` is not supported for vision datasets. For vision-language " + "models, all data processing is performed on the fly rather than upfront, and running a full " + "forward pass of the reference model over the entire dataset is not supported for large " + "multimodal models. Set `precompute_ref_log_probs=False`." + ) + if data_collator is None and not self._is_vision_dataset: + # Get the pad token: if not provided, use the one from the processing class or the eos token + # if the processing class does not have a pad token. + pad_token = args.pad_token or self._tokenizer.pad_token or self._tokenizer.eos_token + if pad_token not in self._tokenizer.get_vocab(): + raise ValueError( + f"The specified `pad_token` ('{pad_token}') is not found in the vocabulary of the given " + f"`processing_class` ({processing_class.__class__.__name__}). Ensure that the `pad_token` exists " + "in the vocabulary before using it as a padding token." + ) + self._tokenizer.pad_token = pad_token + data_collator = DataCollatorForPreference( + pad_token_id=self._tokenizer.pad_token_id, + max_length=args.max_length, + truncation_mode=args.truncation_mode, + pad_to_multiple_of=args.pad_to_multiple_of, + ) + elif data_collator is None and self._is_vision_dataset: + data_collator = DataCollatorForVisionPreference( + processor=processing_class, + max_length=args.max_length, + pad_to_multiple_of=args.pad_to_multiple_of, + ) + + # Training arguments + self.beta = args.beta + self.precompute_ref_logps = args.precompute_ref_log_probs + self.loss_types = args.loss_type # args.loss_type is already a list + self.loss_weights = args.loss_weights or [1.0] * len(self.loss_types) + self.ld_alpha = args.ld_alpha + self.f_divergence_type = args.f_divergence_type + self.f_alpha_divergence_coef = args.f_alpha_divergence_coef + self.label_smoothing = args.label_smoothing + self.use_weighting = args.use_weighting + if self.use_weighting and any(loss_type in {"aot", "aot_unpaired"} for loss_type in self.loss_types): + raise NotImplementedError( + "WPO-style weighting is not implemented for 'aot' or 'aot_unpaired' because those losses sort " + "samples, which would misalign per-pair weights." + ) + if "robust" in self.loss_types and not (0.0 <= self.label_smoothing < 0.5): + logger.warning( + "The `label_smoothing` parameter should lie in [0.0, 0.5) for the 'robust' loss. You provided " + f"{self.label_smoothing}." + ) + if "exo_pair" in self.loss_types and self.label_smoothing == 0.0: + raise ValueError( + "Label smoothing must be greater than 0.0 when using 'exo_pair' loss. The EXO paper recommends a " + "value of 1e-3." + ) + self.use_liger_kernel = args.use_liger_kernel + if args.use_liger_kernel: + if not is_liger_kernel_available(): + raise ImportError( + "You set `use_liger_kernel=True` but the liger kernel is not available. " + "Please install liger-kernel first: `pip install liger-kernel`" + ) + if len(self.loss_types) != 1: + raise NotImplementedError( + "Multiple loss types are not yet supported when using Liger kernel. If you need this feature, " + "please open a feature request at https://github.com/huggingface/trl/issues." + ) + self.liger_loss_fn = LigerFusedLinearDPOLoss(beta=args.beta, loss_type=self.loss_types[0]) + if compute_metrics is not None: + raise ValueError( + "compute_metrics is not supported with the Liger kernel. compute_metrics requires to be able to " + "recover the logits from the forward pass, but Liger kernel does not materialize logits." + ) + if self.precompute_ref_logps: + raise ValueError( + "Liger DPO loss does not support precomputing reference log probabilities. Either disable " + "`precompute_ref_log_probs` or set `use_liger_kernel` to False." + ) + if is_peft_model(model): + raise NotImplementedError("Liger DPO loss is not implemented for PEFT models.") + + # Dataset + # Skip dataset preparation if it's a VLM, where preprocessing (e.g., image-to-pixel conversion) is too costly + # and done on the fly instead. + skip_prepare_dataset = self._is_vision_dataset + if not skip_prepare_dataset: + train_dataset = self._prepare_dataset(train_dataset, processing_class, args, "train") + if eval_dataset is not None: + if isinstance(eval_dataset, dict): + eval_dataset = { + key: self._prepare_dataset(dataset, processing_class, args, key) + for key, dataset in eval_dataset.items() + } + else: + eval_dataset = self._prepare_dataset(eval_dataset, processing_class, args, "eval") + + # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was + # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream + # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we + # default to the recommended non-reentrant behavior here, while preserving any user-provided value. + if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"): + args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {} + args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False) + + super().__init__( + model=model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + ) + + # Initialize activation offloading context + if self.args.activation_offloading: + self.maybe_activation_offload_context = get_act_offloading_ctx_manager(model=self.model) + else: + self.maybe_activation_offload_context = contextlib.nullcontext() + + # Reference model + if ref_model is None: + if is_peft_model(self.model) or args.precompute_ref_log_probs: + # If PEFT is used, the reference model is not needed since the adapter can be disabled to revert to the + # initial model. If precompute_ref_log_probs is True, the reference model does not need to be kept in + # memory during training. + self.ref_model = None + else: + ref_model_init_kwargs = args.model_init_kwargs or {} + # Distributed training requires device_map=None ("auto" fails) + if self.args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + ref_model_init_kwargs["device_map"] = None + ref_model_path = get_config_model_id(self.model.config) + self.ref_model = create_model_from_path(ref_model_path, **ref_model_init_kwargs) + else: + self.ref_model = ref_model + + # Disable dropout in the models + if args.disable_dropout: + disable_dropout_in_model(model) + if self.ref_model is not None: + disable_dropout_in_model(self.ref_model) + + # Initialize the metrics + self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)} + self._total_train_tokens = 0 + + # Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the + # model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set + # self.model_accepts_loss_kwargs to False to enable scaling. + self.model_accepts_loss_kwargs = False + + # Add tags to the model + self.model.add_model_tags(self._tag_names) + + if self.ref_model is not None: + if self.is_deepspeed_enabled: + self.ref_model = prepare_deepspeed(self.ref_model, self.accelerator) + elif self.is_fsdp_enabled: + self.ref_model = prepare_fsdp(self.ref_model, self.accelerator) + else: + self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True) + + if args.sync_ref_model: + if is_peft_model(self.model): + raise NotImplementedError( + "You passed `sync_ref_model=True` while using a PEFT model, which is currently not supported. " + "With PEFT, DPOTrainer does not keep a separate reference model in memory; instead, it recovers " + "reference behavior by temporarily disabling the adapter. As a result, there is no standalone " + "`ref_model` instance to synchronize. Use `sync_ref_model=False`, or opt for full fine-tuning if " + "you need a synced reference model. If you need `sync_ref_model` to work with PEFT, please open a " + "feature request at https://github.com/huggingface/trl/issues." + ) + if args.precompute_ref_log_probs: + raise ValueError( + "You cannot use `sync_ref_model=True` together with `precompute_ref_log_probs=True`. " + "`precompute_ref_log_probs=True` assumes a fixed reference model, but with `sync_ref_model=True` " + "the reference model is periodically updated during training, making any precomputed reference " + "log-probs stale. Set `precompute_ref_log_probs=False` or disable `sync_ref_model`." + ) + self.add_callback(SyncRefModelCallback(ref_model=self.ref_model, accelerator=self.accelerator)) + + if args.precompute_ref_log_probs: + if isinstance(self.train_dataset, IterableDataset) or isinstance( + self.eval_dataset, (IterableDataset, IterableDatasetDict) + ): + raise ValueError( + "`precompute_ref_log_probs=True` is not supported with IterableDataset. Please use a map-style " + "Dataset or set `precompute_ref_log_probs=False`." + ) + + self.train_dataset = self._precompute_ref_logps( + self.train_dataset, + "train", + self.args.precompute_ref_batch_size or self.args.per_device_train_batch_size, + ) + if self.eval_dataset is not None: + if isinstance(self.eval_dataset, dict): + self.eval_dataset = { + name: self._precompute_ref_logps( + dataset, name, self.args.precompute_ref_batch_size or self.args.per_device_eval_batch_size + ) + for name, dataset in self.eval_dataset.items() + } + else: + self.eval_dataset = self._precompute_ref_logps( + self.eval_dataset, + "eval", + self.args.precompute_ref_batch_size or self.args.per_device_eval_batch_size, + ) + + def _tokenize( + self, + processing_class: PreTrainedTokenizerBase | ProcessorMixin, + input: str | list, + **kwargs, + ) -> dict[str, list]: + """Tokenize a single example for dataset preprocessing. + + Dispatches to `apply_chat_template` for conversational input (list of message dicts) and to `__call__` for + non-conversational input (str). For VLMs, normalizes the batch dimension that processors emit even for single + examples. + + Args: + processing_class ([`~transformers.PreTrainedTokenizerBase`] or [`~transformers.ProcessorMixin`]): + The tokenizer or processor to use. + input (`str` or `list`): + A string for non-conversational input, or a list of message dicts for conversational input. + **kwargs: + Forwarded to `apply_chat_template` (e.g. `add_generation_prompt`, `return_assistant_tokens_mask`). + + Returns: + `dict` with at least an `"input_ids"` key mapping to a flat `list[int]`. + """ + if isinstance(input, list): # conversational: list of message dicts + if self._is_vlm: + input = prepare_multimodal_messages(input) + result = processing_class.apply_chat_template(input, tokenize=True, return_dict=True, **kwargs) + else: # non-conversational: plain text string + result = processing_class(text=input) + # VLMs emit a batch dimension even for single examples; unwrap it + if self._is_vlm: + return {k: v[0] for k, v in result.items()} + return result + + def _prepare_dataset( + self, + dataset: Dataset | IterableDataset, + processing_class: PreTrainedTokenizerBase | ProcessorMixin, + args: DPOConfig, + dataset_name: str, + ) -> Dataset | IterableDataset: + # Build the kwargs for the `map` function + map_kwargs = {} + if isinstance(dataset, Dataset): # IterableDataset does not support num_proc + map_kwargs["num_proc"] = args.dataset_num_proc + + with PartialState().main_process_first(): + # Extract the prompt if needed + first_example = next(iter(dataset)) + if "prompt" not in first_example: + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Extracting prompt from {dataset_name} dataset" + dataset = dataset.map(extract_prompt, **map_kwargs) + + # Add EOS token if needed: non-conversational only + first_example = next(iter(dataset)) + if not is_conversational(first_example): + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Adding EOS to {dataset_name} dataset" + + def add_eos(example, eos_token): + if not example["chosen"].endswith(eos_token): + example["chosen"] = example["chosen"] + eos_token + if not example["rejected"].endswith(eos_token): + example["rejected"] = example["rejected"] + eos_token + return example + + dataset = dataset.map(add_eos, fn_kwargs={"eos_token": self._tokenizer.eos_token}, **map_kwargs) + + # Tokenize the dataset + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Tokenizing {dataset_name} dataset" + + def tokenize_fn(example, processing_class): + tools = example.get("tools") + tools = json.loads(tools) if isinstance(tools, str) else tools + output = {} + if is_conversational(example): + prompt_ids = self._tokenize( + processing_class, + example["prompt"], + tools=tools, + add_generation_prompt=True, + **example.get("chat_template_kwargs", {}), + )["input_ids"] + prompt_chosen_ids = self._tokenize( + processing_class, + example["prompt"] + example["chosen"], + tools=tools, + **example.get("chat_template_kwargs", {}), + )["input_ids"] + prompt_rejected_ids = self._tokenize( + processing_class, + example["prompt"] + example["rejected"], + tools=tools, + **example.get("chat_template_kwargs", {}), + )["input_ids"] + else: + prompt_ids = self._tokenize(processing_class, example["prompt"])["input_ids"] + prompt_chosen_ids = self._tokenize(processing_class, example["prompt"] + example["chosen"])[ + "input_ids" + ] + prompt_rejected_ids = self._tokenize(processing_class, example["prompt"] + example["rejected"])[ + "input_ids" + ] + + # Check if the tokenized prompt starts with the tokenized prompt+completion + if not prompt_chosen_ids[: len(prompt_ids)] == prompt_ids: + logger.warning( + "Mismatch between tokenized prompt and the start of tokenized prompt+chosen. " + "This may be due to unexpected tokenizer behavior, whitespace issues, or special " + "token handling. Verify that the tokenizer is processing text consistently." + ) + if not prompt_rejected_ids[: len(prompt_ids)] == prompt_ids: + logger.warning( + "Mismatch between tokenized prompt and the start of tokenized prompt+rejected. " + "This may be due to unexpected tokenizer behavior, whitespace issues, or special " + "token handling. Verify that the tokenizer is processing text consistently." + ) + + output["prompt_ids"] = prompt_ids + output["chosen_ids"] = prompt_chosen_ids[len(prompt_ids) :] + output["rejected_ids"] = prompt_rejected_ids[len(prompt_ids) :] + return output + + dataset = dataset.map(tokenize_fn, fn_kwargs={"processing_class": processing_class}, **map_kwargs) + + return dataset + + def _set_signature_columns_if_needed(self): + # If `self.args.remove_unused_columns` is True, non-signature columns are removed. + # By default, this method sets `self._signature_columns` to the model's expected inputs (usually, "input_ids" + # and "attention_mask"). + if self._signature_columns is None: + if self._is_vision_dataset: + self._signature_columns = [ + "prompt", + "chosen", + "rejected", + "image", + "images", + "tools", + "chat_template_kwargs", + ] + else: + self._signature_columns = [ + "prompt_ids", + "chosen_ids", + "rejected_ids", + "ref_chosen_logps", + "ref_rejected_logps", + ] + + def _precompute_ref_logps(self, dataset: Dataset, name: str, batch_size: int) -> Dataset: + model_hash = hash_module(self.ref_model or self.model) + fingerprint = Hasher.hash((dataset._fingerprint, model_hash)) + cache_file = dataset._get_cache_file_path(fingerprint) + + if os.path.exists(cache_file): + return concatenate_datasets([dataset, Dataset.from_file(cache_file)], axis=1) + + dataloader = DataLoader( + dataset, + batch_size=batch_size, + collate_fn=self.data_collator, + num_workers=self.args.dataloader_num_workers, + pin_memory=self.args.dataloader_pin_memory, + shuffle=False, + ) + data_loader = self.accelerator.prepare(dataloader) + ref_chosen_logps = [] + ref_rejected_logps = [] + for padded_batch in tqdm(iterable=data_loader, desc=f"Computing reference log probs for {name} dataset"): + ref_chosen_logp, ref_rejected_logp = self.compute_ref_log_probs(padded_batch) + ref_chosen_logp, ref_rejected_logp = self.accelerator.gather_for_metrics( + (ref_chosen_logp, ref_rejected_logp) + ) + ref_chosen_logps.append(ref_chosen_logp.cpu()) + ref_rejected_logps.append(ref_rejected_logp.cpu()) + + ref_chosen_logps = torch.cat(ref_chosen_logps) + ref_rejected_logps = torch.cat(ref_rejected_logps) + + if self.accelerator.is_main_process: + + def add_ref_logps(batch, indices): + return { + "ref_chosen_logps": ref_chosen_logps[indices], + "ref_rejected_logps": ref_rejected_logps[indices], + } + + dataset.map( + add_ref_logps, + with_indices=True, + batched=True, + remove_columns=dataset.column_names, + new_fingerprint=fingerprint, + desc=f"Caching reference log probs for {name} dataset", + ) + self.accelerator.wait_for_everyone() + + return concatenate_datasets([dataset, Dataset.from_file(cache_file)], axis=1) + + def compute_ref_log_probs(self, inputs): + """Computes reference log probabilities for a single padded batch.""" + device = self.accelerator.device + + _non_model_keys = {"completion_mask", "ref_chosen_logps", "ref_rejected_logps"} + model_kwargs = {k: v for k, v in inputs.items() if k not in _non_model_keys} + model_kwargs["use_cache"] = False + + with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs): + if self.ref_model is None: + if is_peft_model(self.model): + model = self.accelerator.unwrap_model(self.model) + with use_adapter(model, adapter_name="ref" if "ref" in model.peft_config else None): + ref_outputs = self.model(**model_kwargs) + else: + ref_outputs = self.model(**model_kwargs) + else: + ref_outputs = self.ref_model(**model_kwargs) + + input_ids = inputs["input_ids"] + completion_mask = inputs["completion_mask"] + shift_labels = input_ids[..., 1:] + shift_completion_mask = completion_mask[..., 1:] + ref_shift_logits = ref_outputs.logits[..., :-1, :] + ref_per_token_logps = selective_log_softmax(ref_shift_logits, shift_labels) + ref_per_token_logps[shift_completion_mask == 0] = 0.0 + + if self.ld_alpha is None: + ref_logps = ref_per_token_logps.sum(dim=1) + else: + comp_pos = shift_completion_mask.cumsum(dim=1) + comp_lens = shift_completion_mask.sum(dim=1).long() + chosen_lens, rejected_lens = comp_lens.chunk(2, dim=0) + shared_lens = torch.minimum(chosen_lens, rejected_lens) + shared_lens = torch.cat([shared_lens, shared_lens], dim=0).to(device) + shared_mask = (comp_pos > 0) & (comp_pos <= shared_lens.unsqueeze(1)) + tail_mask = comp_pos > shared_lens.unsqueeze(1) + shared_logps = (ref_per_token_logps * shared_mask).sum(dim=1) + tail_logps = (ref_per_token_logps * tail_mask).sum(dim=1) + ref_logps = shared_logps + self.ld_alpha * tail_logps + + ref_chosen_logps, ref_rejected_logps = ref_logps.chunk(2, dim=0) + return ref_chosen_logps, ref_rejected_logps + + def _compute_loss_liger(self, model, inputs, return_outputs): + if return_outputs: + raise RuntimeError( + "return_outputs=True is not supported with the Liger DPO loss. The Liger loss computes the loss " + "without materializing logits, so outputs cannot be returned." + ) + + mode = "train" if self.model.training else "eval" + + _non_model_keys = {"completion_mask", "ref_chosen_logps", "ref_rejected_logps"} + model_kwargs = {k: v for k, v in inputs.items() if k not in _non_model_keys} + model_kwargs["use_cache"] = False + + # `base_model` gives the backbone model (skipping `lm_head`) — text decoder for LMs, multimodal wrapper for + # VLMs (so vision-token injection runs before the text decoder). `get_decoder()` won't do: on VLMs it + # returns just the text stack and feeds image-placeholder IDs through it. + # Pre-5.0 transformers VLMs set `base_model_prefix = ""` so `base_model is self` (re-runs `lm_head`). + # Fall back to `.model` there. + if self._is_vlm and Version(transformers.__version__) < Version("5.0.0"): + backbone, ref_backbone = model.model, self.ref_model.model + else: + backbone, ref_backbone = model.base_model, self.ref_model.base_model + + outputs = backbone(**model_kwargs) + hidden_states = outputs.last_hidden_state[:, :-1].contiguous() + lm_head = model.get_output_embeddings() + weight = lm_head.weight + bias = lm_head.bias + + with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs): + ref_outputs = ref_backbone(**model_kwargs) + ref_lm_head = self.ref_model.get_output_embeddings() + ref_hidden_states = ref_outputs.last_hidden_state[:, :-1].contiguous() + ref_weight = ref_lm_head.weight + ref_bias = ref_lm_head.bias + + input_ids = model_kwargs["input_ids"] + completion_mask = inputs["completion_mask"] + shift_completion_mask = completion_mask[:, 1:].contiguous() + labels = input_ids[:, 1:].clone() + labels[shift_completion_mask == 0] = -100 + + loss, metrics = self.liger_loss_fn( + weight, hidden_states, labels, bias, ref_hidden_states, ref_weight, ref_bias + ) + + ( + chosen_logps, + rejected_logps, + chosen_logits_mean, + rejected_logits_mean, + nll_loss, + chosen_rewards, + rejected_rewards, + ) = metrics + + if mode == "train": + num_tokens_in_batch = self.accelerator.gather_for_metrics(inputs["attention_mask"].sum()).sum().item() + self._total_train_tokens += num_tokens_in_batch + self._metrics[mode]["num_tokens"] = [self._total_train_tokens] + + avg_chosen_logits = self.accelerator.gather_for_metrics(chosen_logits_mean).mean().item() + avg_rejected_logits = self.accelerator.gather_for_metrics(rejected_logits_mean).mean().item() + self._metrics[mode]["logits/chosen"].append(avg_chosen_logits) + self._metrics[mode]["logits/rejected"].append(avg_rejected_logits) + + agg_chosen_rewards = self.accelerator.gather(chosen_rewards) + agg_rejected_rewards = self.accelerator.gather(rejected_rewards) + self._metrics[mode]["rewards/chosen"].append(agg_chosen_rewards.mean().item()) + self._metrics[mode]["rewards/rejected"].append(agg_rejected_rewards.mean().item()) + + reward_accuracies = (chosen_rewards > rejected_rewards).float() + agg_reward_accuracies = self.accelerator.gather(reward_accuracies) + self._metrics[mode]["rewards/accuracies"].append(agg_reward_accuracies.mean().item()) + + margins = chosen_rewards - rejected_rewards + agg_margins = self.accelerator.gather(margins) + self._metrics[mode]["rewards/margins"].append(agg_margins.mean().item()) + + self._metrics[mode]["logps/chosen"].append(self.accelerator.gather(chosen_logps).mean().item()) + self._metrics[mode]["logps/rejected"].append(self.accelerator.gather(rejected_logps).mean().item()) + + return loss + + def _compute_loss(self, model, inputs, return_outputs): + mode = "train" if self.model.training else "eval" + device = self.accelerator.device + + _non_model_keys = {"completion_mask", "ref_chosen_logps", "ref_rejected_logps"} + model_kwargs = {k: v for k, v in inputs.items() if k not in _non_model_keys} + model_kwargs["use_cache"] = False + outputs = model(**model_kwargs) + + input_ids = inputs["input_ids"] + completion_mask = inputs["completion_mask"] + shift_logits = outputs.logits[..., :-1, :] + shift_labels = input_ids[..., 1:] + shift_completion_mask = completion_mask[..., 1:] + per_token_logps = selective_log_softmax(shift_logits, shift_labels) + per_token_logps[shift_completion_mask == 0] = 0.0 # mask out non-completion tokens + if self.ld_alpha is None: + logps = per_token_logps.sum(dim=1) # sum over sequence length + else: + comp_pos = shift_completion_mask.cumsum(dim=1) + comp_lens = shift_completion_mask.sum(dim=1).long() + chosen_lens, rejected_lens = comp_lens.chunk(2, dim=0) + shared_lens = torch.minimum(chosen_lens, rejected_lens) + shared_lens = torch.cat([shared_lens, shared_lens], dim=0).to(device) + shared_mask = (comp_pos > 0) & (comp_pos <= shared_lens.unsqueeze(1)) # shared: 1 <= pos <= shared_len + tail_mask = comp_pos > shared_lens.unsqueeze(1) # tail: pos > shared_len + shared_logps = (per_token_logps * shared_mask).sum(dim=1) + tail_logps = (per_token_logps * tail_mask).sum(dim=1) + logps = shared_logps + self.ld_alpha * tail_logps + chosen_logps, rejected_logps = logps.chunk(2, dim=0) # batch is [chosen, rejected] + + if self.precompute_ref_logps: + ref_chosen_logps, ref_rejected_logps = inputs["ref_chosen_logps"], inputs["ref_rejected_logps"] + else: + # When gradient checkpointing is enabled with use_reentrant=True (default), calling the model inside a + # torch.no_grad() block triggers a harmless PyTorch warning ("None of the inputs have requires_grad=True"). + # Temporarily disable checkpointing to avoid this warning during inference. + with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs): + if is_peft_model(model) and self.ref_model is None: + # When training a PEFT adapter, how we obtain the reference depends on the setup: + # - New adapter: disabling adapters yields the base model. + # - Re-training an existing adapter: an initial copy is loaded under the name "ref". + model = self.accelerator.unwrap_model(model) + with use_adapter(model, adapter_name="ref" if "ref" in model.peft_config else None): + ref_outputs = self.model(**model_kwargs) + else: + ref_outputs = self.ref_model(**model_kwargs) + + ref_shift_logits = ref_outputs.logits[..., :-1, :] + ref_per_token_logps = selective_log_softmax(ref_shift_logits, shift_labels) + ref_per_token_logps[shift_completion_mask == 0] = 0.0 # mask out non-completion tokens + if self.ld_alpha is None: + ref_logps = ref_per_token_logps.sum(dim=1) # sum over sequence length + else: + # reuse comp_pos/shared_mask/tail_mask computed above (they depend only on completion_mask) + ref_shared_logps = (ref_per_token_logps * shared_mask).sum(dim=1) + ref_tail_logps = (ref_per_token_logps * tail_mask).sum(dim=1) + ref_logps = ref_shared_logps + self.ld_alpha * ref_tail_logps + ref_chosen_logps, ref_rejected_logps = ref_logps.chunk(2, dim=0) # batch is [chosen, rejected] + + # Get the log ratios for the chosen and rejected responses + chosen_logratios = chosen_logps - ref_chosen_logps + rejected_logratios = rejected_logps - ref_rejected_logps + + if self.f_divergence_type == "reverse_kl": # standard DPO + chosen_scores = chosen_logratios + rejected_scores = rejected_logratios + elif self.f_divergence_type == "forward_kl": + # f'(t) = 1 - 1/t -> drop constant -> -exp(-logratio) + chosen_scores = -torch.exp(-chosen_logratios) + rejected_scores = -torch.exp(-rejected_logratios) + elif self.f_divergence_type == "js_divergence": + # f'(t) = log(2t/(t+1)) -> drop log 2 + chosen_scores = F.logsigmoid(chosen_logratios) + rejected_scores = F.logsigmoid(rejected_logratios) + elif self.f_divergence_type == "alpha_divergence": + # alpha-divergence: f'(t) = (t^(α-1) - 1)/(α-1) + if abs(self.f_alpha_divergence_coef - 1.0) < 1e-6: # limit case f'(t) -> log(t), fall back to reverse_kl + chosen_scores = chosen_logratios + rejected_scores = rejected_logratios + else: + coef = 1.0 / (self.f_alpha_divergence_coef - 1.0) + t_chosen = (self.f_alpha_divergence_coef - 1.0) * chosen_logratios + t_rejected = (self.f_alpha_divergence_coef - 1.0) * rejected_logratios + dtype = t_chosen.dtype + # Clamp max so exp(.) stays representable after casting back + clamp_max = {torch.float16: 11.0, torch.bfloat16: 80.0, torch.float32: 80.0}[dtype] + t_chosen_float = torch.clamp(t_chosen.float(), max=clamp_max) + t_rejected_float = torch.clamp(t_rejected.float(), max=clamp_max) + chosen_scores = torch.exp(t_chosen_float).to(dtype) * coef + rejected_scores = torch.exp(t_rejected_float).to(dtype) * coef + else: + raise ValueError(f"Unknown f_divergence_type: {self.f_divergence_type}") + + delta_score = chosen_scores - rejected_scores + + loss = 0.0 + for loss_type, loss_weight in zip(self.loss_types, self.loss_weights, strict=True): + if loss_type == "sigmoid": + per_sequence_loss = -F.logsigmoid(self.beta * delta_score) + + elif loss_type == "hinge": + per_sequence_loss = torch.relu(1 - self.beta * delta_score) + + elif loss_type == "ipo": + # IPO uses sequence-level log-prob differences; in code these are token-summed over the completion, + # which makes the squared loss scale with completion length. We therefore normalize by the number of + # completion tokens (average per token) to make β/loss comparable across variable lengths. This length + # normalization is not explicitly discussed in the IPO paper; we confirmed this choice with the IPO + # authors, and the results reported in the paper correspond to this normalized form. + chosen_mask, rejected_mask = completion_mask.chunk(2, dim=0) + chosen_avg_score = chosen_scores / chosen_mask.sum(dim=1).clamp(min=1.0) + rejected_avg_score = rejected_scores / rejected_mask.sum(dim=1).clamp(min=1.0) + ipo_delta = chosen_avg_score - rejected_avg_score + # (Eq. 17) of the paper where beta is the regularization parameter for the IPO loss, denoted by τ. + per_sequence_loss = (ipo_delta - 1 / (2 * self.beta)) ** 2 + + elif loss_type == "exo_pair": + # Implements EXO-pref from the paper https://huggingface.co/papers/2402.00856, (Eq. 16) + # Minimize KL(p_fθ || p_rh) for K=2; p_fθ = softmax(βπ * (log πθ − log π_ref)) over {chosen, rejected} + # p_rh = [(1−ε), ε]; expanded KL gives the weighted logsigmoid form below + epsilon = torch.tensor(self.label_smoothing, device=device) + qw = torch.sigmoid(self.beta * delta_score) + log_qw = F.logsigmoid(self.beta * delta_score) + log_pw = torch.log1p(-epsilon) + ql = torch.sigmoid(-self.beta * delta_score) + log_ql = F.logsigmoid(-self.beta * delta_score) + log_pl = torch.log(epsilon) + per_sequence_loss = qw * (log_qw - log_pw) + ql * (log_ql - log_pl) + + elif loss_type == "nca_pair": + chosen_rewards = self.beta * chosen_scores + rejected_rewards = self.beta * rejected_scores + per_sequence_loss = ( + -F.logsigmoid(chosen_rewards) + - 0.5 * F.logsigmoid(-chosen_rewards) + - 0.5 * F.logsigmoid(-rejected_rewards) + ) + + elif loss_type == "robust": + clean_loss_term = -(1 - self.label_smoothing) * F.logsigmoid(self.beta * delta_score) + flipped_loss_term = -self.label_smoothing * F.logsigmoid(-self.beta * delta_score) + per_sequence_loss = (clean_loss_term - flipped_loss_term) / (1 - 2 * self.label_smoothing) + + elif loss_type == "bco_pair": + chosen_rewards = self.beta * chosen_scores + rejected_rewards = self.beta * rejected_scores + per_sequence_loss = -F.logsigmoid(chosen_rewards) - F.logsigmoid(-rejected_rewards) + + elif loss_type == "sppo_hard": + # In the paper (https://huggingface.co/papers/2405.00675), SPPO employs a soft probability approach, + # estimated using the PairRM score. The probability calculation is conducted outside of the trainer + # class. The version described here is the hard probability version, where P in Equation (4.7) of + # Algorithm 1 is set to 1 for the winner and 0 for the loser. + winner_margin_error = (chosen_scores - 0.5 / self.beta) ** 2 + loser_margin_error = (rejected_scores + 0.5 / self.beta) ** 2 + per_sequence_loss = winner_margin_error + loser_margin_error + + elif loss_type == "aot": + logratios = chosen_logps - rejected_logps + ref_logratios = ref_chosen_logps - ref_rejected_logps + logratios_sorted, _ = torch.sort(logratios, dim=0) + ref_logratios_sorted, _ = torch.sort(ref_logratios, dim=0) + delta = logratios_sorted - ref_logratios_sorted + per_sequence_loss = ( + -F.logsigmoid(self.beta * delta) * (1 - self.label_smoothing) + - F.logsigmoid(-self.beta * delta) * self.label_smoothing + ) + + elif loss_type == "aot_unpaired": + chosen_logratios_sorted, _ = torch.sort(chosen_logratios, dim=0) + rejected_logratios_sorted, _ = torch.sort(rejected_logratios, dim=0) + delta = chosen_logratios_sorted - rejected_logratios_sorted + per_sequence_loss = ( + -F.logsigmoid(self.beta * delta) * (1 - self.label_smoothing) + - F.logsigmoid(-self.beta * delta) * self.label_smoothing + ) + + elif loss_type == "apo_zero": + # Eqn (7) of the APO paper (https://huggingface.co/papers/2408.06266) + # Use this loss when you believe the chosen outputs are better than your model's default output + # Increase chosen likelihood and decrease rejected likelihood + losses_chosen = 1 - torch.sigmoid(self.beta * chosen_logratios) + losses_rejected = torch.sigmoid(self.beta * rejected_logratios) + per_sequence_loss = losses_chosen + losses_rejected + + elif loss_type == "apo_down": + # Eqn (8) of the APO paper (https://huggingface.co/papers/2408.06266) + # Use this loss when you believe the chosen outputs are worse than your model's default output. + # Decrease chosen likelihood and decrease rejected likelihood more + losses_chosen = torch.sigmoid(self.beta * chosen_logratios) + losses_rejected = 1 - torch.sigmoid(self.beta * delta_score) + per_sequence_loss = losses_chosen + losses_rejected + + elif loss_type == "discopop": + # Eqn (5) of the DiscoPOP paper (https://huggingface.co/papers/2406.08414) + logits = delta_score * self.beta + # Modulate the mixing coefficient based on the log ratio magnitudes + log_ratio_modulation = torch.sigmoid(logits / self.args.discopop_tau) + logistic_component = -F.logsigmoid(logits) + exp_component = torch.exp(-logits) + # Blend between logistic and exponential component based on log ratio modulation + per_sequence_loss = ( + logistic_component * (1 - log_ratio_modulation) + exp_component * log_ratio_modulation + ) + + elif loss_type == "sft": + chosen_logits, _ = shift_logits.chunk(2, dim=0) + chosen_labels, _ = shift_labels.chunk(2, dim=0) + chosen_mask, _ = shift_completion_mask.chunk(2, dim=0) + batch_loss = F.cross_entropy(chosen_logits[chosen_mask.bool()], chosen_labels[chosen_mask.bool()]) + # Implementation convenience: expand the scalar SFT loss to a per-sequence tensor so it matches the + # shape of other losses; only the mean is used, so this is a no-op numerically. + per_sequence_loss = batch_loss.expand(chosen_logits.size(0)) + + elif loss_type == "sigmoid_norm": + chosen_mask, rejected_mask = completion_mask.chunk(2, dim=0) + chosen_avg_score = chosen_scores / chosen_mask.sum(dim=1).clamp(min=1.0) + rejected_avg_score = rejected_scores / rejected_mask.sum(dim=1).clamp(min=1.0) + delta = chosen_avg_score - rejected_avg_score + per_sequence_loss = -F.logsigmoid(self.beta * delta) + + else: + raise ValueError( + f"Unknown loss type: {loss_type}. Should be one of ['sigmoid', 'hinge', 'ipo', 'exo_pair', " + "'nca_pair', 'robust', 'bco_pair', 'sppo_hard', 'aot', 'aot_unpaired', 'apo_zero', 'apo_down', " + "'discopop', 'sft', 'sigmoid_norm']" + ) + + if self.use_weighting: + # Eq (2) of the WPO paper: https://huggingface.co/papers/2406.11827 + completion_lengths = shift_completion_mask.sum(dim=1).clamp_min(1) + with torch.no_grad(): + lse1 = torch.logsumexp(shift_logits, dim=-1) + lse2 = torch.logsumexp(2.0 * shift_logits, dim=-1) + log_denom = lse2 - 2.0 * lse1 + aligned_logps = (per_token_logps - log_denom) * shift_completion_mask + mean_logps = aligned_logps.sum(dim=1) / completion_lengths + weights = torch.exp(mean_logps) + chosen_weights, rejected_weights = weights.chunk(2, dim=0) + per_sequence_loss *= chosen_weights * rejected_weights + + loss += per_sequence_loss.mean() * loss_weight + + # Log the metrics + # Entropy + per_token_entropy = entropy_from_logits(shift_logits.detach()) + mask = shift_completion_mask + entropy_sum = (per_token_entropy * mask).sum() + total_tokens = mask.sum() + + # Gather counts across ranks and weight-average + entropy_sum = self.accelerator.gather_for_metrics(entropy_sum).sum() + total_tokens = self.accelerator.gather_for_metrics(total_tokens).sum() + entropy = (entropy_sum / total_tokens).item() if total_tokens > 0 else 0.0 + self._metrics[mode]["entropy"].append(entropy) + + # Number of tokens + if mode == "train": + num_tokens_in_batch = self.accelerator.gather_for_metrics(inputs["attention_mask"].sum()).sum().item() + self._total_train_tokens += num_tokens_in_batch + self._metrics[mode]["num_tokens"] = [self._total_train_tokens] + + # Average logits for chosen and rejected completions + chosen_logits, rejected_logits = shift_logits.detach().chunk(2, dim=0) + chosen_mask, rejected_mask = shift_completion_mask.chunk(2, dim=0) + total_chosen_logits = chosen_logits[chosen_mask.bool()].mean(-1).sum() + total_chosen_tokens = chosen_mask.sum() + total_rejected_logits = rejected_logits[rejected_mask.bool()].mean(-1).sum() + total_rejected_tokens = rejected_mask.sum() + total_chosen_logits = self.accelerator.gather_for_metrics(total_chosen_logits).sum().item() + total_chosen_tokens = self.accelerator.gather_for_metrics(total_chosen_tokens).sum().item() + total_rejected_logits = self.accelerator.gather_for_metrics(total_rejected_logits).sum().item() + total_rejected_tokens = self.accelerator.gather_for_metrics(total_rejected_tokens).sum().item() + avg_chosen_logits = total_chosen_logits / total_chosen_tokens if total_chosen_tokens > 0 else 0.0 + avg_rejected_logits = total_rejected_logits / total_rejected_tokens if total_rejected_tokens > 0 else 0.0 + self._metrics[mode]["logits/chosen"].append(avg_chosen_logits) + self._metrics[mode]["logits/rejected"].append(avg_rejected_logits) + + # Token accuracy for the chosen completions + predictions = chosen_logits.argmax(dim=-1) + chosen_mask = shift_completion_mask[: len(shift_completion_mask) // 2].bool() + chosen_labels = shift_labels[: len(shift_labels) // 2] + correct_predictions = (predictions == chosen_labels) & chosen_mask + total_tokens = chosen_mask.sum() + correct_tokens = correct_predictions.sum() + correct_tokens = self.accelerator.gather_for_metrics(correct_tokens) + total_tokens = self.accelerator.gather_for_metrics(total_tokens) + total_sum = total_tokens.sum() + accuracy = (correct_tokens.sum() / total_sum).item() if total_sum > 0 else 0.0 + self._metrics[mode]["mean_token_accuracy"].append(accuracy) + + # Rewards for chosen and rejected completions + chosen_rewards = self.beta * chosen_logratios.detach() + rejected_rewards = self.beta * rejected_logratios.detach() + agg_chosen_rewards = self.accelerator.gather(chosen_rewards) + agg_rejected_rewards = self.accelerator.gather(rejected_rewards) + self._metrics[mode]["rewards/chosen"].append(agg_chosen_rewards.mean().item()) + self._metrics[mode]["rewards/rejected"].append(agg_rejected_rewards.mean().item()) + + # Reward accuracy + reward_accuracies = (chosen_rewards > rejected_rewards).float() + agg_reward_accuracies = self.accelerator.gather(reward_accuracies) + self._metrics[mode]["rewards/accuracies"].append(agg_reward_accuracies.mean().item()) + + # Reward margins + margins = chosen_rewards - rejected_rewards + agg_margins = self.accelerator.gather(margins) + self._metrics[mode]["rewards/margins"].append(agg_margins.mean().item()) + + # Average log probabilities for chosen and rejected completions + self._metrics[mode]["logps/chosen"].append(self.accelerator.gather(chosen_logps).mean().item()) + self._metrics[mode]["logps/rejected"].append(self.accelerator.gather(rejected_logps).mean().item()) + + return (loss, outputs) if return_outputs else loss + + def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): + try: + if self.use_liger_kernel: + return self._compute_loss_liger(model, inputs, return_outputs) + return self._compute_loss(model, inputs, return_outputs) + except ValueError as e: + if "Image features and image tokens do not match" in str(e) and self.args.max_length is not None: + raise ValueError( + f"The current `max_length` ({self.args.max_length}) is too short and causes image placeholder " + f"tokens in `input_ids` to be truncated, while the corresponding image features remain intact. " + f"Please increase `max_length` or set it to `None` to disable truncation." + ) from e + raise + + # Override training step to add activation offloading context. + def training_step(self, *args, **kwargs): + with self.maybe_activation_offload_context: + return super().training_step(*args, **kwargs) + + def log(self, logs: dict[str, float], start_time: float | None = None) -> None: + mode = "train" if self.model.training else "eval" + metrics = {key: sum(val) / len(val) for key, val in self._metrics[mode].items()} # average the metrics + # This method can be called both in training and evaluation. When called in evaluation, the keys in `logs` + # start with "eval_". We need to add the prefix "eval_" to the keys in `metrics` to match the format. + if mode == "eval": + metrics = {f"eval_{key}": val for key, val in metrics.items()} + logs.update(metrics) + super().log(logs, start_time) + self._metrics[mode].clear() + + # During eval, Trainer calls prediction_step. If no labels are present in the inputs, it only runs forward and + # returns logits. We override prediction_step to force compute_loss, because this trainer doesn't involve labels. + def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys: list[str] | None = None): + inputs = self._prepare_inputs(inputs) + with torch.no_grad(), self.compute_loss_context_manager(): + if prediction_loss_only: + loss = self.compute_loss(model, inputs, return_outputs=False) # logits aren't materialized with liger + logits, labels = None, None + else: + loss, outputs = self.compute_loss(model, inputs, return_outputs=True) + logits, labels = outputs.logits, inputs["input_ids"] + return loss, logits, labels + + # Ensure the model card is saved along with the checkpoint + def _save_checkpoint(self, model, trial): + if self.args.hub_model_id is None: + model_name = Path(self.args.output_dir).name + else: + model_name = self.args.hub_model_id.split("/")[-1] + self.create_model_card(model_name=model_name) + super()._save_checkpoint(model, trial) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/grpo_config.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/grpo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..b332a5ecacb924ca5077dfceac28ec58eff777c4 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/grpo_config.py @@ -0,0 +1,1015 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from dataclasses import dataclass, field +from typing import Any + +from .base_config import _BaseConfig + + +@dataclass +class GRPOConfig(_BaseConfig): + # docstyle-ignore + r""" + 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]`, *optional*): + 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. + cast_lm_head_to_fp32 (`bool`, *optional*, defaults to `False`): + Whether to cast the language modeling head of the policy and reference models to float32. As recommended by + the [ScaleRL](https://huggingface.co/papers/2510.13786) recipe. This flag is only supported when the model + has untied word embedding and language modeling head layers i.e. `tie_word_embeddings` in the model config + is False. + + > 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`. + num_generations (`int`, *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. + num_generations_eval (`int` or `None`, *optional*): + Number of generations to sample during evaluation. This allows using fewer generations during evaluation to + save computation. If `None`, uses the value of `num_generations`. + 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. + pad_to_multiple_of (`int`, *optional*): + If set, the prompts ids and completions ids will be padded to a multiple of this value. + + > Parameters that control generation + + generation_batch_size (`int`, *optional*): + 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`, *optional*): + 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`, *optional*, defaults to `0`): + Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, top-k-filtering is + disabled and all tokens are considered. + min_p (`float`, *optional*): + 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. + generation_kwargs (`dict[str, Any]`, *optional*): + Additional keyword arguments to pass to [`~transformers.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 `suppress_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. + chat_template_kwargs (`dict[str, Any]`, *optional*): + Additional keyword arguments to pass to the `apply_chat_template` function when generating completions. + 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. + cache_implementation (`str`, *optional*): + Implementation of the cache method for faster generation when `use_vllm` is set to `False`. + + > 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 `"colocate"`): + 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_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. + vllm_structured_outputs_regex (`str`, *optional*): + Regex for vLLM structured outputs. If `None` (default), structured outputs is disabled. + + > Parameters that control the vLLM server (only used when `vllm_mode` is `"server"`) + + vllm_server_base_url (`str`, *optional*): + 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. + vllm_group_port (`int`, *optional*, defaults to `51216`): + Port number for the weight update group. This is used to communicate with the vLLM server. Unless the port + is occupied, there is no need to change it. + + > 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_max_model_length (`int`, *optional*): + Context window for vLLM. Set it to at least the maximum prompt length in the dataset plus + `max_completion_length`; if omitted, it is inferred from the model config. + 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_enable_sleep_mode (`bool`, *optional*, defaults to `False`): + Enable vLLM sleep mode to offload weights/cache during the optimizer step. Keeps GPU memory usage low, but + waking the engine adds host–device transfer latency. + + > 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. [DeepSeek-R1 incentivizes reasoning in LLMs through reinforcement + learning](https://huggingface.co/papers/2501.12948) use a value of `0.001`. + 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`, *optional*): + 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`, *optional*): + 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`. + When used with `loss_type='cispo'`, this corresponds to the ε_max param specified in the [ScaleRL + paper](https://huggingface.co/papers/2510.13786) and the recommended value is `5.0`. + sapo_temperature_neg (`float`, *optional*, defaults to `1.05`): + Temperature for tokens with non-positive advantage scores used in the `sapo` loss function. This parameter + is introduced in the [Soft Adaptive Policy Optimization paper](https://huggingface.co/papers/2511.20347). + sapo_temperature_pos (`float`, *optional*, defaults to `1.0`): + Temperature for tokens with positive advantage scores used in the `sapo` loss function. This parameter is + introduced in the [Soft Adaptive Policy Optimization paper](https://huggingface.co/papers/2511.20347). + vespo_k_pos (`float`, *optional*, defaults to `2.0`): + k parameter for positive advantages, it is the power exponent in the VESPO loss. Controls how aggressively + we down-weight samples with low importance weights (when the importance sampling ratio < 1). + vespo_lambda_pos (`float`, *optional*, defaults to `3.0`): + lambda parameter for positive advantages, it is the decay factor in the VESPO loss. Controls how + aggressively we down-weight samples with high importance weights (when the importance sampling ratio > 1). + vespo_k_neg (`float`, *optional*, defaults to `3.0`): + k parameter for negative advantages, it is the power exponent in the VESPO loss. Controls how aggressively + we down-weight samples with low importance weights (when the importance sampling ratio < 1). + vespo_lambda_neg (`float`, *optional*, defaults to `2.0`): + lambda parameter for negative advantages, it is the exponential decay factor in the VESPO loss. Controls + how aggressively we down-weight samples with high importance weights (when the importance sampling ratio > + 1). + 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]`, *optional*): + Weights for each reward function. Must match the number of reward functions. If `None`, all rewards are + weighted equally with weight `1.0`. + multi_objective_aggregation (`str`, *optional*, defaults to `"sum_then_normalize"`): + Method to aggregate multiple reward functions. Supported values are: + + - `"sum_then_normalize"` (default): First sums the weighted rewards from each reward function, then applies + reward scaling/normalization as specified by `scale_rewards` (see `scale_rewards` for details). + - `"normalize_then_sum"`: First normalizes/scales each reward function across generations (within each + group), then sums the normalized rewards using the specified weights. The aggregated reward is then + normalized at the batch level when forming advantages. This is the suggested approach from the paper + [GDPO: Group reward-Decoupled Normalization Policy Optimization for Multi-reward RL + Optimization](https://huggingface.co/papers/2601.05242). + scale_rewards (`str` or `bool`, *optional*, defaults to `"group"`): + Specifies the scaling strategy for rewards. Supported values are: + + - `True` or `"group"` (default): rewards are scaled by the standard deviation within each group, ensuring + unit variance within a group. + - `"batch"`: rewards are scaled by the standard deviation across the entire batch, as recommended in the + [PPO Lite paper](https://huggingface.co/papers/2508.08221). + - `False` or `"none"`: no scaling is applied. The [Dr. GRPO + paper](https://huggingface.co/papers/2503.20783) recommends not scaling rewards, as scaling by the + standard deviation introduces a question-level difficulty bias. + loss_type (`str`, *optional*, defaults to `"dapo"`): + 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. + - `"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`. + - `"dapo"` (default): Aggregates token-level losses by normalizing with the number of active token in the + global accumulated batch. This method was introduced in the [DAPO + paper](https://huggingface.co/papers/2503.14476) to eliminate length bias. + - `"bnpo"`: Aggregates token-level losses by normalizing with the 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. + - `"cispo"`: Clips the importance sampling weights instead of the advantage scaled importance weights. The + clipped weights are then multiplied with the advantages and policy model's log probs. Individual token + losses are aggregated by normalizing with the number of active tokens in the global accumulated batch. + This method was introduced in the [MiniMax-M1 paper](https://huggingface.co/papers/2506.13585). + - `"sapo"`: Soft Adaptive Policy Optimization loss, as introduced in the [Soft Adaptive Policy Optimization + paper](https://huggingface.co/papers/2511.20347). Replaces hard clipping with a smooth, + temperature-controlled gate that adaptively attenuates off-policy updates while preserving useful + learning signals. + - `"luspo"`: Length-Unbiased Sequence Policy Optimization loss. A sequence-level loss that scales each + sequence's loss by its length. This is a modification of GSPO and requires + `importance_sampling_level="sequence"`. Introduced in the [LUSPO + paper](https://huggingface.co/papers/2602.05261). + - `"vespo"`: Variational Sequence-Level Soft Policy Optimization. Replaces hard clipping with a smooth, + asymmetric Gamma weighting function applied directly to sequence-level importance weights. Introduced in + the [VESPO paper](https://huggingface.co/papers/2602.10693). + 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. + max_tool_calling_iterations (`int`, *optional*): + Maximum number of tool-calling turns when training an agent. If `None`, there is no limit and generation + stops when the model generates a response turn with no tool calls or when the total response length reaches + `max_model_length`. + vllm_importance_sampling_correction (`bool`, *optional*, defaults to `True`): + Whether to apply Importance Sampling (IS) to correct for the mismatch between vLLM completion logprobs and + recomputed training logprobs. If set to `False`, no IS is applied regardless of + `vllm_importance_sampling_mode`. When `True`, the selected mode determines how the IS ratios are computed + and constrained. + vllm_importance_sampling_mode (`str`, *optional*, defaults to `"sequence_mask"`): + Specifies how Importance Sampling is performed when `vllm_importance_sampling_correction=True`. Possible + values are: + + - `"token_truncate"`: Token-level truncated IS (default). Per-token ratios are clipped to + [C_min, C_max]. + - `"token_mask"`: Token-level masked IS. Per-token ratios outside [C_min, C_max] are set to zero. + - `"sequence_truncate"`: Sequence-level truncated IS. A single sequence ratio is clipped to + [C_min, C_max] and applied to all tokens in the sequence. + - `"sequence_mask"`: Sequence-level masked IS. Sequences with ratios outside [C_min, C_max] are masked + out. + vllm_importance_sampling_clip_max (`float`, *optional*, defaults to `3.0`): + Importance sampling upper bound C_max used by `vllm_importance_sampling_mode`. For `*_truncate` modes, + importance ratios are clipped from above at C_max. For `*_mask` modes, ratios larger than C_max are set to + zero. + vllm_importance_sampling_clip_min (`float`, *optional*): + Importance sampling lower bound C_min used by `vllm_importance_sampling_mode`. For `*_truncate` modes, + ratios are clipped from below at C_min. For `*_mask` modes, ratios below C_min are set to zero. To strictly + mask ratios below C_min without upper bound, set `vllm_importance_sampling_clip_max=None`. + off_policy_mask_threshold (`float`, *optional*): + Threshold for off-policy sequence masking. If `None`, off-policy sequence masking is disabled. When set, + sequences with negative advantages and high KL divergence are masked out to stabilize training. This + parameter corresponds to the `delta` threshold in Equation 9 of the [DeepSeek-V3.2 + paper](https://huggingface.co/papers/2512.02556). It expects a positive value (e.g., 0.5). + use_bias_correction_kl (`bool`, *optional*, defaults to `False`): + Whether to use the unbiased KL divergence estimator with importance sampling correction. This corrects the + KL divergence estimate by multiplying it with the importance sampling ratio. This is described in the + [DeepSeek-V3.2 paper](https://huggingface.co/papers/2512.02556). + + > 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` and/or `trackio` logging is enabled, it logs it to `wandb` and/or + `trackio`. + num_completions_to_print (`int`, *optional*): + Number of completions to print with `rich`. If `None`, all completions are logged. + log_unique_prompts (`bool`, *optional*, defaults to `False`): + Whether to log unique prompts. If `True`, only unique prompts are logged. If `False`, all prompts are + logged. + log_completions_hub_repo (`str`, *optional*): + Hugging Face Hub repository to save the completions. Should be a complete repository name like + `'username/reponame'` or `'orgname/reponame'`, or just `'reponame'` in which case the repository will be + created in the currently-logged-in Hugging Face user's namespace. Note that this repository will be public + unless you set `hub_private_repo=True` or your organization's default is to create private repositories." + + > Deprecated parameters + + use_transformers_paged: + + + + Parameter `use_transformers_paged` is deprecated and will be removed in version v2.0.0. It will be + replaced by `transformers` continuous batching support in an upcoming release. + + + + vllm_importance_sampling_cap: + + + + Parameter `vllm_importance_sampling_cap` is deprecated and will be removed in v2.0.0. Use + `vllm_importance_sampling_clip_max` instead. + + + + > [!NOTE] + > These parameters have default values different from [`~transformers.TrainingArguments`]: + > - `logging_steps`: Defaults to `10` instead of `500`. + > - `gradient_checkpointing`: Defaults to `True` instead of `False`. + > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`. + > - `learning_rate`: Defaults to `1e-6` instead of `5e-5`. + """ + + _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"] + + # Parameters whose default values are overridden from TrainingArguments + learning_rate: float = field( + default=1e-6, + metadata={"help": "The initial learning rate for AdamW."}, + ) + + # Parameters that control the model and reference model + model_init_kwargs: dict[str, Any] | str | None = field( + default=None, + metadata={ + "help": "Keyword arguments for `transformers.AutoModelForCausalLM.from_pretrained`, used when the `model` " + "argument of the `GRPOTrainer` is provided as a string." + }, + ) + disable_dropout: bool = field( + default=False, + metadata={ + "help": "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." + }, + ) + cast_lm_head_to_fp32: bool = field( + default=False, + metadata={ + "help": "Whether to cast the language modeling head of the policy and reference, models to float32." + "As recommended by the [ScaleRL](https://huggingface.co/papers/2510.13786) recipe. This flag is only " + "supported when the model has untied word embedding and language modeling head layers i.e. " + "`tie_word_embeddings` in the model config is False." + }, + ) + + # Parameters that control the data preprocessing + # The default value remove_unused_columns is overwritten from the parent class, because in GRPO we usually rely on + # additional columns to compute the reward + remove_unused_columns: bool | None = field( + default=False, + metadata={ + "help": "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`." + }, + ) + num_generations: int | None = field( + default=8, + metadata={ + "help": "Number of generations to sample. The effective batch size (num_processes * per_device_batch_size " + "* gradient_accumulation_steps) must be evenly divisible by this value." + }, + ) + num_generations_eval: int | None = field( + default=None, + metadata={ + "help": "Number of generations to sample during evaluation. This allows using fewer generations during " + "evaluation to save computation. If `None`, uses the value of `num_generations`." + }, + ) + max_completion_length: int | None = field( + default=256, + metadata={"help": "Maximum length of the generated completion."}, + ) + ds3_gather_for_generation: bool = field( + default=True, + metadata={ + "help": "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 | None = field( + default=True, + metadata={"help": "Whether to shuffle the training dataset."}, + ) + pad_to_multiple_of: int | None = field( + default=None, + metadata={"help": "If set, the prompts ids and completions ids will be padded to a multiple of this value."}, + ) + + # Parameters that control generation + generation_batch_size: int | None = field( + default=None, + metadata={ + "help": "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`." + }, + ) + steps_per_generation: int | None = field( + default=None, + metadata={"help": "Number of steps per generation. If `None`, it defaults to `gradient_accumulation_steps`."}, + ) + temperature: float = field( + default=1.0, + metadata={"help": "Temperature for sampling. The higher the temperature, the more random the completions."}, + ) + top_p: float = field( + default=1.0, + metadata={ + "help": "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 = field( + default=0, + metadata={ + "help": "Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, " + "top-k-filtering is disabled and all tokens are considered." + }, + ) + min_p: float | None = field( + default=None, + metadata={ + "help": "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." + }, + ) + generation_kwargs: dict | None = field( + default=None, + metadata={ + "help": "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 `suppress_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." + }, + ) + chat_template_kwargs: dict | None = field( + default=None, + metadata={ + "help": "Additional keyword arguments to pass to the `apply_chat_template` function when generating " + "completions." + }, + ) + repetition_penalty: float = field( + default=1.0, + metadata={ + "help": "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." + }, + ) + cache_implementation: str | None = field( + default=None, + metadata={"help": "Implementation of the cache method for faster generation when use_vllm is set to False."}, + ) + + # Parameters that control generation acceleration powered by vLLM + use_vllm: bool = field( + default=False, + metadata={ + "help": "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 = field( + default="colocate", + metadata={ + "help": "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_model_impl: str = field( + default="vllm", + metadata={ + "help": "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." + }, + ) + vllm_enable_sleep_mode: bool = field( + default=False, + metadata={ + "help": "Enable vLLM sleep mode to offload weights/cache during the optimizer step. Keeps GPU memory " + "usage low, but waking the engine adds host–device transfer latency." + }, + ) + vllm_structured_outputs_regex: str | None = field( + default=None, + metadata={"help": "Regex for vLLM structured outputs. If `None` (default), structured outputs is disabled."}, + ) + + # Parameters that control the vLLM server (only used when `vllm_mode` is `"server"`) + vllm_server_base_url: str | None = field( + default=None, + metadata={ + "help": "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 = field( + default="0.0.0.0", + metadata={"help": "Host of the vLLM server to connect to. Ignored if vllm_server_base_url is provided."}, + ) + vllm_server_port: int = field( + default=8000, + metadata={"help": "Port of the vLLM server to connect to. Ignored if vllm_server_base_url is provided."}, + ) + vllm_server_timeout: float = field( + default=240.0, + metadata={ + "help": "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." + }, + ) + vllm_group_port: int = field( + default=51216, + metadata={ + "help": "Port number for the weight update group. This is used to communicate with the vLLM server. " + "Unless the port is occupied, there is no need to change it.", + }, + ) + + # Parameters that control colocated vLLM execution (only used when `vllm_mode` is `"colocate"`) + vllm_gpu_memory_utilization: float = field( + default=0.3, + metadata={ + "help": "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_max_model_length: int | None = field( + default=None, + metadata={ + "help": "Context window for vLLM. Set it to at least the maximum prompt length in the dataset plus " + "`max_completion_length`; if omitted, it is inferred from the model config." + }, + ) + vllm_tensor_parallel_size: int = field( + default=1, + metadata={ + "help": "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." + }, + ) + + # Parameters that control the training + beta: float = field( + default=0.0, + metadata={ + "help": "KL coefficient. If `0.0` (default), the reference model is not loaded, reducing memory usage and " + "improving training speed. [DeepSeek-R1 incentivizes reasoning in LLMs through reinforcement " + "learning](https://huggingface.co/papers/2501.12948) use a value of `0.001`." + }, + ) + num_iterations: int = field( + default=1, + metadata={"help": "Number of iterations per batch (denoted as μ in the algorithm)."}, + ) + epsilon: float = field( + default=0.2, + metadata={"help": "Epsilon value for clipping."}, + ) + delta: float | None = field( + default=None, + metadata={ + "help": "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 | None = field( + default=None, + metadata={ + "help": "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 recommends `0.28`. " + "When used with `loss_type='cispo'`, this corresponds to the ε_max param specified in the " + "[ScaleRL paper](https://huggingface.co/papers/2510.13786) and the recommended value is `5.0`." + }, + ) + sapo_temperature_neg: float = field( + default=1.05, + metadata={ + "help": "Temperature for tokens with non-positive advantage scores used in the `sapo` loss function. " + "This parameter is introduced in the [Soft Adaptive Policy Optimization " + "paper](https://huggingface.co/papers/2511.20347)." + }, + ) + sapo_temperature_pos: float = field( + default=1.0, + metadata={ + "help": "Temperature for tokens with positive advantage scores used in the `sapo` loss function. " + "This parameter is introduced in the [Soft Adaptive Policy Optimization " + "paper](https://huggingface.co/papers/2511.20347)." + }, + ) + vespo_k_pos: float = field( + default=2.0, + metadata={ + "help": "k parameter for positive advantages, it is the power exponent in the VESPO loss. Controls how " + "aggressively we down-weight samples with low importance weights (when the importance sampling ratio < 1)." + }, + ) + vespo_lambda_pos: float = field( + default=3.0, + metadata={ + "help": "lambda parameter for positive advantages, it is the decay factor in the VESPO loss. Controls " + "how aggressively we down-weight samples with high importance weights (when the importance sampling ratio " + "> 1)." + }, + ) + vespo_k_neg: float = field( + default=3.0, + metadata={ + "help": "k parameter for negative advantages, it is the power exponent in the VESPO loss. Controls how " + "aggressively we down-weight samples with low importance weights (when the importance sampling ratio < 1)." + }, + ) + vespo_lambda_neg: float = field( + default=2.0, + metadata={ + "help": "lambda parameter for negative advantages, it is the exponential decay factor in the VESPO loss. " + "Controls how aggressively we down-weight samples with high importance weights (when the importance " + "sampling ratio > 1)." + }, + ) + importance_sampling_level: str = field( + default="token", + metadata={ + "help": "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 " + "shows that sequence-level sampling often yields more stable training and better alignment with " + "sequence-level rewards." + }, + ) + reward_weights: list[float] | None = field( + default=None, + metadata={ + "help": "Weights for each reward function. Must match the number of reward functions. If `None`, all " + "rewards are weighted equally with weight `1.0`." + }, + ) + multi_objective_aggregation: str = field( + default="sum_then_normalize", + metadata={ + "help": "Method to aggregate multiple reward functions. Supported values are: " + "`'sum_then_normalize'` (default): First sums the weighted rewards from each reward function, then " + "applies reward scaling/normalization as specified by `scale_rewards` (see `scale_rewards` for details). " + "`'normalize_then_sum'`: First normalizes/scales each reward function across generations (within each " + "group), then sums the normalized rewards using the specified weights. The aggregated reward is then " + "normalized at the batch level when forming advantages. This is the suggested approach from the paper " + "GDPO: Group reward-Decoupled Normalization Policy Optimization for Multi-reward RL Optimization." + }, + ) + scale_rewards: str = field( + default="group", + metadata={ + "help": "Specifies the scaling strategy for rewards. Supported values are: " + "`True` or `group'` (default): rewards are scaled by the standard deviation within each group, ensuring " + "unit variance within a group. " + "`'batch'`: rewards are scaled by the standard deviation across the entire batch, as recommended in the " + "PPO Lite paper. " + "`False` or `'none'`: no scaling is applied. The Dr. GRPO paper recommends not scaling rewards, as " + "scaling by the standard deviation introduces a question-level difficulty bias." + }, + ) + loss_type: str = field( + default="dapo", + metadata={ + "help": "Specifies the loss formulation to use. Supported values are 'grpo', 'dapo', 'bnpo', and " + "'dr_grpo'. " + "'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. " + "'dapo' (default): Aggregates token-level losses by normalizing with the number of active token in the " + "global accumulated batch. This method was introduced in the DAPO paper to eliminate length bias. " + "'dr_grpo': Aggregates token-level losses by normalizing with a global constant. This method was " + "introduced in the Dr. GRPO paper to eliminate length bias. The value of the constant corresponds to " + "`max_completion_length`. " + "'bnpo': Aggregates token-level losses by normalizing with the 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." + "'cispo': Clips the importance sampling weights instead of the advantage scaled importance weights. " + "The clipped weights are then multiplied with the advantages and policy model's log probs. " + "Individual token losses are aggregated by normalizing with the number of active tokens in " + "the global accumulated batch. This method was introduced in the " + "[MiniMax-M1 paper](https://huggingface.co/papers/2506.13585). " + "'sapo': Soft Adaptive Policy Optimization loss, as introduced in the " + "[Soft Adaptive Policy Optimization paper](https://huggingface.co/papers/2511.20347). " + "Replaces hard clipping with a smooth, temperature-controlled gate that adaptively attenuates " + "off-policy updates while preserving useful learning signals." + "'luspo': Length-Unbiased Sequence Policy Optimization loss. A sequence-level loss that scales each " + "sequence's loss by its length. This is a modification of GSPO and requires " + "`importance_sampling_level='sequence'`. Introduced in the [LUSPO " + "paper](https://huggingface.co/papers/2602.05261)." + "'vespo': Variational Sequence-Level Soft Policy Optimization. Replaces hard clipping with a smooth, " + "asymmetric Gamma weighting function applied directly to sequence-level importance weights. Introduced in " + "the [VESPO paper](https://huggingface.co/papers/2602.10693)." + }, + ) + mask_truncated_completions: bool = field( + default=False, + metadata={ + "help": "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 paper, this is " + "a good practice for training stability." + }, + ) + sync_ref_model: bool = field( + default=False, + metadata={ + "help": "Whether to synchronize the reference model with the active model every `ref_model_sync_steps` " + "steps, using the `ref_model_mixup_alpha` parameter." + }, + ) + ref_model_mixup_alpha: float = field( + default=0.6, + metadata={ + "help": "α parameter from the TR-DPO 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 = field( + default=512, + metadata={ + "help": "τ parameter from the TR-DPO 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 = field( + default=1.0, + metadata={ + "help": "ρ parameter from Beyond the 80/20 Rule. 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." + }, + ) + max_tool_calling_iterations: int | None = field( + default=None, + metadata={ + "help": "Maximum number of tool-calling turns when training an agent. If `None`, there is no limit and " + "generation stops when the model generates a response turn with no tool calls or when the total " + "response length reaches `max_model_length`." + }, + ) + vllm_importance_sampling_correction: bool = field( + default=True, + metadata={ + "help": "Whether to apply Importance Sampling (IS) to correct for the mismatch between vLLM " + "completion logprobs and recomputed training logprobs. If set to `False`, no IS is applied " + "regardless of `vllm_importance_sampling_mode`. When `True`, the selected mode determines how " + "IS ratios are computed and constrained." + }, + ) + vllm_importance_sampling_mode: str = field( + default="sequence_mask", + metadata={ + "help": "Specifies how Importance Sampling (IS) is performed when " + "vllm_importance_sampling_correction=True. Modes are defined along two orthogonal " + "dimensions: (1) constraint, which determines how to handle ratios outside the bounds " + "[C_min, C_max]—either truncation (clip to range, ρ ← clamp(ρ, C_min, C_max)) or " + "masking (set ratios above C_max or below C_min to zero); and (2) granularity, which determines whether " + "ratios are computed per token or as a single sequence-level ratio applied to all tokens. " + "Supported options are: 'token_truncate', 'token_mask', 'sequence_truncate', and " + "'sequence_mask'." + }, + ) + vllm_importance_sampling_clip_max: float | None = field( + default=3.0, + metadata={ + "help": "Importance sampling upper bound C_max used by `vllm_importance_sampling_mode`. For '*_truncate' " + "modes, ratios are clipped from above at C_max. For '*_mask' modes, ratios larger than C_max are set to " + "zero." + }, + ) + vllm_importance_sampling_clip_min: float | None = field( + default=None, + metadata={ + "help": "Importance sampling lower bound C_min used by `vllm_importance_sampling_mode`. For `*_truncate` " + "modes, ratios are clipped from below at C_min. For `*_mask` modes, ratios below C_min are set to " + "zero. To strictly mask ratios below C_min without upper bound, set `vllm_importance_sampling_clip_max=None`." + }, + ) + off_policy_mask_threshold: float | None = field( + default=None, + metadata={ + "help": "Threshold for off-policy sequence masking. If `None`, off-policy sequence masking is disabled. " + "When set, sequences with negative advantages and high KL divergence are masked out to stabilize " + "training. This parameter corresponds to the `delta` threshold in Equation 9 of the [DeepSeek-V3.2 " + "paper](https://huggingface.co/papers/2512.02556). It expects a positive value (e.g., 0.5)." + }, + ) + use_bias_correction_kl: bool = field( + default=False, + metadata={ + "help": "Whether to use the unbiased KL divergence estimator with importance sampling correction. This " + "corrects the KL divergence estimate by multiplying it with the importance sampling ratio. " + "This is described in the [DeepSeek-V3.2 paper](https://huggingface.co/papers/2512.02556)." + }, + ) + + # Parameters that control the logging + log_completions: bool = field( + default=False, + metadata={ + "help": "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 | None = field( + default=None, + metadata={"help": "Number of completions to print with `rich`. If `None`, all completions are logged."}, + ) + log_unique_prompts: bool = field( + default=False, + metadata={ + "help": "Whether to log unique prompts. If `True`, only unique prompts are logged. If `False`, all " + "prompts are logged." + }, + ) + log_completions_hub_repo: str | None = field( + default=None, + metadata={ + "help": "Hugging Face Hub repository to save the completions. Should be a complete repository name like " + "`'username/reponame'` or `'orgname/reponame'`, or just `'reponame'` in which case the repository will " + "be created in the currently-logged-in Hugging Face user's namespace. Note that this repository will be " + "public unless you set `hub_private_repo=True` or your organization's default is to create private " + "repositories." + }, + ) + + # Deprecated parameters + use_transformers_paged: bool = field( + default=False, + metadata={ + "help": "Deprecated. It will be replaced by `transformers` continuous batching support in an upcoming " + "release." + }, + ) + vllm_importance_sampling_cap: float | None = field( + default=None, + metadata={ + "help": "Deprecated, use `vllm_importance_sampling_clip_max` instead. " + "Importance sampling cap C used by `vllm_importance_sampling_mode`. For '*_truncate' modes, " + "ratios are clipped from above at C. For '*_mask' modes, ratios larger than C are set to zero." + }, + ) + + def __post_init__(self): + super().__post_init__() + + if self.use_transformers_paged: + warnings.warn( + "`use_transformers_paged` is deprecated and will be removed in v2.0.0. It will be replaced by " + "`transformers` continuous batching support in an upcoming release.", + FutureWarning, + stacklevel=3, + ) + + if self.parallelism_config is not None and ( + self.parallelism_config.cp_enabled or self.parallelism_config.sp_enabled + ): + raise ValueError( + "GRPOTrainer does not support sequence-dim parallelism (`parallelism_config.cp_size > 1` or " + "`parallelism_config.sp_size > 1`) yet. GRPO builds model inputs after generation inside the trainer, " + "so Transformers' context-parallel / Ulysses sequence-parallel input sharding cannot be applied to the " + "raw generation batch. Set both `cp_size=1` and `sp_size=1`, or disable `parallelism_config`." + ) + + self.scale_rewards = {True: "group", False: "none"}.get(self.scale_rewards, self.scale_rewards) + + if self.log_completions_hub_repo is not None and not self.log_completions: + raise ValueError( + "log_completions_hub_repo is set, but log_completions is False. Enable log_completions to upload " + "completions to the Hub, or unset log_completions_hub_repo." + ) + + num_processes = self.world_size + # The current default effective batch size + if self.generation_batch_size is None and self.steps_per_generation is None: + self.steps_per_generation = self.gradient_accumulation_steps + self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation + elif self.generation_batch_size is not None and self.steps_per_generation is None: + # Just ensure the value is divisible by the global batch size + if self.generation_batch_size % (self.per_device_train_batch_size * num_processes) != 0: + raise ValueError( + f"generation_batch_size ({self.generation_batch_size}) must be divisible by the global batch size " + f"({self.per_device_train_batch_size * num_processes})." + ) + self.steps_per_generation = self.generation_batch_size // ( + self.per_device_train_batch_size * num_processes + ) + elif self.generation_batch_size is None and self.steps_per_generation is not None: + self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation + else: + raise ValueError( + "'generation_batch_size' and 'steps_per_generation' can not be both configured at the same time" + ) + + if self.do_eval and self.eval_strategy != "no": + # Determine the number of generations to use for evaluation + num_generations = self.num_generations_eval or self.num_generations + + # Just ensure the value is divisible by the global batch size + if (self.per_device_eval_batch_size * num_processes) % num_generations != 0: + raise ValueError( + f"The global eval batch size ({self.per_device_eval_batch_size} * {num_processes}) must be " + f"divisible by the number of generations used for evaluation ({num_generations})." + ) + + # The generation batch must contain full prompt groups (no partials), so it must be divisible by + # num_generations. + if self.generation_batch_size % self.num_generations != 0: + raise ValueError( + f"generation_batch_size ({self.generation_batch_size}) must be divisible by num_generations " + f"({self.num_generations})." + ) + + if self.num_generations < 2: + raise ValueError( + "GRPO requires at least 2 generations per prompt to calculate the advantages. You provided " + f"{self.num_generations}, which is less than the minimum required." + ) + + if self.vllm_importance_sampling_cap is not None: + warnings.warn( + "The `vllm_importance_sampling_cap` argument is deprecated and will be removed in v2.0.0. " + "Use `vllm_importance_sampling_clip_max` instead.", + FutureWarning, + stacklevel=2, + ) + self.vllm_importance_sampling_clip_max = self.vllm_importance_sampling_cap + + if ( + self.vllm_importance_sampling_clip_min is not None + and self.vllm_importance_sampling_clip_max is not None + and self.vllm_importance_sampling_clip_min >= self.vllm_importance_sampling_clip_max + ): + raise ValueError( + f"vllm_importance_sampling_clip_min ({self.vllm_importance_sampling_clip_min}) must be less than " + f"vllm_importance_sampling_clip_max ({self.vllm_importance_sampling_clip_max})." + ) + + if ( + self.vllm_importance_sampling_correction + and self.vllm_importance_sampling_mode in ("token_truncate", "sequence_truncate") + and self.vllm_importance_sampling_clip_min is None + and self.vllm_importance_sampling_clip_max is None + ): + raise ValueError( + "At least one of `vllm_importance_sampling_clip_min` or `vllm_importance_sampling_clip_max` " + "must be set when `vllm_importance_sampling_mode` is a `*_truncate` mode." + ) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/grpo_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/grpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..6bfdc30fef46d59675930bc72bb6d9364464c3a2 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/grpo_trainer.py @@ -0,0 +1,2784 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import asyncio +import atexit +import copy +import importlib.resources as pkg_resources +import inspect +import math +import os +import sys +import textwrap +import time +import warnings +from collections import defaultdict, deque +from collections.abc import Callable +from contextlib import nullcontext +from pathlib import Path +from typing import Any, Protocol + +import numpy as np +import pandas as pd +import torch +import torch.utils.data +import transformers +from accelerate.logging import get_logger +from accelerate.utils import gather, gather_object, is_peft_model, set_seed +from datasets import Dataset, IterableDataset +from huggingface_hub import CommitScheduler, DatasetCard, DatasetCardData, create_repo +from packaging.version import Version +from torch import nn +from torch.utils.data import Sampler +from transformers import ( + AutoModelForSequenceClassification, + AutoProcessor, + AutoTokenizer, + GenerationConfig, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, + is_trackio_available, + is_wandb_available, +) +from transformers.utils import is_peft_available, is_rich_available + +from ..chat_template_utils import ( + add_response_schema, + get_training_chat_template, + is_chat_template_prefix_preserving, + parse_response, + supports_tool_calling, +) +from ..data_utils import apply_chat_template, is_conversational, prepare_multimodal_messages +from ..distributed import DistributedBackend +from ..extras.profiling import profiling_context, profiling_decorator +from ..generation.vllm_generation import VLLMGeneration +from ..import_utils import is_jmespath_available, is_liger_kernel_available +from ..models import prepare_deepspeed, prepare_fsdp, unwrap_model_for_generation +from ..models.utils import _ForwardRedirection, disable_gradient_checkpointing +from .base_trainer import _BaseTrainer +from .callbacks import SyncRefModelCallback +from .grpo_config import GRPOConfig +from .utils import ( + RepeatSampler, + create_model_from_path, + disable_dropout_in_model, + entropy_from_logits, + get_config_model_id, + identity, + nanmax, + nanmin, + nanstd, + pad, + print_prompt_completions_sample, + selective_log_softmax, + shuffle_sequence_dict, + shutdown_event_loop_in_daemon, + split_pixel_values_by_grid, + split_tensor_dict, + start_event_loop_in_daemon, + unsplit_pixel_values_by_grid, + use_adapter, +) + + +if is_peft_available(): + from peft import PeftConfig, PeftModel, get_peft_model + +if is_liger_kernel_available(): + from liger_kernel.chunked_loss import LigerFusedLinearGRPOLoss + + +if is_wandb_available(): + import wandb + +if is_trackio_available(): + import trackio + + +logger = get_logger(__name__) + +# A reward function can be a string, interpreted as a model ID and loaded as a pretrained model, a pretrained model, or +# a callable that returns a list of floats (the rewards). The callable receives prompts, completions, and additional +# arguments from the trainer (refer to the trainer's source for details). To ensure forward compatibility, it should +# accept **kwargs. +RewardFunc = str | PreTrainedModel | Callable[..., list[float | None]] + +# What we call a rollout function is a callable that takes prompts (list) and the trainer instance as parameters and +# returns a dict of generation results. Those results must include "prompt_ids", "completion_ids", and "logprobs" +# fields. Any extra fields (per-completion) are forwarded to the reward functions. +RolloutFunc = Callable[[list[str], "GRPOTrainer"], dict[str, Any]] + + +class _SupportsReset(Protocol): + def reset(self, **kwargs) -> str | None: ... + + +EnvironmentFactory = Callable[[], _SupportsReset] + + +class GRPOTrainer(_BaseTrainer): + """ + Trainer for the Group Relative Policy Optimization (GRPO) method. This algorithm was initially proposed in the + paper [DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language + Models](https://huggingface.co/papers/2402.03300). + + Example: + + ```python + from trl import GRPOTrainer + from trl.rewards import accuracy_reward + from datasets import load_dataset + + dataset = load_dataset("trl-lib/DeepMath-103K", split="train") + + trainer = GRPOTrainer( + model="Qwen/Qwen2.5-0.5B-Instruct", + reward_funcs=accuracy_reward, + train_dataset=dataset, + ) + trainer.train() + ``` + + Args: + model (`str` or [`~transformers.PreTrainedModel`] or [`~peft.PeftModel`]): + Model to be trained. Can be either: + + - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a + path to a *directory* containing model weights saved using + [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded + using `.from_pretrained` (where `` is derived from the model + config) with the keyword arguments in `args.model_init_kwargs`. + - A [`~transformers.PreTrainedModel`] object. Only causal language models are supported. + - A [`~peft.PeftModel`] object. Only causal language models are supported. + reward_funcs (`RewardFunc | list[RewardFunc]`): + Reward functions to be used for computing the rewards. To compute the rewards, we call all the reward + functions with the prompts and completions and sum the rewards. Can be either: + + - A single reward function, such as: + - A string: The *model ID* of a pretrained model hosted inside a model repo on huggingface.co, or a + path to a *directory* containing model weights saved using + [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded + using [`~transformers.AutoModelForSequenceClassification.from_pretrained`] with `num_labels=1` and the + keyword arguments in `args.model_init_kwargs`. + - A [`~transformers.PreTrainedModel`] object: Only sequence classification models are supported. + - A custom reward function: The function is provided with the prompts and the generated completions, + plus any additional columns in the dataset. It should return a list of rewards. Custom reward + functions can be either synchronous or asynchronous and can also return `None` when the reward is + not applicable to those samples. This is useful for multi-task training where different reward + functions apply to different types of samples. When a reward function returns `None` for a sample, + that reward function is excluded from the reward calculation for that sample. For more details, see + [Using a custom reward + function](#using-a-custom-reward-function). + + The trainer's state is also passed to the reward function. The trainer's state is an instance of + [`~transformers.TrainerState`] and can be accessed by accessing the `trainer_state` argument to the + reward function's signature. + - A list of reward functions, where each item can independently be any of the above types. Mixing different + types within the list (e.g., a string model ID and a custom reward function) is allowed. + args ([`GRPOConfig`], *optional*): + Configuration for this trainer. If `None`, a default configuration is used. + train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]): + Dataset to use for training. It must include a column `"prompt"`. Any additional columns in the dataset is + ignored. The format of the samples can be either: + + - [Standard](dataset_formats#standard): Each sample contains plain text. + - [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role + and content). + eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Dataset | IterableDataset]`): + Dataset to use for evaluation. It must meet the same requirements as `train_dataset`. + processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.ProcessorMixin`], *optional*): + Processing class used to process the data. The padding side must be set to "left". If `None`, the + processing class is loaded from the model's name with [`~transformers.AutoProcessor.from_pretrained`]. A + padding token, `tokenizer.pad_token`, must be set. If the processing class has not set a padding token, + `tokenizer.eos_token` will be used as the default. + reward_processing_classes ([`~transformers.PreTrainedTokenizerBase`] or `list[PreTrainedTokenizerBase]`, *optional*): + Processing classes corresponding to the reward functions specified in `reward_funcs`. Can be either: + + - A single processing class: Used when `reward_funcs` contains only one reward function. + - A list of processing classes: Must match the order and length of the reward functions in `reward_funcs`. + If set to `None`, or if an element of the list corresponding to a [`~transformers.PreTrainedModel`] is + `None`, the tokenizer for the model is automatically loaded using + [`~transformers.AutoTokenizer.from_pretrained`]. For elements in `reward_funcs` that are custom reward + functions (not [`~transformers.PreTrainedModel`]), the corresponding entries in `reward_processing_classes` + are ignored. + callbacks (list of [`~transformers.TrainerCallback`], *optional*): + List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed + in [here](https://huggingface.co/docs/transformers/main_classes/callback). + + If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`] + method. + optimizers (`tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None]`, *optional*, defaults to `(None, None)`): + A tuple containing the optimizer and the scheduler to use. Will default to an instance of `AdamW` on your + model and a scheduler given by [`~transformers.get_linear_schedule_with_warmup`] controlled by `args`. + peft_config ([`~peft.PeftConfig`], *optional*): + PEFT configuration used to wrap the model. If `None`, the model is not wrapped. + tools (list of `Callable`, *optional*): + A list of callable tool functions (sync or async) that the model can invoke during generation. Each tool + should be a standard Python function with properly type-hinted arguments and return values, and a + Google-style docstring describing its purpose, arguments, and return value. For more details, see: + https://huggingface.co/docs/transformers/en/chat_extras#passing-tools. The model uses the function's name, + type hints, and docstring to determine how to call it. Ensure that the model's chat template supports tool + use and that it has been fine-tuned for tool calling. + rollout_func (`RolloutFunc`, *optional*): + Function to use for generating completions. It receives the list of prompts allocated to the current + process and the trainer instance. It must return a dict with `"prompt_ids"`, `"completion_ids"`, and + `"logprobs"` fields, and can optionally return `"logprob_token_ids"` (same shape as `"logprobs"`). Any + other fields are forwarded to the reward functions. The function receives the raw per-process prompt slice + with no duplication; it is responsible for returning the correct number of completions per prompt (see + `num_generations` / `num_generations_eval` on the trainer). This feature is experimental and may change or + be removed at any time without prior notice. + environment_factory (`EnvironmentFactory`, *optional*): + A callable that creates and returns an environment instance. The environment class should define methods + that can be invoked as tools during generation. Each method should comply with the same requirements as the + `tools` described above. If `environment_factory` is provided, an instance of the environment is created + for each generation in the batch, allowing for parallel and independent interactions. The environment must + also implement a callable `reset` method that can be used to reset state between generations. The `reset` + method should return either `None` or a string: when it returns a string, that string is appended to the + last user message before generation. This feature is experimental and may change or be removed at any time + without prior notice. + """ + + _tag_names = ["trl", "grpo"] + _name = "GRPO" + _paper = { + "title": "DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models", + "id": "2402.03300", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @article{shao2024deepseekmath, + title = {{DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models}}, + author = {Zhihong Shao and Peiyi Wang and Qihao Zhu and Runxin Xu and Junxiao Song and Mingchuan Zhang and Y. K. Li and Y. Wu and Daya Guo}, + year = 2024, + eprint = {arXiv:2402.03300}, + }"""), + } + + def __init__( + self, + model: "str | PreTrainedModel | PeftModel", + reward_funcs: RewardFunc | list[RewardFunc], + args: GRPOConfig | None = None, + train_dataset: Dataset | IterableDataset | None = None, + eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None, + processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None, + reward_processing_classes: PreTrainedTokenizerBase | list[PreTrainedTokenizerBase] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None), + peft_config: "PeftConfig | None" = None, + tools: list[Callable] | None = None, + rollout_func: RolloutFunc | None = None, + environment_factory: EnvironmentFactory | None = None, + ): + # Args + if args is None: + model_name = model if isinstance(model, str) else get_config_model_id(model.config) + model_name = model_name.split("/")[-1] + args = GRPOConfig(f"{model_name}-GRPO") + + # Model + if isinstance(model, str): + model_init_kwargs = args.model_init_kwargs or {} + # Distributed training requires device_map=None ("auto" fails) + if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + model_init_kwargs["device_map"] = None + model = create_model_from_path(model, **model_init_kwargs) + else: + if args.model_init_kwargs is not None: + logger.warning( + "You passed `model_init_kwargs` to the `GRPOConfig`, but your model is already instantiated. " + "The `model_init_kwargs` will be ignored." + ) + + # Some models (SmolVLM/Idefics3) don't support `logits_to_keep` argument and error out if we pass it + # Inspect the forward method before we wrap the model with PEFT + self.model_kwarg_keys = ( + inspect.signature(model.forward).parameters.keys() + if not hasattr(model, "get_base_model") + else inspect.signature(model.get_base_model().forward).parameters.keys() + ) + + # Processing class + if processing_class is None: + processing_class = AutoProcessor.from_pretrained( + get_config_model_id(model.config), truncation_side="left", padding_side="left" + ) + + # Handle pad token for processors or tokenizers + if isinstance(processing_class, ProcessorMixin): + self._tokenizer = processing_class.tokenizer + self._is_vlm = True + elif isinstance(processing_class, PreTrainedTokenizerBase): + self._tokenizer = processing_class + self._is_vlm = False + else: + raise TypeError("The `processing_class` must be either a `PreTrainedTokenizerBase` or a `ProcessorMixin`") + + if self._tokenizer.pad_token is None: + self._tokenizer.pad_token = self._tokenizer.eos_token + + # Resolve vision placeholder token IDs once. Used by the forward pass to rebuild mm_token_type_ids + # when tool responses inject images into the completion (see _generate forward_kwargs block). + self._image_pad_token_id = None + self._video_pad_token_id = None + if self._is_vlm: + for candidate in ("<|image_pad|>", "<|image|>"): + tid = self._tokenizer.convert_tokens_to_ids(candidate) + if tid != self._tokenizer.unk_token_id: + self._image_pad_token_id = tid + break + tid = self._tokenizer.convert_tokens_to_ids("<|video_pad|>") + if tid != self._tokenizer.unk_token_id: + self._video_pad_token_id = tid + + # PEFT + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + if is_peft_model(model): + raise ValueError( + "You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first merge " + "and unload the existing adapter, save the resulting base model, and then pass that base model along " + "with the new `peft_config` to the trainer." + ) + # Create PEFT model + model = get_peft_model(model, peft_config) + + elif is_peft_model(model) and args.beta != 0.0: + # If the model is a PEFT model with a pretrained adapter, we need to create a "ref" adapter that is a copy + # of the "default" adapter, so that we can use it as the reference model during GRPO training. + model.add_adapter("ref", model.peft_config["default"]) + for name, param in model.named_parameters(): + if ".default." in name: + ref_name = name.replace(".default.", ".ref.") + ref_param = model.get_parameter(ref_name) + ref_param.data.copy_(param.data) + + # When using gradient checkpointing with PEFT, we need to enable input gradients. transformers.Trainer normally + # handles this, but a bug currently prevents it; see https://github.com/huggingface/transformers/issues/42489 + if is_peft_model(model) and args.gradient_checkpointing: + model.enable_input_require_grads() + + # When using QLoRA, the PEFT adapter weights are converted to bf16 to follow the recommendations from the + # original paper (see https://huggingface.co/papers/2305.14314, paragraph 3). Normally, this can be done by + # passing `autocast_adapter_dtype=False` to `get_peft_model`, but this option is not yet supported for + # quantized models. See: https://github.com/huggingface/peft/issues/2889 + # Non-quantized models do not have the `is_loaded_in_{8,4}bit` attributes, whereas quantized models do + if getattr(model, "is_loaded_in_4bit", False) or getattr(model, "is_loaded_in_8bit", False): + for param in model.parameters(): + if param.requires_grad: + param.data = param.data.to(torch.bfloat16) + + # Reward functions + if not isinstance(reward_funcs, list): + reward_funcs = [reward_funcs] + self.reward_func_names = [] + for i, reward_func in enumerate(reward_funcs): + if isinstance(reward_func, str): + model_init_kwargs = args.model_init_kwargs or {} + # Distributed training requires device_map=None ("auto" fails) + if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + model_init_kwargs["device_map"] = None + reward_funcs[i] = AutoModelForSequenceClassification.from_pretrained( + reward_func, num_labels=1, **model_init_kwargs + ) + if isinstance(reward_funcs[i], nn.Module): # Use Module over PretrainedModel for compat w/ compiled models + self.reward_func_names.append(get_config_model_id(reward_funcs[i].config).split("/")[-1]) + else: + self.reward_func_names.append(reward_funcs[i].__name__) + self.reward_funcs = reward_funcs + + # Reward weights + if args.reward_weights is not None: + if len(args.reward_weights) != len(reward_funcs): + raise ValueError( + f"Number of reward weights ({len(args.reward_weights)}) must match number of reward " + f"functions ({len(reward_funcs)})" + ) + self.reward_weights = torch.tensor(args.reward_weights, dtype=torch.float32) + else: + self.reward_weights = torch.ones(len(reward_funcs), dtype=torch.float32) + + # Reward processing class + if reward_processing_classes is None: + reward_processing_classes = [None] * len(reward_funcs) + elif not isinstance(reward_processing_classes, list): + reward_processing_classes = [reward_processing_classes] + if len(reward_processing_classes) != len(reward_funcs): + raise ValueError( + f"The number of reward processing classes ({len(reward_processing_classes)}) must match the number of " + f"reward functions ({len(reward_funcs)})." + ) + + for i, (reward_processing_class, reward_func) in enumerate( + zip(reward_processing_classes, reward_funcs, strict=True) + ): + if isinstance(reward_func, PreTrainedModel): + if reward_processing_class is None: + reward_processing_class = AutoTokenizer.from_pretrained(get_config_model_id(reward_func.config)) + if reward_processing_class.pad_token_id is None: + reward_processing_class.pad_token = reward_processing_class.eos_token + # The reward model computes the reward for the latest non-padded token in the input sequence. + # So it's important to set the pad token ID to the padding token ID of the processing class. + reward_func.config.pad_token_id = reward_processing_class.pad_token_id + reward_processing_classes[i] = reward_processing_class + + self.reward_processing_classes = reward_processing_classes + + # Rollout function + if rollout_func is not None and os.environ.get("TRL_EXPERIMENTAL_SILENCE", "0") != "1": + warnings.warn( + "You are using 'rollout_func', which is an experimental feature. This API may change or be removed at " + "any time without prior notice. Silence this warning by setting environment variable " + "TRL_EXPERIMENTAL_SILENCE=1.", + UserWarning, + stacklevel=2, + ) + self.rollout_func = rollout_func + if environment_factory is not None and os.environ.get("TRL_EXPERIMENTAL_SILENCE", "0") != "1": + warnings.warn( + "You are using 'environment_factory', which is an experimental feature. This API may change or be " + "removed at any time without prior notice. Silence this warning by setting environment variable " + "TRL_EXPERIMENTAL_SILENCE=1.", + UserWarning, + stacklevel=2, + ) + + # Tools + if tools: + if not Version(transformers.__version__) >= Version("5.0.0"): + raise ImportError( + "Using tools with GRPOTrainer requires transformers version 5.0.0 or higher. Please upgrade " + "transformers with `pip install --upgrade transformers` to use this feature." + ) + if environment_factory: + if not Version(transformers.__version__) >= Version("5.2.0"): + raise ImportError( + "Using `environment_factory` with GRPOTrainer requires transformers version 5.2.0 or higher. " + "Please install transformers from the main branch with `pip install " + "git+https://github.com/huggingface/transformers.git@main` to use this feature." + ) + if tools or environment_factory: + if not is_jmespath_available(): + raise ImportError( + "Using tools with GRPOTrainer requires the jmespath library for response parsing. Please install " + "it with `pip install jmespath` to use this feature." + ) + if not supports_tool_calling(processing_class): + raise ValueError( + "The provided chat template does not support tool calling. The template must be able to render a " + "full tool-calling conversation (user -> assistant with tool_calls -> tool)." + ) + + # Create the environments and extract their methods to be used as tools. We create one environment per rollout + generation_batch_size = args.per_device_train_batch_size * args.steps_per_generation + if environment_factory is not None: + self.environments = [environment_factory() for _ in range(generation_batch_size)] + environment_methods = [[] for _ in range(generation_batch_size)] + for i, environment in enumerate(self.environments): + has_reset = False + for name, member in inspect.getmembers(environment, predicate=inspect.ismethod): + if name == "reset": + has_reset = True + elif not name.startswith("_"): + environment_methods[i].append(member) + if not has_reset: + raise ValueError( + "Each environment instance returned by `environment_factory` must define a callable `reset` " + ) + else: + self.environments = None + + tools = tools or [] + self._sync_tool_dicts = [{} for _ in range(generation_batch_size)] + self._async_tool_dicts = [{} for _ in range(generation_batch_size)] + for i in range(generation_batch_size): + for tool in tools + (environment_methods[i] if self.environments is not None else []): + if inspect.iscoroutinefunction(tool): + self._async_tool_dicts[i][tool.__name__] = tool + else: + self._sync_tool_dicts[i][tool.__name__] = tool + + self.tools = tools + (environment_methods[0] if self.environments is not None else []) + + # Check for async functions to start an event loop on a daemon thread + self._has_async_funcs = any(inspect.iscoroutinefunction(func) for func in self.reward_funcs + self.tools) + + if self._has_async_funcs: + self.async_loop_thread, self.async_loop, self.async_loop_ready_event = start_event_loop_in_daemon( + name="GRPOTrainer-AsyncLoop" + ) + # wait until the event loop is running in the daemon thread + self.async_loop_ready_event.wait() + atexit.register(shutdown_event_loop_in_daemon, self.async_loop_thread, self.async_loop) + + # At the time of initial implementation, most tokenizers do not have built-in support for response schemas. + # While waiting for broader adoption, we provide this utility function to manually set the response schema for + # known chat templates. `response_schema` lives on the (inner) tokenizer, since `parse_response` is a tokenizer + # method that reads `self.response_schema`. + if self.tools and getattr(self._tokenizer, "response_schema", None) is None: + processing_class = add_response_schema(processing_class) + # In multi-turn training, the chat template *must* be prefix-preserving. If the tokenizer's original template + # isn't, we replace it at initialization with a training-safe, prefix-preserving template. + if self.tools and not is_chat_template_prefix_preserving(processing_class): + self.chat_template = get_training_chat_template(processing_class) + else: + self.chat_template = None + + # Training arguments + self.max_completion_length = args.max_completion_length # = |o_i| in the GRPO paper + self.num_generations = args.num_generations # = G in the GRPO paper + self.max_tool_calling_iterations = args.max_tool_calling_iterations or sys.maxsize + self.num_generations_eval = args.num_generations_eval or self.num_generations + self.chat_template_kwargs = args.chat_template_kwargs or {} + self.temperature = args.temperature + self.top_p = args.top_p + self.top_k = args.top_k + self.min_p = args.min_p + self.repetition_penalty = args.repetition_penalty + self.use_transformers_paged = args.use_transformers_paged + self.pad_to_multiple_of = args.pad_to_multiple_of + self.use_vllm = args.use_vllm + self.vllm_mode = args.vllm_mode + self.vllm_gpu_memory_utilization = args.vllm_gpu_memory_utilization # only applies to colocation mode + self.vllm_tensor_parallel_size = args.vllm_tensor_parallel_size # only applies to colocation mode + self.vllm_importance_sampling_correction = args.vllm_importance_sampling_correction + self.vllm_importance_sampling_mode = args.vllm_importance_sampling_mode + self.vllm_importance_sampling_clip_max = args.vllm_importance_sampling_clip_max + self.vllm_importance_sampling_clip_min = args.vllm_importance_sampling_clip_min + self.use_liger_kernel = args.use_liger_kernel + self.loss_type = args.loss_type + self.multi_objective_aggregation = args.multi_objective_aggregation + self.scale_rewards = args.scale_rewards + self.importance_sampling_level = args.importance_sampling_level + self.off_policy_mask_threshold = args.off_policy_mask_threshold + if self.use_liger_kernel and self.off_policy_mask_threshold is not None: + raise ValueError("Liger kernel does not support off-policy sequence masking yet.") + self.mask_truncated_completions = args.mask_truncated_completions + self.top_entropy_quantile = args.top_entropy_quantile + if self.use_liger_kernel and self.top_entropy_quantile < 1.0: + raise NotImplementedError( + "Liger Kernels don't currently support masking token positions based on entropy." + ) + if self.use_liger_kernel and self.importance_sampling_level not in ("token", "sequence"): + raise ValueError( + f"Unknown importance sampling level: {self.importance_sampling_level}. " + "Possible values are 'token' and 'sequence'." + ) + + # Datasets + self.shuffle_dataset = args.shuffle_dataset + + if train_dataset is None: + raise ValueError("`train_dataset` is required") + elif ( + isinstance(train_dataset, IterableDataset) + or isinstance(eval_dataset, IterableDataset) + or ( + isinstance(eval_dataset, dict) and any(isinstance(ds, IterableDataset) for ds in eval_dataset.values()) + ) + ): + # See https://github.com/huggingface/trl/issues/3213 + raise NotImplementedError( + "Iterable datasets are not yet supported in GRPOTrainer. Please use a standard dataset instead." + ) + + if args.loss_type == "luspo" and args.importance_sampling_level != "sequence": + logger.warning( + "When using `'luspo'` loss, `importance_sampling_level` should be set to `'sequence'` to mirror the " + "paper's setup." + ) + + if args.loss_type == "vespo" and args.importance_sampling_level != "token": + logger.warning( + "VESPO computes sequence-level importance weights internally. `importance_sampling_level` should be " + "set to `'token'` (the default)." + ) + + if self.loss_type == "vespo" and self.use_vllm and self.vllm_importance_sampling_correction: + if self.vllm_importance_sampling_mode not in ["token_truncate", "token_mask"]: + raise ValueError( + f"VESPO loss requires `vllm_importance_sampling_mode` to be either 'token_truncate' or " + f"'token_mask'. Got: {self.vllm_importance_sampling_mode}." + ) + + # Multi-step + self.num_iterations = args.num_iterations # = 𝜇 in the GRPO paper + self.epsilon_low = args.epsilon + self.epsilon_high = args.epsilon_high if args.epsilon_high is not None else args.epsilon + # Tracks the number of iterations (forward + backward passes), including those within a grad accum cycle + self._step = 0 + # Buffer the batch to reuse generated outputs across multiple updates. For more details, see + # `_get_train_sampler` and `_prepare_inputs`. + self._buffered_inputs = None + + # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was + # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream + # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we + # default to the recommended non-reentrant behavior here, while preserving any user-provided value. + if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"): + args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {} + args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False) + + super().__init__( + model=model, + args=args, + data_collator=identity, # No data collation is needed in GRPO + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + callbacks=callbacks, + optimizers=optimizers, + # In Trainer, `training_step` scales the loss by `gradient_accumulation_steps` only if `compute_loss_func` + # is None. For DAPO, loss scaling instead depends on the total number of completions tokens across the + # global accumulated batch. To control scaling ourselves, we must disable Trainer’s built-in scaling. The + # simplest (though a bit hacky) way is to set `compute_loss_func` to any non-None value, which bypasses + # that behavior without rewriting `training_step`. + compute_loss_func="non-None value to disable scaling", + ) + + # Reference model + self.beta = args.beta + if self.beta == 0.0: + # If beta is 0.0, the reference model is not needed + self.ref_model = None + elif is_peft_model(model): + # If PEFT is used, the reference model is not needed since the adapter can be disabled + # to revert to the initial model. + self.ref_model = None + else: + # For deepspeed, fsdp or non-distributed models, create a reference model from scratch + model_init_kwargs = args.model_init_kwargs or {} + # Distributed training requires device_map=None ("auto" fails) + if self.args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + model_init_kwargs["device_map"] = None + self.ref_model = create_model_from_path(get_config_model_id(self.model.config), **model_init_kwargs) + + # Disable dropout in the models + if args.disable_dropout: + disable_dropout_in_model(model) + if self.ref_model is not None: + disable_dropout_in_model(self.ref_model) + + # Cast LM Head To FP32 + if args.cast_lm_head_to_fp32: + + def _cast_lm_head_to_fp32(target_model: PreTrainedModel): + """Cast lm_head to fp32 while preserving embedding output dtype if tied.""" + + def cast_inputs_to_fp32(module, inputs): + # Preserve other positional args and kwargs untouched + if not inputs: + return inputs + return (inputs[0].to(torch.float32),) + inputs[1:] + + original_dtype_local = target_model.lm_head.weight.dtype + target_model.lm_head = target_model.lm_head.float() + target_model.lm_head.register_forward_pre_hook(cast_inputs_to_fp32) + + if target_model.config.tie_word_embeddings: + + def cast_outputs_to_original_dtype(module, args, output): + return output.to(original_dtype_local) + + # Only cast activations; weights are now fp32 (intentional for numerical stability of logits) + target_model.model.embed_tokens.register_forward_hook(cast_outputs_to_original_dtype) + + _cast_lm_head_to_fp32(model) + if self.ref_model is not None: + _cast_lm_head_to_fp32(self.ref_model) + + # Liger loss + if self.use_liger_kernel: + if not is_liger_kernel_available(): + raise ImportError( + "Liger is required to use `use_liger_kernel` as the GRPO loss. Run `pip install liger-kernel`." + ) + # redirect the model.module forward to the model forward to ensure pre-forward hooks are called + self._forward_redirection = _ForwardRedirection() + + self.liger_grpo_loss = LigerFusedLinearGRPOLoss( + beta=self.beta, + epsilon_low=self.epsilon_low, + epsilon_high=self.epsilon_high, + temperature=self.temperature, + use_ref_model=self.beta != 0.0, + loss_type=self.loss_type, + max_completion_length=self.max_completion_length, + importance_sampling_level=self.importance_sampling_level, + delta=args.delta, + use_bias_correction_kl=args.use_bias_correction_kl, + sapo_temperature_pos=args.sapo_temperature_pos, + sapo_temperature_neg=args.sapo_temperature_neg, + vespo_k_pos=args.vespo_k_pos, + vespo_lambda_pos=args.vespo_lambda_pos, + vespo_k_neg=args.vespo_k_neg, + vespo_lambda_neg=args.vespo_lambda_neg, + ) + + # Initialize the metrics + self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)} + self._total_train_tokens = 0 + self._current_train_step_time = 0.0 + self.log_completions = args.log_completions + self.log_unique_prompts = args.log_unique_prompts + self.num_completions_to_print = args.num_completions_to_print + # Keep logs sized to the generation batch to record only outputs from the latest model update. + self._logs = { + "images": deque(maxlen=args.generation_batch_size), + "prompt": deque(maxlen=args.generation_batch_size), + "completion": deque(maxlen=args.generation_batch_size), + "rewards": defaultdict(lambda: deque(maxlen=args.generation_batch_size)), + "advantages": deque(maxlen=args.generation_batch_size), + "extra": defaultdict(lambda: deque(maxlen=args.generation_batch_size)), + } + # Buffers for user-logged data from reward functions, flushed after gathering + self._pending_extra_logs = defaultdict(list) + self._pending_metrics = defaultdict(list) + + # Ensure each process receives a unique seed to prevent duplicate completions when generating with + # transformers if num_generations exceeds per_device_train_batch_size. We could skip it if we use vLLM, but + # it's safer to set it in all cases. + set_seed(args.seed, device_specific=True) + + if self.use_vllm: + # Initialize vLLM generation backend + self.vllm_generation = VLLMGeneration( + model=self.model, + accelerator=self.accelerator, + processing_class=self.processing_class, + # vLLM configuration + mode=args.vllm_mode, + structured_outputs_regex=args.vllm_structured_outputs_regex, + # Server mode configuration + server_base_url=args.vllm_server_base_url, + server_host=args.vllm_server_host, + server_port=args.vllm_server_port, + group_port=args.vllm_group_port, + server_timeout=args.vllm_server_timeout, + # Colocate mode configuration + tensor_parallel_size=args.vllm_tensor_parallel_size, + gpu_memory_utilization=args.vllm_gpu_memory_utilization, + max_model_length=args.vllm_max_model_length, + max_num_seqs=args.per_device_train_batch_size + * args.vllm_tensor_parallel_size + * args.steps_per_generation, + enable_sleep_mode=args.vllm_enable_sleep_mode, + model_impl=args.vllm_model_impl, + # Generation configuration + repetition_penalty=self.repetition_penalty, + temperature=self.temperature, + top_p=self.top_p, + top_k=self.top_k, + min_p=self.min_p, + max_completion_length=self.max_completion_length, + logprobs=0, # we only need the generated token logprobs for the importance sampling correction + generation_kwargs=args.generation_kwargs, + ) + self._last_loaded_step = -1 # tag to avoid useless loading during grad accumulation + else: + generation_kwargs = { + "max_new_tokens": self.max_completion_length, + "do_sample": True, + "pad_token_id": self._tokenizer.pad_token_id, + "bos_token_id": self._tokenizer.bos_token_id, + "eos_token_id": self._tokenizer.eos_token_id, + "temperature": self.temperature, + "top_p": self.top_p, + "top_k": self.top_k, + "min_p": self.min_p, + "repetition_penalty": self.repetition_penalty, + "cache_implementation": args.cache_implementation, + } + if args.generation_kwargs is not None: + generation_kwargs.update(args.generation_kwargs) + self.generation_config = GenerationConfig(**generation_kwargs, disable_compile=True) + # Keep training-specific generation kwargs to overwrite model's original generation config + self.generation_kwargs = generation_kwargs + + # Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the + # model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set + # self.model_accepts_loss_kwargs to False to enable scaling. + self.model_accepts_loss_kwargs = False + self._dist = DistributedBackend(self.accelerator) + + # Add tags to the model + self.model.add_model_tags(self._tag_names) + + if self.ref_model is not None: + if self.is_deepspeed_enabled: + self.ref_model = prepare_deepspeed(self.ref_model, self.accelerator) + elif self.is_fsdp_enabled: + self.ref_model = prepare_fsdp(self.ref_model, self.accelerator) + else: + self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True) + + if args.sync_ref_model: + if self.beta == 0.0: + raise ValueError( + "You passed `sync_ref_model=True` while `beta=0.0`, which means the reference model is not used " + "during training. Consequently, GRPOTrainer does not create a `ref_model` instance, and there is " + "nothing to synchronize. Please set `sync_ref_model=False`, or set `beta` to a non-zero value." + ) + if is_peft_model(model): + raise NotImplementedError( + "You passed `sync_ref_model=True` while using a PEFT model, which is currently not supported. " + "With PEFT, GRPOTrainer does not keep a separate reference model in memory; instead, it recovers " + "reference behavior by temporarily disabling the adapter. As a result, there is no standalone " + "`ref_model` instance to synchronize. Use `sync_ref_model=False`, or opt for full fine-tuning if " + "you need a synced reference model. If you need `sync_ref_model` to work with PEFT, please open a " + "feature request at https://github.com/huggingface/trl/issues." + ) + self.add_callback(SyncRefModelCallback(ref_model=self.ref_model, accelerator=self.accelerator)) + + for i, reward_func in enumerate(self.reward_funcs): + if isinstance(reward_func, PreTrainedModel): + if self.is_deepspeed_enabled: + self.reward_funcs[i] = prepare_deepspeed(reward_func, self.accelerator) + else: + # set device placement to True to make `prepare_model` move `reward_func` to device when using fsdp + self.reward_funcs[i] = self.accelerator.prepare_model( + reward_func, evaluation_mode=True, device_placement=True + ) + + if self.accelerator.is_main_process and self.log_completions: + os.makedirs(os.path.join(self.args.output_dir, "completions"), exist_ok=True) + if self.args.log_completions_hub_repo is not None: + repo_id = self.args.log_completions_hub_repo + create_repo(repo_id, private=self.args.hub_private_repo, repo_type="dataset", exist_ok=True) + template_path = pkg_resources.files("trl").joinpath("templates/completions_dataset_card.md") + card_data = DatasetCardData( + pretty_name="TRL Completion logs", + tags=["trl", "trl-logs", "completions"], + ) + card = DatasetCard.from_template( + card_data=card_data, + template_path=str(template_path), + repo_id=repo_id, + hub_model_id=self.args.hub_model_id, + ) + card.push_to_hub(repo_id) + self.commit_scheduler = CommitScheduler( + repo_id=repo_id, + repo_type="dataset", + folder_path=f"{self.args.output_dir}/completions", + every=2, # minutes + allow_patterns=["*.parquet"], + ) + + def _set_signature_columns_if_needed(self): + # If `self.args.remove_unused_columns` is True, non-signature columns are removed. + # By default, this method sets `self._signature_columns` to the model's expected inputs (usually, "input_ids" + # and "attention_mask"). In GRPOTrainer, we preprocess data, so using the model's signature columns doesn't + # work. Instead, we set them to the columns expected by the `training_step` method, hence the override. + if self._signature_columns is None: + self._signature_columns = ["prompt", "image", "images"] + + # This method overrides `Trainer.get_train_dataloader` to support our custom batching strategy. + # Instead of returning a standard per-step batch (i.e., `per_device_batch_size), our dataloader loads an + # *generation* batch (i.e., `per_device_batch_size × steps_per_generation`). This allows us to generate completions + # once every steps_per_generation step—rather than once per accumulation step—which is significantly more + # efficient. The only change from the original implementation is multiplying the batch size by + # `steps_per_generation`. Thus, `_prepare_inputs` is called with this *generation* batch, and it handles the + # splitting internally. + # Maintenance note: This method is a copy-paste of the original `Trainer.get_train_dataloader` with only one line + # modification. + def get_train_dataloader(self): + return self._get_dataloader( + dataset=self.train_dataset, + description="Training", + batch_size=self._train_batch_size * self.args.steps_per_generation, # < this is the change + sampler_fn=self._get_train_sampler, + is_training=True, + ) + + def _get_train_sampler(self, dataset: Dataset | None = None) -> Sampler: + # Returns a sampler that + # 1. ensures each prompt is repeated across multiple processes. This guarantees that identical prompts are + # distributed to different GPUs, allowing rewards to be computed and normalized correctly within each prompt + # group. Using the same seed across processes ensures consistent prompt assignment, preventing discrepancies + # in group formation. + # 2. repeats the batch multiple times to allow reusing generations across multiple updates. Refer to + # _prepare_inputs to see how the generations are stored and reused. + + # In the following figure, the values are the prompt indices. The first row shows the first sampled batch, the + # second row shows the second sampled batch, and so on. + # + # | GPU 0 | GPU 1 | + # + # global_step step <-───> num_generations=2 + # <-───────> per_device_train_batch_size=3 + # grad_accum ▲ ▲ 0 0 0 0 1 1 2 2 <- Generate for the first `steps_per_generation` (prompts 0 to 11); store the completions; use the first slice to compute the loss + # =2 ▼ | 0 1 3 3 4 4 5 5 <- Take the stored generations and use the second slice to compute the loss + # | + # | 1 2 6 6 7 7 8 8 <- Take the stored generations and use the third slice to compute the loss + # steps_per_gen=4 ▼ 1 3 9 9 10 10 11 11 <- Take the stored generations and use the fourth slice to compute the loss + # + # 2 4 12 12 13 13 14 14 <- Generate for the second `steps_per_generation` (prompts 12 to 23); store the completions; use the first slice to compute the loss + # 2 5 15 15 16 16 17 17 <- Take the stored generations and use the second slice to compute the loss + # ... + if dataset is None: + dataset = self.train_dataset + return RepeatSampler( + data_source=dataset, + mini_repeat_count=self.num_generations, + batch_size=self.args.generation_batch_size // self.num_generations, + repeat_count=self.num_iterations * self.args.steps_per_generation, + shuffle=self.shuffle_dataset, + seed=self.args.seed, + ) + + def _get_eval_sampler(self, eval_dataset) -> Sampler: + # See _get_train_sampler for an explanation of the sampler. + return RepeatSampler( + data_source=eval_dataset, + mini_repeat_count=self.num_generations_eval, + seed=self.args.seed, + ) + + @profiling_decorator + def _get_last_hidden_state( + self, + unwrapped_model, + input_ids, + attention_mask, + logits_to_keep, + pixel_values=None, + image_grid_thw=None, + pixel_attention_mask=None, + image_sizes=None, + image_position_ids=None, + ): + if is_peft_model(unwrapped_model): + unwrapped_model = unwrapped_model.base_model.model + + # Build model inputs - check if the model supports logits_to_keep (some models and VLMs don't) + model_inputs = {"input_ids": input_ids, "attention_mask": attention_mask} + + # For Qwen models: + if image_grid_thw is not None and pixel_values is not None: + model_inputs["image_grid_thw"] = image_grid_thw + # For Gemma, SmolVLM2, LLaVa-Next etc.: + if pixel_values is not None: + model_inputs["pixel_values"] = pixel_values + # For SmolVLM2 + if pixel_attention_mask is not None: + model_inputs["pixel_attention_mask"] = pixel_attention_mask + # For LLaVa-Next + if image_sizes is not None: + model_inputs["image_sizes"] = image_sizes + if image_position_ids is not None: + model_inputs["image_position_ids"] = image_position_ids + + # Only add logits_to_keep if the model supports it + if "logits_to_keep" in self.model_kwarg_keys: + # We add 1 to `logits_to_keep` because the last logits of the sequence is later excluded + model_inputs["logits_to_keep"] = logits_to_keep + 1 + + model_inputs["use_cache"] = False # only used in generation; set False to suppress warnings + + # `base_model` gives the backbone model (skipping `lm_head`) — text decoder for LMs, multimodal wrapper for + # VLMs (so vision-token injection runs before the text decoder). `get_decoder()` won't do: on VLMs it + # returns just the text stack and feeds image-placeholder IDs through it. + # Pre-5.0 transformers VLMs set `base_model_prefix = ""` so `base_model is self` (re-runs `lm_head`). + # Fall back to `.model` there. + if self._is_vlm and Version(transformers.__version__) < Version("5.0.0"): + backbone = unwrapped_model.model + else: + backbone = unwrapped_model.base_model + last_hidden_state = backbone(**model_inputs).last_hidden_state + # Exclude the last value: it corresponds to the next token pred + last_hidden_state = last_hidden_state[:, :-1, :] # (B, L-1, H) + # Only keep the last logits_to_keep. For model that support logits_to_keep, this is a no-op. + last_hidden_state = last_hidden_state[:, -logits_to_keep:, :] # (B, logits_to_keep, H) + return last_hidden_state + + def get_high_entropy_mask(self, entropies: torch.Tensor, mask: torch.Tensor, threshold: float) -> torch.Tensor: + """ + 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. + """ + local = entropies[mask.bool()].float() + + # Use a negative pad_value as a sentinel because entropy values are always >= 0. + # This guarantees that the sentinel cannot collide with any real entropy value. + pad_value = -1e9 + + # Pad across processes so that every rank has the same tensor length + padded = self.accelerator.pad_across_processes(local, dim=0, pad_index=pad_value) + gathered = self.accelerator.gather(padded) + + # Drop sentinel values (safe because no entropy can be negative) + gathered = gathered[gathered != pad_value] + + if gathered.numel() == 0: + return torch.zeros_like(entropies, dtype=torch.bool) + + entropy_threshold = torch.quantile(gathered, threshold) + masked_entropies = entropies * mask.float() + entropy_mask = masked_entropies >= entropy_threshold + return entropy_mask & mask.bool() # ensure padding tokens are always masked out + + @profiling_decorator + def _get_per_token_logps_and_entropies( + self, + model, + input_ids, + attention_mask, + logits_to_keep, + batch_size=None, + compute_entropy=False, + pixel_values=None, + image_grid_thw=None, + num_images=None, + pixel_attention_mask=None, + image_sizes=None, + token_type_ids=None, + mm_token_type_ids=None, + image_position_ids=None, + ) -> tuple[torch.Tensor, torch.Tensor | None]: + """Compute log-probs and (optionally) entropies for each token.""" + batch_size = batch_size or input_ids.size(0) # Chunk inputs into smaller batches to reduce memory peak + all_logps = [] + all_entropies = [] + for start in range(0, input_ids.size(0), batch_size): + input_ids_batch = input_ids[start : start + batch_size] + attention_mask_batch = attention_mask[start : start + batch_size] + + # Build model inputs + model_inputs = {"input_ids": input_ids_batch, "attention_mask": attention_mask_batch} + if image_grid_thw is not None and pixel_values is not None: + rows_per_image = image_grid_thw.prod(dim=-1) + rows_per_sample = torch.split(rows_per_image, num_images) + rows_per_sample = torch.stack([s.sum() for s in rows_per_sample]) + cum_rows = torch.cat([torch.tensor([0], device=rows_per_sample.device), rows_per_sample.cumsum(0)]) + row_start, row_end = cum_rows[start].item(), cum_rows[start + batch_size].item() + model_inputs["pixel_values"] = pixel_values[row_start:row_end] + cum_imgs = torch.tensor([0] + num_images).cumsum(0) + img_start, img_end = cum_imgs[start], cum_imgs[start + batch_size] + model_inputs["image_grid_thw"] = image_grid_thw[img_start:img_end] + elif image_position_ids is not None and pixel_values is not None: + cum_imgs = torch.tensor([0] + num_images).cumsum(0) + img_start, img_end = cum_imgs[start], cum_imgs[start + batch_size] + model_inputs["pixel_values"] = pixel_values[img_start:img_end] + model_inputs["image_position_ids"] = image_position_ids[img_start:img_end] + elif pixel_values is not None: + model_inputs["pixel_values"] = pixel_values[start : start + batch_size] + if pixel_attention_mask is not None: + model_inputs["pixel_attention_mask"] = pixel_attention_mask[start : start + batch_size] + if image_sizes is not None: + model_inputs["image_sizes"] = image_sizes[start : start + batch_size] + if token_type_ids is not None: + model_inputs["token_type_ids"] = token_type_ids[start : start + batch_size] + if mm_token_type_ids is not None: + model_inputs["mm_token_type_ids"] = mm_token_type_ids[start : start + batch_size] + + # Only add logits_to_keep if the model supports it + if "logits_to_keep" in self.model_kwarg_keys: + # We add 1 to `logits_to_keep` because the last logits of the sequence is later excluded + model_inputs["logits_to_keep"] = logits_to_keep + 1 + + model_inputs["use_cache"] = False # only used in generation; set False to suppress warnings + + logits = model(**model_inputs).logits + # Exclude the last value: it corresponds to the next token pred + logits = logits[:, :-1, :] # (B, L-1, H) + # Only keep the last logits_to_keep. For model that support logits_to_keep, this is a no-op. + logits = logits[:, -logits_to_keep:, :] # (B, logits_to_keep, H) + # Divide logits by sampling temperature. + # See https://huggingface.co/blog/the_n_implementation_details_of_rlhf_with_ppo#policy-training-implementation-details + logits.div_(self.temperature) + completion_ids = input_ids_batch[:, -logits_to_keep:] + logps = selective_log_softmax(logits, completion_ids) # compute logprobs + all_logps.append(logps) + + if compute_entropy: + with torch.no_grad(): + entropies = entropy_from_logits(logits) + all_entropies.append(entropies) + + logps = torch.cat(all_logps, dim=0) + entropies = torch.cat(all_entropies, dim=0) if compute_entropy else None + return logps, entropies + + def training_step(self, model, inputs, num_items_in_batch): + time_before = time.perf_counter() + output = super().training_step(model, inputs, num_items_in_batch) + self._step += 1 + time_after = time.perf_counter() + self._current_train_step_time += time_after - time_before + if self._step % self.current_gradient_accumulation_steps == 0: + self._metrics["train"]["step_time"].append(self._current_train_step_time) + self._current_train_step_time = 0.0 + return output + + @profiling_decorator + def _prepare_inputs(self, generation_batch: dict[str, torch.Tensor | Any]) -> dict[str, torch.Tensor | Any]: + # Prepares inputs for model training/evaluation by managing completion generation and batch handling. + # During training: + # - Receives the local generation batch (Per-GPU batch size × steps per generation) + # from the modified training dataloader instead of the standard local batch + # - Generates completions once for the entire generation batch and splits it into batches of size + # `per_device_train_batch_size` + # - Buffers these completions and returns the appropriate slice for the current accumulation step + # - Optimizes by regenerating completions only periodically (every steps_per_generation * num_iterations) + # During evaluation: + # - The input is treated as a standard local batch (no accumulation, no multiple iterations) + # - Completions are generated for each batch without buffering or reuse + # Returns a single local batch in both cases. + + mode = "train" if self.model.training else "eval" + if mode == "train": + generate_every = self.args.steps_per_generation * self.num_iterations + if self._step % generate_every == 0 or self._buffered_inputs is None: + # self._buffered_inputs=None can occur when resuming from a checkpoint + generation_batch = self._generate_and_score_completions(generation_batch) + generation_batch = split_pixel_values_by_grid(generation_batch) + generation_batch = shuffle_sequence_dict(generation_batch) + generation_batches = split_tensor_dict(generation_batch, self.args.steps_per_generation) + self._buffered_inputs = [unsplit_pixel_values_by_grid(batch) for batch in generation_batches] + inputs = self._buffered_inputs[self._step % self.args.steps_per_generation] + else: + # In evaluation, there is neither batch grouping for generation, nor multiple iterations, hence + # local generation batch == local eval batch + inputs = self._generate_and_score_completions(generation_batch) + return inputs + + def _log_completion_extra(self, column: str, values: list): + """ + Log extra columns to the completions table. Called from reward functions via the `log_extra` kwarg. + + Args: + column (`str`): + Name of the column to add. + values (`list`): + Values for the column, one per sample in the batch. + """ + self._pending_extra_logs[column].extend(values) + + def _log_metric(self, name: str, value: float): + """ + Log a scalar metric from a reward function. Called via the `log_metric` kwarg. Values are averaged over each + logging step and reported alongside built-in metrics like `kl` and `entropy`. + + Args: + name (`str`): + Name of the metric. + value (`float`): + Scalar value for this batch. + """ + self._pending_metrics[name].append(value) + + @profiling_decorator + def _calculate_rewards(self, inputs, prompts, completions, completion_ids_list): + device = self.accelerator.device + rewards_per_func = torch.zeros(len(prompts), len(self.reward_funcs), device=device) + + # Repeat all input columns (but "prompt", "completion", and "completion_ids") to match the num of generations + keys = [key for key in inputs[0] if key not in ["prompt", "completion", "completion_ids"]] + reward_kwargs = {key: [example[key] for example in inputs] for key in keys} + + # This allows for dynamic reward shaping based on training progress. + reward_kwargs["trainer_state"] = self.state + + # Allow reward functions to log extra columns to the completions table. + reward_kwargs["log_extra"] = self._log_completion_extra + + # Allow reward functions to log additional scalar metrics. + reward_kwargs["log_metric"] = self._log_metric + + async_funcs_info = [] # async custom functions for asyncio.gather + + for i, (reward_func, reward_processing_class, reward_func_name) in enumerate( + zip(self.reward_funcs, self.reward_processing_classes, self.reward_func_names, strict=True) + ): + if isinstance(reward_func, nn.Module): # Module (no PretrainedModel) for compat with compiled models + with profiling_context(self, reward_func_name): + if is_conversational(inputs[0]): + messages = [{"messages": p + c} for p, c in zip(prompts, completions, strict=True)] + texts = [ + apply_chat_template(x, reward_processing_class, **self.chat_template_kwargs)["text"] + for x in messages + ] + else: + texts = [p + c for p, c in zip(prompts, completions, strict=True)] + reward_inputs = reward_processing_class( + text=texts, return_tensors="pt", padding=True, padding_side="right", add_special_tokens=False + ) + reward_inputs = super()._prepare_inputs(reward_inputs) + with torch.inference_mode(): + rewards_per_func[:, i] = reward_func(**reward_inputs).logits[:, 0] # Shape (B*G,) + elif inspect.iscoroutinefunction(reward_func): # Separate async reward funcs to run them in parallel later + async_funcs_info.append((i, reward_func, reward_func_name)) + else: + # Run synchronous reward function + with profiling_context(self, reward_func_name): + if self.environments is not None: + reward_kwargs["environments"] = self.environments + output_reward_func = reward_func( + prompts=prompts, completions=completions, completion_ids=completion_ids_list, **reward_kwargs + ) + # Convert None values to NaN + output_reward_func = [reward if reward is not None else torch.nan for reward in output_reward_func] + rewards_per_func[:, i] = torch.tensor(output_reward_func, dtype=torch.float32, device=device) + + # Execute async custom functions in parallel using asyncio.gather + if async_funcs_info: + + async def _invoke_async(index, func, func_name): + with profiling_context(self, func_name): + output = await func( + prompts=prompts, completions=completions, completion_ids=completion_ids_list, **reward_kwargs + ) + output = [r if r is not None else torch.nan for r in output] + return index, output + + async def _run_async_funcs(): + coros = [_invoke_async(i, func, func_name) for (i, func, func_name) in async_funcs_info] + return await asyncio.gather(*coros) + + async_results = asyncio.run_coroutine_threadsafe(_run_async_funcs(), self.async_loop).result() + for idx, output_reward_func in async_results: + rewards_per_func[:, idx] = torch.tensor(output_reward_func, dtype=torch.float32, device=device) + + # If all reward functions return None for a given row, issue a detailed warning + if torch.isnan(rewards_per_func).all(dim=1).any(): + nan_row_idx = torch.isnan(rewards_per_func).all(dim=1).nonzero(as_tuple=True)[0][0] + row_reward_kwargs = { + key: value[nan_row_idx] + for key, value in reward_kwargs.items() + if key not in ("trainer_state", "log_extra", "log_metric") + } + row_reward_kwargs["prompt"] = prompts[nan_row_idx] + row_reward_kwargs["completion"] = completions[nan_row_idx] + logger.warning( + f"All reward functions returned None for the following kwargs:\n{row_reward_kwargs}\n" + "Please ensure that at least one reward function returns a valid reward." + ) + + # Gather the reward per function: this part is crucial, because the rewards are normalized per group and the + # completions may be distributed across processes + rewards_per_func = gather(rewards_per_func) + return rewards_per_func + + def _tokenize_prompts(self, prompts: list): + """Tokenize prompts and extract images/multimodal fields for generation.""" + if is_conversational({"prompt": prompts[0]}): + # Normalize string content to content blocks for VLM processors that don't handle plain strings. + if self._is_vlm: + prompts = [prepare_multimodal_messages(prompt) for prompt in prompts] + + # Extract images from messages for VLM support + images = [] + has_images = False + for prompt in prompts: + prompt_images = [] + for message in prompt: + if isinstance(message["content"], list): + for part in message["content"]: + if part["type"] == "image": + prompt_images.append(part["image"]) + has_images = True + images.append(prompt_images if prompt_images else None) + images = images if has_images else None + + # Workaround for a bug in transformers 5.3.0 where some processors (e.g. Qwen2.5-VL) crash on + # batched unpadded input (transformers#44514). + # Fixed in transformers 5.4.0 (transformers#44563). + needs_padding_workaround = Version("5.3.0") <= Version(transformers.__version__) < Version("5.4.0") + tokenized = self.processing_class.apply_chat_template( + conversation=prompts, + tools=self.tools or None, # `or None`: Llama bug: it renders tool boilerplate for tools=[] + chat_template=self.chat_template, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + **({"padding": True} if needs_padding_workaround else {}), + **self.chat_template_kwargs, + ) + if needs_padding_workaround: + # Unpad input_ids: remove padding tokens using attention_mask to get per-sequence lists + prompt_ids = [ + [tok for tok, m in zip(ids, mask, strict=True) if m] + for ids, mask in zip(tokenized["input_ids"], tokenized["attention_mask"], strict=True) + ] + else: + prompt_ids = tokenized["input_ids"] + # For VLMs, the processor returns extra multimodal fields (pixel_values, image_grid_thw, etc.) + multimodal_fields = {k: v for k, v in tokenized.items() if k not in ("input_ids", "attention_mask")} + else: + prompt_ids = self.processing_class(text=prompts)["input_ids"] + images = None + multimodal_fields = {} + return prompt_ids, images, multimodal_fields + + def _generate_single_turn(self, prompt_ids, images, multimodal_fields): + device = self.accelerator.device + mode = "train" if self.model.training else "eval" + + # Generate completions using either vLLM or regular generation + if self.use_vllm: + # Sync weights if training step changed + if self.state.global_step != self._last_loaded_step: + with profiling_context(self, "sync_weights"): + self.vllm_generation.sync_weights() + self._last_loaded_step = self.state.global_step + + # Generate using vLLM with raw token IDs + num_generations = self.num_generations if mode == "train" else self.num_generations_eval + _, completion_ids, logprobs, _ = self.vllm_generation.generate( + prompts=prompt_ids, + images=images, + num_generations=num_generations, + profiler=profiling_context(self, "vLLM.generate"), + ) + # vLLM returns per-token top-k logprobs; keep only the top-1 (sampled token) logprob + logprobs = [[lp[0] for lp in seq] for seq in logprobs] + + elif self.use_transformers_paged: + with ( + profiling_context(self, "transformers.generate_batch"), + unwrap_model_for_generation( + self.model_wrapped, self.accelerator, gather_deepspeed3_params=self.args.ds3_gather_for_generation + ) as unwrapped_model, + torch.no_grad(), + self._dist.summon_full_params(self.model_wrapped, recurse=False), + ): + # Cast to the appropriate dtype based on training configuration + if self.args.bf16: + unwrapped_model.to(torch.bfloat16) + elif self.args.fp16: + unwrapped_model.to(torch.float16) + if self.args.cast_lm_head_to_fp32: + unwrapped_model.lm_head.to(torch.float32) + # Continuous batching API expects 'inputs' arg only + all_outputs = unwrapped_model.generate_batch( + prompt_ids, generation_config=self.generation_config, progress_bar=False + ) + unwrapped_model.train() # restore training mode, as generate_batch forces eval mode + completion_ids = [output.generated_tokens for output in all_outputs.values()] + logprobs = None # not used in this case + + else: + # Regular generation path: left-pad token IDs into tensors + prompt_tensors = [torch.tensor(ids) for ids in prompt_ids] + padded_ids = pad(prompt_tensors, padding_value=self._tokenizer.pad_token_id, padding_side="left") + attention_mask = pad([torch.ones_like(t) for t in prompt_tensors], padding_value=0, padding_side="left") + generate_inputs = {"input_ids": padded_ids, "attention_mask": attention_mask} + # For VLMs, include multimodal fields as tensors (pixel_values, image_grid_thw, etc.) + for k, v in multimodal_fields.items(): + if isinstance(v, torch.Tensor): + generate_inputs[k] = v + elif isinstance(v, list) and v and isinstance(v[0], list): + # Per-token field (e.g., token_type_ids): left-pad like input_ids + generate_inputs[k] = pad([torch.tensor(x) for x in v], padding_value=0, padding_side="left") + else: + generate_inputs[k] = torch.tensor(np.array(v)) + generate_inputs = super()._prepare_inputs(generate_inputs) + + with ( + profiling_context(self, "transformers.generate"), + unwrap_model_for_generation( + self.model_wrapped, + self.accelerator, + gather_deepspeed3_params=self.args.ds3_gather_for_generation, + generation_kwargs=self.generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762 + ) as unwrapped_model, + torch.no_grad(), + self._dist.summon_full_params(self.model_wrapped, recurse=False), + ): + prompt_completion_ids = unwrapped_model.generate( + **generate_inputs, generation_config=self.generation_config + ) + # Compute prompt length and extract completion ids + prompt_length = generate_inputs["input_ids"].size(1) + completion_ids = prompt_completion_ids[:, prompt_length:] + + # Mask everything after the first EOS token + is_eos = completion_ids == self._tokenizer.eos_token_id + eos_idx = torch.full((is_eos.size(0),), is_eos.size(1), dtype=torch.long, device=device) + eos_idx[is_eos.any(dim=1)] = is_eos.int().argmax(dim=1)[is_eos.any(dim=1)] + sequence_indices = torch.arange(is_eos.size(1), device=device).expand(is_eos.size(0), -1) + completion_mask = (sequence_indices <= eos_idx.unsqueeze(1)).int() + completion_ids = [ + c[m].tolist() for c, m in zip(completion_ids.cpu(), completion_mask.bool().cpu(), strict=True) + ] + logprobs = None # not used in this case + + return completion_ids, logprobs + + def _get_tool_suffix_ids(self, tool_messages): + """Get token IDs for tool result formatting by using a minimal dummy conversation.""" + # Use the real tool name instead of a dummy: some templates (e.g. GPT-OSS) derive the tool response + # header from the assistant's tool call name. + dummy_tool_calls = [{"type": "function", "function": {"name": tool_messages[0]["name"], "arguments": {}}}] + dummy_messages = [ + {"role": "user", "content": "dummy"}, + { + "role": "assistant", + # "content" is required here because VLM processors crash on tokenize=True without it + # (KeyError in processing_utils.py). See huggingface/transformers#45290. + "content": "", + "tool_calls": dummy_tool_calls, + }, + ] + if self._is_vlm: + dummy_messages = prepare_multimodal_messages(dummy_messages) + tool_messages = prepare_multimodal_messages(tool_messages) + + prefix_ids = self.processing_class.apply_chat_template( + dummy_messages, + add_generation_prompt=False, + tokenize=True, + chat_template=self.chat_template, + return_dict=False, + **self.chat_template_kwargs, + ) + full_ids = self.processing_class.apply_chat_template( + dummy_messages + tool_messages, + add_generation_prompt=True, + tokenize=True, + chat_template=self.chat_template, + return_dict=False, + **self.chat_template_kwargs, + ) + # VLM processors return batched output (list of lists), unbatch for single conversation + if self._is_vlm: + prefix_ids = prefix_ids[0] + full_ids = full_ids[0] + + # Some chat templates (notably Qwen3/Qwen3.5) render "...<|im_end|>\n" after an assistant/tool block. + # When we compute `suffix_ids` by slicing `full_ids`, we must align the slicing boundary to + # EOS (not EOS + newline). Templates that don't use EOS as end-of-turn (e.g. Gemma uses + # ) skip this trimming. + eos_positions = [i for i, tok_id in enumerate(prefix_ids) if tok_id == self._tokenizer.eos_token_id] + if eos_positions: + prefix_ids = prefix_ids[: eos_positions[-1] + 1] + + if full_ids[: len(prefix_ids)] != prefix_ids: + raise ValueError("Unexpected tokenization: the EOS-trimmed prefix IDs are not a prefix of the full IDs.") + return full_ids[len(prefix_ids) :] + + def _tool_call_loop(self, prompts, prompt_ids, completion_ids, completions, logprobs, images, multimodal_fields): + # Tool execution loop: execute tools, then regenerate completions with tool results appended to the prompt + tool_calls = [completion[0].get("tool_calls") for completion in completions] + idxs_with_tool = [idx for idx, tool_call in enumerate(tool_calls) if tool_call] + tool_calls = [tool_calls[idx] for idx in idxs_with_tool] + tool_mask = [[1] * len(ids) for ids in completion_ids] # 0 for tool result tokens, 1 elsewhere + # Collect images from multimodal tool responses for the forward pass + tool_images = [[] for _ in completion_ids] + tool_call_count = 0 + tool_failure_count = 0 + iteration_num = 0 + + while idxs_with_tool and iteration_num < self.max_tool_calling_iterations: + prompt_completion_tools = [prompts[i] for i in idxs_with_tool] # select only prompts that need tool calls + # Snapshot state so we can rollback tool results that would exceed max_completion_length + completions_len_before = [len(completions[i]) for i in idxs_with_tool] + tool_images_len_before = [len(tool_images[i]) for i in idxs_with_tool] + prompts_len_before = [len(prompts[i]) for i in idxs_with_tool] + + # Call the tools, and build the new prompt for generation + for idx in range(len(idxs_with_tool)): + idx_with_tool = idxs_with_tool[idx] + tool_call_list = tool_calls[idx] + prompt_completion_tool = prompt_completion_tools[idx] + sync_tool_dict = self._sync_tool_dicts[idx_with_tool] + async_tool_dict = self._async_tool_dicts[idx_with_tool] + # Append the last assistant message (which triggered tool_calls) to the prompt + prompt_completion_tool.append(completions[idx_with_tool][-1]) + async_coros = [] + tool_call_results = [] + for tool_call in tool_call_list: + tool_call_count += 1 + if tool_call["type"] == "function": + function = tool_call["function"] + name = function["name"] + try: + if name in sync_tool_dict: + tool_call_results.append((name, sync_tool_dict[name](**function["arguments"]))) + elif name in async_tool_dict: + async_coros.append((name, async_tool_dict[name](**function["arguments"]))) + else: + raise ValueError(f"Tool {name} not found.") + except Exception as e: + tool_failure_count += 1 + result = {"error": str(e)} + tool_call_results.append((name, result)) + else: + tool_failure_count += 1 + name = tool_call.get("name", "unknown") + tool_call_results.append((name, {"error": f"Unsupported tool call type: {tool_call['type']}"})) + + if async_coros: + + async def _run_async_tools(async_coros): + coros = [coro for _, coro in async_coros] + results = await asyncio.gather(*coros, return_exceptions=True) + return [(name, result) for (name, _), result in zip(async_coros, results, strict=False)] + + async_results = asyncio.run_coroutine_threadsafe( + _run_async_tools(async_coros), self.async_loop + ).result() + + for name, result in async_results: + if isinstance(result, Exception): + tool_failure_count += 1 + tool_call_results.append((name, {"error": str(result)})) + else: + tool_call_results.append((name, result)) + + for name, result in tool_call_results: + # Support multimodal tool responses: if the tool returns a list of content blocks + # (e.g., [{"type": "image", "image": ...}, {"type": "text", "text": "..."}]), + # pass them through directly so _tokenize_prompts can extract images for VLMs. + content = result if isinstance(result, list) else str(result) + tool_message = {"role": "tool", "name": name, "content": content} + # Collect images from multimodal tool responses + if isinstance(content, list): + for part in content: + if isinstance(part, dict) and part.get("type") == "image": + tool_images[idx_with_tool].append(part["image"]) + prompt_completion_tool.append(tool_message) + completions[idx_with_tool].append(tool_message) + + # Build token IDs by concatenation: prompt + completion + tool_suffix. + prompt_completion_tool_ids = [] + for idx in range(len(idxs_with_tool)): + idx_with_tool = idxs_with_tool[idx] + # Extract trailing tool messages from completions + tool_messages = [] + for message in reversed(completions[idx_with_tool]): + if message["role"] == "tool": + tool_messages.insert(0, message) + else: + break + suffix_ids = self._get_tool_suffix_ids(tool_messages) + prompt_completion_tool_ids.append( + prompt_ids[idx_with_tool] + completion_ids[idx_with_tool] + suffix_ids + ) + + # Drop tool results whose addition would push the sequence past max_completion_length (the completion + # budget) or past the backend context ceiling (vLLM and transformers will error out on inputs longer than + # the model's max length). The sample exits the loop with its completion as-is, and the tool + # messages/images appended this iteration are rolled back so completions and tool_images stay consistent + # with completion_ids. + if self.use_vllm and self.vllm_mode == "colocate": + max_model_len = self.vllm_generation.llm.llm_engine.model_config.max_model_len + else: + config = self.model.config.text_config if self._is_vlm else self.model.config + max_model_len = config.max_position_embeddings + overlong = [ + len(pct) - len(prompt_ids[i]) > self.max_completion_length or len(pct) >= max_model_len + for i, pct in zip(idxs_with_tool, prompt_completion_tool_ids, strict=True) + ] + for idx in range(len(idxs_with_tool)): + if overlong[idx]: + idx_with_tool = idxs_with_tool[idx] + del completions[idx_with_tool][completions_len_before[idx] :] + del tool_images[idx_with_tool][tool_images_len_before[idx] :] + del prompts[idx_with_tool][prompts_len_before[idx] :] + # Keep only non-overlong items for further processing + idxs_with_tool = [idx for idx, o in zip(idxs_with_tool, overlong, strict=True) if not o] + prompt_completion_tool_ids = [ + pct for pct, o in zip(prompt_completion_tool_ids, overlong, strict=True) if not o + ] + if not idxs_with_tool: + break # all overlong, exit tool loop + + # Filter images and multimodal fields to match the current subset (index into full batch). + # Merge tool response images so the model can see visual feedback during generation. + merged_images = images + if any(imgs for imgs in tool_images): + if merged_images is None: + merged_images = [imgs if imgs else None for imgs in tool_images] + else: + merged_images = [ + (existing or []) + new for existing, new in zip(merged_images, tool_images, strict=True) + ] + loop_images = [merged_images[i] for i in idxs_with_tool] if merged_images else None + if multimodal_fields: + loop_multimodal_fields = {} + for k, v in multimodal_fields.items(): + selected = [v[i] for i in idxs_with_tool] + # Per-token fields (e.g. token_type_ids) need zero-padding to match extended prompt length + if isinstance(selected[0], list): + selected = [ + s + [0] * (len(pct) - len(s)) + for s, pct in zip(selected, prompt_completion_tool_ids, strict=True) + ] + loop_multimodal_fields[k] = selected + else: + loop_multimodal_fields = {} + + # Generate new completions after tool execution (using concatenated IDs, no re-tokenization) + post_tool_ids, post_tool_logprobs = self._generate_single_turn( + prompt_completion_tool_ids, loop_images, loop_multimodal_fields + ) + + # Truncate so that pct[len(prompt_ids[idx]) :] + post_tool does not exceed max_completion_length. + # The pre-regen check guarantees len(completion_tool_ids) <= max_completion_length, so any + # excess can only come from post_tool_ids. post_tool_ids is model-generated text and never + # contains image tokens, so a plain slice is safe. + for idx in range(len(idxs_with_tool)): + idx_with_tool = idxs_with_tool[idx] + completion_tool_length = len(prompt_completion_tool_ids[idx]) - len(prompt_ids[idx_with_tool]) + excess_length = completion_tool_length + len(post_tool_ids[idx]) - self.max_completion_length + if excess_length > 0: + new_len = len(post_tool_ids[idx]) - excess_length + post_tool_ids[idx] = post_tool_ids[idx][:new_len] + if logprobs is not None: + post_tool_logprobs[idx] = post_tool_logprobs[idx][:new_len] + + # Update tool_mask: the tool result should be 0 and the post-tool 1 + for idx in range(len(idxs_with_tool)): + idx_with_tool = idxs_with_tool[idx] + prompt_completion_tool_length = len(prompt_completion_tool_ids[idx]) + prompt_length = len(prompt_ids[idx_with_tool]) + completion_length = len(completion_ids[idx_with_tool]) + post_tool_length = len(post_tool_ids[idx]) + tool_length = prompt_completion_tool_length - prompt_length - completion_length + tool_mask[idx_with_tool] += [0] * tool_length + [1] * post_tool_length + if logprobs is not None: + logprobs[idx_with_tool] += [0.0] * tool_length + post_tool_logprobs[idx] + + # Update completion_ids with the new completions (after tool execution) + for idx in range(len(idxs_with_tool)): + idx_with_tool = idxs_with_tool[idx] + prompt_length = len(prompt_ids[idx_with_tool]) + pct = prompt_completion_tool_ids[idx] # = prompt-completion-tool + completion_ids[idx_with_tool] = pct[prompt_length:] + post_tool_ids[idx] + + # Decode post-tool completions. + post_tool_completions = [parse_response(self._tokenizer, ids) if ids else {} for ids in post_tool_ids] + + # Add post-tool completions to the existing completions + for idx in range(len(idxs_with_tool)): + idx_with_tool = idxs_with_tool[idx] + if post_tool_completions[idx]: # {} if post-tool completions completely truncated + completions[idx_with_tool].append(post_tool_completions[idx]) + + # Check for further tool calls + tool_calls = [completion.get("tool_calls") for completion in post_tool_completions] + idxs_with_tool = [idx for idx, tool_call in zip(idxs_with_tool, tool_calls, strict=True) if tool_call] + tool_calls = [tool_call for tool_call in tool_calls if tool_call] + iteration_num += 1 + + return tool_mask, completions, completion_ids, logprobs, tool_call_count, tool_failure_count, tool_images + + def _generate(self, prompts: list): + device = self.accelerator.device + mode = "train" if self.model.training else "eval" + + # Copy the prompts to avoid modifying the original list + prompts = copy.deepcopy(prompts) + + if self.rollout_func is not None: + # Keep vLLM weights in sync for custom rollouts that rely on vLLM utilities. + if self.use_vllm and self.state.global_step != self._last_loaded_step: + with profiling_context(self, "sync_weights"): + self.vllm_generation.sync_weights() + self._last_loaded_step = self.state.global_step + + # Pass prompts to rollout_func preserving structured messages. + # Chat templating must happen inside rollout_func, at the backend boundary, so that + # multimodal content (images, typed content blocks) is not lost before rollout logic runs. + output = self.rollout_func(prompts, self) + required_keys = {"prompt_ids", "completion_ids", "logprobs"} + missing_keys = required_keys - output.keys() + if missing_keys: + missing_keys_list = sorted(missing_keys) + raise ValueError(f"rollout_func must return keys {missing_keys_list} in its output dict.") + extra_fields = {k: v for k, v in output.items() if k not in required_keys} + prompt_ids, completion_ids, logprobs = output["prompt_ids"], output["completion_ids"], output["logprobs"] + images = None + multimodal_fields = {} + else: + prompt_ids, images, multimodal_fields = self._tokenize_prompts(prompts) + completion_ids, logprobs = self._generate_single_turn(prompt_ids, images, multimodal_fields) + extra_fields = {} + + # Decode completions. It's important to use `parse_response` when possible, because it handles tool calls. + if is_conversational({"prompt": prompts[0]}): + if ( + Version(transformers.__version__) >= Version("5.0.0") # parse_response added in v5 + and hasattr(self._tokenizer, "response_schema") # attribute not set by default for now + and self._tokenizer.response_schema is not None # only works if the tokenizer has a schema + ): + completions = [[parse_response(self._tokenizer, ids)] for ids in completion_ids] + else: + contents = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True) + completions = [[{"role": "assistant", "content": content}] for content in contents] + else: + completions = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True) + + # Extract tool calls from the completions and (possibly) execute them + tool_images = [] + if self.tools: + ( + tool_mask, + completions, + completion_ids, + logprobs, + tool_call_count, + tool_failure_count, + tool_images, + ) = self._tool_call_loop( + prompts, prompt_ids, completion_ids, completions, logprobs, images, multimodal_fields + ) + # Merge tool response images into the images list for the forward pass + if any(imgs for imgs in tool_images): + if images is None: + images = [imgs if imgs else None for imgs in tool_images] + else: + images = [(existing or []) + new for existing, new in zip(images, tool_images, strict=True)] + else: + # Support custom env_mask from rollout_func (e.g., for environment feedback masking) + # Internally treated as tool_mask - marks model tokens (1) vs external tokens (0) + tool_mask = extra_fields.pop("env_mask", None) + + # Get completion length per sequence, used for logging + prompt_lengths = torch.tensor([len(ids) for ids in prompt_ids], device=device) + if tool_mask is not None: # count only model-generated tokens (tool_mask=1) + completion_lengths = torch.tensor([sum(mask) for mask in tool_mask], device=device) + else: + completion_lengths = torch.tensor([len(ids) for ids in completion_ids], device=device) + agg_prompt_lengths = self.accelerator.gather(prompt_lengths) + agg_completion_lengths = self.accelerator.gather(completion_lengths) + total_prompt_tokens = agg_prompt_lengths.sum() + total_completion_tokens = agg_completion_lengths.sum() # = num_items_in_batch, required for the DAPO loss + + # Log the metrics + if mode == "train": + self.state.num_input_tokens_seen += (total_prompt_tokens + total_completion_tokens).item() + self._metrics[mode]["num_tokens"] = [self.state.num_input_tokens_seen] + + # Log completion lengths, mean, min, max + self._metrics[mode]["completions/mean_length"].append(agg_completion_lengths.float().mean().item()) + self._metrics[mode]["completions/min_length"].append(agg_completion_lengths.float().min().item()) + self._metrics[mode]["completions/max_length"].append(agg_completion_lengths.float().max().item()) + + # Identify sequences that terminated with EOS and log their lengths + eos_and_pad = [self._tokenizer.eos_token_id, self._tokenizer.pad_token_id] + is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids], device=device) + agg_is_truncated = self.accelerator.gather(is_truncated) + self._metrics[mode]["completions/clipped_ratio"].append(agg_is_truncated.float().mean().item()) + term_completion_lengths = agg_completion_lengths[~agg_is_truncated] + if len(term_completion_lengths) == 0: # edge case where no terminated sequences are found + term_completion_lengths = torch.zeros(1, device=device) + self._metrics[mode]["completions/mean_terminated_length"].append(term_completion_lengths.float().mean().item()) + self._metrics[mode]["completions/min_terminated_length"].append(term_completion_lengths.float().min().item()) + self._metrics[mode]["completions/max_terminated_length"].append(term_completion_lengths.float().max().item()) + + if self.tools: + agg_tool_call_count = self.accelerator.gather(torch.tensor(tool_call_count, device=device)).sum() + tool_call_frequency = (agg_tool_call_count / len(agg_prompt_lengths)).item() + self._metrics[mode]["tools/call_frequency"].append(tool_call_frequency) + agg_tool_failure_count = self.accelerator.gather(torch.tensor(tool_failure_count, device=device)).sum() + failure_frequency = ( + (agg_tool_failure_count / agg_tool_call_count).item() if agg_tool_call_count > 0 else 0.0 + ) + self._metrics[mode]["tools/failure_frequency"].append(failure_frequency) + + return ( + prompt_ids, + completion_ids, + tool_mask, + completions, + total_completion_tokens, + logprobs, + extra_fields, + images, + tool_images, + ) + + def _generate_and_score_completions( + self, inputs: list[dict[str, torch.Tensor | Any]] + ) -> dict[str, torch.Tensor | Any]: + device = self.accelerator.device + mode = "train" if self.model.training else "eval" + + prompts = [x["prompt"] for x in inputs] + + if self.environments: + for prompt, environment, reset_kwargs in zip(prompts, self.environments, inputs, strict=True): + observation = environment.reset(**reset_kwargs) + if observation is None: + continue + if isinstance(observation, list) and isinstance(prompt[-1]["content"], str): + prompt[-1]["content"] = [{"type": "text", "text": prompt[-1]["content"]}] + if isinstance(observation, str) and isinstance(prompt[-1]["content"], list): + observation = [{"type": "text", "text": observation}] + prompt[-1]["content"] += observation + + if "images" in inputs[0]: + images = [example.get("images") for example in inputs] + elif "image" in inputs[0]: + images = [[example.get("image")] if example.get("image") is not None else None for example in inputs] + else: + images = None + # Transformers requires at least one image in the batch, otherwise it throws an error + if images is not None and all(img_list == [] for img_list in images): + images = None + + # If the prompts are conversational and the inputs contain images, we need to convert the prompts from + # [{"role": "user", "content": "What color is the sky?"}] to + # [{"role": "user", "content": [{"type": "image", "image": }, {"type": "text", "text": "What color is the sky?"}]}] + if images is not None: + if not is_conversational(inputs[0]): + raise ValueError( + "Multimodal training requires conversational prompts. It looks like the dataset contains " + "non-conversational inputs, likely because a chat template was applied before passing the dataset " + "to the trainer. Please provide the raw conversational prompts and let the trainer apply the chat " + "template internally." + ) + prompts = [ + prepare_multimodal_messages(prompt, images=image_list) + for prompt, image_list in zip(prompts, images, strict=True) + ] + + dataset_images = images # preserve dataset images before _generate may overwrite + ( + prompt_ids_list, + completion_ids_list, + tool_mask_list, + completions, + num_items_in_batch, + sampling_per_token_logps_list, + extra_fields, + images, + tool_images, + ) = self._generate(prompts) + if images is None: + images = dataset_images # restore dataset images (rollout_func path returns None) + + # Convert lists of token IDs to padded tensors + prompt_ids = [torch.tensor(ids) for ids in prompt_ids_list] + prompt_mask = [torch.ones_like(ids, dtype=torch.long) for ids in prompt_ids] + prompt_ids = pad( + prompt_ids, + padding_value=self._tokenizer.pad_token_id, + padding_side="left", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + prompt_mask = pad( + prompt_mask, padding_value=0, padding_side="left", pad_to_multiple_of=self.pad_to_multiple_of + ).to(device=device) + completion_ids = [torch.tensor(ids) for ids in completion_ids_list] + completion_mask = [torch.ones_like(ids, dtype=torch.long) for ids in completion_ids] + completion_ids = pad( + completion_ids, + padding_value=self._tokenizer.pad_token_id, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + completion_mask = pad( + completion_mask, padding_value=0, padding_side="right", pad_to_multiple_of=self.pad_to_multiple_of + ).to(device=device) + if sampling_per_token_logps_list is not None: + sampling_per_token_logps = [torch.tensor(logps) for logps in sampling_per_token_logps_list] + sampling_per_token_logps = pad( + sampling_per_token_logps, + padding_value=0.0, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + else: + sampling_per_token_logps = None + if tool_mask_list is not None: + tool_mask = [torch.tensor(mask) for mask in tool_mask_list] + tool_mask = pad( + tool_mask, padding_value=1, padding_side="right", pad_to_multiple_of=self.pad_to_multiple_of + ).to(device=device) + else: + tool_mask = None + + # If mask_truncated_completions is enabled, zero out truncated completions for attention and loss masking + if self.mask_truncated_completions: + eos_and_pad = [self._tokenizer.eos_token_id, self._tokenizer.pad_token_id] + is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids_list], device=device) + # Mask completion_mask for attention masking + completion_mask = completion_mask * (~is_truncated).unsqueeze(1).int() + # Also mask tool_mask for consistency in multi-turn training + if tool_mask is not None: + tool_mask = tool_mask * (~is_truncated).unsqueeze(1).int() + + # Concatenate prompt_mask with completion_mask for logit computation + prompt_completion_ids = torch.cat([prompt_ids, completion_ids], dim=1) # (B, P+C) + attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) # (B, P+C) + + logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens + batch_size = self.args.per_device_train_batch_size if mode == "train" else self.args.per_device_eval_batch_size + + num_images = [len(img_list) if img_list else 0 for img_list in images] if images is not None else None + + # Get forward_kwargs for models with multimodal inputs. + # When tool images are present (from _tool_call_loop), use image_processor directly and build + # mm_token_type_ids from prompt_completion_ids. Otherwise, use the full processor pipeline + # which returns model-specific keys (image_sizes, pixel_attention_mask, etc.). + if self.tools and any(imgs for imgs in tool_images) and self._is_vlm: + flat_images = [img for img_list in images if img_list for img in img_list] + image_inputs = self.processing_class.image_processor(images=flat_images, return_tensors="pt") + image_inputs = super()._prepare_inputs(image_inputs) + forward_kwargs = dict(image_inputs) + elif images is not None: + prompts_text = [ + apply_chat_template( + {"prompt": prompt}, self.processing_class, tools=self.tools, **self.chat_template_kwargs + )["prompt"] + for prompt in prompts + ] + prompt_inputs = self.processing_class(images=images, text=prompts_text, padding=True, return_tensors="pt") + prompt_inputs = super()._prepare_inputs(prompt_inputs) + forward_kwargs = {k: v for k, v in prompt_inputs.items() if k not in ["input_ids", "attention_mask"]} + else: + forward_kwargs = {} + + # If token_type_ids are used, extend them with zeros for the completion part + if "token_type_ids" in forward_kwargs: + token_type_ids = forward_kwargs["token_type_ids"] + if self.pad_to_multiple_of is not None: + # Needed only with pad_to_multiple_of: otherwise prompt_ids and token_type_ids must have equal len + padding_size = prompt_ids.size(1) - token_type_ids.size(1) + if padding_size > 0: + token_type_ids = torch.cat( + [token_type_ids.new_zeros((token_type_ids.size(0), padding_size)), token_type_ids], dim=1 + ) + forward_kwargs["token_type_ids"] = torch.cat( + [token_type_ids, token_type_ids.new_zeros(completion_ids.shape)], dim=1 + ) + # If mm_token_type_ids are used, extend them with zeros for the completion part + if "mm_token_type_ids" in forward_kwargs: + mm_token_type_ids = forward_kwargs["mm_token_type_ids"] + if self.pad_to_multiple_of is not None: + # Needed only with pad_to_multiple_of: otherwise prompt_ids and mm_token_type_ids must have equal len + padding_size = prompt_ids.size(1) - mm_token_type_ids.size(1) + if padding_size > 0: + mm_token_type_ids = torch.cat( + [mm_token_type_ids.new_zeros((mm_token_type_ids.size(0), padding_size)), mm_token_type_ids], + dim=1, + ) + forward_kwargs["mm_token_type_ids"] = torch.cat( + [mm_token_type_ids, mm_token_type_ids.new_zeros(completion_ids.shape)], dim=1 + ) + + # For VLM tool images: build token type IDs from the full prompt_completion_ids. + # This must happen AFTER the token_type_ids/mm_token_type_ids extension blocks above, + # because our version already covers the full sequence (images are in the completion, + # not just the prompt). + if self.tools and any(imgs for imgs in tool_images) and self._is_vlm: + mm_ids = torch.zeros_like(prompt_completion_ids) + if self._image_pad_token_id is not None: + mm_ids[prompt_completion_ids == self._image_pad_token_id] = 1 + if self._video_pad_token_id is not None: + mm_ids[prompt_completion_ids == self._video_pad_token_id] = 2 + + # Use the same key the model expects: token_type_ids for models like Gemma, + # mm_token_type_ids for models like Qwen. + image_grid_thw = forward_kwargs.get("image_grid_thw") + if image_grid_thw is not None: + forward_kwargs["mm_token_type_ids"] = mm_ids + else: + forward_kwargs["token_type_ids"] = mm_ids + + # Truncation safety (Qwen-style models with image_grid_thw only): if + # max_completion_length truncated some image tokens, the number of image pad tokens + # in input_ids won't match pixel_values features. Check per-sample and drop ALL + # images for any sample with a mismatch (safe fallback). + if image_grid_thw is not None and num_images is not None: + merge_length = getattr(self.processing_class.image_processor, "merge_size", 2) ** 2 + img_offset = 0 + has_mismatch = False + for b in range(mm_ids.shape[0]): + sample_tokens = (mm_ids[b] == 1).sum().item() + sample_features = 0 + for i in range(num_images[b]): + grid_idx = img_offset + i + if grid_idx < image_grid_thw.shape[0]: + sample_features += image_grid_thw[grid_idx].prod().item() // merge_length + if sample_tokens != sample_features: + has_mismatch = True + break + img_offset += num_images[b] + + if has_mismatch: + # Drop all images: safer than partial trim which is error-prone + forward_kwargs.pop("pixel_values", None) + forward_kwargs.pop("image_grid_thw", None) + mm_ids.zero_() + forward_kwargs["mm_token_type_ids"] = mm_ids + num_images = None + + # When gradient checkpointing is enabled with use_reentrant=True (non default), calling the model inside a + # torch.no_grad() block triggers a harmless PyTorch warning ("None of the inputs have requires_grad=True"). + # Temporarily disable checkpointing to avoid this warning during inference. + with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs): + # If the generation and optimization steps are misaligned—i.e., if generation does not occur at the end of + # a full optimizer step (when gradient_accumulation_steps is not a multiple of generate_every)—then the + # samples may come from an earlier version of the model. In that case, we need to track old_per_token_logps + # for importance sampling. If the steps are aligned, importance sampling isn't necessary and we set + # old_per_token_logps to None. + # When using vLLM, we always compute old_per_token_logps for importance sampling, it was shown that the + # distribution mismatch between vLLM and the training model can be large and harm the training. + generate_every = self.args.steps_per_generation * self.num_iterations # generation frequency + if self.args.gradient_accumulation_steps % generate_every != 0 or ( + self.use_vllm and self.vllm_importance_sampling_correction + ): + old_per_token_logps, _ = self._get_per_token_logps_and_entropies( + self.model, + prompt_completion_ids, + attention_mask, + logits_to_keep, + batch_size, + num_images=num_images, + **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask, image_sizes, image_position_ids + ) + else: + old_per_token_logps = None + + # Compute the importance sampling ratio when using vLLM, to correct for potential distribution mismatch + if self.use_vllm and self.vllm_importance_sampling_correction: + mask = completion_mask if tool_mask is None else completion_mask * tool_mask + per_token_logps_diff = (old_per_token_logps - sampling_per_token_logps) * mask + + sequence_level_is = self.vllm_importance_sampling_mode in ["sequence_mask", "sequence_truncate"] + if sequence_level_is: + per_sequence_logps_diff = per_token_logps_diff.sum(dim=-1, keepdim=True) + logps_diff = per_sequence_logps_diff + else: + logps_diff = per_token_logps_diff + + vllm_importance_sampling_ratio = torch.exp(logps_diff) + + # vllm_importance_sampling_ratio.shape: + # token_* modes: (B, T) (per-token ratio) + # sequence_* modes: (B, 1) (per-sequence ratio) + + if self.vllm_importance_sampling_mode in ["sequence_truncate", "token_truncate"]: + vllm_importance_sampling_ratio = torch.clamp( + vllm_importance_sampling_ratio, + min=self.vllm_importance_sampling_clip_min, + max=self.vllm_importance_sampling_clip_max, + ) + elif self.vllm_importance_sampling_mode in ["sequence_mask", "token_mask"]: + min_val = ( + self.vllm_importance_sampling_clip_min + if self.vllm_importance_sampling_clip_min is not None + else -math.inf + ) + max_val = ( + self.vllm_importance_sampling_clip_max + if self.vllm_importance_sampling_clip_max is not None + else math.inf + ) + + invalid_mis_mask = (vllm_importance_sampling_ratio < min_val) | ( + vllm_importance_sampling_ratio > max_val + ) + vllm_importance_sampling_ratio = vllm_importance_sampling_ratio.masked_fill( + invalid_mis_mask, value=0.0 + ) + else: + raise ValueError( + f"Unknown vLLM importance sampling level: {self.vllm_importance_sampling_mode}. Possible values are 'token_truncate', 'token_mask', 'sequence_truncate', and 'sequence_mask'." + ) + + # Compute the per-token log probabilities for the reference model + if self.beta != 0.0: + if self.ref_model is not None: + ref_per_token_logps, _ = self._get_per_token_logps_and_entropies( + self.ref_model, + prompt_completion_ids, + attention_mask, + logits_to_keep, + batch_size=batch_size, + num_images=num_images, + **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask, image_sizes, image_position_ids + ) + else: + # When training a PEFT adapter, how we obtain the reference depends on the setup: + # - New adapter: disabling adapters yields the base model. + # - Re-training an existing adapter: an initial copy is loaded under the name "ref". + model = self.accelerator.unwrap_model(self.model) + with use_adapter(model, adapter_name="ref" if "ref" in model.peft_config else None): + ref_per_token_logps, _ = self._get_per_token_logps_and_entropies( + self.model, + prompt_completion_ids, + attention_mask, + logits_to_keep, + batch_size=batch_size, + num_images=num_images, + **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask, image_sizes, image_position_ids + ) + else: + ref_per_token_logps = None + + # Decode + prompts_text = self.processing_class.batch_decode(prompt_ids, skip_special_tokens=True) + completions_text = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True) + + # Merge extra_fields from rollout_func into inputs for reward functions + if extra_fields: + for i, inp in enumerate(inputs): + for key, values in extra_fields.items(): + if isinstance(values, list) and i < len(values): + inp[key] = values[i] + elif not isinstance(values, list): + inp[key] = values + + # Calculate rewards for each reward function. rewards_per_func aggregates rewards across all processes. This is + # important because rewards will be normalized per group, and completions are distributed. We will later slice + # rewards_per_func to extract each process's subset. + rewards_per_func = self._calculate_rewards(inputs, prompts, completions, completion_ids_list) + num_generations = self.num_generations if mode == "train" else self.num_generations_eval + + # A completion for which every reward function returned None is unscorable. nansum would collapse it to 0, + # which both biases the per-group baseline and hands the completion a spurious advantage. Mark these rows NaN + # so they're excluded from the (nan-aware) baseline below; their advantage is forced to 0 afterwards. + unscorable_mask = torch.isnan(rewards_per_func).all(dim=1) + + if self.multi_objective_aggregation == "sum_then_normalize": + # Apply weights to each reward function's output and sum + rewards = (rewards_per_func * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1) + rewards[unscorable_mask] = torch.nan + mean_grouped_rewards = torch.nanmean(rewards.view(-1, num_generations), dim=1) + mean_grouped_rewards = mean_grouped_rewards.repeat_interleave(num_generations, dim=0) + if self.scale_rewards in ["group", "none"]: + # If self.scale_rewards = "none", we'll only use std_rewards to check for zero std for logging + if num_generations > 1: + std_rewards = nanstd(rewards.view(-1, num_generations), dim=1) + std_rewards = std_rewards.repeat_interleave(num_generations, dim=0) + else: # doesn't occur during training, but could occur in eval when num_generations_eval=1 + std_rewards = torch.zeros_like(rewards) + elif self.scale_rewards == "batch": + # Compute global std + if rewards.numel() > 1: + std_rewards = nanstd(rewards).expand_as(rewards) + else: # doesn't occur during training, but could occur in eval when num_generations_eval=batch_size=1 + std_rewards = torch.zeros_like(rewards) + else: + raise ValueError( + f"Invalid value for scale_rewards: {self.scale_rewards}. Must be one of 'batch', 'group', or 'none'." + ) + + advantages = rewards - mean_grouped_rewards + if self.scale_rewards != "none": + advantages = advantages / (std_rewards + 1e-4) + is_std_zero = torch.isclose(std_rewards, torch.zeros_like(std_rewards)) # for logging + + elif self.multi_objective_aggregation == "normalize_then_sum": + grouped = rewards_per_func.view(-1, num_generations, len(self.reward_funcs)) + mean_k = torch.nanmean(grouped, dim=1, keepdim=True) + std_k = nanstd(grouped, dim=1, keepdim=True) if num_generations > 1 else torch.zeros_like(mean_k) + reward_k = (grouped - mean_k) / (std_k + 1e-4) + reward_k = reward_k.view(-1, len(self.reward_funcs)) + rewards = (reward_k * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1) + rewards[unscorable_mask] = torch.nan + std_rewards = nanstd(rewards).expand_as(rewards) if rewards.numel() > 1 else torch.zeros_like(rewards) + advantages = (rewards - torch.nanmean(rewards)) / (std_rewards + 1e-4) + is_std_zero = torch.isclose(std_rewards, torch.zeros_like(std_rewards)) # for logging + + else: + raise ValueError( + f"Invalid multi_objective_aggregation: {self.multi_objective_aggregation}. Must be " + "'sum_then_normalize' or 'normalize_then_sum'." + ) + + # Unscorable completions (every reward func returned None) carry no learning signal: their reward is NaN here, + # so zero their advantage to keep them from moving the policy. + advantages = torch.nan_to_num(advantages, nan=0.0) + + # Slice to keep only the local part of the data + process_slice = slice( + self.accelerator.process_index * len(prompts), + (self.accelerator.process_index + 1) * len(prompts), + ) + all_process_advantages = advantages.clone() # keep the aggregated advantages for logging + advantages = advantages[process_slice] + + # Calculate mean reward per function, but only for samples where the function was applied (non-NaN values) + for i, reward_func_name in enumerate(self.reward_func_names): + mean_rewards = torch.nanmean(rewards_per_func[:, i]).item() + self._metrics[mode][f"rewards/{reward_func_name}/mean"].append(mean_rewards) + std_func_rewards = nanstd(rewards_per_func[:, i]).item() + self._metrics[mode][f"rewards/{reward_func_name}/std"].append(std_func_rewards) + rewards = (rewards_per_func * self.reward_weights.to(rewards_per_func.device).unsqueeze(0)).nansum(dim=1) + rewards[unscorable_mask] = torch.nan # exclude unscorable rows from the logged reward stats + self._metrics[mode]["reward"].append(torch.nanmean(rewards).item()) + self._metrics[mode]["reward_std"].append(nanstd(rewards).item()) + self._metrics[mode]["frac_reward_zero_std"].append(is_std_zero.float().mean().item()) + + # Log prompt and completion texts + self._logs["prompt"].extend(gather_object(prompts_text)) + self._logs["completion"].extend(gather_object(completions_text)) + for i, name in enumerate(self.reward_func_names): + self._logs["rewards"][name].extend(rewards_per_func[:, i].tolist()) + self._logs["advantages"].extend(all_process_advantages.tolist()) + + # Flush user-logged extra columns (from log_extra), gathering across processes. + # Keys must be sorted so that all ranks call gather_object in the same order, otherwise values + # get mis-attributed across columns (dict insertion order may differ between processes). + for column in sorted(self._pending_extra_logs): + self._logs["extra"][column].extend(gather_object(self._pending_extra_logs[column])) + self._pending_extra_logs.clear() + + # Flush user-logged metrics (from log_metric), averaging across processes. + # Keys must be sorted so that all ranks call accelerator.gather in the same order, otherwise values + # get mis-attributed across metrics (dict insertion order may differ between processes). + for name in sorted(self._pending_metrics): + values = self._pending_metrics[name] + local_mean = sum(values) / len(values) + global_mean = self.accelerator.gather(torch.tensor(local_mean, device=device)).mean().item() + self._metrics[mode][name].append(global_mean) + self._pending_metrics.clear() + + if images is not None: + self._logs["images"].extend(gather_object(images)) + + if self.use_vllm and self.vllm_importance_sampling_correction: + delta = torch.abs(old_per_token_logps - sampling_per_token_logps) + mask = completion_mask.bool() if tool_mask is None else (completion_mask * tool_mask).bool() + delta = delta[mask] + mean_delta = torch.mean(delta) if delta.numel() > 0 else torch.tensor(0.0, device=device) + max_delta = torch.max(delta) if delta.numel() > 0 else torch.tensor(0.0, device=device) + self._metrics[mode]["sampling/sampling_logp_difference/mean"].append( + self.accelerator.gather(mean_delta).mean().item() + ) + self._metrics[mode]["sampling/sampling_logp_difference/max"].append( + self.accelerator.gather(max_delta).max().item() + ) + if sequence_level_is: + flat_is_ratio = vllm_importance_sampling_ratio.flatten() + else: + flat_is_ratio = vllm_importance_sampling_ratio[mask] + + min_importance_sampling_ratio = ( + torch.min(flat_is_ratio) if flat_is_ratio.numel() > 0 else torch.tensor(0.0, device=device) + ) + mean_importance_sampling_ratio = ( + torch.mean(flat_is_ratio) if flat_is_ratio.numel() > 0 else torch.tensor(0.0, device=device) + ) + max_importance_sampling_ratio = ( + torch.max(flat_is_ratio) if flat_is_ratio.numel() > 0 else torch.tensor(0.0, device=device) + ) + self._metrics[mode]["sampling/importance_sampling_ratio/min"].append( + nanmin(self.accelerator.gather(min_importance_sampling_ratio)).item() + ) + self._metrics[mode]["sampling/importance_sampling_ratio/mean"].append( + self.accelerator.gather(mean_importance_sampling_ratio).nanmean().item() + ) + self._metrics[mode]["sampling/importance_sampling_ratio/max"].append( + nanmax(self.accelerator.gather(max_importance_sampling_ratio)).item() + ) + + output = { + "prompt_ids": prompt_ids, + "prompt_mask": prompt_mask, + "completion_ids": completion_ids, + "completion_mask": completion_mask, + "advantages": advantages, + "num_items_in_batch": num_items_in_batch, + } + if old_per_token_logps is not None: + output["old_per_token_logps"] = old_per_token_logps + if self.use_vllm and self.vllm_importance_sampling_correction: + output["importance_sampling_ratio"] = vllm_importance_sampling_ratio + if sampling_per_token_logps is not None: + output["sampling_per_token_logps"] = sampling_per_token_logps + if ref_per_token_logps is not None: + output["ref_per_token_logps"] = ref_per_token_logps + if "pixel_values" in forward_kwargs: + output["pixel_values"] = forward_kwargs["pixel_values"] + if "image_grid_thw" in forward_kwargs: + output["image_grid_thw"] = forward_kwargs["image_grid_thw"] + if "pixel_attention_mask" in forward_kwargs: + output["pixel_attention_mask"] = forward_kwargs["pixel_attention_mask"] + if "image_sizes" in forward_kwargs: + output["image_sizes"] = forward_kwargs["image_sizes"] + if "token_type_ids" in forward_kwargs: + output["token_type_ids"] = forward_kwargs["token_type_ids"] + if "mm_token_type_ids" in forward_kwargs: + output["mm_token_type_ids"] = forward_kwargs["mm_token_type_ids"] + if "image_position_ids" in forward_kwargs: + output["image_position_ids"] = forward_kwargs["image_position_ids"] + if images is not None: + output["num_images"] = num_images + if tool_mask is not None: + output["tool_mask"] = tool_mask + return output + + def compute_liger_loss(self, unwrapped_model, inputs): + # Compute the per-token log probabilities for the model + prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"] + completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"] + input_ids = torch.cat([prompt_ids, completion_ids], dim=1) + attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) + logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens + + # Get the last hidden state of the model + last_hidden_state = self._get_last_hidden_state( + unwrapped_model, + input_ids, + attention_mask, + logits_to_keep, + inputs.get("pixel_values"), + inputs.get("image_grid_thw"), + inputs.get("pixel_attention_mask"), + inputs.get("image_sizes"), + inputs.get("image_position_ids"), + ) + + # Apply tool_mask (from env_mask) for loss computation in multi-turn training scenarios + loss_mask = completion_mask if "tool_mask" not in inputs else completion_mask * inputs["tool_mask"] + lm_head_weight = unwrapped_model.lm_head.weight + lm_head_bias = unwrapped_model.lm_head.bias + # Liger reads `lm_head` directly instead of through `model.forward()`, so its ZeRO-3 gather hook never fires + # and the fused matmul gets an empty shard. Gather the weight/bias ourselves for the call (the weight grad is + # computed during this forward, so it isn't needed in the backward). Skip it when already gathered: with tied + # embeddings `embed_tokens` keeps the weight `AVAILABLE`, and re-partitioning on exit breaks its tracking. + deepspeed_plugin = self.accelerator.state.deepspeed_plugin + gather_ctx = nullcontext() + if deepspeed_plugin is not None and deepspeed_plugin.zero_stage == 3: + from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus + + params = [lm_head_weight] if lm_head_bias is None else [lm_head_weight, lm_head_bias] + if any(p.ds_status != ZeroParamStatus.AVAILABLE for p in params): + import deepspeed + + gather_ctx = deepspeed.zero.GatheredParameters(params, modifier_rank=None) + with gather_ctx: + loss, metrics = self.liger_grpo_loss( + _input=last_hidden_state, + lin_weight=lm_head_weight, + selected_token_ids=completion_ids, + # The attention_mask parameter in liger loss is actually used as a loss mask (not model attention) + attention_mask=loss_mask, + advantages=inputs["advantages"], + bias=lm_head_bias, + old_per_token_logps=inputs.get("old_per_token_logps"), + ref_per_token_logps=inputs.get("ref_per_token_logps"), + vllm_is_ratio=inputs.get("importance_sampling_ratio"), + ) + # Extract metrics from the liger_grpo_loss output + # KL divergence is the first metric when beta is non-zero + mean_kl = metrics[0] if self.beta != 0.0 else None + clip_ratio = metrics[-1] + + mode = "train" if self.model.training else "eval" + if self.beta != 0.0: + self._metrics[mode]["kl"].append(self.accelerator.gather(mean_kl).mean().item()) + self._metrics[mode]["clip_ratio"].append(self.accelerator.gather(clip_ratio).mean().item()) + normalizer = self.current_gradient_accumulation_steps if mode == "train" else 1.0 # no accum in eval + return loss / normalizer + + @profiling_decorator + def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): + if return_outputs: + raise ValueError("The GRPOTrainer does not support returning outputs") + if self.use_liger_kernel: + # Compute the loss using the liger grpo loss + unwrapped_model = self.accelerator.unwrap_model(model) + return self._forward_redirection(model, unwrapped_model, self.compute_liger_loss, unwrapped_model, inputs) + return self._compute_loss(model, inputs) + + @staticmethod + def get_off_policy_mask( + advantages: torch.Tensor, + per_token_logps: torch.Tensor, + sampling_per_token_logps: torch.Tensor, + mask: torch.Tensor, + off_policy_threshold: float, + ) -> torch.Tensor: + """ + Computes the Off-Policy Sequence Mask from DeepSeek-V3.2 paper. Returns a (B, 1) tensor where 1.0 indicates + "Keep" and 0.0 indicates "Drop". + """ + # forward KL div: log(pi_old) - log(pi_theta) + kl_div = sampling_per_token_logps - per_token_logps.detach() + # Sequence-level Mean KL (ignoring prompt+padding) + seq_kl_sum = (kl_div * mask).sum(dim=1, keepdim=True) + avg_seq_kl = seq_kl_sum / mask.sum(dim=1, keepdim=True).clamp(min=1.0) + # Keep if (Advantage >= 0) OR (KL <= delta) + is_pos_adv = advantages >= 0 + is_low_kl = avg_seq_kl <= off_policy_threshold + return (is_pos_adv | is_low_kl).to(dtype=mask.dtype) # (B, 1) + + @staticmethod + @torch.no_grad() + def get_gamma_weights( + advantages: torch.Tensor, + log_ratio_per_token: torch.Tensor, + mask: torch.Tensor, + importance_sampling_ratio: torch.Tensor | None, # (B, T) + k_pos: float = 2.0, + lambda_pos: float = 3.0, + k_neg: float = 3.0, + lambda_neg: float = 2.0, + ) -> torch.Tensor: + """ + Computes the Gamma weights for the VESPO loss. For reference: + φ(w) = e^λ × w^k × e^{-λw} is the gamma weighting (normalized so φ(1)=1) + with w = sequence-level importance sampling ratio + note: we will compute φ(w) in log space + + φ(w) is detached via @torch.no_grad(), only acts as gradient scaling coefficient + + VESPO loss = -φ(w) × A × log_prob, gradient naturally gives φ(w) × A × ∇log π + """ + # reducing clamp range directly to log(1e-8) ~ -18.42, to avoid recomputing log_w=log(w.clamp(min=1e-8)) later + # This is solely for matching truthfully the original implementation, otherwise keeping -20 could be fine. + lower_clamp = math.log(1e-8) + + # Sequence-level log ratio Σ log(π_θ/π_old) (not a mean like for `log_importance_weights`) + log_ratio_clamped = torch.clamp(log_ratio_per_token, -20.0, 20.0) + seq_log_ratio = torch.sum(log_ratio_clamped * mask, dim=-1, keepdim=True) # (B, 1) + + # Apply token-level TIS or MIS correction (in log space) + if importance_sampling_ratio is not None: + log_is_ratio = torch.clamp(torch.log(importance_sampling_ratio), lower_clamp, 20.0) + # log(w) = log(π_θ/π_old) + log(π_old/π_sampler) + seq_log_ratio += torch.sum(log_is_ratio, dim=-1, keepdim=True) + + log_w_seq = torch.clamp(seq_log_ratio, lower_clamp, 20.0) + w_seq = torch.exp(log_w_seq) + + # compute k and lambda based on advantage sign + is_nonneg_adv = advantages >= 0 + k_seq = torch.where(is_nonneg_adv, k_pos, k_neg) + lambda_seq = torch.where(is_nonneg_adv, lambda_pos, lambda_neg).clamp(min=1e-4) + + # log(φ(w)) = λ + k × log(w) - λ × w + log_phi = lambda_seq + k_seq * log_w_seq - lambda_seq * w_seq + phi_seq = torch.exp(log_phi).nan_to_num(nan=0.0, posinf=0.0, neginf=0.0) + + return phi_seq # (B, 1) + + def _compute_loss(self, model, inputs): + # Compute the per-token log probabilities for the model + prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"] + completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"] + input_ids = torch.cat([prompt_ids, completion_ids], dim=1) + attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) + logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens + mask = completion_mask if "tool_mask" not in inputs else completion_mask * inputs["tool_mask"] + + # Compute the per_token_logps and the entropy at each position in the completion + per_token_logps, entropies = self._get_per_token_logps_and_entropies( + model, + input_ids, + attention_mask, + logits_to_keep, + compute_entropy=True, + pixel_values=inputs.get("pixel_values"), + image_grid_thw=inputs.get("image_grid_thw"), + num_images=inputs.get("num_images"), + pixel_attention_mask=inputs.get("pixel_attention_mask"), + image_sizes=inputs.get("image_sizes"), + token_type_ids=inputs.get("token_type_ids"), + mm_token_type_ids=inputs.get("mm_token_type_ids"), + image_position_ids=inputs.get("image_position_ids"), + ) + + if self.top_entropy_quantile < 1.0: + entropy_mask = self.get_high_entropy_mask(entropies, mask, 1 - self.top_entropy_quantile) + else: + entropy_mask = None + + # Compute the loss + advantages = inputs["advantages"] + # In the base GRPO implementation, advantages are expected to have shape (B,). To support subclasses that + # provide advantages with shape (B, T) (e.g., MiniLLM), we *conditionally* unsqueeze the tensor. + if advantages.dim() == 1: + advantages = advantages.unsqueeze(1) + # When num_iterations == 1 and steps_per_generation <= gradient_accumulation_steps, + # old_per_token_logps == per_token_logps. In this case we can skip its computation + # (see _generate_and_score_completions) and instead use per_token_logps.detach(). + # The exception is when using vLLM, where we always compute old_per_token_logps + # for importance sampling + old_per_token_logps = inputs.get("old_per_token_logps") + old_per_token_logps = per_token_logps.detach() if old_per_token_logps is None else old_per_token_logps + + if self.off_policy_mask_threshold is not None: + # OPSM should use inference-time logprobs to detect both sources of off-policyness: + # 1. Drift from gradient updates (always present) + # 2. Drift from training-inference mismatch (when using vLLM) + # When using vLLM, prioritize sampling_per_token_logps, otherwise use old_per_token_logps + sampling_per_token_logps = inputs.get("sampling_per_token_logps", old_per_token_logps) + + off_policy_mask = self.get_off_policy_mask( + advantages=advantages, + per_token_logps=per_token_logps, + sampling_per_token_logps=sampling_per_token_logps, + mask=mask, + off_policy_threshold=self.off_policy_mask_threshold, + ) + + log_ratio = per_token_logps - old_per_token_logps + if self.importance_sampling_level == "token": + log_importance_weights = log_ratio + elif self.importance_sampling_level == "sequence": + log_importance_weights = (log_ratio * mask).sum(-1) / mask.sum(-1).clamp(min=1.0) + log_importance_weights = log_importance_weights.unsqueeze(-1) + else: + raise ValueError( + f"Unknown importance sampling level: {self.importance_sampling_level}. Possible values are 'token' " + "and 'sequence'." + ) + + coef_1 = torch.exp(log_importance_weights) + + # Compute the KL divergence between the model and the reference model + if self.beta != 0.0: + ref_per_token_logps = inputs["ref_per_token_logps"] + per_token_kl = ( + torch.exp(ref_per_token_logps - per_token_logps) - (ref_per_token_logps - per_token_logps) - 1 + ) + # Importance sampling correction for the KL divergence + if self.args.use_bias_correction_kl: + per_token_kl = per_token_kl * coef_1 + + # From here, log_importance_weights (and all subsequent tensors, coef_1, coef_2, etc.) shape depends on + # importance_sampling_level: "token" level: (B, T); "sequence" level: (B, 1) + if self.loss_type == "cispo": + clamped_ratios = torch.clamp(coef_1, max=self.epsilon_high).detach() + per_token_loss = -clamped_ratios * advantages * per_token_logps + elif self.loss_type in ["grpo", "bnpo", "dr_grpo", "dapo", "luspo"]: + coef_2 = torch.clamp(coef_1, 1 - self.epsilon_low, 1 + self.epsilon_high) + # Two-sided clipping + if self.args.delta is not None: + coef_1 = torch.clamp(coef_1, max=self.args.delta) + + per_token_loss1 = coef_1 * advantages + per_token_loss2 = coef_2 * advantages + per_token_loss = -torch.min(per_token_loss1, per_token_loss2) + elif self.loss_type == "sapo": + temperatures = torch.where(advantages > 0, self.args.sapo_temperature_pos, self.args.sapo_temperature_neg) + soft_coef_1 = torch.sigmoid(temperatures * (coef_1 - 1)) * 4 / temperatures + per_token_loss = -soft_coef_1 * advantages + elif self.loss_type == "vespo": + phi_seq = self.get_gamma_weights( + advantages=advantages, + log_ratio_per_token=log_ratio, + mask=mask, + importance_sampling_ratio=inputs.get("importance_sampling_ratio"), + k_pos=self.args.vespo_k_pos, + lambda_pos=self.args.vespo_lambda_pos, + k_neg=self.args.vespo_k_neg, + lambda_neg=self.args.vespo_lambda_neg, + ) + per_token_loss = -phi_seq * advantages * per_token_logps + else: + raise ValueError(f"Unknown loss type: {self.loss_type}") + + if self.off_policy_mask_threshold is not None: + per_token_loss = per_token_loss * off_policy_mask + + if entropy_mask is not None: + per_token_loss = per_token_loss * entropy_mask + + if self.use_vllm and self.vllm_importance_sampling_correction and self.loss_type != "vespo": + per_token_loss = per_token_loss * inputs["importance_sampling_ratio"] + + if self.beta != 0.0: + per_token_loss = per_token_loss + self.beta * per_token_kl + + mode = "train" if self.model.training else "eval" + if self.loss_type in ["grpo", "sapo"]: + loss = ((per_token_loss * mask).sum(-1) / mask.sum(-1).clamp(min=1.0)).mean() + normalizer = self.current_gradient_accumulation_steps if mode == "train" else 1.0 # no accum in eval + loss = loss / normalizer + elif self.loss_type == "bnpo": + loss = (per_token_loss * mask).sum() / mask.sum().clamp(min=1.0) + normalizer = self.current_gradient_accumulation_steps if mode == "train" else 1.0 # no accum in eval + loss = loss / normalizer + elif self.loss_type == "dr_grpo": + loss = (per_token_loss * mask).sum() / (per_token_loss.size(0) * self.max_completion_length) + normalizer = self.current_gradient_accumulation_steps if mode == "train" else 1.0 # no accum in eval + loss = loss / normalizer + elif self.loss_type in ["cispo", "dapo", "vespo"]: + normalizer = inputs["num_items_in_batch"] / self.accelerator.num_processes + loss = (per_token_loss * mask).sum() / normalizer + elif self.loss_type == "luspo": + # Unless importance_sampling_level="token" (not recommended here), per_token_loss is expected to be (B, 1) + loss = (per_token_loss * mask.sum(1, keepdim=True)).mean() + normalizer = self.current_gradient_accumulation_steps if mode == "train" else 1.0 + loss = loss / normalizer + else: + raise ValueError(f"Unknown loss type: {self.loss_type}") + + # Log the metrics + completion_token_count = mask.sum().clamp(min=1.0) + + def masked_batch_mean(x): + if x.shape[1] == 1: # when importance_sampling_level == "sequence" + return x.mean() + else: + return (x * mask).sum() / completion_token_count + + if self.beta != 0.0: + mean_kl = masked_batch_mean(per_token_kl) + self._metrics[mode]["kl"].append(self.accelerator.gather(mean_kl).nanmean().item()) + + mean_entropy = masked_batch_mean(entropies) + self._metrics[mode]["entropy"].append(self.accelerator.gather(mean_entropy).nanmean().item()) + + if self.loss_type in ["grpo", "bnpo", "dr_grpo", "dapo", "luspo"]: + # Compute the clipped probability ratios + is_low_clipped = (coef_1 < 1 - self.epsilon_low) & (advantages < 0) + is_high_clipped = (coef_1 > 1 + self.epsilon_high) & (advantages > 0) + is_region_clipped = is_low_clipped | is_high_clipped + + low_clip = masked_batch_mean(is_low_clipped.float()) + high_clip = masked_batch_mean(is_high_clipped.float()) + clip_ratio = masked_batch_mean(is_region_clipped.float()) + + gathered_low_clip = self.accelerator.gather(low_clip) + self._metrics[mode]["clip_ratio/low_mean"].append(gathered_low_clip.nanmean().item()) + self._metrics[mode]["clip_ratio/low_min"].append(nanmin(gathered_low_clip).item()) + gathered_high_clip = self.accelerator.gather(high_clip) + self._metrics[mode]["clip_ratio/high_mean"].append(gathered_high_clip.nanmean().item()) + self._metrics[mode]["clip_ratio/high_max"].append(nanmax(gathered_high_clip).item()) + gathered_clip_ratio = self.accelerator.gather(clip_ratio) + self._metrics[mode]["clip_ratio/region_mean"].append(gathered_clip_ratio.nanmean().item()) + elif self.loss_type == "cispo": + is_cispo_clipped = (coef_1 > self.epsilon_high) & (advantages > 0) + cispo_clip_ratio = masked_batch_mean(is_cispo_clipped.float()) + gathered_cispo_clip_ratio = self.accelerator.gather(cispo_clip_ratio) + self._metrics[mode]["cispo_clip_ratio"].append(gathered_cispo_clip_ratio.nanmean().item()) + elif self.loss_type == "vespo": + gathered_phi_seq = self.accelerator.gather(phi_seq) + self._metrics[mode]["vespo/phi_seq_mean"].append(gathered_phi_seq.nanmean().item()) + + return loss + + # During eval, Trainer calls prediction_step. If no labels are present in the inputs, it only runs forward and + # returns logits. We override prediction_step to force compute_loss, because this trainer doesn't involve labels. + def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys: list[str] | None = None): + inputs = self._prepare_inputs(inputs) + with torch.no_grad(): + with self.compute_loss_context_manager(): + loss = self.compute_loss(model, inputs) + loss = loss.mean().detach() + return loss, None, None + + def log(self, logs: dict[str, float], start_time: float | None = None) -> None: + mode = "train" if self.model.training else "eval" + # Average the metrics + metrics = {} + for key, val in self._metrics[mode].items(): + # Filter out NaN values before averaging. A reward function that returns None for all samples + # in a batch produces NaN for that batch's metric. With logging_steps > 1, a naive sum()/len() + # would let a single NaN contaminate valid data from other batches. Only return None when no + # valid values remain (e.g. JSON loggers crash on float NaN). + valid = [v for v in val if not math.isnan(v)] + metrics[key] = sum(valid) / len(valid) if valid else None + + # This method can be called both in training and evaluation. When called in evaluation, the keys in `logs` + # start with "eval_". We need to add the prefix "eval_" to the keys in `metrics` to match the format. + if mode == "eval": + metrics = {f"eval_{key}": val for key, val in metrics.items()} + + logs.update(metrics) + super().log(logs, start_time) + self._metrics[mode].clear() + + if self.accelerator.is_main_process and self.log_completions: + if is_rich_available(): + print_prompt_completions_sample( + self._logs["prompt"], + self._logs["completion"], + self._logs["rewards"], + self._logs["advantages"], + self.state.global_step, + self.num_completions_to_print, + extra=dict(self._logs["extra"]), + ) + + logging_backends = [] + if self.args.report_to and "wandb" in self.args.report_to and wandb.run is not None: + logging_backends.append(wandb) + if self.args.report_to and "trackio" in self.args.report_to: + logging_backends.append(trackio) + + table = { + "step": [self.state.global_step] * len(self._logs["prompt"]), + "prompt": self._logs["prompt"], + "completion": self._logs["completion"], + **self._logs["rewards"], + **self._logs["extra"], + "advantage": self._logs["advantages"], + } + + df_base = pd.DataFrame(table) + df_base.to_parquet( + os.path.join( + self.args.output_dir, + "completions", + f"completions_{self.state.global_step:05d}.parquet", + ) + ) + + images_raw = self._logs["images"] or [] + + for logging_backend in logging_backends: + if images_raw: + images = [] + for image_list in self._logs["images"]: + if image_list: + images.append([logging_backend.Image(image) for image in image_list]) + else: + images.append([]) + df = pd.concat( + [df_base, pd.Series(images, name="image")], + axis=1, + copy=False, + ) + else: + df = df_base + + if self.log_unique_prompts: + df = df.drop_duplicates(subset=["prompt"]) + + logging_backend.log({"completions": logging_backend.Table(dataframe=df)}) + + # Ensure the model card is saved along with the checkpoint + def _save_checkpoint(self, model, trial): + if self.args.hub_model_id is None: + model_name = Path(self.args.output_dir).name + else: + model_name = self.args.hub_model_id.split("/")[-1] + self.create_model_card(model_name=model_name) + super()._save_checkpoint(model, trial) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/kto_config.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/kto_config.py new file mode 100644 index 0000000000000000000000000000000000000000..849648a8f74f245df98cab016a7b87fa1b628f93 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/kto_config.py @@ -0,0 +1,36 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from dataclasses import dataclass + +from ..import_utils import suppress_experimental_warning + + +with suppress_experimental_warning(): + from ..experimental.kto import KTOConfig as _KTOConfig + + +@dataclass +class KTOConfig(_KTOConfig): + def __post_init__(self): + warnings.warn( + "The `KTOConfig` is now located in `trl.experimental`. Please update your imports to " + "`from trl.experimental.kto import KTOConfig`. For more information, see " + "https://github.com/huggingface/trl/issues/4223. Promoting KTO to the stable API is a high-priority task. " + "Until then, this current path (`from trl import KTOConfig`) will remain, but API changes may occur.", + FutureWarning, + stacklevel=3, + ) + super().__post_init__() diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/kto_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/kto_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..110e29f0a8062efe09a87cddf2a7574d4f8d999e --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/kto_trainer.py @@ -0,0 +1,36 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from dataclasses import dataclass + +from ..import_utils import suppress_experimental_warning + + +with suppress_experimental_warning(): + from ..experimental.kto import KTOTrainer as _KTOTrainer + + +@dataclass +class KTOTrainer(_KTOTrainer): + def __init__(self, *args, **kwargs): + warnings.warn( + "The `KTOTrainer` is now located in `trl.experimental`. Please update your imports to " + "`from trl.experimental.kto import KTOTrainer`. For more information, see " + "https://github.com/huggingface/trl/issues/4223. Promoting KTO to the stable API is a high-priority task. " + "Until then, this current path (`from trl import KTOTrainer`) will remain, but API changes may occur.", + FutureWarning, + stacklevel=2, + ) + super().__init__(*args, **kwargs) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/model_config.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/model_config.py new file mode 100644 index 0000000000000000000000000000000000000000..60830fe4006d306476ddc0a547b721da72d454b4 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/model_config.py @@ -0,0 +1,190 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field + + +@dataclass +class ModelConfig: + """ + Configuration class for the models. + + 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: + model_name_or_path (`str`, *optional*): + Model checkpoint for weights initialization. + model_revision (`str`, *optional*, defaults to `"main"`): + Specific model version to use. It can be a branch name, a tag name, or a commit id. + dtype (`Literal["auto", "bfloat16", "float16", "float32"]`, *optional*, defaults to `"float32"`): + Override the default `torch.dtype` and load the model under this dtype. Possible values are + + - `"bfloat16"`: `torch.bfloat16` + - `"float16"`: `torch.float16` + - `"float32"`: `torch.float32` + - `"auto"`: Automatically derive the dtype from the model's weights. + + trust_remote_code (`bool`, *optional*, defaults to `False`): + Whether to allow for custom models defined on the Hub in their own modeling files. This option should only + be set to `True` for repositories you trust and in which you have read the code, as it will execute code + present on the Hub on your local machine. + attn_implementation (`str`, *optional*): + Which attention implementation to use. More information in the [Kernels Hub Integrations + Guide](kernels_hub). + use_peft (`bool`, *optional*, defaults to `False`): + Whether to use PEFT for training. + lora_r (`int`, *optional*, defaults to `16`): + LoRA R value. + lora_alpha (`int`, *optional*, defaults to `32`): + LoRA alpha. + lora_dropout (`float`, *optional*, defaults to `0.05`): + LoRA dropout. + lora_target_modules (`str | list[str]`, *optional*): + LoRA target modules. + lora_target_parameters (`str | list[str]`, *optional*): + List of target parameters for LoRA. + lora_modules_to_save (`list[str]`, *optional*): + Model layers to unfreeze & train. + lora_task_type (`str`, *optional*, defaults to `"CAUSAL_LM"`): + Task type to pass for LoRA (use `"SEQ_CLS"` for reward modeling). + use_rslora (`bool`, *optional*, defaults to `False`): + Whether to use Rank-Stabilized LoRA, which sets the adapter scaling factor to `lora_alpha/√r`, instead of + the original default value of `lora_alpha/r`. + use_dora (`bool`, *optional*, defaults to `False`): + Enable [Weight-Decomposed Low-Rank Adaptation (DoRA)](https://huggingface.co/papers/2402.09353). This + technique decomposes the updates of the weights into two parts, magnitude and direction. Direction is + handled by normal LoRA, whereas the magnitude is handled by a separate learnable parameter. This can + improve the performance of LoRA, especially at low ranks. Right now, DoRA only supports linear and Conv2D + layers. DoRA introduces a bigger overhead than pure LoRA, so it is recommended to merge weights for + inference. + load_in_8bit (`bool`, *optional*, defaults to `False`): + Whether to use 8 bit precision for the base model. Works only with LoRA. + load_in_4bit (`bool`, *optional*, defaults to `False`): + Whether to use 4 bit precision for the base model. Works only with LoRA. + bnb_4bit_quant_type (`str`, *optional*, defaults to `"nf4"`): + Quantization type (`"fp4"` or `"nf4"`). + use_bnb_nested_quant (`bool`, *optional*, defaults to `False`): + Whether to use nested quantization. + bnb_4bit_quant_storage (`str`, *optional*): + Quantization storage dtype. + """ + + model_name_or_path: str | None = field( + default=None, + metadata={"help": "Model checkpoint for weights initialization."}, + ) + model_revision: str = field( + default="main", + metadata={"help": "Specific model version to use. It can be a branch name, a tag name, or a commit id."}, + ) + dtype: str | None = field( + default="float32", + metadata={ + "help": "Override the default `torch.dtype` and load the model under this dtype. It defaults to `'float32'`.", + "choices": ["auto", "bfloat16", "float16", "float32"], + }, + ) + trust_remote_code: bool = field( + default=False, + metadata={ + "help": "Whether to allow for custom models defined on the Hub in their own modeling files. This option " + "should only be set to `True` for repositories you trust and in which you have read the code, as it will " + "execute code present on the Hub on your local machine." + }, + ) + attn_implementation: str | None = field( + default=None, + metadata={ + "help": "Which attention implementation to use. You can run `--attn_implementation=flash_attention_2`, in " + "which case you must install this manually by running `pip install flash-attn --no-build-isolation`." + }, + ) + use_peft: bool = field( + default=False, + metadata={"help": "Whether to use PEFT for training."}, + ) + lora_r: int = field( + default=16, + metadata={"help": "LoRA R value."}, + ) + lora_alpha: int = field( + default=32, + metadata={"help": "LoRA alpha."}, + ) + lora_dropout: float = field( + default=0.05, + metadata={"help": "LoRA dropout."}, + ) + lora_target_modules: list[str] | None = field( + default=None, + metadata={"help": "LoRA target modules."}, + ) + lora_target_parameters: list[str] | None = field( + default=None, + metadata={"help": "List of target parameters for LoRA."}, + ) + lora_modules_to_save: list[str] | None = field( + default=None, + metadata={"help": "Model layers to unfreeze & train."}, + ) + lora_task_type: str = field( + default="CAUSAL_LM", + metadata={"help": "Task type to pass for LoRA (use 'SEQ_CLS' for reward modeling)."}, + ) + use_rslora: bool = field( + default=False, + metadata={ + "help": "Whether to use Rank-Stabilized LoRA, which sets the adapter scaling factor to `lora_alpha/√r`, " + "instead of the original default value of `lora_alpha/r`." + }, + ) + use_dora: bool = field( + default=False, + metadata={ + "help": "Enable Weight-Decomposed Low-Rank Adaptation (DoRA). This technique decomposes the updates of " + "the weights into two parts, magnitude and direction. Direction is handled by normal LoRA, whereas the " + "magnitude is handled by a separate learnable parameter. This can improve the performance of LoRA, " + "especially at low ranks. Right now, DoRA only supports linear and Conv2D layers. DoRA introduces a " + "bigger overhead than pure LoRA, so it is recommended to merge weights for inference." + }, + ) + load_in_8bit: bool = field( + default=False, + metadata={"help": "Whether to use 8 bit precision for the base model. Works only with LoRA."}, + ) + load_in_4bit: bool = field( + default=False, + metadata={"help": "Whether to use 4 bit precision for the base model. Works only with LoRA."}, + ) + bnb_4bit_quant_type: str = field( + default="nf4", + metadata={"help": "Quantization type.", "choices": ["fp4", "nf4"]}, + ) + use_bnb_nested_quant: bool = field( + default=False, + metadata={"help": "Whether to use nested quantization."}, + ) + bnb_4bit_quant_storage: str | None = field( + default=None, + metadata={"help": "Quantization storage dtype"}, + ) + + def __post_init__(self): + if self.load_in_8bit and self.load_in_4bit: + raise ValueError("You can't use 8 bit and 4 bit precision at the same time") + + if hasattr(self.lora_target_modules, "__len__") and len(self.lora_target_modules) == 1: + self.lora_target_modules = self.lora_target_modules[0] diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/reward_config.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/reward_config.py new file mode 100644 index 0000000000000000000000000000000000000000..5740bc6e81333bef93106c7ae497cdbed7e916e1 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/reward_config.py @@ -0,0 +1,176 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from dataclasses import dataclass, field +from typing import Any + +from .base_config import _BaseConfig + + +@dataclass +class RewardConfig(_BaseConfig): + # docstyle-ignore + r""" + Configuration class for the [`RewardTrainer`]. + + This class includes only the parameters that are specific to Reward 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 + + model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments for [`~transformers.AutoModelForCausalLM.from_pretrained`], used when the `model` + argument of the [`RewardTrainer`] is provided as a string. If you're training a MoE architecture and want + to include the load balancing/auxiliary loss as a part of the final loss, remember to set + `output_router_logits=True` in this dictionary. + chat_template_path (`str`, *optional*): + If specified, sets the model's chat template. This can either be the path to a tokenizer (local directory + or Hugging Face Hub model) or a direct path to a Jinja template file. When using a Jinja file, you must + ensure that any special tokens referenced in the template are added to the tokenizer and that the model's + embedding layer is resized accordingly. + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the model. + + > Parameters that control the data preprocessing + + dataset_num_proc (`int`, *optional*): + Number of processes to use for processing the dataset. + eos_token (`str`, *optional*): + Token used to indicate the end of a turn or sequence. If `None`, it defaults to + `processing_class.eos_token`. + max_length (`int` or `None`, *optional*, defaults to `1024`): + Maximum length of the tokenized sequence. Samples are filtered out if either chosen or rejected sequence + exceeds this value. If `None`, no filtering is applied. + pad_to_multiple_of (`int`, *optional*): + If set, the sequences will be padded to a multiple of this value. + + > Parameters that control the training + + center_rewards_coefficient (`float`, *optional*): + Coefficient to incentivize the reward model to output mean-zero rewards (proposed by + https://huggingface.co/papers/2312.09244, Eq. 2). Recommended value: `0.01`. + activation_offloading (`bool`, *optional*, defaults to `False`): + Whether to offload the activations to the CPU. + + > Deprecated parameters + + pad_token: + + + + Parameter `pad_token` is deprecated and will be removed in version v2.0.0. Set `tokenizer.pad_token` + directly and pass it as `processing_class` to the trainer instead. + + + + > [!NOTE] + > These parameters have default values different from [`~transformers.TrainingArguments`]: + > - `logging_steps`: Defaults to `10` instead of `500`. + > - `gradient_checkpointing`: Defaults to `True` instead of `False`. + > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`. + > - `learning_rate`: Defaults to `1e-4` instead of `5e-5`. + """ + + _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"] + + # Parameters whose default values are overridden from TrainingArguments + learning_rate: float = field( + default=1e-4, + metadata={"help": "The initial learning rate for AdamW."}, + ) + + # Parameters that control the model + model_init_kwargs: dict[str, Any] | str | None = field( + default=None, + metadata={ + "help": "Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `model` argument of " + "the `RewardTrainer` is provided as a string. If you're training a MoE architecture and want to include " + "the load balancing/auxiliary loss as a part of the final loss, remember to set " + "`output_router_logits=True` in this dictionary." + }, + ) + chat_template_path: str | None = field( + default=None, + metadata={ + "help": "If specified, sets the model's chat template. This can either be the path to a tokenizer (local " + "directory or Hugging Face Hub model) or a direct path to a Jinja template file. When using a Jinja file, " + "you must ensure that any special tokens referenced in the template are added to the tokenizer and " + "that the model's embedding layer is resized accordingly." + }, + ) + disable_dropout: bool = field( + default=True, + metadata={"help": "Whether to disable dropout in the model."}, + ) + + # Parameters that control the data preprocessing + dataset_num_proc: int | None = field( + default=None, + metadata={"help": "Number of processes to use for processing the dataset."}, + ) + eos_token: str | None = field( + default=None, + metadata={ + "help": "Token used to indicate the end of a turn or sequence. If `None`, it defaults to `processing_class.eos_token`." + }, + ) + max_length: int | None = field( + default=1024, + metadata={ + "help": "Maximum length of the tokenized sequence. Sequences longer than `max_length` are truncated from " + "the right. If `None`, no truncation is applied." + }, + ) + pad_to_multiple_of: int | None = field( + default=None, + metadata={"help": "If set, the sequences will be padded to a multiple of this value."}, + ) + + # Parameters that control the training + center_rewards_coefficient: float | None = field( + default=None, + metadata={ + "help": "Coefficient to incentivize the reward model to output mean-zero rewards (proposed by " + "https://huggingface.co/papers/2312.09244, Eq. 2). Recommended value: `0.01`." + }, + ) + activation_offloading: bool = field( + default=False, + metadata={"help": "Whether to offload the activations to the CPU."}, + ) + + # Deprecated parameters + pad_token: str | None = field( + default=None, + metadata={ + "help": "Deprecated. Set `tokenizer.pad_token` directly and pass it as `processing_class` to the trainer instead." + }, + ) + + def __post_init__(self): + super().__post_init__() + if self.pad_token is not None: + warnings.warn( + "`pad_token` is deprecated and will be removed in v2.0.0. " + "Set `tokenizer.pad_token` directly and pass it as `processing_class` to the trainer instead.", + FutureWarning, + stacklevel=3, + ) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/reward_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/reward_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..5e670b373870661381cc6c0fc9ebd027ad057ba1 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/reward_trainer.py @@ -0,0 +1,711 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import contextlib +import json +import logging +import os +import re +import warnings +from collections import defaultdict +from collections.abc import Callable +from contextlib import contextmanager +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import torch +import torch.nn as nn +import transformers +from accelerate import PartialState +from accelerate.logging import get_logger +from accelerate.utils import is_peft_model +from datasets import Dataset, IterableDataset +from packaging.version import Version +from transformers import ( + AutoModelForSequenceClassification, + AutoTokenizer, + DataCollator, + PreTrainedModel, + PreTrainedTokenizerBase, + TrainerCallback, + set_seed, +) +from transformers.data.data_collator import DataCollatorMixin +from transformers.modeling_layers import GenericForSequenceClassification +from transformers.trainer_utils import EvalPrediction +from transformers.utils import is_peft_available + +from ..chat_template_utils import clone_chat_template +from ..data_utils import is_conversational +from ..models import get_act_offloading_ctx_manager +from .base_trainer import _BaseTrainer +from .reward_config import RewardConfig +from .utils import create_model_from_path, disable_dropout_in_model, get_config_model_id, pad + + +if is_peft_available(): + from peft import PeftConfig, PeftModel, get_peft_model + + +logger = get_logger(__name__) + + +# Loading a CausalLM checkpoint into AutoModelForSequenceClassification triggers harmless warnings: +# - MISSING score.weight : the new seq-clf head was not in the checkpoint and is randomly initialized. +# - UNEXPECTED lm_head.weight: the causal LM head is in the checkpoint but absent from seq-clf (>= 4.57.0 only). +# Both are expected consequences of intentional cross-architecture loading. We suppress them to avoid +# confusing users. + + +# Old approach using logging filter (for transformers < 4.57.0) +# Note: in transformers < 4.57.0, only the MISSING score.weight warning is emitted; lm_head.weight is not reported. +@contextmanager +def _suppress_seqcls_cross_arch_keys(logger: logging.Logger): + pattern = re.compile( + r"^Some weights of \S+ were not initialized from the model checkpoint at \S+ and are newly initialized: " + r"\[.*\]\nYou should probably TRAIN this model on a down-stream task to be able to use it for predictions and " + r"inference\.$" + ) + + class _Filter(logging.Filter): + def filter(self, record: logging.LogRecord) -> bool: + return not pattern.search(record.getMessage()) + + f = _Filter() + logger.addFilter(f) + try: + yield + finally: + logger.removeFilter(f) + + +# New approach using scoped override (for transformers >= 4.57.0) +@contextmanager +def _ignore_seqcls_cross_arch_keys(): + # Scoped override: ignore the expected seq-clf head key (newly added) and the causal LM head + # key (present in the checkpoint but absent from seq-clf). + old_missing = getattr(GenericForSequenceClassification, "_keys_to_ignore_on_load_missing", None) + old_unexpected = getattr(GenericForSequenceClassification, "_keys_to_ignore_on_load_unexpected", None) + + merged_missing = list(old_missing) if old_missing is not None else [] + if r"^score\.weight$" not in merged_missing: + merged_missing.append(r"^score\.weight$") + + merged_unexpected = list(old_unexpected) if old_unexpected is not None else [] + if r"^lm_head\." not in merged_unexpected: + merged_unexpected.append(r"^lm_head\.") + + GenericForSequenceClassification._keys_to_ignore_on_load_missing = merged_missing + GenericForSequenceClassification._keys_to_ignore_on_load_unexpected = merged_unexpected + try: + yield + finally: + GenericForSequenceClassification._keys_to_ignore_on_load_missing = old_missing + GenericForSequenceClassification._keys_to_ignore_on_load_unexpected = old_unexpected + + +# Version-aware wrapper that chooses the appropriate approach +@contextmanager +def suppress_seqcls_warning(): + # Use the new approach for transformers >= 4.57.0, old approach for earlier versions + # The old approach is needed for 4.56.2 to avoid meta tensor issues with device_map=None + if Version(transformers.__version__) >= Version("4.57.0"): + with _ignore_seqcls_cross_arch_keys(): + yield + else: + # Get the transformers logger + transformers_logger = logging.getLogger("transformers.modeling_utils") + with _suppress_seqcls_cross_arch_keys(transformers_logger): + yield + + +def get_dataset_column_names(dataset: Dataset | IterableDataset) -> list[str]: + return list(next(iter(dataset)).keys()) if dataset.column_names is None else dataset.column_names + + +@dataclass +class DataCollatorForPreference(DataCollatorMixin): + """ + Data collator used for preference data. Inputs are dynamically padded to the maximum length of a batch. + + This collator expects each example in the input list to be a dictionary containing the `"chosen_ids"` and + `"rejected_ids"` keys. The collator returns a dictionary containing the following keys: + - `"input_ids"`: Tensor of input IDs, padded to the maximum length of the batch. The first half of the batch + corresponds to the `"chosen_ids"` and the second half to the `"rejected_ids"`. + - `"attention_mask"`: Tensor of attention mask, padded to the maximum length of the batch. + + Optionally, the examples can contain a `"margin"` key, in which case the returned dictionary will also contain a + `"margin"` key with a tensor of margins. + + Args: + pad_token_id (`int`): + Token ID to use for padding. + pad_to_multiple_of (`int`, *optional*): + If set, the sequences will be padded to a multiple of this value. + return_tensors (`str`, *optional*, defaults to `"pt"`): + Type of Tensor to return. Only `"pt"` is currently supported. + + Examples: + ```python + >>> from trl.trainer.reward_trainer import DataCollatorForPreference + + >>> collator = DataCollatorForPreference(pad_token_id=0) + >>> examples = [ + ... {"chosen_ids": [1, 2, 3], "rejected_ids": [4, 5]}, + ... {"chosen_ids": [6, 7], "rejected_ids": [8]}, + ... ] + >>> collator(examples) + {'input_ids': tensor([[1, 2, 3], + [6, 7, 0], + [4, 5, 0], + [8, 0, 0]]), + 'attention_mask': tensor([[1, 1, 1], + [1, 1, 0], + [1, 1, 0], + [1, 0, 0]])} + + >>> examples = [ + ... {"chosen_ids": [1, 2, 3], "rejected_ids": [4, 5], "margin": 0.5}, + ... {"chosen_ids": [6, 7], "rejected_ids": [8], "margin": 0.0}, + ... ] + >>> collator(examples) + {'input_ids': tensor([[1, 2, 3], + [6, 7, 0], + [4, 5, 0], + [8, 0, 0]]), + 'attention_mask': tensor([[1, 1, 1], + [1, 1, 0], + [1, 1, 0], + [1, 0, 0]]), + 'margin': tensor([0.5, 0.0])} + ``` + """ + + pad_token_id: int + pad_to_multiple_of: int | None = None + return_tensors: str = "pt" + + def torch_call(self, examples: list[dict[str, Any]]) -> dict[str, Any]: + # Convert to tensor + chosen_ids = [torch.tensor(example["chosen_ids"]) for example in examples] + rejected_ids = [torch.tensor(example["rejected_ids"]) for example in examples] + if "margin" in examples[0]: + margins = torch.tensor([example["margin"] for example in examples], dtype=torch.float) + input_ids = chosen_ids + rejected_ids + attention_mask = [torch.ones_like(ids) for ids in input_ids] + + output = {} + + # Pad + output["input_ids"] = pad( + input_ids, + padding_value=self.pad_token_id, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ) + output["attention_mask"] = pad( + attention_mask, + padding_value=0, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ) + if "margin" in examples[0]: + output["margin"] = margins + return output + + +class RewardTrainer(_BaseTrainer): + """ + Trainer for Outcome-supervised Reward Models (ORM). + + This class is a wrapper around the [`~transformers.Trainer`] class and inherits all of its attributes and methods. + + Example: + + ```python + from trl import RewardTrainer + from datasets import load_dataset + + dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train") + + trainer = RewardTrainer( + model="Qwen/Qwen2.5-0.5B-Instruct", + train_dataset=dataset, + ) + trainer.train() + ``` + + Args: + model (`str` or [`~transformers.PreTrainedModel`] or [`~peft.PeftModel`]): + Model to be trained. Can be either: + + - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a + path to a *directory* containing model weights saved using + [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded + using `AutoModelForSequenceClassification.from_pretrained` with the keyword arguments in + `args.model_init_kwargs`. + - A sequence classification [`~transformers.PreTrainedModel`] object. + - A sequence classification [`~peft.PeftModel`] object. + args ([`RewardConfig`], *optional*): + Configuration for this trainer. If `None`, a default configuration is used. + data_collator ([`~transformers.DataCollator`], *optional*): + Function to use to form a batch from a list of elements of the processed `train_dataset` or `eval_dataset`. + Will default to [`~trainer.reward_trainer.DataCollatorForPreference`]. + train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]): + Dataset to use for training. This trainer supports [preference](#preference) type (both implicit and + explicit prompt). The format of the samples can be either: + + - [Standard](dataset_formats#standard): Each sample contains plain text. + - [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role + and content). + + The trainer also supports processed datasets (tokenized) as long as they contain `chosen_ids` and + `rejected_ids` fields. + eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Dataset | IterableDataset]`): + Dataset to use for evaluation. It must meet the same requirements as `train_dataset`. + processing_class ([`~transformers.PreTrainedTokenizerBase`], *optional*): + Tokenizer used to process the data. If `None`, the tokenizer is loaded from the model's name with + [`~transformers.AutoTokenizer.from_pretrained`]. A padding token, `processing_class.pad_token`, must be + set. If the processing class has not set a padding token, `processing_class.eos_token` will be used as the + default. + compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*): + The function that will be used to compute metrics at evaluation. Must take a + [`~transformers.EvalPrediction`] and return a dictionary string to metric values. When passing + [`RewardConfig`] with `batch_eval_metrics` set to `True`, your `compute_metrics` function must take a + boolean `compute_result` argument. This will be triggered after the last eval batch to signal that the + function needs to calculate and return the global summary statistics rather than accumulating the + batch-level statistics. + callbacks (list of [`~transformers.TrainerCallback`], *optional*): + List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed + in [here](https://huggingface.co/docs/transformers/main_classes/callback). + + If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`] + method. + optimizers (`tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None]`, *optional*, defaults to `(None, None)`): + A tuple containing the optimizer and the scheduler to use. Will default to an instance of `AdamW` on your + model and a scheduler given by [`~transformers.get_linear_schedule_with_warmup`] controlled by `args`. + optimizer_cls_and_kwargs (`tuple[Type[torch.optim.Optimizer], Dict[str, Any]]`, *optional*): + A tuple containing the optimizer class and keyword arguments to use. Overrides `optim` and `optim_args` in + `args`. Incompatible with the `optimizers` argument. + + Unlike `optimizers`, this argument avoids the need to place model parameters on the correct devices before + initializing the Trainer. + preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`, *optional*): + A function that preprocess the logits right before caching them at each evaluation step. Must take two + tensors, the logits and the labels, and return the logits once processed as desired. The modifications made + by this function will be reflected in the predictions received by `compute_metrics`. + + Note that the labels (second parameter) will be `None` if the dataset does not have them. + peft_config ([`~peft.PeftConfig`], *optional*): + PEFT configuration used to wrap the model. If `None`, the model is not wrapped. Note that if the loaded + model is a causal LM, it's highly recommended to set `modules_to_save=["score"]` in the PEFT configuration + to ensure that the reward head is properly trained. + """ + + _tag_names = ["trl", "reward-trainer"] + _name = "Reward" + _template_file = "rm_model_card.md" + + def __init__( + self, + model: "str | PreTrainedModel | PeftModel", + args: RewardConfig | None = None, + data_collator: DataCollator | None = None, + train_dataset: Dataset | IterableDataset | None = None, + eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None, + processing_class: PreTrainedTokenizerBase | None = None, + compute_metrics: Callable[[EvalPrediction], dict] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None), + optimizer_cls_and_kwargs: tuple[type[torch.optim.Optimizer], dict[str, Any]] | None = None, + preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None, + peft_config: "PeftConfig | None" = None, + ): + # Args + if args is None: + model_name = model if isinstance(model, str) else get_config_model_id(model.config) + model_name = model_name.split("/")[-1] + args = RewardConfig(f"{model_name}-Reward") + + if train_dataset is None: + raise ValueError("`train_dataset` is required") + elif isinstance(train_dataset, IterableDataset): + # IterableDataset requires dispatch_batches=False because Accelerate's dispatch mode may try to concatenate + # batches from multiple processes, leading to mismatch errors. + if args.accelerator_config.dispatch_batches is True: + logger.warning( + "You are using an `IterableDataset` for training with `dispatch_batches=True`. `dispatch_batches` " + "is forced to `False` when using an `IterableDataset`. To remove this warning, unset " + "`dispatch_batches` in `RewardConfig` or set it to `False`." + ) + args.accelerator_config.dispatch_batches = False + + # Model + # As AutoModelForSequenceClassification.from_pretrained() will add a random head for the model, set_seed must + # be done before loading the model to ensure reproducibility. + set_seed(args.seed) + if isinstance(model, str): + model_init_kwargs = args.model_init_kwargs or {} + # Distributed training requires device_map=None ("auto" fails) + if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + model_init_kwargs["device_map"] = None + model_init_kwargs["num_labels"] = 1 # the only output of the model is the reward score + with suppress_seqcls_warning(): + model = create_model_from_path(model, AutoModelForSequenceClassification, **model_init_kwargs) + else: + if args.model_init_kwargs is not None: + logger.warning( + "You passed `model_init_kwargs` to the `RewardConfig`, but your model is already instantiated. " + "The `model_init_kwargs` will be ignored." + ) + # Validate that the model has num_labels = 1 (required for reward models) + if getattr(model.config, "num_labels", None) != 1: + raise ValueError( + f"The model has `num_labels={model.config.num_labels}`, but reward models require `num_labels=1` " + "to output a single scalar reward per sequence. Please instantiate your model with `num_labels=1` " + "or pass a model name as a string to have it configured automatically." + ) + + # Processing class + if processing_class is None: + processing_class = AutoTokenizer.from_pretrained(get_config_model_id(model.config)) + + # Handle pad token for processors or tokenizers + if args.eos_token is not None: + if args.eos_token not in processing_class.get_vocab(): + raise ValueError( + f"The specified `eos_token` ('{args.eos_token}') is not found in the vocabulary of the given " + f"`processing_class` ({processing_class.__class__.__name__}). Ensure that the `eos_token` exists " + "in the vocabulary before using it as an EOS token." + ) + processing_class.eos_token = args.eos_token + + if args.chat_template_path is not None: + if os.path.isfile(args.chat_template_path) and args.chat_template_path.endswith((".jinja", ".j2")): + with open(args.chat_template_path, encoding="utf-8") as chat_template_file: + processing_class.chat_template = chat_template_file.read() + added_tokens = [] + else: + model, processing_class, added_tokens = clone_chat_template( + model, processing_class, args.chat_template_path + ) + else: + added_tokens = [] + + # PEFT + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + if is_peft_model(model): + raise ValueError( + "You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first merge " + "and unload the existing adapter, save the resulting base model, and then pass that base model along " + "with the new `peft_config` to the trainer." + ) + if added_tokens: + # Ensure that the added tokens are trainable + if peft_config.trainable_token_indices is None: + peft_config.trainable_token_indices = {"embed_tokens": added_tokens} + elif "embed_tokens" not in peft_config.trainable_token_indices: + peft_config.trainable_token_indices["embed_tokens"] = added_tokens + else: + peft_config.trainable_token_indices["embed_tokens"].extend(added_tokens) + # Ensure that the lm_head is trainable + if peft_config.modules_to_save is None or "lm_head" not in peft_config.modules_to_save: + logger.warning( + "Cloning chat template added new tokens to the tokenizer, but 'lm_head' is not in PEFT's " + "`modules_to_save`. As a result, the model may not learn to generate outputs with these new " + "tokens, leading to degraded generation quality. To fix this, add " + "`modules_to_save=['lm_head']` to your PEFT configuration." + ) + + if peft_config.modules_to_save is None: + peft_config.modules_to_save = ["lm_head"] + else: + peft_config.modules_to_save.append("lm_head") + # Create PEFT model + model = get_peft_model(model, peft_config) + + # When using gradient checkpointing with PEFT, we need to enable input gradients. transformers.Trainer normally + # handles this, but a bug currently prevents it; see https://github.com/huggingface/transformers/issues/42489 + if is_peft_model(model) and args.gradient_checkpointing: + model.enable_input_require_grads() + + # When using QLoRA, the PEFT adapter weights are converted to bf16 to follow the recommendations from the + # original paper (see https://huggingface.co/papers/2305.14314, paragraph 3). Normally, this can be done by + # passing `autocast_adapter_dtype=False` to `get_peft_model`, but this option is not yet supported for + # quantized models. See: https://github.com/huggingface/peft/issues/2889 + # Non-quantized models do not have the `is_loaded_in_{8,4}bit` attributes, whereas quantized models do + if getattr(model, "is_loaded_in_4bit", False) or getattr(model, "is_loaded_in_8bit", False): + for param in model.parameters(): + if param.requires_grad: + param.data = param.data.to(torch.bfloat16) + + # Disable dropout in the model + if args.disable_dropout: + disable_dropout_in_model(model) + + # Pad token (needed for SequenceClassification models) + # If not provided, use the one from the processing class or the eos token if the processing class does not have + # a pad token. + pad_token = args.pad_token or processing_class.pad_token or processing_class.eos_token + if pad_token not in processing_class.get_vocab(): + raise ValueError( + f"The specified `pad_token` ('{pad_token}') is not found in the vocabulary of the given " + f"`processing_class` ({processing_class.__class__.__name__}). Ensure that the `pad_token` exists " + "in the vocabulary before using it as a padding token." + ) + processing_class.pad_token = pad_token + + # Data collator + if data_collator is None: + data_collator = DataCollatorForPreference( + pad_token_id=processing_class.pad_token_id, + pad_to_multiple_of=args.pad_to_multiple_of, + ) + + # Dataset + train_dataset = self._prepare_dataset(train_dataset, processing_class, args, "train") + if eval_dataset is not None: + if isinstance(eval_dataset, dict): + eval_dataset = { + key: self._prepare_dataset(dataset, processing_class, args, key) + for key, dataset in eval_dataset.items() + } + else: + eval_dataset = self._prepare_dataset(eval_dataset, processing_class, args, "eval") + + # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was + # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream + # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we + # default to the recommended non-reentrant behavior here, while preserving any user-provided value. + if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"): + args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {} + args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False) + + super().__init__( + model=model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + optimizer_cls_and_kwargs=optimizer_cls_and_kwargs, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + ) + + # During evaluation, Trainer calls compute_loss() only if can_return_loss is True and label_names is empty. + self.can_return_loss = True + self.label_names = [] + + # Initialize activation offloading context + if self.args.activation_offloading: + self.maybe_activation_offload_context = get_act_offloading_ctx_manager(model=self.model) + else: + self.maybe_activation_offload_context = contextlib.nullcontext() + + self.aux_loss_enabled = getattr(model.config, "output_router_logits", False) + + # Initialize the metrics + self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)} + self._total_train_tokens = 0 + + # Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the + # model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set + # self.model_accepts_loss_kwargs to False to enable scaling. + self.model_accepts_loss_kwargs = False + + # Add tags to the model + self.model.add_model_tags(self._tag_names) + + def _prepare_dataset( + self, + dataset: Dataset | IterableDataset, + processing_class: PreTrainedTokenizerBase, + args: RewardConfig, + dataset_name: str, + ) -> Dataset | IterableDataset: + # If the dataset is already preprocessed (tokenized), skip the processing steps. + column_names = get_dataset_column_names(dataset) + is_processed = "chosen_ids" in column_names and "rejected_ids" in column_names + has_legacy_processed_columns = "chosen_input_ids" in column_names and "rejected_input_ids" in column_names + if has_legacy_processed_columns and not is_processed: + warnings.warn( + "Detected legacy dataset columns `chosen_input_ids`/`rejected_input_ids`; they are deprecated and " + "will not be supported in v1. Please migrate to `chosen_ids`/`rejected_ids`.", + FutureWarning, + stacklevel=2, + ) + dataset = dataset.rename_column("chosen_input_ids", "chosen_ids") + dataset = dataset.rename_column("rejected_input_ids", "rejected_ids") + is_processed = True + + # Build the kwargs for the `map` function + map_kwargs = {} + if isinstance(dataset, Dataset): # IterableDataset does not support num_proc + map_kwargs["num_proc"] = args.dataset_num_proc + + with PartialState().main_process_first(): + if not is_processed: + # Add EOS token if needed: non-conversational only + first_example = next(iter(dataset)) + if not is_conversational(first_example): + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Adding EOS to {dataset_name} dataset" + + def add_eos(example, eos_token): + if not example["chosen"].endswith(eos_token): + example["chosen"] = example["chosen"] + eos_token + if "rejected" in example and not example["rejected"].endswith(eos_token): + example["rejected"] = example["rejected"] + eos_token + return example + + dataset = dataset.map( + add_eos, + fn_kwargs={"eos_token": processing_class.eos_token}, + **map_kwargs, + ) + + # Tokenize the dataset + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Tokenizing {dataset_name} dataset" + + def tokenize_fn(example, processing_class): + tools = example.get("tools") + tools = json.loads(tools) if isinstance(tools, str) else tools + if "prompt" in example: # explicit prompt case + example["chosen"] = example["prompt"] + example["chosen"] + example["rejected"] = example["prompt"] + example["rejected"] + + if is_conversational(example): + chosen_ids = processing_class.apply_chat_template( + example["chosen"], + tools=tools, + return_dict=True, + **example.get("chat_template_kwargs", {}), + )["input_ids"] + rejected_ids = processing_class.apply_chat_template( + example["rejected"], + tools=tools, + return_dict=True, + **example.get("chat_template_kwargs", {}), + )["input_ids"] + output = {"chosen_ids": chosen_ids, "rejected_ids": rejected_ids} + else: + output = { + "chosen_ids": processing_class(text=example["chosen"])["input_ids"], + "rejected_ids": processing_class(text=example["rejected"])["input_ids"], + } + return output + + dataset = dataset.map(tokenize_fn, fn_kwargs={"processing_class": processing_class}, **map_kwargs) + + # Filter samples that are longer than `max_length` + if args.max_length is not None: + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Filtering {dataset_name} >{args.max_length} tokens" + dataset = dataset.filter( + lambda example: len(example["chosen_ids"]) <= args.max_length + and len(example["rejected_ids"]) <= args.max_length, + **map_kwargs, + ) + + return dataset + + def _set_signature_columns_if_needed(self): + # If `self.args.remove_unused_columns` is True, non-signature columns are removed. + # By default, this method sets `self._signature_columns` to the model's expected inputs (usually, "input_ids" + # and "attention_mask"). + if self._signature_columns is None: + self._signature_columns = ["chosen_ids", "rejected_ids", "margin"] + + def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): + mode = "train" if self.model.training else "eval" + + # If not set, defaults from model config and may warn since cache isn't compatible with gradient checkpointing + inputs["use_cache"] = False + outputs = model(**inputs) + + # Split the rewards into chosen and rejected + rewards_chosen, rewards_rejected = torch.chunk(outputs.logits.squeeze(-1), chunks=2) + + # Calculate loss, optionally modulate with margin + if "margin" in inputs: + loss = -nn.functional.logsigmoid(rewards_chosen - rewards_rejected - inputs["margin"]).mean() + else: + loss = -nn.functional.logsigmoid(rewards_chosen - rewards_rejected).mean() + + if self.args.center_rewards_coefficient is not None: + loss += self.args.center_rewards_coefficient * torch.mean((rewards_chosen + rewards_rejected) ** 2) + + if mode == "train": + num_tokens_in_batch = self.accelerator.gather_for_metrics(inputs["attention_mask"].sum()).sum().item() + self._total_train_tokens += num_tokens_in_batch + self._metrics[mode]["num_tokens"] = [self._total_train_tokens] + + # Compute min, mean, max, accuracy and margin + with torch.no_grad(): + all_rewards = self.accelerator.gather(outputs.logits) + self._metrics[mode]["min_reward"].append(all_rewards.min().item()) + self._metrics[mode]["mean_reward"].append(all_rewards.mean().item()) + self._metrics[mode]["max_reward"].append(all_rewards.max().item()) + + mean_accuracy = (rewards_chosen > rewards_rejected).float().mean() + mean_accuracy = self.accelerator.gather_for_metrics(mean_accuracy).mean().item() + self._metrics[mode]["accuracy"].append(mean_accuracy) + + mean_margin = (rewards_chosen - rewards_rejected).mean() + mean_margin = self.accelerator.gather_for_metrics(mean_margin).mean() + self._metrics[mode]["margin"].append(mean_margin.item()) + + return (loss, outputs) if return_outputs else loss + + # Override training step to add activation offloading context. + def training_step(self, *args, **kwargs): + with self.maybe_activation_offload_context: + return super().training_step(*args, **kwargs) + + def log(self, logs: dict[str, float], start_time: float | None = None) -> None: + mode = "train" if self.model.training else "eval" + metrics = {key: sum(val) / len(val) for key, val in self._metrics[mode].items()} # average the metrics + + # This method can be called both in training and evaluation. When called in evaluation, the keys in `logs` + # start with "eval_". We need to add the prefix "eval_" to the keys in `metrics` to match the format. + if mode == "eval": + metrics = {f"eval_{key}": val for key, val in metrics.items()} + + logs.update(metrics) + super().log(logs, start_time) + self._metrics[mode].clear() + + # Ensure the model card is saved along with the checkpoint + def _save_checkpoint(self, model, trial): + if self.args.hub_model_id is None: + model_name = Path(self.args.output_dir).name + else: + model_name = self.args.hub_model_id.split("/")[-1] + self.create_model_card(model_name=model_name) + super()._save_checkpoint(model, trial) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/rloo_config.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/rloo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..d8f463e417dd4c9de753bfd8758032f3ba501035 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/rloo_config.py @@ -0,0 +1,622 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from dataclasses import dataclass, field +from typing import Any + +from .base_config import _BaseConfig + + +@dataclass +class RLOOConfig(_BaseConfig): + # docstyle-ignore + r""" + Configuration class for the [`RLOOTrainer`]. + + This class includes only the parameters that are specific to RLOO 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]`, *optional*): + Keyword arguments for [`~transformers.AutoModelForCausalLM.from_pretrained`], used when the `model` + argument of the [`RLOOTrainer`] 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`. + num_generations (`int`, *optional*, defaults to `2`): + 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. + num_generations_eval (`int` or `None`, *optional*): + Number of generations to sample during evaluation. This allows using fewer generations during evaluation to + save computation. If `None`, uses the value of `num_generations`. + 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. + pad_to_multiple_of (`int`, *optional*): + If set, the prompts ids and completions ids will be padded to a multiple of this value. + + > Parameters that control generation + + generation_batch_size (`int`, *optional*): + 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`, *optional*): + 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`, *optional*, defaults to `0`): + Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, top-k-filtering is + disabled and all tokens are considered. + min_p (`float`, *optional*): + 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. + generation_kwargs (`dict[str, Any]`, *optional*): + Additional keyword arguments to pass to [`~transformers.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 `suppress_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. + chat_template_kwargs (`dict[str, Any]`, *optional*): + Additional keyword arguments to pass to the `apply_chat_template` function when generating completions. + 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. + cache_implementation (`str`, *optional*): + Implementation of the cache method for faster generation when `use_vllm` is set to `False`. + + > 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 `"colocate"`): + 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_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. + vllm_structured_outputs_regex (`str`, *optional*): + Regex for vLLM structured outputs. If `None` (default), structured outputs is disabled. + + > Parameters that control the vLLM server (only used when `vllm_mode` is `"server"`) + + vllm_server_base_url (`str`, *optional*): + 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. + vllm_group_port (`int`, *optional*, defaults to `51216`): + Port number for the weight update group. This is used to communicate with the vLLM server. Unless the port + is occupied, there is no need to change it. + + > 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_max_model_length (`int`, *optional*): + Context window for vLLM. Set it to at least the maximum prompt length in the dataset plus + `max_completion_length`; if omitted, it is inferred from the model config. + 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_enable_sleep_mode (`bool`, *optional*, defaults to `False`): + Enable vLLM sleep mode to offload weights/cache during the optimizer step. Keeps GPU memory usage low, but + waking the engine adds host–device transfer latency. + + > Parameters that control the training + + beta (`float`, *optional*, defaults to `0.05`): + KL coefficient. If `0.0`, 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. + epsilon_high (`float`, *optional*): + 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`. + reward_weights (`list[float]`, *optional*): + Weights for each reward function. Must match the number of reward functions. If `None`, all rewards are + weighted equally with weight `1.0`. + normalize_advantages (`bool`, *optional*, defaults to `False`): + Whether to normalize advantages. Normalization is done per generation batch to have mean `0.0` and standard + deviation of `1.0`. + reward_clip_range (`tuple[float, float]`, *optional*): + Clip range for rewards as (min, max). If `None`, no clipping is applied. + 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`. + + > 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` and/or `trackio` logging is enabled, it logs it to `wandb` and/or + `trackio`. + num_completions_to_print (`int`, *optional*): + Number of completions to print with `rich`. If `None`, all completions are logged. + log_unique_prompts (`bool`, *optional*, defaults to `False`): + Whether to log unique prompts. If `True`, only unique prompts are logged. If `False`, all prompts are + logged. + + > Deprecated parameters + + use_transformers_paged: + + + + Parameter `use_transformers_paged` is deprecated and will be removed in version v2.0.0. It will be + replaced by `transformers` continuous batching support in an upcoming release. + + + + > [!NOTE] + > These parameters have default values different from [`~transformers.TrainingArguments`]: + > - `logging_steps`: Defaults to `10` instead of `500`. + > - `gradient_checkpointing`: Defaults to `True` instead of `False`. + > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`. + > - `learning_rate`: Defaults to `1e-6` instead of `5e-5`. + """ + + _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"] + + # Parameters whose default values are overridden from TrainingArguments + learning_rate: float = field( + default=1e-6, + metadata={"help": "The initial learning rate for AdamW."}, + ) + + # Parameters that control the model and reference model + model_init_kwargs: dict[str, Any] | str | None = field( + default=None, + metadata={ + "help": "Keyword arguments for `transformers.AutoModelForCausalLM.from_pretrained`, used when the `model` " + "argument of the `RLOOTrainer` is provided as a string." + }, + ) + disable_dropout: bool = field( + default=False, + metadata={ + "help": "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 + # The default value remove_unused_columns is overwritten from the parent class, because in RLOO we usually rely on + # additional columns to compute the reward + remove_unused_columns: bool | None = field( + default=False, + metadata={ + "help": "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`." + }, + ) + num_generations: int | None = field( + default=2, + metadata={ + "help": "Number of generations to sample. The effective batch size (num_processes * per_device_batch_size " + "* gradient_accumulation_steps) must be evenly divisible by this value." + }, + ) + num_generations_eval: int | None = field( + default=None, + metadata={ + "help": "Number of generations to sample during evaluation. This allows using fewer generations during " + "evaluation to save computation. If `None`, uses the value of `num_generations`." + }, + ) + max_completion_length: int | None = field( + default=256, + metadata={"help": "Maximum length of the generated completion."}, + ) + ds3_gather_for_generation: bool = field( + default=True, + metadata={ + "help": "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 | None = field( + default=True, + metadata={"help": "Whether to shuffle the training dataset."}, + ) + pad_to_multiple_of: int | None = field( + default=None, + metadata={"help": "If set, the prompts ids and completions ids will be padded to a multiple of this value."}, + ) + + # Parameters that control generation + generation_batch_size: int | None = field( + default=None, + metadata={ + "help": "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`." + }, + ) + steps_per_generation: int | None = field( + default=None, + metadata={"help": "Number of steps per generation. If `None`, it defaults to `gradient_accumulation_steps`."}, + ) + temperature: float = field( + default=1.0, + metadata={"help": "Temperature for sampling. The higher the temperature, the more random the completions."}, + ) + top_p: float = field( + default=1.0, + metadata={ + "help": "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 = field( + default=0, + metadata={ + "help": "Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, " + "top-k-filtering is disabled and all tokens are considered." + }, + ) + min_p: float | None = field( + default=None, + metadata={ + "help": "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." + }, + ) + generation_kwargs: dict | None = field( + default=None, + metadata={ + "help": "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 `suppress_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." + }, + ) + chat_template_kwargs: dict | None = field( + default=None, + metadata={ + "help": "Additional keyword arguments to pass to the `apply_chat_template` function when generating " + "completions." + }, + ) + repetition_penalty: float = field( + default=1.0, + metadata={ + "help": "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." + }, + ) + cache_implementation: str | None = field( + default=None, + metadata={"help": "Implementation of the cache method for faster generation when use_vllm is set to False."}, + ) + + # Parameters that control generation acceleration powered by vLLM + use_vllm: bool = field( + default=False, + metadata={ + "help": "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 = field( + default="colocate", + metadata={ + "help": "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_model_impl: str = field( + default="vllm", + metadata={ + "help": "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." + }, + ) + vllm_enable_sleep_mode: bool = field( + default=False, + metadata={ + "help": "Enable vLLM sleep mode to offload weights/cache during the optimizer step. Keeps GPU memory " + "usage low, but waking the engine adds host–device transfer latency." + }, + ) + vllm_structured_outputs_regex: str | None = field( + default=None, + metadata={"help": "Regex for vLLM structured outputs. If `None` (default), structured outputs is disabled."}, + ) + + # Parameters that control the vLLM server (only used when `vllm_mode` is `"server"`) + vllm_server_base_url: str | None = field( + default=None, + metadata={ + "help": "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 = field( + default="0.0.0.0", + metadata={"help": "Host of the vLLM server to connect to. Ignored if vllm_server_base_url is provided."}, + ) + vllm_server_port: int = field( + default=8000, + metadata={"help": "Port of the vLLM server to connect to. Ignored if vllm_server_base_url is provided."}, + ) + vllm_server_timeout: float = field( + default=240.0, + metadata={ + "help": "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." + }, + ) + vllm_group_port: int = field( + default=51216, + metadata={ + "help": "Port number for the weight update group. This is used to communicate with the vLLM server. " + "Unless the port is occupied, there is no need to change it.", + }, + ) + + # Parameters that control colocated vLLM execution (only used when `vllm_mode` is `"colocate"`) + vllm_gpu_memory_utilization: float = field( + default=0.3, + metadata={ + "help": "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_max_model_length: int | None = field( + default=None, + metadata={ + "help": "Context window for vLLM. Set it to at least the maximum prompt length in the dataset plus " + "`max_completion_length`; if omitted, it is inferred from the model config." + }, + ) + vllm_tensor_parallel_size: int = field( + default=1, + metadata={ + "help": "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." + }, + ) + + # Parameters that control the training + beta: float = field( + default=0.05, + metadata={ + "help": "KL coefficient. If `0.0`, the reference model is not loaded, reducing memory usage and improving " + "training speed." + }, + ) + num_iterations: int = field( + default=1, + metadata={"help": "Number of iterations per batch (denoted as μ in the algorithm)."}, + ) + epsilon: float = field( + default=0.2, + metadata={"help": "Epsilon value for clipping."}, + ) + epsilon_high: float | None = field( + default=None, + metadata={ + "help": "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 recommends `0.28`." + }, + ) + reward_weights: list[float] | None = field( + default=None, + metadata={ + "help": "Weights for each reward function. Must match the number of reward functions. If `None`, all " + "rewards are weighted equally with weight `1.0`." + }, + ) + normalize_advantages: bool = field( + default=False, + metadata={ + "help": "Whether to normalize advantages. Normalization is done per generation batch to have mean `0.0` " + "and standard deviation of `1.0`." + }, + ) + reward_clip_range: tuple[float, float] | None = field( + default=None, + metadata={"help": "Clip range for rewards as (min, max). If None, no clipping is applied."}, + ) + mask_truncated_completions: bool = field( + default=False, + metadata={ + "help": "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 paper, this is " + "a good practice for training stability." + }, + ) + sync_ref_model: bool = field( + default=False, + metadata={ + "help": "Whether to synchronize the reference model with the active model every `ref_model_sync_steps` " + "steps, using the `ref_model_mixup_alpha` parameter." + }, + ) + ref_model_mixup_alpha: float = field( + default=0.6, + metadata={ + "help": "α parameter from the TR-DPO 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 = field( + default=512, + metadata={ + "help": "τ parameter from the TR-DPO 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`." + }, + ) + + # Parameters that control the logging + log_completions: bool = field( + default=False, + metadata={ + "help": "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 | None = field( + default=None, + metadata={"help": "Number of completions to print with `rich`. If `None`, all completions are logged."}, + ) + log_unique_prompts: bool = field( + default=False, + metadata={ + "help": "Whether to log unique prompts. If `True`, only unique prompts are logged. If `False`, all " + "prompts are logged." + }, + ) + + # Deprecated parameters + use_transformers_paged: bool = field( + default=False, + metadata={ + "help": "Deprecated. It will be replaced by `transformers` continuous batching support in an upcoming " + "release." + }, + ) + + def __post_init__(self): + super().__post_init__() + + if self.use_transformers_paged: + warnings.warn( + "`use_transformers_paged` is deprecated and will be removed in v2.0.0. It will be replaced by " + "`transformers` continuous batching support in an upcoming release.", + FutureWarning, + stacklevel=3, + ) + + if self.parallelism_config is not None and ( + self.parallelism_config.cp_enabled or self.parallelism_config.sp_enabled + ): + raise ValueError( + "RLOOTrainer does not support sequence-dim parallelism (`parallelism_config.cp_size > 1` or " + "`parallelism_config.sp_size > 1`) yet. RLOO builds model inputs after generation inside the trainer, " + "so Transformers' context-parallel / Ulysses sequence-parallel input sharding cannot be applied to the " + "raw generation batch. Set both `cp_size=1` and `sp_size=1`, or disable `parallelism_config`." + ) + + num_processes = self.world_size + # The current default effective batch size + if self.generation_batch_size is None and self.steps_per_generation is None: + self.steps_per_generation = self.gradient_accumulation_steps + self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation + elif self.generation_batch_size is not None and self.steps_per_generation is None: + # Just ensure the value is divisible by the global batch size + if self.generation_batch_size % (self.per_device_train_batch_size * num_processes) != 0: + raise ValueError( + f"generation_batch_size ({self.generation_batch_size}) must be divisible by the global batch size " + f"({self.per_device_train_batch_size * num_processes})." + ) + self.steps_per_generation = self.generation_batch_size // ( + self.per_device_train_batch_size * num_processes + ) + elif self.generation_batch_size is None and self.steps_per_generation is not None: + self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation + else: + raise ValueError( + "'generation_batch_size' and 'steps_per_generation' can not be both configured at the same time" + ) + + if self.do_eval and self.eval_strategy != "no": + # Determine the number of generations to use for evaluation + num_generations = self.num_generations_eval or self.num_generations + + # Just ensure the value is divisible by the global batch size + if (self.per_device_eval_batch_size * num_processes) % num_generations != 0: + raise ValueError( + f"The global eval batch size ({self.per_device_eval_batch_size} * {num_processes}) must be " + f"divisible by the number of generations used for evaluation ({num_generations})." + ) + + # The generation batch must contain full prompt groups (no partials), so it must be divisible by + # num_generations. + if self.generation_batch_size % self.num_generations != 0: + raise ValueError( + f"generation_batch_size ({self.generation_batch_size}) must be divisible by num_generations " + f"({self.num_generations})." + ) + + if self.num_generations < 2: + raise ValueError( + "RLOO requires at least 2 generations per prompt to calculate the advantages. You provided " + f"{self.num_generations}, which is less than the minimum required." + ) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/rloo_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/rloo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..98c6d5c803c00322fcd4e9462e6ba6143a73e737 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/rloo_trainer.py @@ -0,0 +1,1546 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import asyncio +import atexit +import copy +import inspect +import math +import textwrap +import time +from collections import defaultdict, deque +from collections.abc import Callable +from pathlib import Path +from typing import Any + +import numpy as np +import pandas as pd +import torch +import torch.utils.data +import transformers +from accelerate.logging import get_logger +from accelerate.utils import gather, gather_object, is_peft_model, set_seed +from datasets import Dataset, IterableDataset +from packaging.version import Version +from torch import nn +from torch.utils.data import Sampler +from transformers import ( + AutoModelForSequenceClassification, + AutoProcessor, + AutoTokenizer, + GenerationConfig, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, + is_trackio_available, + is_wandb_available, +) +from transformers.utils import is_peft_available, is_rich_available + +from ..data_utils import apply_chat_template, is_conversational, prepare_multimodal_messages +from ..distributed import DistributedBackend +from ..extras.profiling import profiling_context, profiling_decorator +from ..generation.vllm_generation import VLLMGeneration +from ..models import prepare_deepspeed, prepare_fsdp, unwrap_model_for_generation +from ..models.utils import disable_gradient_checkpointing +from .base_trainer import _BaseTrainer +from .callbacks import SyncRefModelCallback +from .rloo_config import RLOOConfig +from .utils import ( + RepeatSampler, + create_model_from_path, + disable_dropout_in_model, + entropy_from_logits, + get_config_model_id, + identity, + nanmax, + nanmin, + nanstd, + pad, + print_prompt_completions_sample, + selective_log_softmax, + shuffle_sequence_dict, + shutdown_event_loop_in_daemon, + split_pixel_values_by_grid, + split_tensor_dict, + start_event_loop_in_daemon, + unsplit_pixel_values_by_grid, + use_adapter, +) + + +if is_peft_available(): + from peft import PeftConfig, PeftModel, get_peft_model + + +if is_wandb_available(): + import wandb + +if is_trackio_available(): + import trackio + + +logger = get_logger(__name__) + +# A reward function can be a string, interpreted as a model ID and loaded as a pretrained model, a pretrained model, or +# a callable that returns a list of floats (the rewards). The callable receives prompts, completions, and additional +# arguments from the trainer (refer to the trainer's source for details). To ensure forward compatibility, it should +# accept **kwargs. +RewardFunc = str | PreTrainedModel | Callable[..., list[float | None]] + + +class RLOOTrainer(_BaseTrainer): + """ + Trainer for the Reinforce Leave One Out (RLOO) method. This algorithm was initially proposed in the paper [Back to + Basics: Revisiting REINFORCE Style Optimization for Learning from Human Feedback in + LLMs](https://huggingface.co/papers/2402.14740). + + Example: + + ```python + from trl import RLOOTrainer + from trl.rewards import accuracy_reward + from datasets import load_dataset + + dataset = load_dataset("trl-lib/DeepMath-103K", split="train") + + trainer = RLOOTrainer( + model="Qwen/Qwen2.5-0.5B-Instruct", + reward_funcs=accuracy_reward, + train_dataset=dataset, + ) + trainer.train() + ``` + + Args: + model (`str` or [`~transformers.PreTrainedModel`] or [`~peft.PeftModel`]): + Model to be trained. Can be either: + + - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a + path to a *directory* containing model weights saved using + [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded + using `.from_pretrained` (where `` is derived from the model + config) with the keyword arguments in `args.model_init_kwargs`. + - A [`~transformers.PreTrainedModel`] object. Only causal language models are supported. + - A [`~peft.PeftModel`] object. Only causal language models are supported. + reward_funcs (`RewardFunc | list[RewardFunc]`): + Reward functions to be used for computing the rewards. To compute the rewards, we call all the reward + functions with the prompts and completions and sum the rewards. Can be either: + + - A single reward function, such as: + - A string: The *model ID* of a pretrained model hosted inside a model repo on huggingface.co, or a + path to a *directory* containing model weights saved using + [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded + using [`~transformers.AutoModelForSequenceClassification.from_pretrained`] with `num_labels=1` and the + keyword arguments in `args.model_init_kwargs`. + - A [`~transformers.PreTrainedModel`] object: Only sequence classification models are supported. + - A custom reward function: The function is provided with the prompts and the generated completions, + plus any additional columns in the dataset. It should return a list of rewards. Custom reward + functions can be either synchronous or asynchronous and can also return `None` when the reward is + not applicable to those samples. This is useful for multi-task training where different reward + functions apply to different types of samples. When a reward function returns `None` for a sample, + that reward function is excluded from the reward calculation for that sample. For more details, see + [Using a custom reward + function](#using-a-custom-reward-function). + + The trainer's state is also passed to the reward function. The trainer's state is an instance of + [`~transformers.TrainerState`] and can be accessed by accessing the `trainer_state` argument to the + reward function's signature. + - A list of reward functions, where each item can independently be any of the above types. Mixing different + types within the list (e.g., a string model ID and a custom reward function) is allowed. + args ([`RLOOConfig`], *optional*): + Configuration for this trainer. If `None`, a default configuration is used. + train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]): + Dataset to use for training. It must include a column `"prompt"`. Any additional columns in the dataset is + ignored. The format of the samples can be either: + + - [Standard](dataset_formats#standard): Each sample contains plain text. + - [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role + and content). + eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Dataset | IterableDataset]`): + Dataset to use for evaluation. It must meet the same requirements as `train_dataset`. + processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.ProcessorMixin`], *optional*): + Processing class used to process the data. The padding side must be set to "left". If `None`, the + processing class is loaded from the model's name with [`~transformers.AutoProcessor.from_pretrained`]. A + padding token, `tokenizer.pad_token`, must be set. If the processing class has not set a padding token, + `tokenizer.eos_token` will be used as the default. + reward_processing_classes ([`~transformers.PreTrainedTokenizerBase`] or `list[PreTrainedTokenizerBase]`, *optional*): + Processing classes corresponding to the reward functions specified in `reward_funcs`. Can be either: + + - A single processing class: Used when `reward_funcs` contains only one reward function. + - A list of processing classes: Must match the order and length of the reward functions in `reward_funcs`. + If set to `None`, or if an element of the list corresponding to a [`~transformers.PreTrainedModel`] is + `None`, the tokenizer for the model is automatically loaded using + [`~transformers.AutoTokenizer.from_pretrained`]. For elements in `reward_funcs` that are custom reward + functions (not [`~transformers.PreTrainedModel`]), the corresponding entries in `reward_processing_classes` + are ignored. + callbacks (list of [`~transformers.TrainerCallback`], *optional*): + List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed + in [here](https://huggingface.co/docs/transformers/main_classes/callback). + + If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`] + method. + optimizers (`tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None]`, *optional*, defaults to `(None, None)`): + A tuple containing the optimizer and the scheduler to use. Will default to an instance of `AdamW` on your + model and a scheduler given by [`~transformers.get_linear_schedule_with_warmup`] controlled by `args`. + peft_config ([`~peft.PeftConfig`], *optional*): + PEFT configuration used to wrap the model. If `None`, the model is not wrapped. + """ + + _tag_names = ["trl", "rloo"] + _name = "RLOO" + _paper = { + "title": "Back to Basics: Revisiting REINFORCE-Style Optimization for Learning from Human Feedback in LLMs", + "id": "2402.14740", + # docstyle-ignore + "citation": textwrap.dedent("""\ + @inproceedings{ahmadian2024back, + title = {{Back to Basics: Revisiting REINFORCE-Style Optimization for Learning from Human Feedback in LLMs}}, + author = {Arash Ahmadian and Chris Cremer and Matthias Gall{\'{e}} and Marzieh Fadaee and Julia Kreutzer and Olivier Pietquin and Ahmet {\"{U}}st{\"{u}}n and Sara Hooker}, + year = 2024, + booktitle = {Proceedings of the 62nd Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), {ACL} 2024, Bangkok, Thailand, August 11-16, 2024}, + pages = {12248--12267}, + publisher = {Association for Computational Linguistics}, + editor = {Lun{-}Wei Ku and Andre Martins and Vivek Srikumar}, + }"""), + } + + def __init__( + self, + model: "str | PreTrainedModel | PeftModel", + reward_funcs: RewardFunc | list[RewardFunc], + args: RLOOConfig | None = None, + train_dataset: Dataset | IterableDataset | None = None, + eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None, + processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None, + reward_processing_classes: PreTrainedTokenizerBase | list[PreTrainedTokenizerBase] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None), + peft_config: "PeftConfig | None" = None, + ): + # Args + if args is None: + model_name = model if isinstance(model, str) else get_config_model_id(model.config) + model_name = model_name.split("/")[-1] + args = RLOOConfig(f"{model_name}-RLOO") + + # Model + if isinstance(model, str): + model_init_kwargs = args.model_init_kwargs or {} + # Distributed training requires device_map=None ("auto" fails) + if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + model_init_kwargs["device_map"] = None + model = create_model_from_path(model, **model_init_kwargs) + else: + if args.model_init_kwargs is not None: + logger.warning( + "You passed `model_init_kwargs` to the `RLOOConfig`, but your model is already instantiated. " + "The `model_init_kwargs` will be ignored." + ) + + # Some models (SmolVLM/Idefics3) don't support `logits_to_keep` argument and error out if we pass it + # Inspect the forward method before we wrap the model with PEFT + self.model_kwarg_keys = ( + inspect.signature(model.forward).parameters.keys() + if not hasattr(model, "get_base_model") + else inspect.signature(model.get_base_model().forward).parameters.keys() + ) + + # Processing class + if processing_class is None: + processing_class = AutoProcessor.from_pretrained( + get_config_model_id(model.config), truncation_side="left", padding_side="left" + ) + + # Handle pad token for processors or tokenizers + if isinstance(processing_class, ProcessorMixin): + self._tokenizer = processing_class.tokenizer + elif isinstance(processing_class, PreTrainedTokenizerBase): + self._tokenizer = processing_class + else: + raise TypeError("The `processing_class` must be either a `PreTrainedTokenizerBase` or a `ProcessorMixin`") + + if self._tokenizer.pad_token is None: + self._tokenizer.pad_token = self._tokenizer.eos_token + + # PEFT + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + if is_peft_model(model): + raise ValueError( + "You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first merge " + "and unload the existing adapter, save the resulting base model, and then pass that base model along " + "with the new `peft_config` to the trainer." + ) + # Create PEFT model + model = get_peft_model(model, peft_config) + + elif is_peft_model(model): + # If the model is a PEFT model with a pretrained adapter, we need to create a "ref" adapter that is a copy + # of the "default" adapter, so that we can use it as the reference model during the training. + model.add_adapter("ref", model.peft_config["default"]) + for name, param in model.named_parameters(): + if ".default." in name: + ref_name = name.replace(".default.", ".ref.") + ref_param = model.get_parameter(ref_name) + ref_param.data.copy_(param.data) + + # When using gradient checkpointing with PEFT, we need to enable input gradients. transformers.Trainer normally + # handles this, but a bug currently prevents it; see https://github.com/huggingface/transformers/issues/42489 + if is_peft_model(model) and args.gradient_checkpointing: + model.enable_input_require_grads() + + # When using QLoRA, the PEFT adapter weights are converted to bf16 to follow the recommendations from the + # original paper (see https://huggingface.co/papers/2305.14314, paragraph 3). Normally, this can be done by + # passing `autocast_adapter_dtype=False` to `get_peft_model`, but this option is not yet supported for + # quantized models. See: https://github.com/huggingface/peft/issues/2889 + # Non-quantized models do not have the `is_loaded_in_{8,4}bit` attributes, whereas quantized models do + if getattr(model, "is_loaded_in_4bit", False) or getattr(model, "is_loaded_in_8bit", False): + for param in model.parameters(): + if param.requires_grad: + param.data = param.data.to(torch.bfloat16) + + # Reward functions + if not isinstance(reward_funcs, list): + reward_funcs = [reward_funcs] + self.reward_func_names = [] + for i, reward_func in enumerate(reward_funcs): + if isinstance(reward_func, str): + model_init_kwargs = args.model_init_kwargs or {} + # Distributed training requires device_map=None ("auto" fails) + if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + model_init_kwargs["device_map"] = None + reward_funcs[i] = AutoModelForSequenceClassification.from_pretrained( + reward_func, num_labels=1, **model_init_kwargs + ) + if isinstance(reward_funcs[i], nn.Module): # Use Module over PretrainedModel for compat w/ compiled models + self.reward_func_names.append(get_config_model_id(reward_funcs[i].config).split("/")[-1]) + else: + self.reward_func_names.append(reward_funcs[i].__name__) + self.reward_funcs = reward_funcs + + self._has_async_funcs = any(inspect.iscoroutinefunction(func) for func in self.reward_funcs) + if self._has_async_funcs: + self.async_loop_thread, self.async_loop, self.async_loop_ready_event = start_event_loop_in_daemon( + name="RLOOTrainer-AsyncRewardLoop" + ) + # wait until the event loop is running in the daemon thread + self.async_loop_ready_event.wait() + atexit.register(shutdown_event_loop_in_daemon, self.async_loop_thread, self.async_loop) + + # Reward weights + if args.reward_weights is not None: + if len(args.reward_weights) != len(reward_funcs): + raise ValueError( + f"Number of reward weights ({len(args.reward_weights)}) must match number of reward " + f"functions ({len(reward_funcs)})" + ) + self.reward_weights = torch.tensor(args.reward_weights, dtype=torch.float32) + else: + self.reward_weights = torch.ones(len(reward_funcs), dtype=torch.float32) + + # Reward processing class + if reward_processing_classes is None: + reward_processing_classes = [None] * len(reward_funcs) + elif not isinstance(reward_processing_classes, list): + reward_processing_classes = [reward_processing_classes] + if len(reward_processing_classes) != len(reward_funcs): + raise ValueError( + f"The number of reward processing classes ({len(reward_processing_classes)}) must match the number of " + f"reward functions ({len(reward_funcs)})." + ) + + for i, (reward_processing_class, reward_func) in enumerate( + zip(reward_processing_classes, reward_funcs, strict=True) + ): + if isinstance(reward_func, PreTrainedModel): + if reward_processing_class is None: + reward_processing_class = AutoTokenizer.from_pretrained(get_config_model_id(reward_func.config)) + if reward_processing_class.pad_token_id is None: + reward_processing_class.pad_token = reward_processing_class.eos_token + # The reward model computes the reward for the latest non-padded token in the input sequence. + # So it's important to set the pad token ID to the padding token ID of the processing class. + reward_func.config.pad_token_id = reward_processing_class.pad_token_id + reward_processing_classes[i] = reward_processing_class + + self.reward_processing_classes = reward_processing_classes + + # Training arguments + self.max_completion_length = args.max_completion_length + self.num_generations = args.num_generations + self.num_generations_eval = args.num_generations_eval or self.num_generations + self.chat_template_kwargs = args.chat_template_kwargs or {} + self.temperature = args.temperature + self.top_p = args.top_p + self.top_k = args.top_k + self.min_p = args.min_p + self.repetition_penalty = args.repetition_penalty + self.use_transformers_paged = args.use_transformers_paged + self.pad_to_multiple_of = args.pad_to_multiple_of + self.use_vllm = args.use_vllm + self.vllm_mode = args.vllm_mode + self.vllm_gpu_memory_utilization = args.vllm_gpu_memory_utilization # only applies to colocation mode + self.vllm_tensor_parallel_size = args.vllm_tensor_parallel_size # only applies to colocation mode + self.normalize_advantages = args.normalize_advantages + self.mask_truncated_completions = args.mask_truncated_completions + self.reward_clip_range = args.reward_clip_range + + # Datasets + self.shuffle_dataset = args.shuffle_dataset + + if train_dataset is None: + raise ValueError("`train_dataset` is required") + elif ( + isinstance(train_dataset, IterableDataset) + or isinstance(eval_dataset, IterableDataset) + or ( + isinstance(eval_dataset, dict) and any(isinstance(ds, IterableDataset) for ds in eval_dataset.values()) + ) + ): + # See https://github.com/huggingface/trl/issues/3213 + raise NotImplementedError( + "Iterable datasets are not yet supported in RLOOTrainer. Please use a standard dataset instead." + ) + + # Multi-step + self.num_iterations = args.num_iterations + self.epsilon_low = args.epsilon + self.epsilon_high = args.epsilon_high if args.epsilon_high is not None else args.epsilon + # Tracks the number of iterations (forward + backward passes), including those within a grad accum cycle + self._step = 0 + # Buffer the batch to reuse generated outputs across multiple updates. For more details, see + # `_get_train_sampler` and `_prepare_inputs`. + self._buffered_inputs = None + + # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was + # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream + # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we + # default to the recommended non-reentrant behavior here, while preserving any user-provided value. + if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"): + args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {} + args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False) + + super().__init__( + model=model, + args=args, + data_collator=identity, # No data collation is needed in RLOO + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + callbacks=callbacks, + optimizers=optimizers, + ) + + # Reference model + self.beta = args.beta + if self.beta == 0.0: + # If beta is 0.0, the reference model is not needed + self.ref_model = None + elif is_peft_model(model): + # If PEFT is used, the reference model is not needed since the adapter can be disabled + # to revert to the initial model. + self.ref_model = None + else: + # For deepspeed, fsdp or non-distributed models, create a reference model from scratch + model_init_kwargs = args.model_init_kwargs or {} + # Distributed training requires device_map=None ("auto" fails) + if self.args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + model_init_kwargs["device_map"] = None + self.ref_model = create_model_from_path(get_config_model_id(self.model.config), **model_init_kwargs) + + # Disable dropout in the models + if args.disable_dropout: + disable_dropout_in_model(model) + if self.ref_model is not None: + disable_dropout_in_model(self.ref_model) + + # Initialize the metrics + self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)} + self._total_train_tokens = 0 + self._current_train_step_time = 0.0 + self.log_completions = args.log_completions + self.log_unique_prompts = args.log_unique_prompts + self.num_completions_to_print = args.num_completions_to_print + # Keep logs sized to the generation batch to record only outputs from the latest model update. + self._logs = { + "images": deque(maxlen=args.generation_batch_size), + "prompt": deque(maxlen=args.generation_batch_size), + "completion": deque(maxlen=args.generation_batch_size), + "rewards": defaultdict(lambda: deque(maxlen=args.generation_batch_size)), + "advantages": deque(maxlen=args.generation_batch_size), + "extra": defaultdict(lambda: deque(maxlen=args.generation_batch_size)), + } + # Buffers for user-logged data from reward functions, flushed after gathering + self._pending_extra_logs = defaultdict(list) + self._pending_metrics = defaultdict(list) + + # Ensure each process receives a unique seed to prevent duplicate completions when generating with + # transformers if num_generations exceeds per_device_train_batch_size. We could skip it if we use vLLM, but + # it's safer to set it in all cases. + set_seed(args.seed, device_specific=True) + + if self.use_vllm: + # Initialize vLLM generation backend + self.vllm_generation = VLLMGeneration( + model=self.model, + accelerator=self.accelerator, + processing_class=self.processing_class, + # vLLM configuration + mode=args.vllm_mode, + structured_outputs_regex=args.vllm_structured_outputs_regex, + # Server mode configuration + server_base_url=args.vllm_server_base_url, + server_host=args.vllm_server_host, + server_port=args.vllm_server_port, + group_port=args.vllm_group_port, + server_timeout=args.vllm_server_timeout, + # Colocate mode configuration + tensor_parallel_size=args.vllm_tensor_parallel_size, + gpu_memory_utilization=args.vllm_gpu_memory_utilization, + max_model_length=args.vllm_max_model_length, + max_num_seqs=args.per_device_train_batch_size + * args.vllm_tensor_parallel_size + * args.steps_per_generation, + enable_sleep_mode=args.vllm_enable_sleep_mode, + model_impl=args.vllm_model_impl, + # Generation configuration + repetition_penalty=self.repetition_penalty, + temperature=self.temperature, + top_p=self.top_p, + top_k=self.top_k, + min_p=self.min_p, + max_completion_length=self.max_completion_length, + logprobs=None, # we don't need logprobs from vLLM in RLOO + generation_kwargs=args.generation_kwargs, + ) + self._last_loaded_step = -1 # tag to avoid useless loading during grad accumulation + else: + generation_kwargs = { + "max_new_tokens": self.max_completion_length, + "do_sample": True, + "pad_token_id": self._tokenizer.pad_token_id, + "bos_token_id": self._tokenizer.bos_token_id, + "eos_token_id": self._tokenizer.eos_token_id, + "temperature": self.temperature, + "top_p": self.top_p, + "top_k": self.top_k, + "min_p": self.min_p, + "repetition_penalty": self.repetition_penalty, + "cache_implementation": args.cache_implementation, + } + if args.generation_kwargs is not None: + generation_kwargs.update(args.generation_kwargs) + self.generation_config = GenerationConfig(**generation_kwargs, disable_compile=True) + # Keep training-specific generation kwargs to overwrite model's original generation config + self.generation_kwargs = generation_kwargs + + # Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the + # model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set + # self.model_accepts_loss_kwargs to False to enable scaling. + self.model_accepts_loss_kwargs = False + self._dist = DistributedBackend(self.accelerator) + + # Add tags to the model + self.model.add_model_tags(self._tag_names) + + if self.ref_model is not None: + if self.is_deepspeed_enabled: + self.ref_model = prepare_deepspeed(self.ref_model, self.accelerator) + elif self.is_fsdp_enabled: + self.ref_model = prepare_fsdp(self.ref_model, self.accelerator) + else: + self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True) + + if args.sync_ref_model: + if self.beta == 0.0: + raise ValueError( + "You passed `sync_ref_model=True` while `beta=0.0`, which means the reference model is not used " + "during training. Consequently, RLOOTrainer does not create a `ref_model` instance, and there is " + "nothing to synchronize. Please set `sync_ref_model=False`, or set `beta` to a non-zero value." + ) + if is_peft_model(model): + raise NotImplementedError( + "You passed `sync_ref_model=True` while using a PEFT model, which is currently not supported. " + "With PEFT, RLOOTrainer does not keep a separate reference model in memory; instead, it recovers " + "reference behavior by temporarily disabling the adapter. As a result, there is no standalone " + "`ref_model` instance to synchronize. Use `sync_ref_model=False`, or opt for full fine-tuning if " + "you need a synced reference model. If you need `sync_ref_model` to work with PEFT, please open a " + "feature request at https://github.com/huggingface/trl/issues." + ) + self.add_callback(SyncRefModelCallback(ref_model=self.ref_model, accelerator=self.accelerator)) + + for i, reward_func in enumerate(self.reward_funcs): + if isinstance(reward_func, PreTrainedModel): + if self.is_deepspeed_enabled: + self.reward_funcs[i] = prepare_deepspeed(reward_func, self.accelerator) + else: + # set device placement to True to make `prepare_model` move `reward_func` to device when using fsdp + self.reward_funcs[i] = self.accelerator.prepare_model( + reward_func, evaluation_mode=True, device_placement=True + ) + + def _set_signature_columns_if_needed(self): + # If `self.args.remove_unused_columns` is True, non-signature columns are removed. + # By default, this method sets `self._signature_columns` to the model's expected inputs (usually, "input_ids" + # and "attention_mask"). In RLOOTrainer, we preprocess data, so using the model's signature columns doesn't + # work. Instead, we set them to the columns expected by the `training_step` method, hence the override. + if self._signature_columns is None: + self._signature_columns = ["prompt", "image", "images"] + + # This method overrides `Trainer.get_train_dataloader` to support our custom batching strategy. + # Instead of returning a standard per-step batch (i.e., `per_device_batch_size), our dataloader loads an + # *generation* batch (i.e., `per_device_batch_size × steps_per_generation`). This allows us to generate completions + # once every steps_per_generation step—rather than once per accumulation step—which is significantly more + # efficient. The only change from the original implementation is multiplying the batch size by + # `steps_per_generation`. Thus, `_prepare_inputs` is called with this *generation* batch, and it handles the + # splitting internally. + # Maintenance note: This method is a copy-paste of the original `Trainer.get_train_dataloader` with only one line + # modification. + def get_train_dataloader(self): + return self._get_dataloader( + dataset=self.train_dataset, + description="Training", + batch_size=self._train_batch_size * self.args.steps_per_generation, # < this is the change + sampler_fn=self._get_train_sampler, + is_training=True, + ) + + def _get_train_sampler(self, dataset: Dataset | None = None) -> Sampler: + # Returns a sampler that + # 1. ensures each prompt is repeated across multiple processes. This guarantees that identical prompts are + # distributed to different GPUs, allowing rewards to be computed and normalized correctly within each prompt + # group. Using the same seed across processes ensures consistent prompt assignment, preventing discrepancies + # in group formation. + # 2. repeats the batch multiple times to allow reusing generations across multiple updates. Refer to + # _prepare_inputs to see how the generations are stored and reused. + + # In the following figure, the values are the prompt indices. The first row shows the first sampled batch, the + # second row shows the second sampled batch, and so on. + # + # | GPU 0 | GPU 1 | + # + # global_step step <-───> num_generations=2 + # <-───────> per_device_train_batch_size=3 + # grad_accum ▲ ▲ 0 0 0 0 1 1 2 2 <- Generate for the first `steps_per_generation` (prompts 0 to 11); store the completions; use the first slice to compute the loss + # =2 ▼ | 0 1 3 3 4 4 5 5 <- Take the stored generations and use the second slice to compute the loss + # | + # | 1 2 6 6 7 7 8 8 <- Take the stored generations and use the third slice to compute the loss + # steps_per_gen=4 ▼ 1 3 9 9 10 10 11 11 <- Take the stored generations and use the fourth slice to compute the loss + # + # 2 4 12 12 13 13 14 14 <- Generate for the second `steps_per_generation` (prompts 12 to 23); store the completions; use the first slice to compute the loss + # 2 5 15 15 16 16 17 17 <- Take the stored generations and use the second slice to compute the loss + # ... + if dataset is None: + dataset = self.train_dataset + return RepeatSampler( + data_source=dataset, + mini_repeat_count=self.num_generations, + batch_size=self.args.generation_batch_size // self.num_generations, + repeat_count=self.num_iterations * self.args.steps_per_generation, + shuffle=self.shuffle_dataset, + seed=self.args.seed, + ) + + def _get_eval_sampler(self, eval_dataset) -> Sampler: + # See _get_train_sampler for an explanation of the sampler. + return RepeatSampler( + data_source=eval_dataset, + mini_repeat_count=self.num_generations_eval, + seed=self.args.seed, + ) + + @profiling_decorator + def _get_per_token_logps_and_entropies( + self, + model, + input_ids, + attention_mask, + logits_to_keep, + batch_size=None, + compute_entropy=False, + pixel_values=None, + image_grid_thw=None, + num_images=None, + pixel_attention_mask=None, + image_sizes=None, + token_type_ids=None, + mm_token_type_ids=None, + image_position_ids=None, + ) -> tuple[torch.Tensor, torch.Tensor | None]: + """Compute log-probs and (optionally) entropies for each token.""" + batch_size = batch_size or input_ids.size(0) # Chunk inputs into smaller batches to reduce memory peak + all_logps = [] + all_entropies = [] + for start in range(0, input_ids.size(0), batch_size): + input_ids_batch = input_ids[start : start + batch_size] + attention_mask_batch = attention_mask[start : start + batch_size] + + # Build model inputs + model_inputs = {"input_ids": input_ids_batch, "attention_mask": attention_mask_batch} + if image_grid_thw is not None and pixel_values is not None: + rows_per_image = image_grid_thw.prod(dim=-1) + rows_per_sample = torch.split(rows_per_image, num_images) + rows_per_sample = torch.stack([s.sum() for s in rows_per_sample]) + cum_rows = torch.cat([torch.tensor([0], device=rows_per_sample.device), rows_per_sample.cumsum(0)]) + row_start, row_end = cum_rows[start].item(), cum_rows[start + batch_size].item() + model_inputs["pixel_values"] = pixel_values[row_start:row_end] + cum_imgs = torch.tensor([0] + num_images).cumsum(0) + img_start, img_end = cum_imgs[start], cum_imgs[start + batch_size] + model_inputs["image_grid_thw"] = image_grid_thw[img_start:img_end] + elif image_position_ids is not None and pixel_values is not None: + cum_imgs = torch.tensor([0] + num_images).cumsum(0) + img_start, img_end = cum_imgs[start], cum_imgs[start + batch_size] + model_inputs["pixel_values"] = pixel_values[img_start:img_end] + model_inputs["image_position_ids"] = image_position_ids[img_start:img_end] + elif pixel_values is not None: + model_inputs["pixel_values"] = pixel_values[start : start + batch_size] + if pixel_attention_mask is not None: + model_inputs["pixel_attention_mask"] = pixel_attention_mask[start : start + batch_size] + if image_sizes is not None: + model_inputs["image_sizes"] = image_sizes[start : start + batch_size] + if token_type_ids is not None: + model_inputs["token_type_ids"] = token_type_ids[start : start + batch_size] + if mm_token_type_ids is not None: + model_inputs["mm_token_type_ids"] = mm_token_type_ids[start : start + batch_size] + + # Only add logits_to_keep if the model supports it + if "logits_to_keep" in self.model_kwarg_keys: + # We add 1 to `logits_to_keep` because the last logits of the sequence is later excluded + model_inputs["logits_to_keep"] = logits_to_keep + 1 + + model_inputs["use_cache"] = False # only used in generation; set False to suppress warnings + + logits = model(**model_inputs).logits + # Exclude the last value: it corresponds to the next token pred + logits = logits[:, :-1, :] # (B, L-1, H) + # Only keep the last logits_to_keep. For model that support logits_to_keep, this is a no-op. + logits = logits[:, -logits_to_keep:, :] # (B, logits_to_keep, H) + # Divide logits by sampling temperature. + # See https://huggingface.co/blog/the_n_implementation_details_of_rlhf_with_ppo#policy-training-implementation-details + logits.div_(self.temperature) + completion_ids = input_ids_batch[:, -logits_to_keep:] + logps = selective_log_softmax(logits, completion_ids) # compute logprobs + all_logps.append(logps) + + if compute_entropy: + with torch.no_grad(): + entropies = entropy_from_logits(logits) + all_entropies.append(entropies) + + logps = torch.cat(all_logps, dim=0) + entropies = torch.cat(all_entropies, dim=0) if compute_entropy else None + return logps, entropies + + def training_step(self, model, inputs, num_items_in_batch): + time_before = time.perf_counter() + output = super().training_step(model, inputs, num_items_in_batch) + self._step += 1 + time_after = time.perf_counter() + self._current_train_step_time += time_after - time_before + if self._step % self.current_gradient_accumulation_steps == 0: + self._metrics["train"]["step_time"].append(self._current_train_step_time) + self._current_train_step_time = 0.0 + return output + + @profiling_decorator + def _prepare_inputs(self, generation_batch: dict[str, torch.Tensor | Any]) -> dict[str, torch.Tensor | Any]: + # Prepares inputs for model training/evaluation by managing completion generation and batch handling. + # During training: + # - Receives the local generation batch (Per-GPU batch size × steps per generation) + # from the modified training dataloader instead of the standard local batch + # - Generates completions once for the entire generation batch and splits it into batches of size + # `per_device_train_batch_size` + # - Buffers these completions and returns the appropriate slice for the current accumulation step + # - Optimizes by regenerating completions only periodically (every steps_per_generation * num_iterations) + # During evaluation: + # - The input is treated as a standard local batch (no accumulation, no multiple iterations) + # - Completions are generated for each batch without buffering or reuse + # Returns a single local batch in both cases. + + mode = "train" if self.model.training else "eval" + if mode == "train": + generate_every = self.args.steps_per_generation * self.num_iterations + if self._step % generate_every == 0 or self._buffered_inputs is None: + # self._buffered_inputs=None can occur when resuming from a checkpoint + generation_batch = self._generate_and_score_completions(generation_batch) + generation_batch = split_pixel_values_by_grid(generation_batch) + generation_batch = shuffle_sequence_dict(generation_batch) + generation_batches = split_tensor_dict(generation_batch, self.args.steps_per_generation) + self._buffered_inputs = [unsplit_pixel_values_by_grid(batch) for batch in generation_batches] + inputs = self._buffered_inputs[self._step % self.args.steps_per_generation] + else: + # In evaluation, there is neither batch grouping for generation, nor multiple iterations, hence + # local generation batch == local eval batch + inputs = self._generate_and_score_completions(generation_batch) + return inputs + + def _log_completion_extra(self, column: str, values: list): + """ + Log extra columns to the completions table. Called from reward functions via the `log_extra` kwarg. + + Args: + column (`str`): + Name of the column to add. + values (`list`): + Values for the column, one per sample in the batch. + """ + self._pending_extra_logs[column].extend(values) + + def _log_metric(self, name: str, value: float): + """ + Log a scalar metric from a reward function. Called via the `log_metric` kwarg. Values are averaged over each + logging step and reported alongside built-in metrics like `kl` and `entropy`. + + Args: + name (`str`): + Name of the metric. + value (`float`): + Scalar value for this batch. + """ + self._pending_metrics[name].append(value) + + @profiling_decorator + def _calculate_rewards(self, inputs, prompts, completions, completion_ids_list): + device = self.accelerator.device + rewards_per_func = torch.zeros(len(prompts), len(self.reward_funcs), device=device) + + # Repeat all input columns (but "prompt", "completion", and "completion_ids") to match the num of generations + keys = [key for key in inputs[0] if key not in ["prompt", "completion", "completion_ids"]] + reward_kwargs = {key: [example[key] for example in inputs] for key in keys} + + # This allows for dynamic reward shaping based on training progress. + reward_kwargs["trainer_state"] = self.state + + # Allow reward functions to log extra columns to the completions table. + reward_kwargs["log_extra"] = self._log_completion_extra + + # Allow reward functions to log additional scalar metrics. + reward_kwargs["log_metric"] = self._log_metric + + async_funcs_info = [] # async custom functions for asyncio.gather + + for i, (reward_func, reward_processing_class, reward_func_name) in enumerate( + zip(self.reward_funcs, self.reward_processing_classes, self.reward_func_names, strict=True) + ): + if isinstance(reward_func, nn.Module): # Module (no PretrainedModel) for compat with compiled models + with profiling_context(self, reward_func_name): + if is_conversational(inputs[0]): + messages = [{"messages": p + c} for p, c in zip(prompts, completions, strict=True)] + texts = [ + apply_chat_template(x, reward_processing_class, **self.chat_template_kwargs)["text"] + for x in messages + ] + else: + texts = [p + c for p, c in zip(prompts, completions, strict=True)] + reward_inputs = reward_processing_class( + text=texts, return_tensors="pt", padding=True, padding_side="right", add_special_tokens=False + ) + reward_inputs = super()._prepare_inputs(reward_inputs) + with torch.inference_mode(): + rewards_per_func[:, i] = reward_func(**reward_inputs).logits[:, 0] # Shape (B*G,) + elif inspect.iscoroutinefunction(reward_func): # Separate async reward funcs to run them in parallel later + async_funcs_info.append((i, reward_func, reward_func_name)) + else: + # Run synchronous reward function + with profiling_context(self, reward_func_name): + output_reward_func = reward_func( + prompts=prompts, completions=completions, completion_ids=completion_ids_list, **reward_kwargs + ) + # Convert None values to NaN + output_reward_func = [reward if reward is not None else torch.nan for reward in output_reward_func] + rewards_per_func[:, i] = torch.tensor(output_reward_func, dtype=torch.float32, device=device) + + # Execute async custom functions in parallel using asyncio.gather + if async_funcs_info: + + async def _invoke_async(index, func, func_name): + with profiling_context(self, func_name): + output = await func( + prompts=prompts, completions=completions, completion_ids=completion_ids_list, **reward_kwargs + ) + output = [r if r is not None else torch.nan for r in output] + return index, output + + async def _run_async_funcs(): + coros = [_invoke_async(i, func, func_name) for (i, func, func_name) in async_funcs_info] + return await asyncio.gather(*coros) + + async_results = asyncio.run_coroutine_threadsafe(_run_async_funcs(), self.async_loop).result() + for idx, output_reward_func in async_results: + rewards_per_func[:, idx] = torch.tensor(output_reward_func, dtype=torch.float32, device=device) + + # If all reward functions return None for a given row, issue a detailed warning + if torch.isnan(rewards_per_func).all(dim=1).any(): + nan_row_idx = torch.isnan(rewards_per_func).all(dim=1).nonzero(as_tuple=True)[0][0] + row_reward_kwargs = { + key: value[nan_row_idx] + for key, value in reward_kwargs.items() + if key not in ("trainer_state", "log_extra", "log_metric") + } + row_reward_kwargs["prompt"] = prompts[nan_row_idx] + row_reward_kwargs["completion"] = completions[nan_row_idx] + logger.warning( + f"All reward functions returned None for the following kwargs:\n{row_reward_kwargs}\n" + "Please ensure that at least one reward function returns a valid reward." + ) + + # Gather the reward per function: this part is crucial, because the rewards are normalized per group and the + # completions may be distributed across processes + rewards_per_func = gather(rewards_per_func) + return rewards_per_func + + def _tokenize_prompts(self, prompts: list): + """Tokenize prompts and extract images/multimodal fields for generation.""" + if is_conversational({"prompt": prompts[0]}): + # Extract images from messages for VLM support + images = [] + has_images = False + for prompt in prompts: + prompt_images = [] + for message in prompt: + if isinstance(message["content"], list): + for part in message["content"]: + if part["type"] == "image": + prompt_images.append(part["image"]) + has_images = True + images.append(prompt_images if prompt_images else None) + images = images if has_images else None + + # Workaround for a bug in transformers 5.3.0 where some processors (e.g. Qwen2.5-VL) crash on + # batched unpadded input (transformers#44514). + # Fixed in transformers 5.4.0 (transformers#44563). + needs_padding_workaround = Version("5.3.0") <= Version(transformers.__version__) < Version("5.4.0") + tokenized = self.processing_class.apply_chat_template( + conversation=prompts, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + **({"padding": True} if needs_padding_workaround else {}), + **self.chat_template_kwargs, + ) + if needs_padding_workaround: + # Unpad input_ids: remove padding tokens using attention_mask to get per-sequence lists + prompt_ids = [ + [tok for tok, m in zip(ids, mask, strict=True) if m] + for ids, mask in zip(tokenized["input_ids"], tokenized["attention_mask"], strict=True) + ] + else: + prompt_ids = tokenized["input_ids"] + # For VLMs, the processor returns extra multimodal fields (pixel_values, image_grid_thw, etc.) + multimodal_fields = {k: v for k, v in tokenized.items() if k not in ("input_ids", "attention_mask")} + else: + prompt_ids = self.processing_class(text=prompts)["input_ids"] + images = None + multimodal_fields = {} + return prompt_ids, images, multimodal_fields + + def _generate_single_turn(self, prompt_ids, images, multimodal_fields): + device = self.accelerator.device + mode = "train" if self.model.training else "eval" + + # Generate completions using either vLLM or regular generation + if self.use_vllm: + # Sync weights if training step changed + if self.state.global_step != self._last_loaded_step: + with profiling_context(self, "sync_weights"): + self.vllm_generation.sync_weights() + self._last_loaded_step = self.state.global_step + + # Generate using vLLM (note: RLOO doesn't use logprobs from generation, so we ignore them) + num_generations = self.num_generations if mode == "train" else self.num_generations_eval + _, completion_ids, _, _ = self.vllm_generation.generate( + prompts=prompt_ids, + images=images, + num_generations=num_generations, + profiler=profiling_context(self, "vLLM.generate"), + ) + + elif self.use_transformers_paged: + with ( + profiling_context(self, "transformers.generate_batch"), + unwrap_model_for_generation( + self.model_wrapped, self.accelerator, gather_deepspeed3_params=self.args.ds3_gather_for_generation + ) as unwrapped_model, + torch.no_grad(), + self._dist.summon_full_params(self.model_wrapped, recurse=False), + ): + # Cast to the appropriate dtype based on training configuration + if self.args.bf16: + unwrapped_model.to(torch.bfloat16) + elif self.args.fp16: + unwrapped_model.to(torch.float16) + # Continuous batching API expects 'inputs' arg only + all_outputs = unwrapped_model.generate_batch( + prompt_ids, generation_config=self.generation_config, progress_bar=False + ) + unwrapped_model.train() # restore training mode, as generate_batch forces eval mode + completion_ids = [output.generated_tokens for output in all_outputs.values()] + + else: + # Regular generation path: left-pad token IDs into tensors + prompt_tensors = [torch.tensor(ids) for ids in prompt_ids] + padded_ids = pad(prompt_tensors, padding_value=self._tokenizer.pad_token_id, padding_side="left") + attention_mask = pad([torch.ones_like(t) for t in prompt_tensors], padding_value=0, padding_side="left") + generate_inputs = {"input_ids": padded_ids, "attention_mask": attention_mask} + # For VLMs, include multimodal fields as tensors (pixel_values, image_grid_thw, etc.) + for k, v in multimodal_fields.items(): + if isinstance(v, torch.Tensor): + generate_inputs[k] = v + elif isinstance(v, list) and v and isinstance(v[0], list): + # Per-token field (e.g., token_type_ids): left-pad like input_ids + generate_inputs[k] = pad([torch.tensor(x) for x in v], padding_value=0, padding_side="left") + else: + generate_inputs[k] = torch.tensor(np.array(v)) + generate_inputs = super()._prepare_inputs(generate_inputs) + + with ( + profiling_context(self, "transformers.generate"), + unwrap_model_for_generation( + self.model_wrapped, + self.accelerator, + gather_deepspeed3_params=self.args.ds3_gather_for_generation, + generation_kwargs=self.generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762 + ) as unwrapped_model, + torch.no_grad(), + self._dist.summon_full_params(self.model_wrapped, recurse=False), + ): + prompt_completion_ids = unwrapped_model.generate( + **generate_inputs, generation_config=self.generation_config + ) + # Compute prompt length and extract completion ids + prompt_length = generate_inputs["input_ids"].size(1) + completion_ids = prompt_completion_ids[:, prompt_length:] + + # Mask everything after the first EOS token + is_eos = completion_ids == self._tokenizer.eos_token_id + eos_idx = torch.full((is_eos.size(0),), is_eos.size(1), dtype=torch.long, device=device) + eos_idx[is_eos.any(dim=1)] = is_eos.int().argmax(dim=1)[is_eos.any(dim=1)] + sequence_indices = torch.arange(is_eos.size(1), device=device).expand(is_eos.size(0), -1) + completion_mask = (sequence_indices <= eos_idx.unsqueeze(1)).int() + completion_ids = [ + c[m].tolist() for c, m in zip(completion_ids.cpu(), completion_mask.bool().cpu(), strict=True) + ] + + return completion_ids + + def _generate(self, prompts: list): + device = self.accelerator.device + mode = "train" if self.model.training else "eval" + + # Copy the prompts to avoid modifying the original list + prompts = copy.deepcopy(prompts) + + prompt_ids, images, multimodal_fields = self._tokenize_prompts(prompts) + completion_ids = self._generate_single_turn(prompt_ids, images, multimodal_fields) + + # Decode completions. It's important to use `parse_response` when possible, because it handles tool calls. + if is_conversational({"prompt": prompts[0]}): + contents = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True) + completions = [[{"role": "assistant", "content": content}] for content in contents] + else: + completions = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True) + + # Get completion length per sequence, used for logging + prompt_lengths = torch.tensor([len(ids) for ids in prompt_ids], device=device) + completion_lengths = torch.tensor([len(ids) for ids in completion_ids], device=device) + agg_prompt_lengths = self.accelerator.gather(prompt_lengths) + agg_completion_lengths = self.accelerator.gather(completion_lengths) + total_prompt_tokens = agg_prompt_lengths.sum() + total_completion_tokens = agg_completion_lengths.sum() # = num_items_in_batch, required for the DAPO loss + + # Log the metrics + if mode == "train": + self.state.num_input_tokens_seen += (total_prompt_tokens + total_completion_tokens).item() + self._metrics[mode]["num_tokens"] = [self.state.num_input_tokens_seen] + + # Log completion lengths, mean, min, max + self._metrics[mode]["completions/mean_length"].append(agg_completion_lengths.float().mean().item()) + self._metrics[mode]["completions/min_length"].append(agg_completion_lengths.float().min().item()) + self._metrics[mode]["completions/max_length"].append(agg_completion_lengths.float().max().item()) + + # Identify sequences that terminated with EOS and log their lengths + eos_and_pad = [self._tokenizer.eos_token_id, self._tokenizer.pad_token_id] + is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids], device=device) + agg_is_truncated = self.accelerator.gather(is_truncated) + self._metrics[mode]["completions/clipped_ratio"].append(agg_is_truncated.float().mean().item()) + term_completion_lengths = agg_completion_lengths[~agg_is_truncated] + if len(term_completion_lengths) == 0: # edge case where no terminated sequences are found + term_completion_lengths = torch.zeros(1, device=device) + self._metrics[mode]["completions/mean_terminated_length"].append(term_completion_lengths.float().mean().item()) + self._metrics[mode]["completions/min_terminated_length"].append(term_completion_lengths.float().min().item()) + self._metrics[mode]["completions/max_terminated_length"].append(term_completion_lengths.float().max().item()) + + return prompt_ids, completion_ids, completions + + def _generate_and_score_completions( + self, inputs: list[dict[str, torch.Tensor | Any]] + ) -> dict[str, torch.Tensor | Any]: + device = self.accelerator.device + mode = "train" if self.model.training else "eval" + + prompts = [x["prompt"] for x in inputs] + + if "images" in inputs[0]: + images = [example.get("images") for example in inputs] + elif "image" in inputs[0]: + images = [[example.get("image")] if example.get("image") is not None else None for example in inputs] + else: + images = None + # Transformers requires at least one image in the batch, otherwise it throws an error + if images is not None and all(img_list == [] for img_list in images): + images = None + + # If the prompts are conversational and the inputs contain images, we need to convert the prompts from + # [{"role": "user", "content": "What color is the sky?"}] to + # [{"role": "user", "content": [{"type": "image", "image": }, {"type": "text", "text": "What color is the sky?"}]}] + if images is not None: + if not is_conversational(inputs[0]): + raise ValueError( + "Multimodal training requires conversational prompts. It looks like the dataset contains " + "non-conversational inputs, likely because a chat template was applied before passing the dataset " + "to the trainer. Please provide the raw conversational prompts and let the trainer apply the chat " + "template internally." + ) + prompts = [ + prepare_multimodal_messages(prompt, images=image_list) + for prompt, image_list in zip(prompts, images, strict=True) + ] + + prompt_ids_list, completion_ids_list, completions = self._generate(prompts) + + # Convert lists of token IDs to padded tensors + prompt_ids = [torch.tensor(ids) for ids in prompt_ids_list] + prompt_mask = [torch.ones_like(ids, dtype=torch.long) for ids in prompt_ids] + prompt_ids = pad( + prompt_ids, + padding_value=self._tokenizer.pad_token_id, + padding_side="left", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + prompt_mask = pad( + prompt_mask, padding_value=0, padding_side="left", pad_to_multiple_of=self.pad_to_multiple_of + ).to(device=device) + completion_ids = [torch.tensor(ids) for ids in completion_ids_list] + completion_mask = [torch.ones_like(ids, dtype=torch.long) for ids in completion_ids] + completion_ids = pad( + completion_ids, + padding_value=self._tokenizer.pad_token_id, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ).to(device=device) + completion_mask = pad( + completion_mask, padding_value=0, padding_side="right", pad_to_multiple_of=self.pad_to_multiple_of + ).to(device=device) + + # If mask_truncated_completions is enabled, zero out truncated completions in completion_mask + if self.mask_truncated_completions: + eos_and_pad = [self._tokenizer.eos_token_id, self._tokenizer.pad_token_id] + # Mask completion_mask for attention masking + is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids_list], device=device) + completion_mask = completion_mask * (~is_truncated).unsqueeze(1).int() + + # Concatenate prompt_mask with completion_mask for logit computation + prompt_completion_ids = torch.cat([prompt_ids, completion_ids], dim=1) # (B, P+C) + attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) # (B, P+C) + + logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens + batch_size = self.args.per_device_train_batch_size if mode == "train" else self.args.per_device_eval_batch_size + + num_images = [len(img_list) if img_list else 0 for img_list in images] if images is not None else None + + # Get forward_kwargs for models with multimodal inputs + if images is not None: + prompts_text = [ + apply_chat_template({"prompt": prompt}, self.processing_class, **self.chat_template_kwargs)["prompt"] + for prompt in prompts + ] + prompt_inputs = self.processing_class(images=images, text=prompts_text, padding=True, return_tensors="pt") + prompt_inputs = super()._prepare_inputs(prompt_inputs) + forward_kwargs = {k: v for k, v in prompt_inputs.items() if k not in ["input_ids", "attention_mask"]} + else: + forward_kwargs = {} + + # If token_type_ids are used, extend them with zeros for the completion part + if "token_type_ids" in forward_kwargs: + token_type_ids = forward_kwargs["token_type_ids"] + if self.pad_to_multiple_of is not None: + # Needed only with pad_to_multiple_of: otherwise prompt_ids and token_type_ids must have equal len + padding_size = prompt_ids.size(1) - token_type_ids.size(1) + if padding_size > 0: + token_type_ids = torch.cat( + [token_type_ids.new_zeros((token_type_ids.size(0), padding_size)), token_type_ids], dim=1 + ) + forward_kwargs["token_type_ids"] = torch.cat( + [token_type_ids, token_type_ids.new_zeros(completion_ids.shape)], dim=1 + ) + # If mm_token_type_ids are used, extend them with zeros for the completion part + if "mm_token_type_ids" in forward_kwargs: + mm_token_type_ids = forward_kwargs["mm_token_type_ids"] + if self.pad_to_multiple_of is not None: + # Needed only with pad_to_multiple_of: otherwise prompt_ids and mm_token_type_ids must have equal len + padding_size = prompt_ids.size(1) - mm_token_type_ids.size(1) + if padding_size > 0: + mm_token_type_ids = torch.cat( + [mm_token_type_ids.new_zeros((mm_token_type_ids.size(0), padding_size)), mm_token_type_ids], + dim=1, + ) + forward_kwargs["mm_token_type_ids"] = torch.cat( + [mm_token_type_ids, mm_token_type_ids.new_zeros(completion_ids.shape)], dim=1 + ) + + # When gradient checkpointing is enabled with use_reentrant=True (non default), calling the model inside a + # torch.no_grad() block triggers a harmless PyTorch warning ("None of the inputs have requires_grad=True"). + # Temporarily disable checkpointing to avoid this warning during inference. + with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs): + # Compute the per-token log probabilities for the current model + old_per_token_logps, _ = self._get_per_token_logps_and_entropies( + self.model, + prompt_completion_ids, + attention_mask, + logits_to_keep, + batch_size, + num_images=num_images, + **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask, image_sizes, image_position_ids + ) + old_logps = (old_per_token_logps * completion_mask).sum(1) # mask out padding and tokens after EOS + + # Compute the per-token log probabilities for the reference model + if self.beta != 0.0: + if self.ref_model is not None: + ref_per_token_logps, _ = self._get_per_token_logps_and_entropies( + self.ref_model, + prompt_completion_ids, + attention_mask, + logits_to_keep, + batch_size=batch_size, + num_images=num_images, + **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask, image_sizes, image_position_ids + ) + else: + # When training a PEFT adapter, how we obtain the reference depends on the setup: + # - New adapter: disabling adapters yields the base model. + # - Re-training an existing adapter: an initial copy is loaded under the name "ref". + model = self.accelerator.unwrap_model(self.model) + with use_adapter(model, adapter_name="ref" if "ref" in model.peft_config else None): + ref_per_token_logps, _ = self._get_per_token_logps_and_entropies( + self.model, + prompt_completion_ids, + attention_mask, + logits_to_keep, + batch_size=batch_size, + num_images=num_images, + **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask, image_sizes, image_position_ids + ) + else: + ref_per_token_logps = None + + # Decode + prompts_text = self.processing_class.batch_decode(prompt_ids, skip_special_tokens=True) + completions_text = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True) + + # Calculate rewards for each reward function. rewards_per_func aggregates rewards across all processes. This is + # important because rewards will be normalized per group, and completions are distributed. We will later slice + # rewards_per_func to extract each process's subset. + rewards_per_func = self._calculate_rewards(inputs, prompts, completions, completion_ids_list) + num_generations = self.num_generations if mode == "train" else self.num_generations_eval + + # A completion for which every reward function returned None is unscorable. nansum would collapse it to 0, + # which both biases the leave-one-out baseline and hands the completion a spurious advantage. Mark these rows + # NaN so they're excluded from the (nan-aware) baseline below; their advantage is forced to 0 afterwards. + unscorable_mask = torch.isnan(rewards_per_func).all(dim=1) + + # Apply weights to each reward function's output and sum + rewards = (rewards_per_func * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1) + rewards[unscorable_mask] = torch.nan + + # Apply reward clipping if specified + if self.reward_clip_range: + rewards = rewards.clamp(min=self.reward_clip_range[0], max=self.reward_clip_range[1]) + + # Include the KL penalty in the reward + if self.beta != 0.0: + per_token_kl = old_per_token_logps - ref_per_token_logps + # Apply sequence-level KL penalty to rewards (sum KL across tokens first, then apply to each sequence) + kl = (per_token_kl * completion_mask).sum(-1) + kl = gather(kl) # rewards are gathered, so kl must be too + rewards = rewards - self.beta * kl + + grouped_rewards = rewards.view(-1, num_generations) + mean_grouped_rewards = torch.nanmean(grouped_rewards, dim=1) + if num_generations > 1: + std_rewards = nanstd(grouped_rewards, dim=1) + else: # doesn't occur during training, but could occur in eval when num_generations_eval=1 + std_rewards = torch.zeros_like(mean_grouped_rewards) + + # RLOO advantages computation. The leave-one-out baseline averages over scorable siblings only: nansum drops + # unscorable rewards and the divisor is (scorable count − 1). A group with a single scorable completion yields + # 0/0 = NaN, and unscorable rows stay NaN; both are zeroed by nan_to_num below. + scorable_counts = (~torch.isnan(grouped_rewards)).sum(dim=1, keepdim=True) # (num_prompts, 1) + grouped_sum = torch.nansum(grouped_rewards, dim=1, keepdim=True) # (num_prompts, 1) + if num_generations > 1: + baselines = (grouped_sum - grouped_rewards) / (scorable_counts - 1) # (num_prompts, num_generations) + baselines = baselines.view(-1) # Flatten back to match rewards shape + advantages = rewards - baselines + else: # this case doesn't occur during training, but could in eval when num_generations_eval=1 + advantages = torch.zeros_like(rewards) + + # Normalize advantages over the scorable subset only (unscorable advantages are still NaN here). + if self.normalize_advantages: + advantages = (advantages - torch.nanmean(advantages)) / (nanstd(advantages) + 1e-4) + + # Unscorable completions carry no learning signal: zero their advantage to keep them from moving the policy. + advantages = torch.nan_to_num(advantages, nan=0.0) + + is_std_zero = torch.isclose(std_rewards, torch.zeros_like(std_rewards)) # for logging + + # Slice to keep only the local part of the data + process_slice = slice( + self.accelerator.process_index * len(prompts), + (self.accelerator.process_index + 1) * len(prompts), + ) + all_process_advantages = advantages.clone() # keep the aggregated advantages for logging + advantages = advantages[process_slice] + + # Calculate and log the mean KL divergence between current and reference model + if self.beta != 0.0: + mean_kl = (per_token_kl * completion_mask).sum() / completion_mask.sum().clamp(min=1.0) + self._metrics[mode]["kl"].append(self.accelerator.gather(mean_kl).nanmean().item()) + + # Calculate mean reward per function, but only for samples where the function was applied (non-NaN values) + for i, reward_func_name in enumerate(self.reward_func_names): + mean_rewards = torch.nanmean(rewards_per_func[:, i]).item() + self._metrics[mode][f"rewards/{reward_func_name}/mean"].append(mean_rewards) + std_func_rewards = nanstd(rewards_per_func[:, i]).item() + self._metrics[mode][f"rewards/{reward_func_name}/std"].append(std_func_rewards) + rewards = (rewards_per_func * self.reward_weights.to(rewards_per_func.device).unsqueeze(0)).nansum(dim=1) + rewards[unscorable_mask] = torch.nan # exclude unscorable rows from the logged reward stats + self._metrics[mode]["reward"].append(torch.nanmean(rewards).item()) + self._metrics[mode]["reward_std"].append(nanstd(rewards).item()) + self._metrics[mode]["frac_reward_zero_std"].append(is_std_zero.float().mean().item()) + + # Log prompt and completion texts + self._logs["prompt"].extend(gather_object(prompts_text)) + self._logs["completion"].extend(gather_object(completions_text)) + for i, name in enumerate(self.reward_func_names): + self._logs["rewards"][name].extend(rewards_per_func[:, i].tolist()) + self._logs["advantages"].extend(all_process_advantages.tolist()) + + # Flush user-logged extra columns (from log_extra), gathering across processes. + # Keys must be sorted so that all ranks call gather_object in the same order, otherwise values + # get mis-attributed across columns (dict insertion order may differ between processes). + for column in sorted(self._pending_extra_logs): + self._logs["extra"][column].extend(gather_object(self._pending_extra_logs[column])) + self._pending_extra_logs.clear() + + # Flush user-logged metrics (from log_metric), averaging across processes. + # Keys must be sorted so that all ranks call accelerator.gather in the same order, otherwise values + # get mis-attributed across metrics (dict insertion order may differ between processes). + for name in sorted(self._pending_metrics): + values = self._pending_metrics[name] + local_mean = sum(values) / len(values) + global_mean = self.accelerator.gather(torch.tensor(local_mean, device=device)).mean().item() + self._metrics[mode][name].append(global_mean) + self._pending_metrics.clear() + + if images is not None: + self._logs["images"].extend(gather_object(images)) + + output = { + "prompt_ids": prompt_ids, + "prompt_mask": prompt_mask, + "completion_ids": completion_ids, + "completion_mask": completion_mask, + "old_logps": old_logps, + "advantages": advantages, + } + if "pixel_values" in forward_kwargs: + output["pixel_values"] = forward_kwargs["pixel_values"] + if "image_grid_thw" in forward_kwargs: + output["image_grid_thw"] = forward_kwargs["image_grid_thw"] + if "pixel_attention_mask" in forward_kwargs: + output["pixel_attention_mask"] = forward_kwargs["pixel_attention_mask"] + if "image_sizes" in forward_kwargs: + output["image_sizes"] = forward_kwargs["image_sizes"] + if "token_type_ids" in forward_kwargs: + output["token_type_ids"] = forward_kwargs["token_type_ids"] + if "mm_token_type_ids" in forward_kwargs: + output["mm_token_type_ids"] = forward_kwargs["mm_token_type_ids"] + if "image_position_ids" in forward_kwargs: + output["image_position_ids"] = forward_kwargs["image_position_ids"] + if images is not None: + output["num_images"] = num_images + return output + + @profiling_decorator + def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): + if return_outputs: + raise ValueError("The RLOOTrainer does not support returning outputs") + return self._compute_loss(model, inputs) + + def _compute_loss(self, model, inputs): + # Compute the per-token log probabilities for the model + prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"] + completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"] + input_ids = torch.cat([prompt_ids, completion_ids], dim=1) + attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) + logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens + + # Compute the per_token_logps and the entropy at each position in the completion + per_token_logps, entropies = self._get_per_token_logps_and_entropies( + model, + input_ids, + attention_mask, + logits_to_keep, + compute_entropy=True, + pixel_values=inputs.get("pixel_values"), + image_grid_thw=inputs.get("image_grid_thw"), + num_images=inputs.get("num_images"), + pixel_attention_mask=inputs.get("pixel_attention_mask"), + image_sizes=inputs.get("image_sizes"), + token_type_ids=inputs.get("token_type_ids"), + mm_token_type_ids=inputs.get("mm_token_type_ids"), + image_position_ids=inputs.get("image_position_ids"), + ) + + logps = (per_token_logps * completion_mask).sum(1) # mask out padding and tokens after EOS + old_logps = inputs["old_logps"] + log_ratio = logps - old_logps + + # Compute the loss + advantages = inputs["advantages"] + coef_1 = torch.exp(log_ratio) + coef_2 = torch.clamp(coef_1, 1 - self.epsilon_low, 1 + self.epsilon_high) + per_sequence_loss1 = coef_1 * advantages + per_sequence_loss2 = coef_2 * advantages + per_sequence_loss = -torch.min(per_sequence_loss1, per_sequence_loss2) + loss = per_sequence_loss.mean() + + # Log the metrics + mode = "train" if self.model.training else "eval" + + # Entropy + mean_entropy = (entropies * completion_mask).sum() / completion_mask.sum().clamp(min=1.0) + self._metrics[mode]["entropy"].append(self.accelerator.gather(mean_entropy).nanmean().item()) + + # Compute the clipped probability ratios + is_low_clipped = (coef_1 < 1 - self.epsilon_low) & (advantages < 0) + is_high_clipped = (coef_1 > 1 + self.epsilon_high) & (advantages > 0) + is_region_clipped = is_low_clipped | is_high_clipped + gathered_low_clip = self.accelerator.gather(is_low_clipped.float().mean()) + self._metrics[mode]["clip_ratio/low_mean"].append(gathered_low_clip.nanmean().item()) + self._metrics[mode]["clip_ratio/low_min"].append(nanmin(gathered_low_clip).item()) + gathered_high_clip = self.accelerator.gather(is_high_clipped.float().mean()) + self._metrics[mode]["clip_ratio/high_mean"].append(gathered_high_clip.nanmean().item()) + self._metrics[mode]["clip_ratio/high_max"].append(nanmax(gathered_high_clip).item()) + gathered_clip_ratio = self.accelerator.gather(is_region_clipped.float().mean()) + self._metrics[mode]["clip_ratio/region_mean"].append(gathered_clip_ratio.nanmean().item()) + return loss + + # During eval, Trainer calls prediction_step. If no labels are present in the inputs, it only runs forward and + # returns logits. We override prediction_step to force compute_loss, because this trainer doesn't involve labels. + def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys: list[str] | None = None): + inputs = self._prepare_inputs(inputs) + with torch.no_grad(): + with self.compute_loss_context_manager(): + loss = self.compute_loss(model, inputs) + loss = loss.mean().detach() + return loss, None, None + + def log(self, logs: dict[str, float], start_time: float | None = None) -> None: + mode = "train" if self.model.training else "eval" + # Average the metrics + metrics = {} + for key, val in self._metrics[mode].items(): + # Filter out NaN values before averaging. A reward function that returns None for all samples + # in a batch produces NaN for that batch's metric. With logging_steps > 1, a naive sum()/len() + # would let a single NaN contaminate valid data from other batches. Only return None when no + # valid values remain (e.g. JSON loggers crash on float NaN). + valid = [v for v in val if not math.isnan(v)] + metrics[key] = sum(valid) / len(valid) if valid else None + + # This method can be called both in training and evaluation. When called in evaluation, the keys in `logs` + # start with "eval_". We need to add the prefix "eval_" to the keys in `metrics` to match the format. + if mode == "eval": + metrics = {f"eval_{key}": val for key, val in metrics.items()} + + logs.update(metrics) + super().log(logs, start_time) + self._metrics[mode].clear() + + if self.accelerator.is_main_process and self.log_completions: + if is_rich_available(): + print_prompt_completions_sample( + self._logs["prompt"], + self._logs["completion"], + self._logs["rewards"], + self._logs["advantages"], + self.state.global_step, + self.num_completions_to_print, + extra=dict(self._logs["extra"]), + ) + + logging_backends = [] + if self.args.report_to and "wandb" in self.args.report_to and wandb.run is not None: + logging_backends.append(wandb) + if self.args.report_to and "trackio" in self.args.report_to: + logging_backends.append(trackio) + + table = { + "step": [self.state.global_step] * len(self._logs["prompt"]), + "prompt": self._logs["prompt"], + "completion": self._logs["completion"], + **self._logs["rewards"], + **self._logs["extra"], + "advantage": self._logs["advantages"], + } + + df_base = pd.DataFrame(table) + images_raw = self._logs["images"] or [] + + for logging_backend in logging_backends: + if images_raw: + images = [] + for image_list in self._logs["images"]: + images.append([logging_backend.Image(image) for image in image_list]) + df = pd.concat( + [df_base, pd.Series(images, name="image")], + axis=1, + copy=False, + ) + else: + df = df_base + + if self.log_unique_prompts: + df = df.drop_duplicates(subset=["prompt"]) + + logging_backend.log({"completions": logging_backend.Table(dataframe=df)}) + + # Ensure the model card is saved along with the checkpoint + def _save_checkpoint(self, model, trial): + if self.args.hub_model_id is None: + model_name = Path(self.args.output_dir).name + else: + model_name = self.args.hub_model_id.split("/")[-1] + self.create_model_card(model_name=model_name) + super()._save_checkpoint(model, trial) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/sft_config.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/sft_config.py new file mode 100644 index 0000000000000000000000000000000000000000..c5d793b19df1a44c6b3afc81d5c987e56847cb5c --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/sft_config.py @@ -0,0 +1,321 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from dataclasses import dataclass, field +from typing import Any + +from .base_config import _BaseConfig + + +@dataclass +class SFTConfig(_BaseConfig): + # docstyle-ignore + r""" + Configuration class for the [`SFTTrainer`]. + + This class includes only the parameters that are specific to SFT 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 + + model_init_kwargs (`dict[str, Any]`, *optional*): + Keyword arguments for [`~transformers.AutoModelForCausalLM.from_pretrained`], used when the `model` + argument of the [`SFTTrainer`] is provided as a string. If you're training a MoE architecture and want to + include the load balancing/auxiliary loss as a part of the final loss, remember to set + `output_router_logits=True` in this dictionary. + chat_template_path (`str`, *optional*): + If specified, sets the model's chat template. This can either be the path to a tokenizer (local directory + or Hugging Face Hub model) or a direct path to a Jinja template file. When using a Jinja file, you must + ensure that any special tokens referenced in the template are added to the tokenizer and that the model's + embedding layer is resized accordingly. + + > Parameters that control the data preprocessing + + dataset_text_field (`str`, *optional*, defaults to `"text"`): + Name of the column that contains text data in the dataset. + dataset_kwargs (`dict[str, Any]`, *optional*): + Dictionary of optional keyword arguments for the dataset preparation. The only supported key is + `skip_prepare_dataset`. When the model is a VLM, `skip_prepare_dataset` is automatically treated as `True` + regardless of the provided value, since preprocessing is done on the fly. + dataset_num_proc (`int`, *optional*): + Number of processes to use for processing the dataset. + eos_token (`str`, *optional*): + Token used to indicate the end of a turn or sequence. If `None`, it defaults to + `processing_class.eos_token`. + max_length (`int` or `None`, *optional*, defaults to `1024`): + Maximum length of the tokenized sequence. Sequences longer than `max_length` are truncated from the left + or right depending on `truncation_mode`. If `None`, no truncation is applied. When packing is enabled, + this value sets the sequence length. + truncation_mode (`str`, *optional*, defaults to `"keep_start"`): + Truncation mode to use when the sequence exceeds `max_length`. The only supported value is + `"keep_start"`. The `"keep_end"` value is deprecated and will be removed in v2.0.0. + shuffle_dataset (`bool`, *optional*, defaults to `False`): + Whether to shuffle the dataset. + packing (`bool`, *optional*, defaults to `False`): + Whether to group multiple sequences into fixed-length blocks to improve computational efficiency and reduce + padding. Uses `max_length` to define sequence length. + packing_strategy (`str`, *optional*, defaults to `"bfd"`): + Strategy for packing sequences. Can be `"bfd"` (best-fit decreasing, truncates overflow), `"bfd_split"` + (best-fit decreasing, splits overflow sequences), or `"wrapped"` (aggressive, cuts mid-sequence). + padding_free (`bool`, *optional*, defaults to `False`): + Whether to perform forward passes without padding by flattening all sequences in the batch into a single + continuous sequence. This reduces memory usage by eliminating padding overhead. Currently, this is only + supported with the FlashAttention 2 or 3, which can efficiently handle the flattened batch structure. When + packing is enabled with strategy `"bfd"`, padding-free is enabled, regardless of the value of this + parameter. + pad_to_multiple_of (`int`, *optional*): + If set, the sequences will be padded to a multiple of this value. + eval_packing (`bool`, *optional*): + Whether to pack the eval dataset. If `None`, uses the same value as `packing`. + + > Parameters that control the training + + completion_only_loss (`bool`, *optional*): + Whether to compute loss only on the completion part of the sequence. If set to `True`, loss is computed + only on the completion, which is supported only for [prompt-completion](#prompt-completion) datasets. If + `False`, loss is computed on the entire sequence. If `None` (default), the behavior depends on the dataset: + loss is computed on the completion for [prompt-completion](#prompt-completion) datasets, and on the full + sequence for [language modeling](#language-modeling) datasets. + assistant_only_loss (`bool`, *optional*, defaults to `False`): + Whether to compute loss only on the assistant part of the sequence. If set to `True`, loss is computed only + on the assistant responses, which is supported only for [conversational](#conversational) datasets. If + `False`, loss is computed on the entire sequence. + loss_type (`str`, *optional*, defaults to `"chunked_nll"`): + Type of loss to use. When left unset, it defaults to `"chunked_nll"`, except when `use_liger_kernel=True`, + in which case it defaults to `"nll"`. Possible values are: + + - `"nll"`: standard negative log-likelihood. + - `"dft"`: Dynamic Fine-Tuning, as described in + [this paper](https://huggingface.co/papers/2508.05629). + - `"chunked_nll"`: same math as `"nll"`, but the `lm_head` projection is computed on non-ignored tokens + only (positions with `labels == -100` are dropped before the matmul) and the cross-entropy is processed + in chunks of tokens to reduce peak activation memory. Not compatible with `use_liger_kernel`. Under + FSDP2, set `fsdp_reshard_after_forward false` in the accelerate config — the chunked path otherwise + re-gathers `lm_head.weight` per chunk during backward, adding noticeable wall-time. + + activation_offloading (`bool`, *optional*, defaults to `False`): + Whether to offload the activations to the CPU. + + > Deprecated parameters + + pad_token: + + + + Parameter `pad_token` is deprecated and will be removed in version v2.0.0. Set `tokenizer.pad_token` + directly and pass it as `processing_class` to the trainer instead. + + + + > [!NOTE] + > These parameters have default values different from [`~transformers.TrainingArguments`]: + > - `logging_steps`: Defaults to `10` instead of `500`. + > - `gradient_checkpointing`: Defaults to `True` instead of `False`. + > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`. + > - `learning_rate`: Defaults to `2e-5` instead of `5e-5`. + """ + + _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"] + + # Parameters whose default values are overridden from TrainingArguments + learning_rate: float = field( + default=2e-5, + metadata={"help": "The initial learning rate for AdamW."}, + ) + + # Parameters that control the model + model_init_kwargs: dict[str, Any] | str | None = field( + default=None, + metadata={ + "help": "Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `model` argument of " + "the `SFTTrainer` is provided as a string. If you're training a MoE architecture and want to include the " + "load balancing/auxiliary loss as a part of the final loss, remember to set `output_router_logits=True` " + "in this dictionary." + }, + ) + chat_template_path: str | None = field( + default=None, + metadata={ + "help": "If specified, sets the model's chat template. This can either be the path to a tokenizer (local " + "directory or Hugging Face Hub model) or a direct path to a Jinja template file. When using a Jinja file, " + "you must ensure that any special tokens referenced in the template are added to the tokenizer and " + "that the model's embedding layer is resized accordingly." + }, + ) + + # Parameters that control the data preprocessing + dataset_text_field: str = field( + default="text", + metadata={"help": "Name of the column that contains text data in the dataset."}, + ) + dataset_kwargs: dict[str, Any] | None = field( + default=None, + metadata={ + "help": "Dictionary of optional keyword arguments for the dataset preparation. The only supported key is " + "`skip_prepare_dataset`. If the model is a VLM, `skip_prepare_dataset` value is ignored. When the model " + "is a VLM, `skip_prepare_dataset` is automatically treated as `True` regardless of the provided value, " + "since preprocessing is done on the fly." + }, + ) + dataset_num_proc: int | None = field( + default=None, + metadata={"help": "Number of processes to use for processing the dataset."}, + ) + eos_token: str | None = field( + default=None, + metadata={ + "help": "Token used to indicate the end of a turn or sequence. If `None`, it defaults to `processing_class.eos_token`." + }, + ) + max_length: int | None = field( + default=1024, + metadata={ + "help": "Maximum length of the tokenized sequence. Sequences longer than `max_length` are truncated from " + "the left or right depending on the `truncation_mode`. If `None`, no truncation is applied. When packing " + "is enabled, this value sets the sequence length." + }, + ) + truncation_mode: str = field( + default="keep_start", + metadata={ + "help": "Truncation mode to use when the sequence exceeds `max_length`. The only supported value is " + "`'keep_start'`. The `'keep_end'` value is deprecated and will be removed in v2.0.0.", + "choices": ["keep_end", "keep_start"], + }, + ) + shuffle_dataset: bool = field( + default=False, + metadata={"help": "Whether to shuffle the dataset."}, + ) + packing: bool = field( + default=False, + metadata={ + "help": "Whether to group multiple sequences into fixed-length blocks to improve computational efficiency " + "and reduce padding. Uses `max_length` to define sequence length." + }, + ) + packing_strategy: str = field( + default="bfd", + metadata={ + "help": "Strategy for packing sequences. Can be `'bfd'` (best-fit decreasing, truncates overflow), " + "`'bfd_split'` (best-fit decreasing, splits overflow sequences), or `'wrapped'` (aggressive, cuts " + "mid-sequence).", + "choices": ["bfd", "bfd_split", "wrapped"], + }, + ) + padding_free: bool = field( + default=False, + metadata={ + "help": "Whether to perform forward passes without padding by flattening all sequences in the batch into " + "a single continuous sequence. This reduces memory usage by eliminating padding overhead. Currently, this " + "is only supported with the FlashAttention 2 or 3, which can efficiently handle the flattened batch " + "structure. When packing is enabled with strategy `'bfd'`, padding-free is enabled, regardless of the " + "value of this parameter." + }, + ) + pad_to_multiple_of: int | None = field( + default=None, + metadata={"help": "If set, the sequences will be padded to a multiple of this value."}, + ) + eval_packing: bool | None = field( + default=None, + metadata={"help": "Whether to pack the eval dataset. If `None`, uses the same value as `packing`."}, + ) + + # Parameters that control the training + completion_only_loss: bool | None = field( + default=None, + metadata={ + "help": ( + "Whether to compute loss only on the completion part of the sequence. If set to `True`, loss is " + "computed only on the completion, which is supported only for prompt-completion datasets. If `False`, " + "loss is computed on the entire sequence. If `None` (default), the behavior depends on the dataset: " + "loss is computed on the completion for prompt-completion datasets, and on the full sequence for " + "language modeling datasets." + ) + }, + ) + assistant_only_loss: bool = field( + default=False, + metadata={ + "help": ( + "Whether to compute loss only on the assistant part of the sequence. If set to `True`, loss is " + "computed only on the assistant responses, which is supported only for conversational datasets. If `False`, " + "loss is computed on the entire sequence." + ) + }, + ) + loss_type: str | None = field( + default=None, + metadata={ + "help": "Type of loss to use. When left unset, it defaults to `'chunked_nll'`, except when " + "`use_liger_kernel=True`, in which case it defaults to `'nll'`. Possible values are `'nll'` (standard " + "negative log-likelihood), `'dft'` (Dynamic Fine-Tuning, https://huggingface.co/papers/2508.05629), and " + "`'chunked_nll'` (same math as `'nll'`, but the `lm_head` projection is computed on non-ignored tokens " + "only — positions with `labels == -100` are dropped before the matmul — and the cross-entropy is " + "processed in chunks of tokens to reduce peak activation memory; not compatible with `use_liger_kernel`; " + "under FSDP2, set `fsdp_reshard_after_forward false` in the accelerate config — the chunked path " + "otherwise re-gathers `lm_head.weight` per chunk during backward, adding noticeable wall-time; the " + "patched `lm_head` path covers standard causal LMs and VLMs whose language model exposes a top-level " + "`lm_head`, architectures with a non-standard head are not supported)." + }, + ) + activation_offloading: bool = field( + default=False, + metadata={"help": "Whether to offload the activations to the CPU."}, + ) + + # Deprecated parameters + pad_token: str | None = field( + default=None, + metadata={ + "help": "Deprecated. Set `tokenizer.pad_token` directly and pass it as `processing_class` to the trainer instead." + }, + ) + + def __post_init__(self): + super().__post_init__() + if self.pad_token is not None: + warnings.warn( + "`pad_token` is deprecated and will be removed in v2.0.0. " + "Set `tokenizer.pad_token` directly and pass it as `processing_class` to the trainer instead.", + FutureWarning, + stacklevel=3, + ) + if self.truncation_mode == "keep_end": + warnings.warn( + "The `'keep_end'` truncation mode is deprecated and will be removed in v2.0.0. " + "Use `truncation_mode='keep_start'` (the default) instead.", + FutureWarning, + stacklevel=3, + ) + if self.packing_strategy == "bfd-requeue": + warnings.warn( + "The `bfd-requeue` packing strategy has been renamed to `bfd_split`. Please update your configuration accordingly. " + "The `bfd-requeue` strategy is deprecated and will be removed in v2.0.0.", + FutureWarning, + stacklevel=3, + ) + self.packing_strategy = "bfd_split" + + # When unset, default to "chunked_nll" unless `use_liger_kernel=True`, in which case default to "nll". + if self.loss_type is None: + self.loss_type = "nll" if self.use_liger_kernel else "chunked_nll" diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/sft_trainer.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/sft_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..1930c1672c925dafca15af4ce95c07837a71230a --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/sft_trainer.py @@ -0,0 +1,1786 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import contextlib +import json +import os +import types +import warnings +from collections import defaultdict +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import accelerate +import torch +import torch.nn as nn +import torch.nn.functional as F +import transformers +from accelerate import PartialState +from accelerate.logging import get_logger +from accelerate.utils import is_peft_model +from datasets import Dataset, IterableDataset +from packaging.version import Version +from transformers import ( + AutoProcessor, + DataCollator, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainingArguments, +) +from transformers.data.data_collator import DataCollatorMixin +from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast +from transformers.trainer_callback import TrainerCallback +from transformers.trainer_utils import EvalPrediction +from transformers.utils import is_peft_available + +from ..chat_template_utils import ( + clone_chat_template, + get_training_chat_template, + has_generation_markers, + is_chat_template_stop_token_trained, +) +from ..data_utils import ( + apply_chat_template, + is_conversational, + is_conversational_from_value, + maybe_convert_to_chatml, + pack_dataset, + prepare_multimodal_messages, +) +from ..models import get_act_offloading_ctx_manager +from .base_trainer import _BaseTrainer +from .sft_config import SFTConfig +from .utils import ( + create_model_from_path, + entropy_from_logits, + flush_left, + get_config_model_id, + pad, + selective_log_softmax, +) + + +_CHUNKED_LM_HEAD_CHUNK_SIZE = 256 + + +if is_peft_available(): + from peft import PeftConfig, PeftModel, PeftType, get_peft_model + + +@dataclass +class _ChunkedCELMHeadOutput(CausalLMOutputWithPast): + """`CausalLMOutputWithPast` with extra fields populated by the chunked-CE path.""" + + num_correct_tokens: torch.Tensor | None = None + entropy_sum: torch.Tensor | None = None + num_valid_tokens: torch.Tensor | None = None + aux_loss: torch.Tensor | None = None + + +def _maybe_gather_lm_head_ctx(w, b): + # Allgather ZeRO-3 partitioned `lm_head` weight/bias for the chunked matmul. No-op if not ZeRO-3, or if the + # param is already gathered (tied embeddings: `embed_tokens` shares the weight and keeps it `AVAILABLE`, so + # partitioning on our exit would collide with its active-submodule tracking). + from transformers.integrations.deepspeed import is_deepspeed_zero3_enabled + + if not is_deepspeed_zero3_enabled(): + return contextlib.nullcontext() + + import deepspeed + from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus + + params = [w] if b is None else [w, b] + if all(p.ds_status == ZeroParamStatus.AVAILABLE for p in params): + return contextlib.nullcontext() + return deepspeed.zero.GatheredParameters(params) + + +def _chunk(h, w, b, lbl, logit_scale, final_logit_softcapping): + with _maybe_gather_lm_head_ctx(w, b): + logits = h.float() @ w.float().t() + if b is not None: + logits = logits + b.float() + if logit_scale != 1.0: + logits = logits * logit_scale + if final_logit_softcapping is not None: + logits = final_logit_softcapping * torch.tanh(logits / final_logit_softcapping) + log_p = F.log_softmax(logits, dim=-1) + chunk_loss = F.nll_loss(log_p, lbl, reduction="sum") + chunk_correct = (logits.argmax(dim=-1) == lbl).sum().float() + chunk_entropy = -(log_p.exp() * log_p).sum(dim=-1).sum() + return chunk_loss, chunk_correct, chunk_entropy + + +def _chunked_cross_entropy_loss( + hidden_states: torch.Tensor, + lm_head_weight: torch.Tensor, + chunk_size: int, + labels: torch.Tensor | None = None, + shift_labels: torch.Tensor | None = None, + num_items_in_batch: torch.Tensor | int | None = None, + logit_scale: float = 1.0, + final_logit_softcapping: float | None = None, + lm_head_bias: torch.Tensor | None = None, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Memory-efficient next-token cross-entropy over hidden states and an `lm_head` weight. + + The full `lm_head` projection is never materialized. Positions where labels equal `-100` are dropped before the + matmul, and the remaining tokens are processed in chunks of `chunk_size`. Each chunk's `[chunk_size, vocab_size]` + logits tensor is kept alive only during its own forward/backward pass via gradient checkpointing, so peak + logits-activation memory is `chunk_size * vocab_size` instead of `batch_size * seq_len * vocab_size`. + + At least one of `labels` or `shift_labels` must be provided. Passing `labels` alone is the standard path and + triggers the internal `labels[..., 1:]` / `hidden_states[..., :-1, :]` shift. Passing `shift_labels` skips the + shift and assumes the caller has already aligned labels with hidden states — this is the contract used under + context / sequence parallelism, where labels are shifted before being sharded. If both are provided, `shift_labels` + wins (matching [`~transformers.loss.ForCausalLMLoss`]). + + Args: + hidden_states (`torch.Tensor`): + Base decoder output of shape `(B, S, H)`, i.e. before the `lm_head` projection. + lm_head_weight (`torch.Tensor`): + Weight of the `lm_head` linear layer, shape `(V, H)`. + chunk_size (`int`): + Number of valid tokens processed per chunk. Peak memory scales linearly with this. + labels (`torch.Tensor`, *optional*): + Labels of shape `(B, S)`. Positions equal to `-100` are excluded from both the `lm_head` matmul and the + loss. Mutually exclusive with `shift_labels`. + shift_labels (`torch.Tensor`, *optional*): + Pre-shifted labels of shape `(B, S)`, aligned with `hidden_states` (position `i` predicts + `shift_labels[i]`). Mutually exclusive with `labels`. + num_items_in_batch (`torch.Tensor`, `int` or `None`, *optional*): + Total number of valid tokens across the global batch, as plumbed by [`~transformers.Trainer`]. When + provided, the loss is reduced as `sum / num_items_in_batch`, matching the gradient-accumulation-correct + behavior of HF's default cross-entropy. When `None`, reduction is `mean` over local valid tokens. + logit_scale (`float`, *optional*, defaults to `1.0`): + Multiplier applied to each chunk's logits before the cross-entropy, matching the `logit_scale` behavior of + Cohere-style models. + final_logit_softcapping (`float`, *optional*): + If set, applies `softcap * tanh(logits / softcap)` to each chunk's logits before the cross-entropy, + matching the `final_logit_softcapping` behavior of Gemma-style models. Applied after `logit_scale`. + lm_head_bias (`torch.Tensor`, *optional*): + Bias of the `lm_head` linear layer, shape `(V,)`. Added to each chunk's logits when provided. + + Returns: + `tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]`: scalar loss, number of correctly-predicted + tokens (count), sum of per-token Shannon entropy (in nats), and number of valid (non-`-100`) target tokens — + all over the local batch. Raw sums are returned so callers can reduce correctly across ranks. + """ + if labels is None and shift_labels is None: + raise ValueError("At least one of `labels` or `shift_labels` must be provided.") + + if shift_labels is not None: + hidden = hidden_states.reshape(-1, hidden_states.size(-1)) + labels = shift_labels.reshape(-1) + else: + hidden = hidden_states[..., :-1, :].reshape(-1, hidden_states.size(-1)) + labels = labels[..., 1:].reshape(-1) + + valid = labels != -100 + hidden = hidden[valid] + labels = labels[valid] + n_valid = hidden.size(0) + + correct = hidden.new_zeros((), dtype=torch.float32) + entropy_sum = hidden.new_zeros((), dtype=torch.float32) + n_valid_tensor = torch.tensor(n_valid, device=hidden.device, dtype=torch.long) + if n_valid == 0: + # Whole micro-batch masked (e.g. completion-only loss + truncation). Keep the loss connected + # to the autograd graph through every trainable parameter so `.backward()` succeeds and DDP / + # FSDP gradient sync doesn't hang on a missing param. + with _maybe_gather_lm_head_ctx(lm_head_weight, lm_head_bias): + loss = (hidden_states.float().sum() + lm_head_weight.float().sum()) * 0.0 + if lm_head_bias is not None: + loss = loss + lm_head_bias.float().sum() * 0.0 + return loss, correct, entropy_sum, n_valid_tensor + + loss = hidden.new_zeros((), dtype=torch.float32) + + for start in range(0, n_valid, chunk_size): + h_chunk = hidden[start : start + chunk_size] + lbl_chunk = labels[start : start + chunk_size] + chunk_loss, chunk_correct, chunk_entropy = torch.utils.checkpoint.checkpoint( + _chunk, + h_chunk, + lm_head_weight, + lm_head_bias, + lbl_chunk, + logit_scale, + final_logit_softcapping, + use_reentrant=False, + ) + loss = loss + chunk_loss + correct = correct + chunk_correct + entropy_sum = entropy_sum + chunk_entropy + + if num_items_in_batch is None: + loss = loss / n_valid + else: + if isinstance(num_items_in_batch, torch.Tensor): + num_items_in_batch = num_items_in_batch.to(loss.device) + loss = loss / num_items_in_batch + return loss, correct, entropy_sum, n_valid_tensor + + +def _patch_chunked_ce_lm_head( + model: torch.nn.Module, chunk_size: int, is_vlm: bool = False, with_peft: bool = False +) -> None: + """ + Patch `model.forward` to compute the LM loss via [`_chunked_cross_entropy_loss`]. + + When `labels` (or pre-shifted `shift_labels`, for CP/SP) are provided, the patched forward runs the decoder up to + `last_hidden_state` (skipping the `lm_head` matmul), drops `labels == -100` positions, and computes the + cross-entropy in chunks of `chunk_size` valid tokens. Returns a [`_ChunkedCELMHeadOutput`] with `loss` set, + `logits=None`, and `num_correct_tokens` / `entropy_sum` / `num_valid_tokens` over non-ignored tokens. For MoE + models (`output_router_logits=True`), the load-balancing aux loss is added with the same coefficient and formula as + the model's reference forward. + + Without labels, the original forward runs unchanged — generation and labels-free eval preserve any per-model logits + post-processing (`logit_scale`, `final_logit_softcapping`, `logits_to_keep` slicing). + + Args: + model (`torch.nn.Module`): + Model to patch. For PEFT, pass `peft_model.get_base_model()` rather than the `PeftModel` wrapper, so + prompt-learning variants (PromptTuning, PrefixTuning, PTuning) keep their virtual-token injection in + `PeftModel.forward` before delegating into the patched forward. + chunk_size (`int`): + Number of valid tokens processed per CE chunk. + is_vlm (`bool`): + Set to `True` for VLMs. Only used to read `logit_scale` / `final_logit_softcapping` / + `output_router_logits` from `model.config.text_config` instead of the top-level config. + """ + # VLM scaling configs (`logit_scale`, `final_logit_softcapping`, MoE `output_router_logits`) live on `text_config`; + # text-only models keep them on the top-level config. + text_config = model.config.text_config if is_vlm else model.config + final_logit_softcapping = getattr(text_config, "final_logit_softcapping", None) + logit_scale = getattr(text_config, "logit_scale", 1.0) + original_forward = model.forward + lm_head = model.get_output_embeddings() + + def _chunked_ce_forward( + self: torch.nn.Module, + input_ids: torch.Tensor | None = None, + attention_mask: torch.Tensor | None = None, + labels: torch.Tensor | None = None, + num_items_in_batch: torch.Tensor | int | None = None, + shift_labels: torch.Tensor | None = None, + output_router_logits: bool | None = None, + **kwargs, + ) -> CausalLMOutputWithPast: + # Without labels, fall back to the original forward so generation and labels-free evaluation + # preserve any per-model logits post-processing (e.g. Cohere `logit_scale`, Gemma + # `final_logit_softcapping`, `logits_to_keep` slicing). + if labels is None and shift_labels is None: + if output_router_logits is not None: + kwargs["output_router_logits"] = output_router_logits + return original_forward(input_ids=input_ids, attention_mask=attention_mask, **kwargs) + + if output_router_logits is None: + output_router_logits = getattr(text_config, "output_router_logits", False) + + kwargs.pop("use_cache", None) + decoder_kwargs = {} + if output_router_logits: + decoder_kwargs["output_router_logits"] = True + # `base_model` gives the backbone model (skipping `lm_head`) — text decoder for LMs, multimodal wrapper + # for VLMs (so vision-token injection runs before the text decoder). `get_decoder()` won't do: on VLMs it + # returns just the text stack and feeds image-placeholder IDs through it. + # Pre-5.0 transformers VLMs set `base_model_prefix = ""` so `self.base_model is self` (re-runs `lm_head`). + # Fall back to `self.model` there. + if is_vlm and Version(transformers.__version__) < Version("5.0.0"): + backbone = self.model + else: + backbone = self.base_model + outputs: BaseModelOutputWithPast = backbone( + input_ids=input_ids, attention_mask=attention_mask, use_cache=False, **decoder_kwargs, **kwargs + ) + hidden_states = outputs.last_hidden_state + + lm_head_weight = lm_head.weight + lm_head_bias = lm_head.bias + # Under FSDP2 + PEFT, the outer FSDP module wraps PeftModel while lm_head.weight + # belongs to the nested causal-LM FSDP module, which is never entered directly inside + # _chunked_ce_forward. The weight therefore stays in Shard(0) placement; full_tensor() + # all-gathers the shards into the complete weight before the chunked matmul. + if with_peft and isinstance(lm_head_weight, torch.distributed.tensor.DTensor): + lm_head_weight = lm_head_weight.full_tensor() + if lm_head_bias is not None: + lm_head_bias = lm_head_bias.full_tensor() + loss, num_correct_tokens, entropy_sum, num_valid_tokens = _chunked_cross_entropy_loss( + hidden_states, + lm_head_weight, + chunk_size, + labels=labels, + shift_labels=shift_labels, + num_items_in_batch=num_items_in_batch, + logit_scale=logit_scale, + final_logit_softcapping=final_logit_softcapping, + lm_head_bias=lm_head_bias, + ) + + aux_loss = None + if output_router_logits: + # Mirror the per-family MoE forward: add `router_aux_loss_coef * load_balancing_loss_func(...)` to + # the main loss. Mixtral is the source of truth — every MoE family (Qwen3Moe, GptOss, OLMoE, + # Qwen2Moe, DBRX, JetMoE, PhiMoE, …) pulls this function from mixtral via the modular system, so a + # single import keeps us in lockstep with upstream for every family we test. + from transformers.models.mixtral.modeling_mixtral import load_balancing_loss_func + + if Version(transformers.__version__) < Version("5.0.0") and not is_vlm: + num_experts = self.num_experts + num_experts_per_tok = self.num_experts_per_tok + router_aux_loss_coef = self.router_aux_loss_coef + else: + # Upstream bug AttributeError: 'GptOssConfig' object has no attribute 'num_experts'; see #5754 + if text_config.model_type == "gpt_oss" and Version("5.0.0") <= Version( + transformers.__version__ + ) < Version("5.6.0"): + num_experts = self.num_experts + else: + num_experts = text_config.num_experts + num_experts_per_tok = text_config.num_experts_per_tok + router_aux_loss_coef = text_config.router_aux_loss_coef + aux_loss = load_balancing_loss_func( + outputs.router_logits, num_experts, num_experts_per_tok, attention_mask + ) + loss = loss + router_aux_loss_coef * aux_loss.to(loss.device) + + return _ChunkedCELMHeadOutput( + loss=loss, + logits=None, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + num_correct_tokens=num_correct_tokens, + entropy_sum=entropy_sum, + num_valid_tokens=num_valid_tokens, + aux_loss=aux_loss, + ) + + model.forward = types.MethodType(_chunked_ce_forward, model) + + +logger = get_logger(__name__) + + +FLASH_ATTENTION_VARIANTS = { + "flash_attention_2", + "flash_attention_3", + "kernels-community/flash-attn2", + "kernels-community/flash-attn3", + "kernels-community/vllm-flash-attn3", +} + + +def get_dataset_column_names(dataset: Dataset | IterableDataset) -> list[str]: + return list(next(iter(dataset)).keys()) if dataset.column_names is None else dataset.column_names + + +@dataclass +class DataCollatorForLanguageModeling(DataCollatorMixin): + """ + Data collator used for language modeling data. Inputs are dynamically padded to the maximum length of a batch. + + This collator expects each example in the input list to be a dictionary containing at least the `"input_ids"` key. + If the input contains a `"completion_mask"`, it is used to set the labels to `-100` for tokens that are not in the + completion. If `"assistant_masks"` are present, they are used to set the labels to `-100` for tokens that are not + in the assistant part of the sequence. The collator returns a dictionary containing the following keys: + - `"input_ids"`: Tensor of input IDs, padded to the maximum length of the batch. + - `"labels"`: Tensor of labels, padded to the maximum length of the batch. If `completion_only_loss` is set to + `True`, tokens that are not in the completion are set to -100. If `assistant_masks` are present, tokens that are + not in the assistant part of the sequence are set to -100. If `padding_free` is set to `False`, the following key + is also returned: + - `"attention_mask"`: Tensor of attention masks, padded to the maximum length of the batch. + If `padding_free` is set to `True`, the following key is also returned: + - `"position_ids"`: Tensor of position IDs, padded to the maximum length of the batch. + + Args: + pad_token_id (`int`): + Token ID to use for padding. + max_length (`int`, *optional*): + Maximum length of the sequences in the batch. Sequences longer than `max_length` are truncated to + `max_length`. + truncation_mode (`str`, *optional*, defaults to `"keep_start"`): + Truncation mode to use when the sequence exceeds `max_length`. Possible values are `"keep_end"` and + `"keep_start"`. + completion_only_loss (`bool`, *optional*, defaults to `True`): + When the input contains a completion mask (`completion_mask`), the labels are set to -100 for the tokens + that are no in the completion. + padding_free (`bool`, *optional*, defaults to `False`): + If set to `True`, the sequences will be flattened into a single sequence, and the position IDs will be + generated accordingly and returned instead of the attention mask. + pad_to_multiple_of (`int`, *optional*): + If set, the sequences will be padded to a multiple of this value. + return_tensors (`str`, *optional*, defaults to `"pt"`): + Type of Tensor to return. Only `"pt"` is currently supported. + + Examples: + ```python + >>> from trl.trainer.sft_trainer import DataCollatorForLanguageModeling + + >>> collator = DataCollatorForLanguageModeling(pad_token_id=0) + >>> examples = [{"input_ids": [1, 2, 3]}, {"input_ids": [4, 5]}] + >>> collator(examples) + {'input_ids': tensor([[ 1, 2, 3], + [ 4, 5, 0]]), + 'attention_mask': tensor([[ 1, 1, 1], + [ 1, 1, 0]]), + 'labels': tensor([[ 1, 2, 3], + [ 4, 5, -100]])} + + >>> # With completion mask + >>> examples = [ + ... {"input_ids": [1, 2, 3], "completion_mask": [0, 1, 1]}, + ... {"input_ids": [4, 5], "completion_mask": [0, 1]}, + ... ] + >>> collator(examples) + {'input_ids': tensor([[ 1, 2, 3], + [ 4, 5, 0]]), + 'attention_mask': tensor([[ 1, 1, 1], + [ 1, 1, 0]]), + 'labels': tensor([[-100, 2, 3], + [-100, 5, -100]])} + + >>> # With padding_free + >>> collator = DataCollatorForLanguageModeling(pad_token_id=0, padding_free=True) + >>> collator(examples) + {'input_ids': tensor([[ 1, 2, 3, 4, 5]]), + 'position_ids': tensor([[0, 1, 2, 0, 1]]), + 'labels': tensor([[1, 2, 3, 4, 5]])} + ``` + """ + + pad_token_id: int + max_length: int | None = None + truncation_mode: str = "keep_start" + completion_only_loss: bool = True + padding_free: bool = False + pad_to_multiple_of: int | None = None + return_tensors: str = "pt" + + def torch_call(self, examples: list[dict[str, Any]]) -> dict[str, Any]: + input_ids = [example["input_ids"] for example in examples] + batch_seq_lengths = [example["seq_lengths"] for example in examples] if "seq_lengths" in examples[0] else None + labels = [example.get("labels", example["input_ids"]) for example in examples] + completion_mask = ( + [example["completion_mask"] for example in examples] + if self.completion_only_loss and "completion_mask" in examples[0] + else None + ) + assistant_masks = ( + [example["assistant_masks"] for example in examples] if "assistant_masks" in examples[0] else None + ) + + # Truncate per sequence if necessary + if self.max_length is not None and not self.padding_free: + if self.truncation_mode == "keep_start": + sl = slice(None, self.max_length) + elif self.truncation_mode == "keep_end": + sl = slice(-self.max_length, None) + else: + raise ValueError( + f"Unsupported truncation mode: {self.truncation_mode}, expected 'keep_start' or 'keep_end'" + ) + input_ids = [ids[sl] for ids in input_ids] + labels = [lbl[sl] for lbl in labels] + if completion_mask is not None: + completion_mask = [m[sl] for m in completion_mask] + if assistant_masks is not None: + assistant_masks = [m[sl] for m in assistant_masks] + + # Convert to tensor + input_ids = [torch.tensor(ids) for ids in input_ids] + labels = [torch.tensor(lbl) for lbl in labels] + if completion_mask is not None: + completion_mask = [torch.tensor(m) for m in completion_mask] + if assistant_masks is not None: + assistant_masks = [torch.tensor(m) for m in assistant_masks] + + # For padding-free, we should NOT create attention_mask as it causes FlashAttention to ignore position_ids and + # compute wrong cu_seq_lens from the all-1s mask + if self.padding_free: + if batch_seq_lengths is not None: + position_ids = self.get_position_ids_from_packed_seq_lengths(batch_seq_lengths) + else: + position_ids = [torch.arange(len(ids)) for ids in input_ids] + else: + attention_mask = [torch.ones_like(ids) for ids in input_ids] + + # If padding_free, flatten everything into a single sequence + output = {} + if self.padding_free: + input_ids = [torch.cat(input_ids, dim=0)] + labels = [torch.cat(labels, dim=0)] + position_ids = [torch.cat(position_ids, dim=0)] + if completion_mask is not None: + completion_mask = [torch.cat(completion_mask, dim=0)] + if assistant_masks is not None: + assistant_masks = [torch.cat(assistant_masks, dim=0)] + + # Pad + output["input_ids"] = pad( + input_ids, + padding_value=self.pad_token_id, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + ) + output["labels"] = pad( + labels, padding_value=-100, padding_side="right", pad_to_multiple_of=self.pad_to_multiple_of + ) + if self.padding_free: + output["position_ids"] = pad( + position_ids, padding_value=0, padding_side="right", pad_to_multiple_of=self.pad_to_multiple_of + ) + output["labels"][output["position_ids"] == 0] = -100 + else: + output["attention_mask"] = pad( + attention_mask, padding_value=0, padding_side="right", pad_to_multiple_of=self.pad_to_multiple_of + ) + if completion_mask is not None: + completion_mask = pad( + completion_mask, padding_value=0, padding_side="right", pad_to_multiple_of=self.pad_to_multiple_of + ) + output["labels"][completion_mask == 0] = -100 # mask everything that is not in the completion + if assistant_masks is not None: + assistant_masks = pad( + assistant_masks, padding_value=0, padding_side="right", pad_to_multiple_of=self.pad_to_multiple_of + ) + output["labels"][assistant_masks == 0] = -100 + return output + + @staticmethod + def get_position_ids_from_packed_seq_lengths(batch_seq_lengths: list[list[int]]) -> list[torch.Tensor]: + """ + Get position IDs for packed sequences. + + Args: + batch_seq_lengths (`list[list[int]]`): + A list of lists containing the lengths of each individual document in the packed batch. + + Return: + `list[torch.Tensor]`: + A list of tensors containing the position IDs for each packed sequence. + """ + # Get lengths per row + example_lengths = [sum(seq_lengths) for seq_lengths in batch_seq_lengths] + # Flat list of lengths + batch_seq_lengths = torch.tensor( + [seq_length for seq_lengths in batch_seq_lengths for seq_length in seq_lengths] + ) + position_ids = torch.ones(sum(example_lengths), dtype=batch_seq_lengths.dtype) + position_ids[0] = 0 + # Reset position ids to 0 at the start of each sequence + position_ids[batch_seq_lengths[:-1].cumsum(0)] = -(batch_seq_lengths[:-1] - 1) + position_ids = position_ids.cumsum(0) + # Split back into one tensor per example + return list(position_ids.split(example_lengths)) + + +@dataclass +class DataCollatorForVisionLanguageModeling(DataCollatorMixin): + """ + Data collator for vision-language modeling tasks. + + Unlike text-only datasets, where the collator typically receives pre-tokenized inputs ready for batching, + vision-language data processing involves converting images into pixel values. This conversion is disk-intensive, + making upfront preprocessing of the entire dataset impractical. Therefore, this collator performs tokenization and + image processing on-the-fly to efficiently prepare batches. + + Each input example should be a dictionary containing at least: + - An `"images"` key holding a list of images, or an `"image"` key holding a single image. + - [language modeling](#language-modeling) type: either a `"messages"` key for conversational inputs or a `"text"` + key for standard text inputs. + - [prompt-completion](#prompt-completion) type: keys `"prompt"` and `"completion"` for the prompt and completion. + + The collator outputs a dictionary including: + - `"input_ids"`: Tensor of token IDs. + - `"attention_mask"`: Tensor indicating attention mask. + - `"pixel_values"`: Tensor representing image pixel values. + - `"labels"`: Tensor for training labels. + + Additional keys may be present depending on the processor, such as `"image_grid_thw"` or `"image_position_ids"`. + + Args: + processor ([`~transformers.ProcessorMixin`]): + The processor used to tokenize text and process images. It must be a subclass of + [`~transformers.ProcessorMixin`] and include a `tokenizer` with a defined `pad_token_id`. + max_length (`int` or `None`, optional, defaults to `None`): + Maximum sequence length for input tokens. If `None`, no truncation is applied. + completion_only_loss (`bool`, *optional*, defaults to `False`): + Whether to compute loss only on the completion part of the sequence. When `True`, the labels for the prompt + part are set to -100. It requires the dataset type to be prompt-completion. + pad_to_multiple_of (`int` or `None`, optional, defaults to `None`): + If set, the sequences will be padded to a multiple of this value. + dataset_text_field (`str`, optional, defaults to `"text"`): + Name of the column that contains text data in the dataset. This parameter is only relevant for [standard + datasets format](dataset_formats#standard). + return_tensors (`str`, optional, defaults to `"pt"`): + The tensor type to return. Currently, only `"pt"` (PyTorch tensors) is supported. + + Example: + ```python + >>> from trl.trainer.sft_trainer import DataCollatorForVisionLanguageModeling + >>> from transformers import AutoProcessor + + >>> processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct") + >>> collator = DataCollatorForVisionLanguageModeling(processor) + >>> examples = [ + ... {"images": [Image.open("image_0.png")], "messages": [{"role": "user", "content": "What is this?"}]}, + ... {"images": [Image.open("image_1.png")], "messages": [{"role": "user", "content": "Describe this image."}]}, + ... ] + >>> collator(examples) + {'input_ids': tensor([[151644, 8948, 198, 2610, 525, 264, 10950, 17847, 13, 151645, 198, + 151644, 872, 198, 151652, 151655, 151655, 151655, 151655, 151653, 3838, 374, + 419, 30, 151645, 198], + [151644, 8948, 198, 2610, 525, 264, 10950, 17847, 13, 151645, 198, + 151644, 872, 198, 151652, 151655, 151655, 151655, 151655, 151653, 74785, 419, + 2168, 13, 151645, 198]]), + 'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]), + 'pixel_values': tensor([[-0.9893, 0.1785, 1.5362, ..., -0.0582, 0.8661, -0.2431], + [-0.2302, 0.9522, -1.1061, ..., 0.0555, 1.3354, -0.6412], + [ 1.2150, 0.9084, 0.7041, ..., 0.2404, -0.8403, -0.5133], + ..., + [ 0.6895, 0.2807, 0.2515, ..., -0.2004, -1.2100, 0.0555], + [ 0.8209, -0.9748, 1.5654, ..., 1.6055, -0.4706, 0.5817], + [-1.0915, 0.4559, 0.9230, ..., 0.5106, 0.0982, -0.1720]]), + 'image_grid_thw': tensor([[1, 4, 4], + [1, 4, 4]]), + 'labels': tensor([[151644, 8948, 198, 2610, 525, 264, 10950, 17847, 13, 151645, 198, + 151644, 872, 198, 151652, 151655, 151655, 151655, 151655, 151653, 3838, 374, + 419, 30, 151645, 198], + [151644, 8948, 198, 2610, 525, 264, 10950, 17847, 13, 151645, 198, + 151644, 872, 198, 151652, 151655, 151655, 151655, 151655, 151653, 74785, 419, + 2168, 13, 151645, 198]])} + ``` + """ + + processor: ProcessorMixin + max_length: int | None = None + completion_only_loss: bool = False # default not used in practice; SFTTrainer always passes the relevant value + pad_to_multiple_of: int | None = None + dataset_text_field: str = "text" + return_tensors: str = "pt" + + def torch_call(self, examples: list[dict[str, Any]]) -> dict[str, Any]: + if "messages" in examples[0] or self.dataset_text_field in examples[0]: + if self.completion_only_loss: + raise ValueError( + "The `completion_only_loss` argument is not supported for language modeling datasets." + ) + return self._collate_language_modeling(examples) + elif "prompt" in examples[0] and "completion" in examples[0]: + return self._collate_prompt_completion(examples) + else: + raise KeyError(f"Unexpected input keys in examples: {list(examples[0].keys())}.") + + def _collate_language_modeling(self, examples: list[dict[str, Any]]) -> dict[str, Any]: + if "image" in examples[0]: + for example in examples: + example["images"] = [example.pop("image")] + images = [example["images"] for example in examples] + # Transformers requires at least one image in the batch, otherwise it throws an error + if all(img_list == [] for img_list in images): + images = None + + if "messages" in examples[0]: # conversational case + messages = [ + prepare_multimodal_messages(example["messages"], images=example["images"]) for example in examples + ] + texts = self.processor.apply_chat_template(messages) + elif self.dataset_text_field in examples[0]: # standard case + texts = [example[self.dataset_text_field] for example in examples] + else: + raise KeyError( + "The input examples must contain either 'messages' for conversational data or 'text' for standard " + "data." + ) + + output = self.processor( + images=images, + text=texts, + padding=True, + padding_side="right", + pad_to_multiple_of=self.pad_to_multiple_of, + truncation=self.max_length is not None, + max_length=self.max_length, + return_tensors=self.return_tensors, + add_special_tokens=False, # to avoid adding the BOS, twice see https://huggingface.co/blog/qgallouedec/gotchas-in-tokenizer-behavior#7-chat-template-and-tokenization-dont-compose-due-to-special-tokens + ) + labels = output["input_ids"].clone() + labels[output["attention_mask"] == 0] = -100 + # We mask only padding tokens (-100) in the labels. Vision tokens are left unchanged because their handling in + # loss computation has to be done by the model, and masking them here would be infeasible in practice as vision + # token definitions vary across architectures. + output["labels"] = labels + return output + + def _collate_prompt_completion(self, examples: list[dict[str, Any]]) -> dict[str, Any]: + if self.pad_to_multiple_of is not None: + raise NotImplementedError( + "Padding to a multiple of a value is not yet implemented for vision-language modeling and " + "prompt-completion data." + ) + if "image" in examples[0]: + for example in examples: + example["images"] = [example.pop("image")] + images = [example["images"] for example in examples] + # Transformers requires at least one image in the batch, otherwise it throws an error + if all(img_list == [] for img_list in images): + images = None + if is_conversational(examples[0]): # conversational case + for example in examples: + example["prompt"] = prepare_multimodal_messages(example["prompt"], images=example["images"]) + example["completion"] = prepare_multimodal_messages(example["completion"]) + examples = [apply_chat_template(example, self.processor) for example in examples] + + prompts = [example["prompt"] for example in examples] + completions = [example["completion"] for example in examples] + + processed_prompts = self.processor( + images=images, + text=prompts, + padding=True, + padding_side="left", + return_tensors=self.return_tensors, + add_special_tokens=False, # to avoid adding the BOS, twice see https://huggingface.co/blog/qgallouedec/gotchas-in-tokenizer-behavior#7-chat-template-and-tokenization-dont-compose-due-to-special-tokens + ) + processed_completions = self.processor( + text=completions, + padding=True, + padding_side="right", + return_tensors=self.return_tensors, + add_special_tokens=False, # to avoid adding the BOS, twice see https://huggingface.co/blog/qgallouedec/gotchas-in-tokenizer-behavior#7-chat-template-and-tokenization-dont-compose-due-to-special-tokens + ) + + # Concatenate prompts and completions + prompt_ids, prompt_mask = processed_prompts["input_ids"], processed_prompts["attention_mask"] + completion_ids, completion_mask = processed_completions["input_ids"], processed_completions["attention_mask"] + input_ids = torch.cat((prompt_ids, completion_ids), dim=1) + attention_mask = torch.cat((prompt_mask, completion_mask), dim=1) + completion_mask = torch.cat((torch.zeros_like(prompt_mask), completion_mask), dim=1) + if "token_type_ids" in processed_prompts: # special case for Gemma + prompt_token_type_ids = processed_prompts["token_type_ids"] + completion_token_type_ids = processed_completions["token_type_ids"] + token_type_ids = torch.cat((prompt_token_type_ids, completion_token_type_ids), dim=1) + if "mm_token_type_ids" in processed_prompts: # special case for ERNIE-VL + prompt_mm_token_type_ids = processed_prompts["mm_token_type_ids"] + completion_mm_token_type_ids = processed_completions.get( + "mm_token_type_ids", torch.zeros_like(completion_ids) + ) + mm_token_type_ids = torch.cat((prompt_mm_token_type_ids, completion_mm_token_type_ids), dim=1) + + # Flush left to reduce padding + if "token_type_ids" in processed_prompts and "mm_token_type_ids" in processed_prompts: + attention_mask, input_ids, completion_mask, token_type_ids, mm_token_type_ids = flush_left( + attention_mask, input_ids, completion_mask, token_type_ids, mm_token_type_ids + ) + elif "token_type_ids" in processed_prompts: + attention_mask, input_ids, completion_mask, token_type_ids = flush_left( + attention_mask, input_ids, completion_mask, token_type_ids + ) + elif "mm_token_type_ids" in processed_prompts: + attention_mask, input_ids, completion_mask, mm_token_type_ids = flush_left( + attention_mask, input_ids, completion_mask, mm_token_type_ids + ) + else: + attention_mask, input_ids, completion_mask = flush_left(attention_mask, input_ids, completion_mask) + + # Truncate if necessary + if self.max_length is not None: + input_ids = input_ids[:, : self.max_length] + attention_mask = attention_mask[:, : self.max_length] + completion_mask = completion_mask[:, : self.max_length] + if "token_type_ids" in processed_prompts: + token_type_ids = token_type_ids[:, : self.max_length] + if "mm_token_type_ids" in processed_prompts: + mm_token_type_ids = mm_token_type_ids[:, : self.max_length] + + # Create labels and mask padding tokens + labels = input_ids.clone() + labels[attention_mask == 0] = -100 + if self.completion_only_loss: + labels[completion_mask == 0] = -100 + + # Build the output dictionary + output = processed_prompts # we take processed_prompts because it contains the images + output["input_ids"] = input_ids + output["attention_mask"] = attention_mask + output["labels"] = labels + if "token_type_ids" in processed_prompts: + output["token_type_ids"] = token_type_ids + if "mm_token_type_ids" in processed_prompts: + output["mm_token_type_ids"] = mm_token_type_ids + return output + + +def dft_loss(outputs, labels, num_items_in_batch=None): + """ + DFT loss function, as presented in [On the Generalization of SFT: A Reinforcement Learning Perspective with Reward + Rectification](https://huggingface.co/papers/2508.05629) + """ + labels = nn.functional.pad(labels, (0, 1), value=-100) + shift_labels = labels[..., 1:].contiguous() + loss_mask = shift_labels != -100 + shift_labels[~loss_mask] = 0 + logprobs = selective_log_softmax(outputs.logits, shift_labels) + per_token_loss = -logprobs.exp().detach() * logprobs + if num_items_in_batch is None: + num_items_in_batch = loss_mask.sum() + loss = (per_token_loss * loss_mask).sum() / num_items_in_batch + return loss + + +class SFTTrainer(_BaseTrainer): + """ + Trainer for Supervised Fine-Tuning (SFT) method. + + This class is a wrapper around the [`~transformers.Trainer`] class and inherits all of its attributes and methods. + + Example: + + ```python + from trl import SFTTrainer + from datasets import load_dataset + + dataset = load_dataset("roneneldan/TinyStories", split="train[:1%]") + + trainer = SFTTrainer( + model="Qwen/Qwen2.5-0.5B-Instruct", + train_dataset=dataset, + ) + trainer.train() + ``` + + Args: + model (`str` or [`~transformers.PreTrainedModel`] or [`~peft.PeftModel`]): + Model to be trained. Can be either: + + - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a + path to a *directory* containing model weights saved using + [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded + using `.from_pretrained` (where `` is derived from the model + config) with the keyword arguments in `args.model_init_kwargs`. + - A [`~transformers.PreTrainedModel`] object. Only causal language models are supported. + - A [`~peft.PeftModel`] object. Only causal language models are supported. + If you're training a model with an MoE architecture and want to include the load balancing/auxiliary loss + as a part of the final loss, remember to set the `output_router_logits` config of the model to `True`. + args ([`SFTConfig`], *optional*): + Configuration for this trainer. If `None`, a default configuration is used. + data_collator ([`~transformers.DataCollator`], *optional*): + Function to use to form a batch from a list of elements of the processed `train_dataset` or `eval_dataset`. + Will default to [`~trainer.sft_trainer.DataCollatorForLanguageModeling`] if the model is a language model + and [`~trainer.sft_trainer.DataCollatorForVisionLanguageModeling`] if the model is a vision-language model. + Custom collators must truncate sequences before padding; the trainer does not apply post-collation + truncation. + train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]): + Dataset to use for training. This trainer supports both [language modeling](#language-modeling) type and + [prompt-completion](#prompt-completion) type. The format of the samples can be either: + + - [Standard](dataset_formats#standard): Each sample contains plain text. + - [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role + and content). + + The trainer also supports processed datasets (tokenized) as long as they contain an `input_ids` field. + eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Dataset | IterableDataset]`): + Dataset to use for evaluation. It must meet the same requirements as `train_dataset`. + processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.ProcessorMixin`], *optional*): + Processing class used to process the data. If `None`, the processing class is loaded from the model's name + with [`~transformers.AutoProcessor.from_pretrained`]. A padding token, `tokenizer.pad_token`, must be set. + If the processing class has not set a padding token, `tokenizer.eos_token` will be used as the default. + compute_loss_func (`Callable`, *optional*): + A function that accepts the raw model outputs, labels, and the number of items in the entire accumulated + batch (batch_size * gradient_accumulation_steps) and returns the loss. For example, see the default [loss + function](https://github.com/huggingface/transformers/blob/052e652d6d53c2b26ffde87e039b723949a53493/src/transformers/trainer.py#L3618) + used by [`Trainer`]. + compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*): + The function that will be used to compute metrics at evaluation. Must take a + [`~transformers.EvalPrediction`] and return a dictionary string to metric values. When passing + [`SFTConfig`] with `batch_eval_metrics` set to `True`, your `compute_metrics` function must take a boolean + `compute_result` argument. This will be triggered after the last eval batch to signal that the function + needs to calculate and return the global summary statistics rather than accumulating the batch-level + statistics. + callbacks (list of [`~transformers.TrainerCallback`], *optional*): + List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed + in [here](https://huggingface.co/docs/transformers/main_classes/callback). + + If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`] + method. + optimizers (`tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None]`, *optional*, defaults to `(None, None)`): + A tuple containing the optimizer and the scheduler to use. Will default to an instance of `AdamW` on your + model and a scheduler given by [`~transformers.get_linear_schedule_with_warmup`] controlled by `args`. + optimizer_cls_and_kwargs (`tuple[Type[torch.optim.Optimizer], Dict[str, Any]]`, *optional*): + A tuple containing the optimizer class and keyword arguments to use. Overrides `optim` and `optim_args` in + `args`. Incompatible with the `optimizers` argument. + + Unlike `optimizers`, this argument avoids the need to place model parameters on the correct devices before + initializing the Trainer. + preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`, *optional*): + A function that preprocess the logits right before caching them at each evaluation step. Must take two + tensors, the logits and the labels, and return the logits once processed as desired. The modifications made + by this function will be reflected in the predictions received by `compute_metrics`. + + Note that the labels (second parameter) will be `None` if the dataset does not have them. + peft_config ([`~peft.PeftConfig`], *optional*): + PEFT configuration used to wrap the model. If `None`, the model is not wrapped. + formatting_func (`Callable`, *optional*): + Formatting function applied to the dataset before tokenization. Applying the formatting function explicitly + converts the dataset into a [language modeling](#language-modeling) type. + """ + + _tag_names = ["trl", "sft"] + _name = "SFT" + + def __init__( + self, + model: "str | PreTrainedModel | PeftModel", + args: SFTConfig | TrainingArguments | None = None, + data_collator: DataCollator | None = None, + train_dataset: Dataset | IterableDataset | None = None, + eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None, + processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None, + compute_loss_func: Callable | None = None, + compute_metrics: Callable[[EvalPrediction], dict] | None = None, + callbacks: list[TrainerCallback] | None = None, + optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None), + optimizer_cls_and_kwargs: tuple[type[torch.optim.Optimizer], dict[str, Any]] | None = None, + preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None, + peft_config: "PeftConfig | None" = None, + formatting_func: Callable[[dict], str] | None = None, + ): + # Args + if args is None: + model_name = model if isinstance(model, str) else get_config_model_id(model.config) + model_name = model_name.split("/")[-1] + args = SFTConfig(f"{model_name}-SFT") + elif isinstance(args, TrainingArguments) and not isinstance(args, SFTConfig): + dict_args = args.to_dict() + dict_args["hub_token"] = args.hub_token # to_dict hides the hub_token + if Version(transformers.__version__) < Version("5.0.0"): + dict_args.pop("push_to_hub_token") + args = SFTConfig(**dict_args) + + if train_dataset is None: + raise ValueError("`train_dataset` is required") + elif isinstance(train_dataset, IterableDataset): + # IterableDataset requires dispatch_batches=False because Accelerate's dispatch mode may try to concatenate + # batches from multiple processes, leading to mismatch errors. + if args.accelerator_config.dispatch_batches is True: + logger.warning( + "You are using an `IterableDataset` for training with `dispatch_batches=True`. `dispatch_batches` " + "is forced to `False` when using an `IterableDataset`. To remove this warning, unset " + "`dispatch_batches` in `SFTConfig` or set it to `False`." + ) + args.accelerator_config.dispatch_batches = False + + # Model + if isinstance(model, str): + model_init_kwargs = args.model_init_kwargs or {} + # Distributed training requires device_map=None ("auto" fails) + if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]: + model_init_kwargs["device_map"] = None + model = create_model_from_path(model, **model_init_kwargs) + else: + if args.model_init_kwargs is not None: + logger.warning( + "You passed `model_init_kwargs` to the `SFTConfig`, but your model is already instantiated. " + "The `model_init_kwargs` will be ignored." + ) + + # Processing class + if processing_class is None: + processing_class = AutoProcessor.from_pretrained(get_config_model_id(model.config)) + + # Handle pad token for processors or tokenizers + if isinstance(processing_class, ProcessorMixin): + self._tokenizer = processing_class.tokenizer + self._is_vlm = True + elif isinstance(processing_class, PreTrainedTokenizerBase): + self._tokenizer = processing_class + self._is_vlm = False + else: + raise TypeError("The `processing_class` must be either a `PreTrainedTokenizerBase` or a `ProcessorMixin`") + + if args.eos_token is not None: + if args.eos_token not in self._tokenizer.get_vocab(): + raise ValueError( + f"The specified `eos_token` ('{args.eos_token}') is not found in the vocabulary of the given " + f"`processing_class` ({processing_class.__class__.__name__}). Ensure that the `eos_token` exists " + "in the vocabulary before using it as an EOS token." + ) + self._tokenizer.eos_token = args.eos_token + + if args.chat_template_path is not None: + if os.path.isfile(args.chat_template_path) and args.chat_template_path.endswith((".jinja", ".j2")): + with open(args.chat_template_path, encoding="utf-8") as chat_template_file: + processing_class.chat_template = chat_template_file.read() + added_tokens = [] + else: + model, processing_class, added_tokens = clone_chat_template( + model, processing_class, args.chat_template_path + ) + else: + added_tokens = [] + + # Catch some wrong configurations related to VLMs + if self._is_vlm and args.packing: + raise ValueError( + "Packing is not supported for vision-language models. Please set `packing=False` in the SFTConfig." + ) + if self._is_vlm and args.padding_free: + raise ValueError( + "Padding-free training is yet not supported for vision-language models. Please set " + "`padding_free=False` in the `SFTConfig`." + ) + if self._is_vlm and args.assistant_only_loss: + raise ValueError( + "Assistant-only loss is not yet supported for vision-language models. Please set " + "`assistant_only_loss=False` in the `SFTConfig`." + ) + if self._is_vlm and args.max_length is not None and args.truncation_mode == "keep_end": + raise ValueError( + "truncation_mode='keep_end' is not supported for vision-language models. Image tokens reside " + "inside the prompt portion of the sequence; depending on the example, keep_end may silently " + "drop them, causing pixel_values to be forwarded to the model with no corresponding visual " + "tokens in input_ids. Use truncation_mode='keep_start' (the default) or set max_length=None." + ) + + # PEFT + if peft_config is not None: + if not is_peft_available(): + raise ImportError( + "You passed `peft_config` but the `peft` library is not installed. " + "Install it with `pip install trl[peft]`." + ) + if not isinstance(peft_config, PeftConfig): + raise TypeError( + f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), " + f"got {type(peft_config).__name__}." + ) + if is_peft_model(model): + raise ValueError( + "You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first merge " + "and unload the existing adapter, save the resulting base model, and then pass that base model along " + "with the new `peft_config` to the trainer." + ) + if added_tokens: + # Ensure that the added tokens are trainable + if peft_config.trainable_token_indices is None: + peft_config.trainable_token_indices = {"embed_tokens": added_tokens} + elif "embed_tokens" not in peft_config.trainable_token_indices: + peft_config.trainable_token_indices["embed_tokens"] = added_tokens + else: + peft_config.trainable_token_indices["embed_tokens"].extend(added_tokens) + # Ensure that the lm_head is trainable + if peft_config.modules_to_save is None or "lm_head" not in peft_config.modules_to_save: + logger.warning( + "Cloning chat template added new tokens to the tokenizer, but 'lm_head' is not in PEFT's " + "`modules_to_save`. As a result, the model may not learn to generate outputs with these new " + "tokens, leading to degraded generation quality. To fix this, add " + "`modules_to_save=['lm_head']` to your PEFT configuration." + ) + + if peft_config.modules_to_save is None: + peft_config.modules_to_save = ["lm_head"] + else: + peft_config.modules_to_save.append("lm_head") + # Create PEFT model + model = get_peft_model(model, peft_config) + + # PEFT + DeepSpeed ZeRO-3 requires reentrant checkpointing. For more details, see + # https://github.com/huggingface/trl/issues/2514#issuecomment-2692152703 + if ( + is_peft_model(model) + and args.deepspeed_plugin is not None + and args.deepspeed_plugin.zero_stage == 3 + and args.gradient_checkpointing + ): + args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {} + use_reentrant = args.gradient_checkpointing_kwargs.get("use_reentrant") + if use_reentrant is False: + logger.warning( + "You are using PEFT with DeepSpeed ZeRO-3 and gradient checkpointing with `use_reentrant=False`. " + "`use_reentrant` is forced to `True` in this configuration to ensure correct training. To remove " + "this warning, unset `use_reentrant` in `gradient_checkpointing_kwargs` or set it to `True`." + ) + args.gradient_checkpointing_kwargs["use_reentrant"] = True + + # When using gradient checkpointing with PEFT, we need to enable input gradients. transformers.Trainer normally + # handles this, but a bug currently prevents it; see https://github.com/huggingface/transformers/issues/42489 + if is_peft_model(model) and args.gradient_checkpointing: + model.enable_input_require_grads() + + # When using QLoRA, the PEFT adapter weights are converted to bf16 to follow the recommendations from the + # original paper (see https://huggingface.co/papers/2305.14314, paragraph 3). Normally, this can be done by + # passing `autocast_adapter_dtype=False` to `get_peft_model`, but this option is not yet supported for + # quantized models. See: https://github.com/huggingface/peft/issues/2889 + # Non-quantized models do not have the `is_loaded_in_{8,4}bit` attributes, whereas quantized models do + if getattr(model, "is_loaded_in_4bit", False) or getattr(model, "is_loaded_in_8bit", False): + for param in model.parameters(): + if param.requires_grad: + param.data = param.data.to(torch.bfloat16) + + # In Prompt Tuning a small set of trainable virtual tokens (continuous prompt embeddings) is prepended to the + # input. We store the number of these tokens so we can account for them correctly when calculating accuracy. + self.num_virtual_tokens = 0 + if is_peft_model(model): + if model.active_adapter in model.peft_config: + peft_model_config = model.peft_config[model.active_adapter] + self.num_virtual_tokens = getattr(peft_model_config, "num_virtual_tokens", 0) + + # Data collator + # BFD packing requires padding-free mode; otherwise, the collator outputs padded attention masks, causing + # FlashAttention to ignore position_ids and recompute them incorrectly from the padded attention mask. + self.padding_free = args.padding_free or (args.packing and args.packing_strategy in {"bfd", "bfd_split"}) + use_flash_attention = model.config._attn_implementation in FLASH_ATTENTION_VARIANTS + if self.padding_free: + if data_collator is not None: + raise ValueError("Passing a custom data collator is not supported when using padding-free.") + if args.packing and args.packing_strategy == "wrapped": + logger.warning( + "You are passing `padding_free=True` with the 'wrapped' packing strategy, which is not " + "recommended. Please refer to the documentation to understand why this is not recommended." + ) + if not use_flash_attention: + logger.warning( + "Padding-free training is enabled, but the attention implementation is not set to a supported " + "Flash Attention variant. Padding-free training flattens batches into a single sequence, and only " + "the following implementations are known to reliably support this: " + f"{', '.join(sorted(FLASH_ATTENTION_VARIANTS))}. Using other implementations may lead to " + "unexpected behavior. To ensure compatibility, set `attn_implementation` in the model " + "configuration to one of these supported options or verify that your attention mechanism can " + "handle flattened sequences." + ) + + if args.per_device_train_batch_size == 1 and not args.packing: + logger.warning( + "You are using a per_device_train_batch_size of 1 with padding-free training. Using a batch size " + "of 1 annihilate the benefits of padding-free training. Please consider increasing the batch size " + "to at least 2." + ) + + # Decide whether to use completion-only loss: if not specified, then it is set to True if the dataset format + # is prompt-completion, and False if the dataset format is language modeling. + dataset_sample = next(iter(train_dataset)) + if args.completion_only_loss is None: + self.completion_only_loss = "prompt" in dataset_sample and "completion" in dataset_sample + else: + self.completion_only_loss = args.completion_only_loss + + self._is_vision_dataset = "image" in dataset_sample or "images" in dataset_sample + if self._is_vision_dataset and not self._is_vlm: + raise ValueError( + "The dataset appears to be vision-related (contains 'image' or 'images' keys), but the provided " + "model does not seem to be a vision-language model. Please check your model and dataset." + ) + + if data_collator is None and not self._is_vision_dataset: + # Get the pad token: if not provided, use the one from the processing class or the eos token + # if the processing class does not have a pad token. + pad_token = args.pad_token or self._tokenizer.pad_token or self._tokenizer.eos_token + if pad_token not in self._tokenizer.get_vocab(): + raise ValueError( + f"The specified `pad_token` ('{pad_token}') is not found in the vocabulary of the given " + f"`processing_class` ({processing_class.__class__.__name__}). Ensure that the `pad_token` exists " + "in the vocabulary before using it as a padding token." + ) + self._tokenizer.pad_token = pad_token + data_collator = DataCollatorForLanguageModeling( + pad_token_id=self._tokenizer.pad_token_id, + max_length=None if self.padding_free else args.max_length, + truncation_mode=args.truncation_mode, + completion_only_loss=self.completion_only_loss, + padding_free=self.padding_free, + pad_to_multiple_of=args.pad_to_multiple_of, + ) + elif data_collator is None and self._is_vision_dataset: + data_collator = DataCollatorForVisionLanguageModeling( + processor=processing_class, + max_length=args.max_length, + completion_only_loss=self.completion_only_loss, + pad_to_multiple_of=args.pad_to_multiple_of, + dataset_text_field=args.dataset_text_field, + ) + + if args.packing and args.packing_strategy in {"bfd", "bfd_split"} and not use_flash_attention: + logger.warning( + "You are using packing, but the attention implementation is not set to a supported Flash Attention " + "variant. Packing gathers multiple samples into a single sequence, and only the following " + f"implementations are known to reliably support this: {', '.join(sorted(FLASH_ATTENTION_VARIANTS))}. " + "Using other implementations may lead to cross-contamination between samples. To avoid this, either " + "disable packing by setting `packing=False`, or set `attn_implementation` in the model configuration " + "to one of these supported options." + ) + if args.assistant_only_loss and not is_conversational(dataset_sample): + raise ValueError( + "You set `assistant_only_loss=True`, but the dataset is not conversational. This option is only " + "supported for conversational datasets." + ) + + # When assistant_only_loss is enabled, swap in a training chat template with {% generation %} markers + # if the current template doesn't already have them. + if args.assistant_only_loss and not has_generation_markers(processing_class.chat_template): + self.chat_template = get_training_chat_template(processing_class) + else: + self.chat_template = None + + # A template can define generation markers and still attribute the assistant's end-of-turn token to the next + # message, leaving it out of the assistant mask so the model is never trained to stop. + if args.assistant_only_loss and not is_chat_template_stop_token_trained( + processing_class, chat_template=self.chat_template + ): + logger.warning( + "The chat template does not include the assistant turn's end-of-turn token in the loss mask; " + "the model may not learn to stop." + ) + + # Dataset + if self.padding_free and not args.packing and args.max_length is not None and not self._is_vision_dataset: + raise ValueError( + "When `padding_free=True` without packing, `max_length` is not enforced. Either enable packing " + "(e.g., `packing=True, packing_strategy='bfd'`), provide already truncated inputs, or set " + "`max_length=None`." + ) + # Skip dataset preparation if `skip_prepare_dataset=True` in `dataset_kwargs`, or if it's a VLM, where + # preprocessing (e.g., image-to-pixel conversion) is too costly and done on the fly instead. + skip_prepare_dataset = ( + args.dataset_kwargs is not None + and args.dataset_kwargs.get("skip_prepare_dataset", False) + or self._is_vision_dataset + ) + if not skip_prepare_dataset: + if self.completion_only_loss and formatting_func: + raise ValueError( + "A formatting function was provided while `completion_only_loss=True`, which is incompatible. " + "Using a formatter converts the dataset to a language modeling type, conflicting with " + "completion-only loss. To resolve this, apply your formatting function before passing the " + "dataset, or disable `completion_only_loss` in `SFTConfig`." + ) + train_dataset = self._prepare_dataset( + train_dataset, processing_class, args, args.packing, formatting_func, "train" + ) + if eval_dataset is not None: + packing = args.packing if args.eval_packing is None else args.eval_packing + if isinstance(eval_dataset, dict): + eval_dataset = { + key: self._prepare_dataset(dataset, processing_class, args, packing, formatting_func, key) + for key, dataset in eval_dataset.items() + } + else: + eval_dataset = self._prepare_dataset( + eval_dataset, processing_class, args, packing, formatting_func, "eval" + ) + + # Loss function + if not args.use_liger_kernel: # liger supports dft loss by just passing use_token_scaling=True + if args.loss_type == "nll": + pass # use the default loss + elif args.loss_type == "dft": + if compute_loss_func is not None: + raise ValueError( + "You passed a `compute_loss_func` together with `loss_type='dft'` to the `SFTTrainer`. " + "When using `loss_type='dft'`, the loss function is internally set to the DFT loss, so " + "passing a `compute_loss_func` is not allowed." + ) + compute_loss_func = dft_loss + elif args.loss_type == "chunked_nll": + # Same math as `"nll"` but the `lm_head` matmul is skipped on ignored tokens and the CE is computed in + # chunks of tokens. Implemented by patching the model's forward before `super().__init__` so accelerate + # wraps the patched forward. + # For PEFT, patch the inner causal LM rather than the `PeftModel` wrapper. LoRA / IA³ / + # `modules_to_save` adapters live in the module tree, so they're hit even when we bypass + # `PeftModel.forward`. Prompt-learning variants need `PeftModel.forward` to run first (to inject + # virtual tokens), then it delegates into the patched inner forward. + target = model.get_base_model() if is_peft_model(model) else model + # The chunked path reads the output projection weight directly, which would silently drop the + # adapter delta (and starve its parameters of gradients) if the head itself is a PEFT tuner layer. + if is_peft_model(model): + from peft.tuners.tuners_utils import BaseTunerLayer + + if isinstance(target.get_output_embeddings(), BaseTunerLayer): + raise ValueError( + "`loss_type='chunked_nll'` is not supported when `lm_head` is wrapped by a PEFT adapter " + "(e.g. `target_modules='all-linear'` or explicitly including `'lm_head'`). Either remove " + "`lm_head` from `target_modules`, or switch to `loss_type='nll'`. If this is a real use " + "case for you, please open an issue at https://github.com/huggingface/trl/issues." + ) + _patch_chunked_ce_lm_head( + target, chunk_size=_CHUNKED_LM_HEAD_CHUNK_SIZE, is_vlm=self._is_vlm, with_peft=is_peft_model(model) + ) + else: + raise ValueError( + f"Invalid `loss_type` {args.loss_type} passed. Supported values are 'nll', 'dft', and " + "'chunked_nll'." + ) + elif args.loss_type == "chunked_nll": + raise ValueError("`loss_type='chunked_nll'` is not compatible with `use_liger_kernel=True`.") + + # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was + # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream + # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we + # default to the recommended non-reentrant behavior here, while preserving any user-provided value. + if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"): + args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {} + args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False) + + super().__init__( + model=model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + compute_loss_func=compute_loss_func, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + optimizer_cls_and_kwargs=optimizer_cls_and_kwargs, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + ) + + # Initialize activation offloading context + if self.args.activation_offloading: + self.maybe_activation_offload_context = get_act_offloading_ctx_manager(model=self.model) + else: + self.maybe_activation_offload_context = contextlib.nullcontext() + + self.aux_loss_enabled = getattr(model.config, "output_router_logits", False) + + # Under FSDP2 with `reshard_after_forward=True` (accelerate's default), the chunked CE path triggers a + # redundant `lm_head.weight` all-gather per chunk during backward, adding significant wall-time. Setting + # `reshard_after_forward=False` keeps the un-wrapped `lm_head` resident and closes the gap without meaningfully + # affecting peak memory. + # `AcceleratorState.is_fsdp2` was added in accelerate 1.6.0; guard so older (but still-supported) versions + # don't `AttributeError` on every SFTTrainer init. + if ( + args.loss_type == "chunked_nll" + and Version(accelerate.__version__) >= Version("1.6.0") + and self.accelerator.state.is_fsdp2 + and self.accelerator.state.fsdp_plugin.reshard_after_forward + ): + logger.warning( + "`loss_type='chunked_nll'` under FSDP2 with `reshard_after_forward=True` is significantly slower than " + "necessary due to per-chunk all-gathers of `lm_head.weight`. Consider passing " + "`--fsdp_reshard_after_forward false` to `accelerate launch` (or equivalent in your FSDP config)." + ) + + # Initialize the metrics + self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)} + self._total_train_tokens = 0 + + # Add tags to the model + self.model.add_model_tags(self._tag_names) + + def _tokenize( + self, + processing_class: PreTrainedTokenizerBase | ProcessorMixin, + input: str | list, + **kwargs, + ) -> dict[str, list]: + """Tokenize a single example for dataset preprocessing. + + Dispatches to `apply_chat_template` for conversational input (list of message dicts) and to `__call__` for + non-conversational input (str). For VLMs, normalizes the batch dimension that processors emit even for single + examples. + + Args: + processing_class ([`~transformers.PreTrainedTokenizerBase`] or [`~transformers.ProcessorMixin`]): + The tokenizer or processor to use. + input (`str` or `list`): + A string for non-conversational input, or a list of message dicts for conversational input. + **kwargs: + Forwarded to `apply_chat_template` (e.g. `add_generation_prompt`, `return_assistant_tokens_mask`). + + Returns: + `dict` with at least an `"input_ids"` key mapping to a flat `list[int]`. + """ + if isinstance(input, list): # conversational: list of message dicts + if self._is_vlm: + input = prepare_multimodal_messages(input) + result = processing_class.apply_chat_template( + input, tokenize=True, return_dict=True, chat_template=self.chat_template, **kwargs + ) + else: # non-conversational: plain text string + result = processing_class(text=input) + # VLMs emit a batch dimension even for single examples; unwrap it + if self._is_vlm: + return {k: v[0] for k, v in result.items()} + return result + + def _prepare_dataset( + self, + dataset: Dataset | IterableDataset, + processing_class: PreTrainedTokenizerBase | ProcessorMixin, + args: SFTConfig, + packing: bool, + formatting_func: Callable[[dict], str] | None, + dataset_name: str, + ) -> Dataset | IterableDataset: + if isinstance(dataset, Dataset) and dataset.format["type"] == "custom": + raise ValueError( + "SFTTrainer cannot prepare a dataset that uses `Dataset.with_transform()`. The preparation pipeline " + "calls `Dataset.map()`, which reads through the transform and can bake a random or stateful transform " + "into the tokenized columns. Pass `dataset_kwargs={'skip_prepare_dataset': True}` and make the " + "transform return trainer-ready examples, including tokenized fields, or materialize deterministic " + "transforms with `Dataset.map()` before constructing the trainer." + ) + + # If the dataset is already preprocessed (tokenized), skip the processing steps. + column_names = get_dataset_column_names(dataset) + is_processed = "input_ids" in column_names + + # Build the kwargs for the `map` function + map_kwargs = {} + if isinstance(dataset, Dataset): # IterableDataset does not support num_proc + map_kwargs["num_proc"] = args.dataset_num_proc + + with PartialState().main_process_first(): + # Apply the formatting function if any + if formatting_func is not None and is_processed: + logger.warning( + "You passed a dataset that is already processed (contains an `input_ids` field) together with a " + "formatting function. Therefore `formatting_func` will be ignored. Either remove the " + "`formatting_func` or pass a dataset that is not already processed.", + ) + + if formatting_func is not None and not is_processed: + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Applying formatting function to {dataset_name} dataset" + + def _func(example): + return {"text": formatting_func(example)} + + dataset = dataset.map(_func, batched=False, **map_kwargs) + + if not is_processed: + # Convert the dataset to ChatML if needed + first_example = next(iter(dataset)) + if is_conversational_from_value(first_example): + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Converting {dataset_name} dataset to ChatML" + column_names = get_dataset_column_names(dataset) + dataset = dataset.map( + maybe_convert_to_chatml, + remove_columns="conversations" if "conversations" in column_names else None, + **map_kwargs, + ) + + # Add EOS token if needed: non-conversational only + first_example = next(iter(dataset)) + if not is_conversational(first_example): + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Adding EOS to {dataset_name} dataset" + + def add_eos(example, eos_token): + if "text" in example and not example["text"].endswith(eos_token): # language modeling case + example["text"] = example["text"] + eos_token + elif "completion" in example and not example["completion"].endswith(eos_token): + example["completion"] = example["completion"] + eos_token + return example + + dataset = dataset.map( + add_eos, + fn_kwargs={"eos_token": self._tokenizer.eos_token}, + remove_columns="messages" if "messages" in column_names else None, # renamed to "text" + **map_kwargs, + ) + + # Tokenize the dataset + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Tokenizing {dataset_name} dataset" + + def tokenize_fn(example, processing_class, dataset_text_field, assistant_only_loss): + tools = example.get("tools") + tools = json.loads(tools) if isinstance(tools, str) else tools + if "prompt" in example: # prompt-completion case + output = {} + if is_conversational(example): + prompt_ids = self._tokenize( + processing_class, + example["prompt"], + tools=tools, + add_generation_prompt=True, + **example.get("chat_template_kwargs", {}), + )["input_ids"] + prompt_completion_processed = self._tokenize( + processing_class, + example["prompt"] + example["completion"], + tools=tools, + return_assistant_tokens_mask=assistant_only_loss, + **example.get("chat_template_kwargs", {}), + ) + prompt_completion_ids = prompt_completion_processed["input_ids"] + if "assistant_masks" in prompt_completion_processed: + output["assistant_masks"] = prompt_completion_processed["assistant_masks"] + else: + prompt_ids = self._tokenize(processing_class, example["prompt"])["input_ids"] + prompt_completion_ids = self._tokenize( + processing_class, example["prompt"] + example["completion"] + )["input_ids"] + + # Check if the tokenized prompt starts with the tokenized prompt+completion + if not prompt_completion_ids[: len(prompt_ids)] == prompt_ids: + logger.warning( + "Mismatch between tokenized prompt and the start of tokenized prompt+completion. " + "This may be due to unexpected tokenizer behavior, whitespace issues, or special " + "token handling. Verify that the tokenizer is processing text consistently." + ) + + # Create completion mask + completion_mask = [0] * len(prompt_ids) + [1] * (len(prompt_completion_ids) - len(prompt_ids)) + output["input_ids"] = prompt_completion_ids + output["completion_mask"] = completion_mask + + else: # language modeling case + if is_conversational(example): + processed = self._tokenize( + processing_class, + example["messages"], + tools=tools, + return_assistant_tokens_mask=assistant_only_loss, + **example.get("chat_template_kwargs", {}), + ) + output = {k: processed[k] for k in ("input_ids", "assistant_masks") if k in processed} + else: + output = { + "input_ids": self._tokenize(processing_class, example[dataset_text_field])["input_ids"] + } + + if "assistant_masks" in output and 1 not in output["assistant_masks"]: + raise RuntimeError( + "You're using `assistant_only_loss=True`, but at least one example has no assistant " + "tokens. This usually means the tokenizer's chat template doesn't generate assistant " + "masks — it may be missing the `{% generation %}` keyword. Please check the template and " + "ensure it's correctly configured to support assistant masking." + ) + return output + + dataset = dataset.map( + tokenize_fn, + fn_kwargs={ + "processing_class": processing_class, + "dataset_text_field": args.dataset_text_field, + "assistant_only_loss": args.assistant_only_loss, + }, + **map_kwargs, + ) + + # Pack + if packing: + if args.max_length is None: + raise ValueError("When packing is enabled, `max_length` can't be `None`.") + if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc` + map_kwargs["desc"] = f"Packing {dataset_name} dataset" + + columns = ["input_ids"] + if "completion_mask" in get_dataset_column_names(dataset): + columns.append("completion_mask") + if "assistant_masks" in get_dataset_column_names(dataset): + columns.append("assistant_masks") + + dataset = dataset.select_columns(columns) + + # Shuffle the dataset before packing. When using wrapped packing, it's important to shuffle before + # packing as well to avoid correlations between sequences packed together. + if args.shuffle_dataset: + dataset = dataset.shuffle(seed=args.seed) + + # Packing adds new column "seq_lengths" needed for document aware FlashAttention + dataset = pack_dataset(dataset, args.max_length, args.packing_strategy, map_kwargs) + # For Liger kernel, ensure only the essential columns + if args.use_liger_kernel: + collator_expected_keys = {"input_ids", "seq_lengths", "completion_mask", "assistant_masks"} + column_names = get_dataset_column_names(dataset) + dataset = dataset.select_columns(collator_expected_keys.intersection(column_names)) + + if args.shuffle_dataset: + dataset = dataset.shuffle(seed=args.seed) + + return dataset + + def _set_signature_columns_if_needed(self): + # If `self.args.remove_unused_columns` is True, non-signature columns are removed. + # By default, this method sets `self._signature_columns` to the model's expected inputs (usually, "input_ids" + # and "attention_mask"). When using `train_on_completion_only` we add a "completion_mask" column to the + # dataset. So we need to override the default signature columns to include "completion_mask" as well. + if self._signature_columns is None: + if self._is_vision_dataset: + self._signature_columns = ["messages", "prompt", "completion", "image", "images"] + else: + self._signature_columns = ["input_ids", "labels", "seq_lengths", "completion_mask", "assistant_masks"] + + def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): + mode = "train" if self.model.training else "eval" + prediction_loss_only = inputs.pop("_prediction_loss_only", None) + + # Set aside labels as it will be dropped by super().compute_loss() if a custom `compute_loss_func` is used. + # This can be removed when this issue is fixed. + # When using CP or SP, labels are pre-shifted, we must use shift_labels instead. + labels = inputs["labels"] if "shift_labels" not in inputs else None + + # If not set, defaults from model config and may warn since cache isn't compatible with gradient checkpointing + inputs["use_cache"] = False + + # Request token accuracy from Liger kernel and set token scaling if using DFT loss + if self.args.use_liger_kernel: + # Avoid materializing full logits during eval unless explicitly needed. + # By default, liger kernel only skips logits during training (self.training=True). + # When only loss is needed for eval (no compute_metrics), we can safely skip logits. + # prediction_step communicates whether logits are expected via `_prediction_loss_only`; + # this prevents skipping logits during `predict()` where outputs are requested. + # Keep logits when preprocess_logits_for_metrics is set, even if compute_metrics is None. + # to prevent massive vRAM spikes from the lm_head projection. + # See: https://github.com/huggingface/trl/issues/4679 + inputs["skip_logits"] = ( + self.model.training + or self.args.prediction_loss_only + or ( + self.compute_metrics is None + and self.preprocess_logits_for_metrics is None + and prediction_loss_only is not False + ) + ) + inputs["return_token_accuracy"] = True + inputs["use_token_scaling"] = self.args.loss_type == "dft" + + try: + (loss, outputs) = super().compute_loss( + model, inputs, return_outputs=True, num_items_in_batch=num_items_in_batch + ) + except ValueError as e: + if "Image features and image tokens do not match" in str(e) and self.args.max_length is not None: + raise ValueError( + f"The current `max_length` ({self.args.max_length}) is too short and causes image placeholder " + f"tokens in `input_ids` to be truncated, while the corresponding image features remain intact. " + f"Please increase `max_length` or set it to `None` to disable truncation." + ) from e + raise + + # Compute entropy + if self.args.loss_type == "chunked_nll": + # Use `num_valid_tokens` from the patched forward rather than recomputing from `labels`. Prompt-learning + # PEFT (PromptTuning, P-Tuning) prepends `-100`-padded virtual tokens before delegating into the patched + # forward, so the valid-token count over the padded labels can differ from the un-padded `labels[..., 1:]` + # count by up to one per sequence; using the patched output keeps numerator and denominator aligned. + num_valid = self.accelerator.gather_for_metrics(outputs.num_valid_tokens).sum() + entropy_sum = self.accelerator.gather_for_metrics(outputs.entropy_sum).sum() + entropy = (entropy_sum / num_valid).item() if num_valid > 0 else 0.0 + self._metrics[mode]["entropy"].append(entropy) + elif not self.args.use_liger_kernel: # liger doesn't return logits + with torch.no_grad(): + if "shift_labels" in inputs: + # When using CP or SP, labels are pre-shifted. + shift_logits = outputs.logits + shift_labels = inputs["shift_labels"] + else: + shift_logits = outputs.logits[..., :-1, :] + shift_labels = labels[..., 1:] + + # Prompt Tuning and P-Tuning output logits for virtual tokens but Prefix-Tuning does not. + if ( + self.num_virtual_tokens > 0 + and model.peft_config[model.active_adapter].peft_type != PeftType.PREFIX_TUNING + ): + shift_logits = shift_logits[:, self.num_virtual_tokens :, :] + + per_token_entropy = entropy_from_logits(shift_logits) + predictions = shift_logits.argmax(dim=-1) + mask = shift_labels != -100 + + entropy_sum = (per_token_entropy * mask).sum() + total_tokens = mask.sum() + correct_predictions = (predictions == shift_labels) & mask + correct_tokens = correct_predictions.sum() + + # Gather counts across ranks and weight-average + entropy_sum = self.accelerator.gather_for_metrics(entropy_sum).sum() + total_tokens = self.accelerator.gather_for_metrics(total_tokens).sum() + correct_tokens = self.accelerator.gather_for_metrics(correct_tokens) + entropy = (entropy_sum / total_tokens).item() if total_tokens > 0 else 0.0 + + total_sum = total_tokens.sum() + accuracy = (correct_tokens.sum() / total_sum).item() if total_sum > 0 else 0.0 + self._metrics[mode]["entropy"].append(entropy) + self._metrics[mode]["mean_token_accuracy"].append(accuracy) + + if mode == "train": + # When using padding-free, the attention_mask is not present in the inputs, instead we have cu_seq_lens_q, + # cu_seq_lens_k, and max_length_k, max_length_q and position_ids. + if "attention_mask" in inputs: + num_tokens_in_batch = self.accelerator.gather_for_metrics(inputs["attention_mask"].sum()).sum().item() + elif "position_ids" in inputs: + local_num_tokens = torch.tensor(inputs["position_ids"].size(1), device=inputs["position_ids"].device) + num_tokens_in_batch = self.accelerator.gather_for_metrics(local_num_tokens).sum().item() + else: + raise ValueError("Expected 'attention_mask' or 'position_ids' in inputs.") + self._total_train_tokens += num_tokens_in_batch + self._metrics[mode]["num_tokens"] = [self._total_train_tokens] + + if self.args.loss_type == "chunked_nll": + correct = self.accelerator.gather_for_metrics(outputs.num_correct_tokens).sum() + accuracy = (correct / num_valid).item() if num_valid > 0 else 0.0 + self._metrics[mode]["mean_token_accuracy"].append(accuracy) + elif self.args.use_liger_kernel: + if hasattr(outputs, "token_accuracy") and outputs.token_accuracy is not None: + token_accuracy = self.accelerator.gather_for_metrics(outputs.token_accuracy).mean().item() + self._metrics[mode]["mean_token_accuracy"].append(token_accuracy) + else: + warnings.warn( + "liger-kernel did not return token_accuracy when requested. The mean_token_accuracy metric will " + "not be logged. This is unexpected; please report it to the liger-kernel repository.", + stacklevel=2, + ) + # Log auxiliary loss if enabled (applies to both Liger and non-Liger) + if self.aux_loss_enabled: + aux_loss = outputs.aux_loss + aux_loss = self.accelerator.gather_for_metrics(aux_loss).mean().item() + self._metrics[mode]["aux_loss"].append(aux_loss) + + return (loss, outputs) if return_outputs else loss + + def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys=None): + # Preserve the eval loop intent so compute_loss can decide whether logits are needed. + inputs["_prediction_loss_only"] = prediction_loss_only + return super().prediction_step(model, inputs, prediction_loss_only, ignore_keys=ignore_keys) + + # Override training step to add activation offloading context. + def training_step(self, *args, **kwargs): + with self.maybe_activation_offload_context: + return super().training_step(*args, **kwargs) + + def log(self, logs: dict[str, float], start_time: float | None = None) -> None: + mode = "train" if self.model.training else "eval" + metrics = {key: sum(val) / len(val) for key, val in self._metrics[mode].items()} # average the metrics + + # This method can be called both in training and evaluation. When called in evaluation, the keys in `logs` + # start with "eval_". We need to add the prefix "eval_" to the keys in `metrics` to match the format. + if mode == "eval": + metrics = {f"eval_{key}": val for key, val in metrics.items()} + + logs.update(metrics) + super().log(logs, start_time) + self._metrics[mode].clear() + + # Ensure the model card is saved along with the checkpoint + def _save_checkpoint(self, model, trial): + if self.args.hub_model_id is None: + model_name = Path(self.args.output_dir).name + else: + model_name = self.args.hub_model_id.split("/")[-1] + self.create_model_card(model_name=model_name) + super()._save_checkpoint(model, trial) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/utils.py b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3712e506dd09e64b2a518b4229fd5df66e3ab851 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/source/trl/trainer/utils.py @@ -0,0 +1,1456 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import asyncio +import hashlib +import importlib.resources as pkg_resources +import os +import random +import socket +import threading +import types +from collections.abc import Mapping, Sequence, Sized +from contextlib import contextmanager +from importlib.metadata import version +from itertools import accumulate +from typing import TypeVar + +import numpy as np +import pandas as pd +import torch +import torch.nn.functional as F +import transformers +from accelerate import PartialState, logging +from huggingface_hub import ModelCard, ModelCardData +from packaging.version import Version +from torch.utils.data import Sampler +from transformers import ( + AutoConfig, + BitsAndBytesConfig, + PretrainedConfig, + PreTrainedModel, + is_comet_available, + is_trackio_available, +) +from transformers.models.auto.auto_factory import _BaseAutoModelClass +from transformers.utils import ( + is_peft_available, + is_rich_available, + is_torch_xpu_available, +) + +from ..trainer.model_config import ModelConfig + + +if is_rich_available(): + from rich.console import Console + from rich.panel import Panel + from rich.table import Table + from rich.text import Text + +if is_comet_available(): + import comet_ml + +if is_peft_available(): + from peft import LoraConfig, PeftConfig, PeftModel + + +logger = logging.get_logger(__name__) + + +def _is_port_free(port: int, host: str = "127.0.0.1") -> bool: + try: + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + s.bind((host, port)) + return True + except OSError: + return False + + +def _find_free_port() -> int: + candidates = (29500, 23456, 12355, 12345) + for p in candidates: + if _is_port_free(p): + return p + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.bind(("", 0)) + return s.getsockname()[1] + + +def ensure_master_addr_port(addr: str | None = None, port: int | None = None) -> None: + """ + Ensure `MASTER_ADDR`/`MASTER_PORT` are set safely. + + - Respects existing environment variables. + - Defaults `MASTER_ADDR` to localhost if unset. + - Chooses a free TCP port if `MASTER_PORT` is unset to avoid collisions. + - If `MASTER_PORT` is set to `"0"` or `"auto"`, it is resolved to a free port. + """ + os.environ["MASTER_ADDR"] = os.environ.get("MASTER_ADDR") or addr or "localhost" + + env_port = os.environ.get("MASTER_PORT", "").strip().lower() + if port is None and env_port not in {"", "0", "auto"}: + try: + port = int(env_port) + except ValueError: + pass + + os.environ["MASTER_PORT"] = str(_find_free_port() if port in (None, 0) else port) + + +def pad( + tensors: list[torch.Tensor], + padding_value: int = 0, + padding_side: str = "right", + pad_to_multiple_of: int | None = None, +) -> torch.Tensor: + """ + Pads a list of tensors to the same shape along the first dimension. + + Args: + tensors (`list[torch.Tensor]`): + List of input tensors to pad. + padding_value (`int`): + Value to use for padding. Default is 0. + padding_side (`str`): + Side on which to add padding. Must be 'left' or 'right'. Default is 'right'. + pad_to_multiple_of (`int`, *optional*): + If set will pad the sequence to a multiple of the provided value. + + Returns: + `torch.Tensor`: + A single tensor containing the padded tensors. + + Examples: + ```python + >>> import torch + + >>> pad([torch.tensor([1, 2, 3]), torch.tensor([4, 5])]) + tensor([[1, 2, 3], + [4, 5, 0]]) + + >>> pad([torch.tensor([[1, 2], [3, 4]]), torch.tensor([[5, 6]])]) + tensor([[[1, 2], + [3, 4]], + [[5, 6], + [0, 0]]]) + ``` + """ + # Determine the maximum shape for each dimension + output_shape = np.max([t.shape for t in tensors], 0).tolist() + + # Apply pad_to_multiple_of to the first (sequence) dimension + if pad_to_multiple_of is not None: + remainder = output_shape[0] % pad_to_multiple_of + if remainder != 0: + output_shape[0] += pad_to_multiple_of - remainder + + # Create an output tensor filled with the padding value + output = torch.full((len(tensors), *output_shape), padding_value, dtype=tensors[0].dtype, device=tensors[0].device) + + for i, t in enumerate(tensors): + if padding_side == "left": + seq_start = output_shape[0] - t.shape[0] + elif padding_side == "right": + seq_start = 0 + else: + raise ValueError("padding_side must be 'left' or 'right'") + + # Define the slices + seq_slice = slice(seq_start, seq_start + t.shape[0]) + slices = (seq_slice,) + tuple(slice(0, s) for s in t.shape[1:]) + output[i][slices] = t + + return output + + +def disable_dropout_in_model(model: torch.nn.Module) -> None: + for module in model.modules(): + if isinstance(module, torch.nn.Dropout): + module.p = 0 + + +def get_quantization_config(model_args: ModelConfig) -> BitsAndBytesConfig | None: + if model_args.load_in_4bit: + quantization_config = BitsAndBytesConfig( + load_in_4bit=True, + bnb_4bit_compute_dtype=model_args.dtype, # For consistency with model weights, we use the same value as `dtype` + bnb_4bit_quant_type=model_args.bnb_4bit_quant_type, + bnb_4bit_use_double_quant=model_args.use_bnb_nested_quant, + bnb_4bit_quant_storage=model_args.bnb_4bit_quant_storage, + ) + elif model_args.load_in_8bit: + quantization_config = BitsAndBytesConfig( + load_in_8bit=True, + ) + else: + quantization_config = None + + return quantization_config + + +def get_kbit_device_map() -> dict[str, int] | None: + if torch.cuda.is_available() or is_torch_xpu_available(): + return {"": PartialState().local_process_index} + else: + return None + + +def get_peft_config(model_args: ModelConfig) -> "PeftConfig | None": + if model_args.use_peft is False: + return None + + if not is_peft_available(): + raise ValueError( + "You need to have PEFT library installed in your environment, make sure to install `peft`. " + "Make sure to run `pip install -U peft`." + ) + + peft_config = LoraConfig( + task_type=model_args.lora_task_type, + r=model_args.lora_r, + target_modules=model_args.lora_target_modules, + target_parameters=model_args.lora_target_parameters, + lora_alpha=model_args.lora_alpha, + lora_dropout=model_args.lora_dropout, + bias="none", + use_rslora=model_args.use_rslora, + use_dora=model_args.use_dora, + modules_to_save=model_args.lora_modules_to_save, + ) + + return peft_config + + +def generate_model_card( + base_model: str | None, + model_name: str, + hub_model_id: str, + dataset_name: str | None, + tags: list[str], + wandb_url: str | None, + trackio_url: str | None, + trainer_name: str, + trainer_citation: str | None = None, + template_file: str | None = None, + paper_title: str | None = None, + paper_id: str | None = None, + comet_url: str | None = None, +) -> ModelCard: + """ + Generate a [`~huggingface_hub.ModelCard`] from a template. + + Args: + base_model (`str` or `None`): + Base model name. + model_name (`str`): + Model name. + hub_model_id (`str`): + Hub model ID as `username/model_id`. + dataset_name (`str` or `None`): + Dataset name. + tags (`list[str]`): + Tags. + wandb_url (`str` or `None`): + Weights & Biases run URL. + trackio_url (`str` or `None`): + Trackio Space URL. + comet_url (`str` or `None`): + Comet experiment URL. + trainer_name (`str`): + Trainer name. + trainer_citation (`str` or `None`, defaults to `None`): + Trainer citation as a BibTeX entry. + template_file (`str` *optional*): + Template file name located in the `trl/templates` directory. Defaults to `lm_model_card.md`. + paper_title (`str` or `None`, defaults to `None`): + Paper title. + paper_id (`str` or `None`, defaults to `None`): + ArXiv paper ID as `YYMM.NNNNN`. + + Returns: + [`~huggingface_hub.ModelCard`]: + A ModelCard object. + """ + card_data = ModelCardData( + base_model=base_model, + datasets=dataset_name, + library_name="transformers", + licence="license", + model_name=model_name, + tags=["generated_from_trainer", *tags], + ) + template_file = template_file or "lm_model_card.md" + card = ModelCard.from_template( + card_data, + template_path=str(pkg_resources.files("trl").joinpath(f"templates/{template_file}")), + base_model=base_model, + model_name=model_name, + hub_model_id=hub_model_id, + dataset_name=dataset_name, + wandb_url=wandb_url, + trackio_url=trackio_url, + comet_url=comet_url, + trainer_name=trainer_name, + trainer_citation=trainer_citation, + paper_title=paper_title, + paper_id=paper_id, + trl_version=version("trl"), + transformers_version=version("transformers"), + pytorch_version=version("torch"), + datasets_version=version("datasets"), + tokenizers_version=version("tokenizers"), + ) + return card + + +def get_comet_experiment_url() -> str | None: + """ + If Comet integration is enabled, return the URL of the current Comet experiment; otherwise, return `None`. + """ + if not is_comet_available(): + return None + + if comet_ml.get_running_experiment() is not None: + return comet_ml.get_running_experiment().url + + return None + + +def get_trackio_space_url() -> str | None: + """ + If Trackio integration is enabled, return the URL of the current Trackio Space; otherwise, return `None`. + """ + if not is_trackio_available(): + return None + + from trackio import context_vars + + run = context_vars.current_run.get() + if run is None: + return None + space_id = run._space_id + if space_id is None: + return None + space_id = space_id.replace("/", "-") + project = run.project + name = run.name + return f"https://{space_id}.hf.space?project={project}&runs={name}&sidebar=collapsed" + + +def log_table_to_comet_experiment(name: str, table: pd.DataFrame) -> None: + """ + If Comet integration is enabled logs a table to the Comet experiment if it is currently running. + + Args: + name (`str`): + Table name. + table (`pandas.DataFrame`): + The Pandas DataFrame containing the table to log. + """ + if not is_comet_available(): + raise ModuleNotFoundError("The comet-ml is not installed. Please install it first: pip install comet-ml") + + experiment = comet_ml.get_running_experiment() + if experiment is not None: + experiment.log_table(tabular_data=table, filename=name) + + +def flush_left(mask: torch.Tensor, *tensors: torch.Tensor) -> torch.Tensor | tuple[torch.Tensor, ...]: + """ + Shift non-zero elements in the mask and corresponding tensors to the left. + + This function operates on a binary mask and any number of additional tensors with the same dimensions as the mask. + For each row, non-zero values are shifted to the leftmost positions. Then, columns that contain only zeros across + all rows are truncated from the mask and tensors. Visually, this operation can be represented as follows: + + ``` + [[0, 0, x, x, x, x], -> [[x, x, x, x], + [0, x, x, x, 0, 0]] [x, x, x, 0]] + ``` + + Args: + mask (`torch.Tensor`): + 2D tensor (binary mask) with shape `(N, M)`. + *tensors (`torch.Tensor`): + One or more 2D tensors with the same shape as `mask`. These tensors will be processed alongside `mask`, + with non-zero values shifted and excess zero columns truncated in the same manner. + + Returns: + `torch.Tensor`: + Updated binary mask with non-zero values flushed to the left and trailing zero columns removed. + `*torch.Tensor` + Updated tensors, processed in the same way as the mask. + + Example: + ```python + >>> mask = torch.tensor([[0, 0, 1, 1, 1], [0, 1, 1, 0, 0]]) + >>> tensor = torch.tensor([[9, 9, 2, 3, 4], [9, 5, 6, 9, 9]]) + >>> new_mask, new_tensor = flush_left(mask, tensor) + >>> print(new_mask) + tensor([[1, 1, 1], + [1, 1, 0]]) + + >>> print(new_tensor) + tensor([[2, 3, 4], + [5, 6, 0]]) + ``` + """ + _, M = mask.shape + + # Create copy of mask and tensors + mask_copy = mask.clone() + tensors = [t.clone() for t in tensors] + + # Shift non-zero values to the left + first_non_zero = mask_copy.argmax(dim=1) + pos = torch.arange(M, device=mask_copy.device).unsqueeze(0) + idx_roll = (pos + first_non_zero.unsqueeze(1)) % M + mask_roll = mask_copy.gather(1, idx_roll) + rolled_tensors = [t.gather(1, idx_roll) for t in tensors] + + # Truncate trailing columns that are all zeros in mask_roll + col_sums = mask_roll.sum(dim=0) + empty_cols = col_sums == 0 + first_empty_col = int(empty_cols.to(torch.int8).argmax()) if empty_cols.any() else M + flushed_mask = mask_roll[:, :first_empty_col] + flushed_tensors = [t[:, :first_empty_col] for t in rolled_tensors] + + if not flushed_tensors: + return flushed_mask + return flushed_mask, *flushed_tensors + + +def selective_log_softmax(logits, index) -> torch.Tensor: + """ + A memory-efficient implementation of the common `log_softmax -> gather` operation. + + This function is equivalent to the following naive implementation: + ```python + # for index with shape (...): + logps = torch.gather(logits.log_softmax(-1), dim=-1, index=index.unsqueeze(-1)).squeeze(-1) + # for index with shape (..., K): + logps = torch.gather(logits.log_softmax(-1), dim=-1, index=index) + ``` + + Args: + logits (`torch.Tensor`): + Logits tensor of shape `(..., num_classes)`. + index (`torch.Tensor`): + Index tensor of shape `(..., K)` or `(...)`, specifying the positions to gather from the log-softmax + output. When the last case is used, `K` log-probabilities are gathered per position (e.g. for top-K) + + Returns: + `torch.Tensor`: + Gathered log probabilities with the same shape as `index`. + """ + squeeze = index.ndim == logits.ndim - 1 + if squeeze: + index = index.unsqueeze(-1) + + if logits.dtype in [torch.float32, torch.float64]: + selected_logits = torch.gather(logits, dim=-1, index=index) + # loop to reduce peak mem consumption + logsumexp_values = torch.stack([torch.logsumexp(lg, dim=-1) for lg in logits]) + per_token_logps = selected_logits - logsumexp_values.unsqueeze(-1) # log_softmax(x_i) = x_i - logsumexp(x) + else: + # logsumexp approach is unstable with bfloat16, fall back to slightly less efficient approach + per_token_logps = [] + for row_logits, row_labels in zip(logits, index, strict=True): # loop to reduce peak mem consumption + row_logps = F.log_softmax(row_logits, dim=-1) + row_per_token_logps = row_logps.gather(dim=-1, index=row_labels) + per_token_logps.append(row_per_token_logps) + per_token_logps = torch.stack(per_token_logps) + + if squeeze: + per_token_logps = per_token_logps.squeeze(-1) + + return per_token_logps + + +def entropy_from_logits(logits: torch.Tensor, chunk_size: int = 128) -> torch.Tensor: + """ + Compute the Shannon entropy (in nats) for each row of *logits* in a memory-efficient way. + + Instead of materializing the full softmax for all rows at once, the logits are flattened to shape (N, num_classes), + where N is the product of all leading dimensions. Computation is then performed in chunks of size `chunk_size` + along this flattened dimension, reducing peak memory usage. The result is reshaped back to match the input's + leading dimensions. + + Args: + logits (`torch.Tensor`): + Logits tensor of shape `(..., num_classes)`. Entropy is taken along the last axis; all leading dimensions + are preserved in the output. + chunk_size (`int`, *optional*, defaults to `128`): + Number of rows from the flattened logits to process per iteration. Smaller values reduce memory usage at + the cost of more iterations. + + Returns: + `torch.Tensor`: + Entropy values with shape `logits.shape[:-1]`. + """ + original_shape = logits.shape[:-1] # all dims except num_classes + num_classes = logits.shape[-1] + + # Flatten all leading dimensions into one + flat_logits = logits.reshape(-1, num_classes) + + entropies = [] + for chunk in flat_logits.split(chunk_size, dim=0): + logps = F.log_softmax(chunk, dim=-1) + chunk_entropy = -(torch.exp(logps) * logps).sum(-1) + entropies.append(chunk_entropy) + + entropies = torch.cat(entropies, dim=0) + return entropies.reshape(original_shape) + + +def print_prompt_completions_sample( + prompts: list, + completions: list, + rewards: dict[str, list[float]], + advantages: list[float], + step: int, + num_samples: int = None, + extra: dict[str, list] | None = None, +) -> None: + """ + Print out a sample of model completions to the console with multiple reward metrics. + + This function creates a nicely formatted table showing prompt-completion pairs, useful for monitoring model outputs + during training. It requires the `rich` library to be installed. + + Args: + prompts (`list`): + List of prompts. Can be either strings or lists of messages. + completions (`list`): + List of completions corresponding to the prompts. Can be either strings or lists of messages. + rewards (`dict[str, list[float]]`): + Dictionary where keys are reward names and values are lists of rewards. + advantages (`list[float]`): + List of advantages corresponding to the prompts and completions. + step (`int`): + Current training step number, used in the output title. + num_samples (`int`, *optional*): + Number of random samples to display. If `None` (default), all items will be displayed. + extra (`dict[str, list]`, *optional*): + Additional columns to display after the advantage column. Keys are column names and values are lists of + per-completion data (strings or any value convertible to string). Typically populated via `log_extra` in + reward functions. If `None` (default), no extra columns are shown. + + Example: + ```python + >>> from trl.trainer.utils import print_prompt_completions_sample + + >>> prompts = ["The sky is", "The sun is"] + >>> completions = [" blue.", " in the sky."] + >>> rewards = {"Correctness": [0.123, 0.456], "Format": [0.789, 0.101]} + >>> advantages = [0.987, 0.654] + >>> extra = {"source": ["dataset_A", "dataset_B"]} + >>> print_prompt_completions_sample(prompts, completions, rewards, advantages, 42, extra=extra) + ╭────────────────────────────────── Step 42 ───────────────────────────────────╮ + │ ┏━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━┓ │ + │ ┃ Prompt ┃ Completion ┃ Correctness ┃ Format ┃ Advantage ┃ source ┃ │ + │ ┡━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━┩ │ + │ │ The sky is │ blue. │ 0.12 │ 0.79 │ 0.99 │ dataset_A │ │ + │ ├────────────┼──────────────┼─────────────┼────────┼───────────┼───────────┤ │ + │ │ The sun is │ in the sky. │ 0.46 │ 0.10 │ 0.65 │ dataset_B │ │ + │ └────────────┴──────────────┴─────────────┴────────┴───────────┴───────────┘ │ + ╰──────────────────────────────────────────────────────────────────────────────╯ + ``` + """ + if not is_rich_available(): + raise ImportError( + "The function `print_prompt_completions_sample` requires the `rich` library. Please install it with " + "`pip install rich`." + ) + console = Console() + table = Table(show_header=True, header_style="bold white", expand=True) + + extra = extra or {} + + # Add columns + table.add_column("Prompt", style="bright_yellow") + table.add_column("Completion", style="bright_green") + for reward_name in rewards.keys(): + table.add_column(reward_name, style="bold cyan", justify="right") + table.add_column("Advantage", style="bold magenta", justify="right") + for extra_name in extra.keys(): + table.add_column(extra_name, style="bright_white") + + def format_entry(entry) -> Text: + t = Text() + if isinstance(entry, list) and all(isinstance(m, dict) for m in entry): + for j, msg in enumerate(entry): + role = msg.get("role", "") + if "content" in msg or "reasoning_content" in msg or "thinking" in msg: + # Chat message + t.append(f"{role.upper()}\n", style="bold red") + reasoning = msg.get("reasoning_content") or msg.get("thinking") + if reasoning: + t.append(reasoning, style="italic dim white") + t.append("\n") + if "content" in msg: + t.append(msg["content"]) + elif "name" in msg and "args" in msg: + # Tool call + t.append(f"{role.upper()}\n", style="bold red") + t.append(f"{msg['name']}({msg['args']})") + else: + # Fallback + t.append(str(msg)) + if j < len(entry) - 1: + t.append("\n\n") + else: + t.append(str(entry)) + return t + + # Some basic input validation + if num_samples is not None: + if num_samples >= len(prompts): + num_samples = None + elif num_samples <= 0: + return + + # Subsample data if num_samples is specified + if num_samples is not None: + indices = random.sample(range(len(prompts)), num_samples) + prompts = [prompts[i] for i in indices] + completions = [completions[i] for i in indices] + rewards = {key: [val[i] for i in indices] for key, val in rewards.items()} + advantages = [advantages[i] for i in indices] + extra = {key: [val[i] for i in indices] for key, val in extra.items()} + + for i in range(len(prompts)): + reward_values = [f"{rewards[key][i]:.2f}" for key in rewards.keys()] # 2 decimals + extra_values = [format_entry(extra[key][i]) for key in extra.keys()] + table.add_row( + format_entry(prompts[i]), + format_entry(completions[i]), + *reward_values, + f"{advantages[i]:.2f}", + *extra_values, + ) + table.add_section() # Adds a separator between rows + + panel = Panel(table, expand=False, title=f"Step {step}", border_style="bold white") + console.print(panel) + + +class RepeatSampler(Sampler): + """ + Sampler that repeats the indices of a dataset in a structured manner. + + Args: + data_source (`Sized`): + Dataset to sample from. + mini_repeat_count (`int`): + Number of times to repeat each index per batch. + batch_size (`int`, *optional*, defaults to `1`): + Number of unique indices per batch. + repeat_count (`int`, *optional*, defaults to `1`): + Number of times to repeat the full sampling process. + shuffle (`bool`, *optional*, defaults to `True`): + Whether to shuffle the dataset. + seed (`int`, *optional*): + Random seed for reproducibility (only affects this sampler). + + Example: + ```python + >>> sampler = RepeatSampler(["a", "b", "c", "d", "e", "f", "g"], mini_repeat_count=2, batch_size=3, repeat_count=4) + >>> list(sampler) + [4, 4, 3, 3, 0, 0, + 4, 4, 3, 3, 0, 0, + 4, 4, 3, 3, 0, 0, + 4, 4, 3, 3, 0, 0, + 1, 1, 2, 2, 6, 6, + 1, 1, 2, 2, 6, 6, + 1, 1, 2, 2, 6, 6, + 1, 1, 2, 2, 6, 6] + ``` + + ```txt + mini_repeat_count = 3 + - - - + [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, | + 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, | + 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, | + repeat_count = 2 + 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, | + 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, | + 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, ...] | + --------- --------- --------- --------- + --------- --------- --------- --------- + --------- --------- --------- --------- + batch_size = 12 + ``` + """ + + def __init__( + self, + data_source: Sized, + mini_repeat_count: int, + batch_size: int = 1, + repeat_count: int = 1, + shuffle: bool = True, + seed: int | None = None, + ): + self.data_source = data_source + self.mini_repeat_count = mini_repeat_count + self.batch_size = batch_size + self.repeat_count = repeat_count + self.num_samples = len(data_source) + self.shuffle = shuffle + self.seed = seed + + if shuffle: + self.generator = torch.Generator() # Create a local random generator + if seed is not None: + self.generator.manual_seed(seed) + + def __iter__(self): + if self.shuffle: + # E.g., [2, 4, 3, 1, 0, 6, 5] (num_samples = 7) + indexes = torch.randperm(self.num_samples, generator=self.generator).tolist() + else: + indexes = list(range(self.num_samples)) + + # [2, 4, 3, 1, 0, 6, 5] + # -> [[2, 4, 3], [1, 0, 6], [5]] (batch_size = 3) + indexes = [indexes[i : i + self.batch_size] for i in range(0, len(indexes), self.batch_size)] + + # [[2, 4, 3], [1, 0, 6], [5]] + # -> [[2, 4, 3], [1, 0, 6]] + indexes = [chunk for chunk in indexes if len(chunk) == self.batch_size] + + for chunk in indexes: + for _ in range(self.repeat_count): + for index in chunk: + for _ in range(self.mini_repeat_count): + yield index + + def __len__(self) -> int: + return (self.num_samples // self.batch_size) * self.batch_size * self.mini_repeat_count * self.repeat_count + + +# torch.nanstd doesn't exist, so we define it here +def nanstd(tensor: torch.Tensor, dim: int | tuple[int, ...] | None = None, keepdim: bool = False) -> torch.Tensor: + """ + Compute the standard deviation of a tensor, ignoring NaNs. + + Args: + tensor (`torch.Tensor`): + Input tensor. + dim (`int` or `tuple[int, ...]`, *optional*): + Dimension(s) to reduce. Defaults to all dimensions. + keepdim (`bool`, *optional*, defaults to `False`): + Whether to keep reduced dimensions. + + Returns: + `torch.Tensor`: + Standard deviation of the tensor, ignoring NaNs. + """ + # Compute variance ignoring NaNs + mean = torch.nanmean(tensor, dim=dim, keepdim=True) + variance = torch.nanmean((tensor - mean) ** 2, dim=dim, keepdim=True) + count = torch.sum(~torch.isnan(tensor), dim=dim, keepdim=True) # count of non-NaN values + correction = count / (count - 1) + correction = torch.where(count > 1, correction, torch.full_like(correction, float("nan"))) + variance *= correction # Bessel's correction + std = torch.sqrt(variance) + if keepdim: + return std + if dim is None: + return std.squeeze() + if isinstance(dim, int): + return std.squeeze(dim) + dims = [(d if d >= 0 else d + std.ndim) for d in dim] + for d in sorted(dims, reverse=True): + std = std.squeeze(d) + return std + + +def split_tensor_dict( + tensor_dict: dict[str, torch.Tensor | None], num_chunks: int +) -> list[dict[str, torch.Tensor | None]]: + """ + Splits a dictionary of tensors along the first dimension into `num_chunks` equal parts. + + Example: + ```python + >>> x = torch.arange(12).reshape(6, 2) + >>> y = torch.arange(6).reshape(6, 1) + >>> tensor_dict = {"x": x, "y": y} + >>> split_tensor_dict(tensor_dict, 3) + [ + {"x": tensor([[0, 1], [2, 3]]), "y": tensor([[0], [1]])}, + {"x": tensor([[4, 5], [6, 7]]), "y": tensor([[2], [3]])}, + {"x": tensor([[ 8, 9], [10, 11]]), "y": tensor([[4], [5]])} + ] + ``` + """ + first_tensor = next(tensor for tensor in tensor_dict.values() if tensor is not None) + chunk_size = first_tensor.shape[0] // num_chunks + chunks = [] + for i in range(num_chunks): + chunk_dict = {} + for key, tensor in tensor_dict.items(): + if tensor is not None and (isinstance(tensor, list) or tensor.ndim > 0): + chunk_dict[key] = tensor[i * chunk_size : (i + 1) * chunk_size] + elif tensor is not None and tensor.ndim == 0: + chunk_dict[key] = tensor + else: + chunk_dict[key] = None + chunks.append(chunk_dict) + return chunks + + +def shuffle_sequence_dict(seq_dict: dict[str, Sequence | None]) -> dict[str, Sequence | None]: + """ + Shuffles all sequence-like values in a dictionary along the first dimension in unison. + + Example: + ```python + >>> x = torch.arange(6).reshape(3, 2) + >>> y = ["a", "b", "c"] + >>> seq_dict = {"x": x, "y": y} + >>> shuffle_sequence_dict(seq_dict) + {'x': tensor([[2, 3], + [0, 1], + [4, 5]]), + 'y': ['b', 'a', 'c']} + ``` + """ + # Determine batch size from the first non-None sequence + batch_size = len(next(v for v in seq_dict.values() if v is not None)) + permutation = torch.randperm(batch_size) + + def permute(v: Sequence | None) -> Sequence | None: + if v is None: + return None + if isinstance(v, torch.Tensor) and v.ndim == 0: + return v + if isinstance(v, torch.Tensor) and v.ndim >= 1: + return v[permutation] + return [v[i] for i in permutation] + + return {key: permute(val) for key, val in seq_dict.items()} + + +def nanmin(tensor: torch.Tensor) -> torch.Tensor: + """ + Compute the minimum value of a tensor, ignoring NaNs. This function only supports 1D tensors. + + Args: + tensor (`torch.Tensor`): Input tensor of shape `(N,)`. + + Returns: + `torch.Tensor`: Minimum value of the tensor, ignoring NaNs. Returns NaN if all values are NaN. + """ + if torch.isnan(tensor).all(): + return torch.tensor(float("nan"), dtype=tensor.dtype, device=tensor.device) + return torch.min(tensor[~torch.isnan(tensor)]) + + +def nanmax(tensor: torch.Tensor) -> torch.Tensor: + """ + Compute the maximum value of a tensor, ignoring NaNs. This function only supports 1D tensors. + + Args: + tensor (`torch.Tensor`): Input tensor of shape `(N,)`. + + Returns: + `torch.Tensor`: Maximum value of the tensor, ignoring NaNs. Returns NaN if all values are NaN. + """ + if torch.isnan(tensor).all(): + return torch.tensor(float("nan"), dtype=tensor.dtype, device=tensor.device) + return torch.max(tensor[~torch.isnan(tensor)]) + + +def identity(x): + """Do we really need docs for this?""" + return x + + +def split_pixel_values_by_grid(batch: dict[str, torch.Tensor]) -> dict[str, torch.Tensor | list[torch.Tensor]]: + """ + Splits `batch["pixel_values"]` into a list of tensors, one per sample, based on `batch["num_images"]`. + + For models with `image_grid_thw` (e.g. Qwen), the grid dimensions determine how many rows of `pixel_values` belong + to each image. For models with `image_position_ids` instead (e.g. Gemma), `pixel_values` is indexed directly by + image count. + """ + if "pixel_values" not in batch or "num_images" not in batch: + return batch + + num_images = batch["num_images"] + pixel_values = batch["pixel_values"] # [total, feature_dim] + + if "image_grid_thw" in batch: + lengths = batch["image_grid_thw"].prod(-1).tolist() # [num_images] + if sum(lengths) != pixel_values.size(0): + raise ValueError( + f"Mismatch: sum(lengths) = {sum(lengths)} != pixel_values.size(0) = {pixel_values.size(0)}" + ) + + boundaries = [0, *accumulate(num_images)] + image_grid_thw = batch["image_grid_thw"] # [total, 3] + sections = [sum(lengths[boundaries[i] : boundaries[i + 1]]) for i in range(len(num_images))] + split_pixel_values = list(torch.split(pixel_values, sections, dim=0)) + split_image_grid_thw = list(torch.split(image_grid_thw, num_images, dim=0)) + return {**batch, "pixel_values": split_pixel_values, "image_grid_thw": split_image_grid_thw} + + if "image_position_ids" in batch: + image_position_ids = batch["image_position_ids"] # [total] + split_pixel_values = list(torch.split(pixel_values, num_images, dim=0)) + split_image_position_ids = list(torch.split(image_position_ids, num_images, dim=0)) + return {**batch, "pixel_values": split_pixel_values, "image_position_ids": split_image_position_ids} + + return batch + + +def unsplit_pixel_values_by_grid(batch: dict[str, torch.Tensor | list[torch.Tensor]]) -> dict[str, torch.Tensor]: + """ + Opposite of `split_pixel_values_by_grid`. Merges a list of tensors in `batch["pixel_values"]` back into a single + tensor along the first dimension. + """ + pixel_values = batch.get("pixel_values") + if isinstance(pixel_values, list): + merged = torch.cat(pixel_values, dim=0) + batch = {**batch, "pixel_values": merged} + + image_grid_thw = batch.get("image_grid_thw") + if isinstance(image_grid_thw, list): + merged = torch.cat(image_grid_thw, dim=0) + batch = {**batch, "image_grid_thw": merged} + + image_position_ids = batch.get("image_position_ids") + if isinstance(image_position_ids, list): + merged = torch.cat(image_position_ids, dim=0) + batch = {**batch, "image_position_ids": merged} + + return batch + + +TListOrMapping = TypeVar("TListOrMapping", list, Mapping) + + +# This function is intentionally not used internally. It is provided as a utility for users whose datasets contain +# `None` values inserted by tabular backends (e.g., Arrow/Parquet) for missing keys in nested structures. This +# situation arises when loading datasets created before `datasets` v4.7.0 (which introduced the Json dtype), or when +# datasets created after that version were saved without using the Json feature. In both cases, users can apply this +# function via `dataset = dataset.with_transform(remove_none_values)` before training to strip the spurious `None` +# values. See the migration guide for more details. +def remove_none_values(example: TListOrMapping) -> TListOrMapping: + """ + Recursively removes entries with `None` values from a nested structure (list or dictionary). + + Args: + example (`list` or `Mapping`): + Input nested structure (list or dictionary) from which to remove `None`. + + Examples: + ```python + >>> dataset = dataset.with_transform(remove_none_values) + ``` + ```python + >>> [ + ... { + ... "a": {"aa": None, "ab": 1}, + ... "b": "my_string", + ... } + ... ] + >>> remove_none_values(example) + [{'a': {'ab': 1}, 'b': 'my_string'}] + ``` + """ + if isinstance(example, list): + return [remove_none_values(value) if isinstance(value, (dict, list)) else value for value in example] + elif isinstance(example, Mapping): + return { + key: remove_none_values(value) if isinstance(value, (dict, list)) else value + for key, value in example.items() + if value is not None + } + else: + raise TypeError("Input must be a list or a dictionary.") + + +def create_model_from_path( + model_id: str, architecture: _BaseAutoModelClass | None = None, **kwargs +) -> PreTrainedModel: + """ + Create a model from a given path using the specified initialization arguments. + + Args: + model_id (`str`): + Path to the model. Can be either a local directory or a model identifier from the Hugging Face Hub. + architecture (`_BaseAutoModelClass` or `None`, *optional*): + Model architecture class to instantiate. The model is initialized using the `from_pretrained` method of + this class. If `None`, the architecture will be inferred from the model's configuration. + kwargs (`dict`): + Initialization keyword arguments to pass to the model's `from_pretrained` method. When `'dtype'` is + specified, it can be either a `torch.dtype` or one of the strings: `'bfloat16'`, `'float16'`, `'float32'`, + or `'auto'`. If not explicitly set, `dtype` defaults to `'float32'`. + + Returns: + [`~transformers.PreTrainedModel`]: + The instantiated model. + """ + dtype = kwargs.get("dtype", "float32") + if isinstance(dtype, torch.dtype) or dtype == "auto" or dtype is None: + pass # dtype is already a torch.dtype or "auto" or None + elif isinstance(dtype, str) and dtype in ["bfloat16", "float16", "float32"]: + kwargs["dtype"] = getattr(torch, dtype) + else: + raise ValueError( + "Invalid `dtype` passed to the config. Expected either 'auto' or a string representing " + f"a valid `torch.dtype` (e.g., 'float32'), but got {dtype}." + ) + kwargs["device_map"] = kwargs.get("device_map", "auto") + if architecture is None: + config = AutoConfig.from_pretrained(model_id) + architecture = getattr(transformers, config.architectures[0]) + model = architecture.from_pretrained(model_id, **kwargs) + return model + + +def hash_module(module: torch.nn.Module) -> str: + h = hashlib.sha256() + for _, tensor in sorted(module.state_dict().items()): + tensor = tensor.cpu() + h.update(str(tensor.dtype).encode()) + if tensor.dtype in [torch.bfloat16, torch.float8_e4m3fn, torch.float8_e5m2]: + tensor = tensor.to(torch.float32) + h.update(tensor.numpy().tobytes()) + return h.hexdigest() + + +def get_config_model_id(config: PretrainedConfig) -> str: + """ + Retrieve the model identifier from a given model configuration. + + Args: + config ([`~transformers.PreTrainedConfig`]): + Configuration from which to extract the model identifier. + + Returns: + `str`: + The model identifier associated with the model configuration. + """ + return getattr(config, "_name_or_path", "") + + +@contextmanager +def use_adapter(model: "PeftModel", adapter_name: str | None): + """ + Context manager to temporarily set and reset the active adapter in a PEFT model. + + Args: + model ([`~peft.PeftModel`]): + PEFT model to manage. + adapter_name (`str` or `None`): + Name of the adapter to set as active. If `None`, the context manager will disable all adapters. + + Example: + ```python + >>> from trl.trainer.utils import use_adapter + >>> from peft import AutoPeftModelForCausalLM + >>> import torch + + >>> model = AutoPeftModelForCausalLM.from_pretrained("path/to/model") + >>> input_ids = torch.tensor([[1, 2, 3]]) + >>> with use_adapter(model, "adapter_name"): + ... outputs = model(input_ids) + ``` + """ + + if not is_peft_available(): + raise ImportError( + "You're trying to use a PEFT adapter but PEFT is not installed. Please install it with `pip install peft`." + ) + if adapter_name is None: + with model.disable_adapter(): + yield + else: + previous_adapter = model.active_adapter + model.set_adapter(adapter_name) + try: + yield + finally: + model.set_adapter(previous_adapter) + + +def start_event_loop_in_daemon( + name: str | None = None, +) -> tuple[threading.Thread, asyncio.AbstractEventLoop, threading.Event]: + """ + This function creates a new daemon thread that runs the provided event loop. + + Args: + name (`str`, *optional*): + Name of the thread. If `None`, the default thread naming will be used. + + Returns: + `threading.Thread`: + The thread running the event loop. + `asyncio.AbstractEventLoop`: + The event loop being run in the thread. + `threading.Event`: + An event that is set when the loop is ready. + """ + loop = asyncio.new_event_loop() + loop_ready_event = threading.Event() + + def run_loop(): + asyncio.set_event_loop(loop) + loop_ready_event.set() + loop.run_forever() + + thread = threading.Thread(target=run_loop, name=name, daemon=True) + thread.start() + return thread, loop, loop_ready_event + + +def shutdown_event_loop_in_daemon( + thread: threading.Thread | None, + loop: asyncio.AbstractEventLoop | None, +) -> None: + """ + Shutdown an asyncio event loop running in a separate thread. + + This function stops the event loop and waits for the associated thread to finish execution. + + Args: + thread (`threading.Thread`): + The thread running the event loop. + loop (`asyncio.AbstractEventLoop`): + The asyncio event loop to shut down. + """ + if loop is None or thread is None: + return + loop.call_soon_threadsafe(loop.stop) + thread.join(timeout=5) + + +class _ChunkedLogProbFunction(torch.autograd.Function): + """Compute per-token log-probs and entropy without materializing [N, V] logits. + + Processes the lm_head in chunks and uses online logsumexp + """ + + @staticmethod + def forward( + ctx, + last_hidden: torch.Tensor, # [N, H] + weight: torch.Tensor, # [V, H] + targets: torch.Tensor, # [N] + temperature: float, + chunk_size: int, + final_logit_softcapping: float | None = None, + logit_scale: float = 1.0, + ) -> tuple[torch.Tensor, torch.Tensor]: + device = last_hidden.device + N, _ = last_hidden.shape + vocab, _ = weight.shape + inv_t = 1 / temperature + + # NOTE(@aminediro): always acc in fp32 for stability + max_old = torch.full((N,), float("-inf"), device=device, dtype=torch.float32) + sum_exp = torch.zeros((N,), device=device, dtype=torch.float32) + x_sum_exp = torch.zeros((N,), device=device, dtype=torch.float32) + target_logit = torch.zeros((N,), device=device, dtype=torch.float32) + + # Pre-allocate reusable buffers to avoid per-chunk allocation + mm_buf = torch.empty((N, chunk_size), device=device, dtype=last_hidden.dtype) + logits_buf = torch.empty((N, chunk_size), device=device, dtype=torch.float32) + + for start in range(0, vocab, chunk_size): + end = min(start + chunk_size, vocab) + C = end - start + # using fp16=True, the model's hidden states get cast to float16 by autocast, but the mm_buf is allocated + # with last_hidden.dtype (float16) while w_chunk (the lm_head weights) is not auto casted + w_chunk = weight[start:end].to(last_hidden.dtype) # [C, H] + torch.mm(last_hidden, w_chunk.t(), out=mm_buf[:, :C]) + logits_chunk = logits_buf[:, :C] + logits_chunk.copy_(mm_buf[:, :C]) + + logits_chunk.mul_(logit_scale) + if final_logit_softcapping is not None: + logits_chunk.div_(final_logit_softcapping).tanh_().mul_(final_logit_softcapping) + + logits_chunk.mul_(inv_t) # [N, C] + + # Online logsumexp update + chunk_max = logits_chunk.amax(dim=-1) # [N] + max_new = torch.maximum(max_old, chunk_max) + rescale = torch.exp(max_old - max_new) + chunk_exp = torch.exp(logits_chunk - max_new.unsqueeze(-1)) # [N, C] + + sum_exp = sum_exp * rescale + chunk_exp.sum(dim=-1) + x_sum_exp = x_sum_exp * rescale + (chunk_exp * logits_chunk).sum(dim=-1) + max_old = max_new + + # Gather target logits for labels in this chunk + in_chunk_cond = (targets >= start) & (targets < end) + local_idx = torch.clamp(targets - start, 0, end - start - 1) + # take the new logit if target_idx is in this chunk bounds else 0 + target_logit += logits_chunk[torch.arange(N, device=device), local_idx] * in_chunk_cond + + log_z = max_old + torch.log(sum_exp) + logprobs = target_logit - log_z + entropy = log_z - x_sum_exp / sum_exp + + ctx.save_for_backward(last_hidden, weight, targets, log_z) + ctx.temperature = temperature + ctx.chunk_size = chunk_size + ctx.logit_scale = logit_scale + ctx.final_logit_softcapping = final_logit_softcapping + + return logprobs, entropy + + @staticmethod + def backward(ctx, grad_logprobs: torch.Tensor, grad_entropy: torch.Tensor): # type: ignore + hidden, weight, labels, log_z = ctx.saved_tensors + temperature: float = ctx.temperature + chunk_size: int = ctx.chunk_size + logit_scale: float = ctx.logit_scale + final_logit_softcapping: float = ctx.final_logit_softcapping + inv_t = 1 / temperature + + N, _ = hidden.shape + vocab = weight.shape[0] + + # NOTE(@aminediro): always acc in fp32 even if input is not + grad_hidden = torch.zeros(hidden.shape, device=hidden.device, dtype=torch.float32) + grad_weight = torch.zeros(weight.shape, device=weight.device, dtype=torch.float32) + + # Pre-allocate reusable buffers to avoid per-chunk allocation + mm_buf = torch.empty((N, chunk_size), device=hidden.device, dtype=hidden.dtype) + logits_buf = torch.empty((N, chunk_size), device=hidden.device, dtype=torch.float32) + + g = grad_logprobs.to(torch.float32) # [N] + row_idx = torch.arange(N, device=hidden.device) + + for start in range(0, vocab, chunk_size): + end = min(start + chunk_size, vocab) + C = end - start + w_chunk = weight[start:end] # [C, H] + + torch.mm(hidden, w_chunk.t(), out=mm_buf[:, :C]) + logits_chunk = logits_buf[:, :C] + logits_chunk.copy_(mm_buf[:, :C]) + + logits_chunk.mul_(logit_scale) + if final_logit_softcapping is not None: + tanh_scaled = torch.tanh(logits_chunk / final_logit_softcapping) + logits_chunk.copy_(tanh_scaled * final_logit_softcapping) + + logits_chunk.mul_(inv_t) # [N, C] + probs = torch.exp(logits_chunk - log_z.unsqueeze(-1)) # [N, C] + + # dL/d(logits) = g * (1_[label] - p) + grad_logits = (-g).unsqueeze(-1) * probs # [N, C] + + in_chunk_cond = (labels >= start) & (labels < end) + local_idx = torch.clamp(labels - start, 0, end - start - 1) + # If label in chunk add g to grad else it stays the same + grad_logits[row_idx, local_idx] += g * in_chunk_cond + + grad_logits = grad_logits * inv_t + if final_logit_softcapping is not None: + grad_logits.mul_(1 - tanh_scaled.pow(2)) + + grad_logits = grad_logits * logit_scale + + grad_hidden.add_(grad_logits @ w_chunk.float()) + grad_weight[start:end].add_(grad_logits.t() @ hidden.float()) + + return grad_hidden.to(hidden.dtype), grad_weight.to(weight.dtype), None, None, None, None, None + + +def patch_chunked_lm_head(model: torch.nn.Module, chunk_size: int, temperature: float) -> None: + final_logit_softcapping = getattr(model.config, "final_logit_softcapping", None) + + def _chunked_forward( + self: torch.nn.Module, + input_ids: torch.Tensor | None = None, + attention_mask: torch.Tensor | None = None, + labels: torch.Tensor | None = None, + completion_mask: torch.Tensor | None = None, + use_cache: bool = False, + **kwargs, + ) -> dict[str, torch.Tensor]: + assert labels is not None, "requires labels to not be None for logprob computation" + + outputs = self.model(input_ids=input_ids, attention_mask=attention_mask, use_cache=use_cache, **kwargs) + # NOTE(@aminediro): supporting Cohere2 models + logit_scale = getattr(self.config, "logit_scale", 1.0) + hidden_states = outputs.last_hidden_state # [B, S+1, H] + + # Shift: predict next token + hidden_states = hidden_states[:, :-1, :] # [B, S-1, H] + labels = labels[:, 1:] # [B, S-1] + + b, s, h = hidden_states.shape + hidden_flat = hidden_states.reshape(b * s, h) + targets_flat = labels.reshape(b * s) + + # Filter to completion tokens only to avoid expensive matmuls on prompt tokens and tool results + valid_mask = None + if completion_mask is not None: + completion_mask = completion_mask[:, 1:] # same shift as labels + valid_mask = completion_mask.bool().reshape(b * s) + hidden_flat = hidden_flat[valid_mask] # [N_valid, H] + targets_flat = targets_flat[valid_mask] # [N_valid] + + logprobs_valid, entropy_valid = _ChunkedLogProbFunction.apply( + hidden_flat, + self.lm_head.weight, + targets_flat, + temperature, + chunk_size, + final_logit_softcapping, + logit_scale, + ) + + if valid_mask is not None: + logprobs = torch.zeros(b * s, device=logprobs_valid.device, dtype=logprobs_valid.dtype) + entropy = torch.zeros(b * s, device=entropy_valid.device, dtype=entropy_valid.dtype) + logprobs[valid_mask] = logprobs_valid + entropy[valid_mask] = entropy_valid + else: + logprobs = logprobs_valid + entropy = entropy_valid + + return { + "log_probs": logprobs.reshape(b, s), + "entropy": entropy.reshape(b, s), + } + + model.forward = types.MethodType(_chunked_forward, model) + + +def compute_flops_per_token(config: PretrainedConfig, seq_len: int) -> int: + """ + Estimate training FLOPs per token for a causal language model (forward + backward). + + Supports dense and MoE architectures. Backward is assumed to cost 2× the forward pass, so total training FLOPs = 3 + × forward FLOPs. The attention-score term uses the non-causal convention (every token attends to the full + `seq_len`, matching PaLM / Megatron / nanoGPT); pass the resulting MFU through [`adjusted_mfu`] for the Llama / + DeepSpeed Ulysses causal-corrected convention. + + Args: + config ([`~transformers.PretrainedConfig`]): + The model configuration. + seq_len (`int`): + The sequence length used for training. + + Returns: + `int`: Estimated training FLOPs per token. + """ + h = config.hidden_size + L = config.num_hidden_layers + V = config.vocab_size + n_heads = config.num_attention_heads + n_kv_heads = config.num_key_value_heads + head_dim = config.head_dim + + # Attention: Q/K/V/O projections + attention score (Q·Kᵀ and attn·V). + qkv_flops = 2 * h * (n_heads * head_dim + 2 * n_kv_heads * head_dim) + o_proj_flops = 2 * n_heads * head_dim * h + attn_score_flops = 2 * 2 * n_heads * head_dim * seq_len + attn_flops = qkv_flops + o_proj_flops + attn_score_flops + + # MoE dispatch: `num_experts_per_tok` is the canonical MoE marker — present on Mixtral, + # Qwen3-MoE, DeepSeek-V2, etc.; absent on dense configs. + num_experts_per_tok = getattr(config, "num_experts_per_tok", None) + if num_experts_per_tok is None: + mlp_flops = 2 * 3 * h * config.intermediate_size + total_layer_flops = L * (attn_flops + mlp_flops) + else: + # Routed experts (gate + up + down, 3 matmuls each) + router. + if Version(transformers.__version__) >= Version("5.1.0"): + num_experts = config.num_local_experts + else: + num_experts = config.num_experts + moe_mlp_flops = num_experts_per_tok * 2 * 3 * h * config.moe_intermediate_size + moe_mlp_flops += 2 * h * num_experts + dense_mlp_flops = 2 * 3 * h * config.intermediate_size # interspersed dense layers + sparse_step = config.decoder_sparse_step + total_layer_flops = sum( + attn_flops + (moe_mlp_flops if layer_idx % sparse_step == 0 else dense_mlp_flops) for layer_idx in range(L) + ) + + embed_flops = 2 * V * h + lm_head_flops = 0 if config.tie_word_embeddings else 2 * V * h + + forward_flops = total_layer_flops + embed_flops + lm_head_flops + return 3 * forward_flops + + +def compute_mfu( + flops_per_token: int, + tokens_per_second: float, + world_size: int, + peak_flops_per_device: float = 989.5e12, +) -> float: + """ + Compute Model FLOPs Utilization (MFU) as a percentage. + + The caller is responsible for correcting `tokens_per_second` for any parallelism dimension that causes the + trainer's token counter to over-count (e.g. context parallelism, sequence parallelism, tensor parallelism — every + rank in those dims sees the same input tokens). + + Args: + flops_per_token (`int`): + Training FLOPs per token (from [`compute_flops_per_token`]). + tokens_per_second (`float`): + Aggregate tokens per second across all devices, after any parallelism corrections. + world_size (`int`): + Number of devices (GPUs). + peak_flops_per_device (`float`, *optional*, defaults to `989.5e12`): + Theoretical peak FLOPs per device in bf16. Defaults to H100 SXM5. + + Returns: + `float`: MFU as a percentage (0-100). + """ + return 100 * (flops_per_token * tokens_per_second) / (peak_flops_per_device * world_size) + + +def adjusted_mfu(mfu: float, config: PretrainedConfig, seq_len: int) -> float: + """ + Apply a causal-masking correction to an MFU computed with [`compute_flops_per_token`]. + + [`compute_flops_per_token`] uses the non-causal attention convention (every token treated as attending to the full + `seq_len`, matching PaLM / Megatron / nanoGPT). With causal masking, only half of the attention-score FLOPs (`Q·Kᵀ` + and `attn·V`) are actually performed. This function subtracts that half from the per-token total and rescales `mfu` + accordingly. Use it to compare against reports that follow the Llama 2/3 / DeepSpeed Ulysses convention. + + Args: + mfu (`float`): + MFU as a percentage, computed via [`compute_mfu`] (i.e., using the non-causal [`compute_flops_per_token`]). + config ([`~transformers.PretrainedConfig`]): + The model configuration. + seq_len (`int`): + The sequence length used for training. + + Returns: + `float`: Causal-corrected MFU as a percentage. + """ + flops_full = compute_flops_per_token(config, seq_len) + # Half of the attention-score FLOPs (Q·Kᵀ and attn·V), per layer, ×3 for fwd+bwd. + half_attn_score = config.num_hidden_layers * 3 * 2 * config.num_attention_heads * config.head_dim * seq_len + return mfu * (flops_full - half_attn_score) / flops_full diff --git a/tasks/tasksmith-5b4f21a2a450/tests/test.sh b/tasks/tasksmith-5b4f21a2a450/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..426176b8bea79061cb126a143199bafd3c1d6a41 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +exec /usr/local/bin/python -I /tests/grade.py diff --git a/tasks/tasksmith-5b4f21a2a450/tests/test_driver.py b/tasks/tasksmith-5b4f21a2a450/tests/test_driver.py new file mode 100644 index 0000000000000000000000000000000000000000..c0b8bb331c4499e300b92f0e022ff6a723a4a562 --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/test_driver.py @@ -0,0 +1,41 @@ +"""Private pytest entry point with a bounded framework-tampering check. + +The host still owns reward parsing. This guard detects replacement or in-place +editing of unittest assertions, a demonstrated attack against repository tests. +It does not claim to isolate arbitrary test and solution code in one interpreter. +""" + +from __future__ import annotations + +import sys +import unittest + + +def run(arguments: list[str]) -> int: + import pytest + + # Capture before pytest imports any repository modules. Retain code objects + # too: an attacker can mutate function.__code__ without replacing a method. + original = { + name: (value, getattr(value, "__code__", None)) + for name, value in vars(unittest.TestCase).items() + if name.startswith("assert") and callable(value) + } + case = unittest.TestCase + # The harness supplies selectors and reporting explicitly. Repository addopts + # often enable optional coverage/report plugins that are intentionally not + # auto-loaded in this isolated verifier; they are not test dependencies. + code = int(pytest.main(["-o", "addopts=", *arguments])) + changed = [] + for name, (method, implementation) in original.items(): + current = getattr(case, name, None) + if current is not method or getattr(current, "__code__", None) is not implementation: + changed.append(name) + if unittest.TestCase is not case or changed: + sys.stderr.write("Verifier framework was modified: " + ", ".join(changed) + "\n") + return 254 + return code + + +if __name__ == "__main__": + raise SystemExit(run(sys.argv[1:])) diff --git a/tasks/tasksmith-5b4f21a2a450/tests/test_results.py b/tasks/tasksmith-5b4f21a2a450/tests/test_results.py new file mode 100644 index 0000000000000000000000000000000000000000..05ce2c730e38e02bad44f2344e88e5f1cb02cb8d --- /dev/null +++ b/tasks/tasksmith-5b4f21a2a450/tests/test_results.py @@ -0,0 +1,65 @@ +"""Strict test evidence used by repository recipes and their exported verifiers.""" + +from __future__ import annotations + +from dataclasses import dataclass +from xml.etree import ElementTree + + +@dataclass(frozen=True) +class TestResults: + __test__ = False + statuses: dict[str, str] + returncode: int + + @property + def passed(self) -> set[str]: + return {name for name, status in self.statuses.items() if status == "passed"} + + +def parse_junit(text: str, *, returncode: int) -> TestResults: + if " dict[str, list[str]]: + if healthy.returncode != 0 or not healthy.passed: + raise ValueError("Reference must execute successfully with passing tests") + if healthy.statuses.keys() != defective.statuses.keys(): + raise ValueError("Mutation changed test collection; contrast is not comparable") + failing = sorted( + name for name in healthy.passed if defective.statuses[name] in {"failed", "error"} + ) + if not failing or defective.returncode != 1: + raise ValueError("No intended fail-to-pass contrast") + return {"FAIL_TO_PASS": failing, "PASS_TO_PASS": sorted(healthy.passed - set(failing))} diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/Dockerfile b/tasks/tasksmith-5cbfd9f64dbc/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..199a2018ef8a0427f9610270b6fb33e6bfc1bbc2 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/Dockerfile @@ -0,0 +1,15 @@ +FROM pytorch/pytorch:2.11.0-cuda12.8-cudnn9-runtime +WORKDIR /workspace +RUN apt-get update && apt-get install -y --no-install-recommends python3-venv && rm -rf /var/lib/apt/lists/* +RUN python -m venv --system-site-packages /opt/tasksmith-venv +ENV PATH=/opt/tasksmith-venv/bin:$PATH +RUN python -m pip install --no-cache-dir filelock huggingface-hub==0.36.2 'numpy>=1.17' 'packaging>=20.0' 'pyyaml>=5.1' 'regex!=2019.12.17' requests 'safetensors>=0.4.3' tokenizers==0.21.0 'tqdm>=4.27' 'Pillow>=10.0.1' parameterized==0.9.0 pytest==9.1.1 pytest-timeout setuptools 'datasets>=2.15.0' 'pandas<2.3.0' pyarrow accelerate +COPY source /workspace +RUN python -m pip install --no-cache-dir --no-deps --no-build-isolation -e . +ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 +ENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 HF_DATASETS_OFFLINE=1 +RUN apt-get update && apt-get install -y --no-install-recommends tmux && rm -rf /var/lib/apt/lists/* +RUN useradd -m learner && chown -R learner:learner /workspace +RUN sh -c 'set -eu; profile="$1/.bash_profile"; original=""; if [ -e "$profile" ]; then original=.repo2rlenv-original-bash-profile; test ! -e "$1/$original"; mv "$profile" "$1/$original"; elif [ -r "$1/.bash_login" ]; then original=.bash_login; elif [ -r "$1/.profile" ]; then original=.profile; fi; if [ -n "$original" ]; then printf '"'"'if [ -r "$HOME/%s" ]; then . "$HOME/%s"; fi\n'"'"' "$original" "$original" > "$profile"; else : > "$profile"; fi; printf '"'"'\nexport PATH="%s/bin:$PATH"\nexport VIRTUAL_ENV="%s"\n'"'"' "$2" "$2" >> "$profile"' -- /home/learner /opt/tasksmith-venv && chown learner:learner /home/learner/.bash_profile +RUN printf 'export PATH="%s/bin:$PATH"\nexport VIRTUAL_ENV="%s"\n' /opt/tasksmith-venv /opt/tasksmith-venv > /etc/repo2rlenv-venv.sh +ENV BASH_ENV=/etc/repo2rlenv-venv.sh diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/.gitattributes b/tasks/tasksmith-5cbfd9f64dbc/environment/source/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..6505bc7edf9af5694cee1a93b90c565872fbbeb9 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/.gitattributes @@ -0,0 +1,4 @@ +*.py eol=lf +*.rst eol=lf +*.md eol=lf +*.mdx eol=lf \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/.gitignore b/tasks/tasksmith-5cbfd9f64dbc/environment/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..cdf189505dc73e798046de3f631b281d08aba96a --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/.gitignore @@ -0,0 +1,172 @@ +# Initially taken from Github's Python gitignore file + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# tests and logs +tests/fixtures/cached_*_text.txt +logs/ +lightning_logs/ +lang_code_data/ + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# vscode +.vs +.vscode + +# Pycharm +.idea + +# TF code +tensorflow_code + +# Models +proc_data + +# examples +runs +/runs_old +/wandb +/examples/runs +/examples/**/*.args +/examples/rag/sweep + +# data +/data +serialization_dir + +# emacs +*.*~ +debug.env + +# vim +.*.swp + +#ctags +tags + +# pre-commit +.pre-commit* + +# .lock +*.lock + +# DS_Store (MacOS) +.DS_Store + +# ruff +.ruff_cache + +# modular conversion +*.modular_backup diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/AGENTS.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/AGENTS.md new file mode 100644 index 0000000000000000000000000000000000000000..2788ab99af8961fe11a826b6392073ddc38cf1ed --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/AGENTS.md @@ -0,0 +1,39 @@ +# AGENTS.md Guide for Hugging Face Transformers + +This AGENTS.md file provides guidance for code agents working with this codebase. + +## Core Project Structure + +- `/src/transformers`: This contains the core source code for the library + - `/models`: Code for individual models. Models inherit from base classes in the root `/src/transformers` directory. +- `/tests`: This contains the core test classes for the library. These are usually inherited rather than directly run. + - `/models`: Tests for individual models. Model tests inherit from common tests in the root `/tests` directory. +- `/docs`: This contains the documentation for the library, including guides, tutorials, and API references. + +## Coding Conventions for Hugging Face Transformers + +- PRs should be as brief as possible. Bugfix PRs in particular can often be only one or two lines long, and do not need large comments, docstrings or new functions in this case. Aim to minimize the size of the diff. +- When writing tests, they should be added to an existing file. The only exception is for PRs to add a new model, when a new test directory should be created for that model. +- Code style is enforced in the CI. You can install the style tools with `pip install -e .[quality]`. You can then run `make fixup` to apply style and consistency fixes to your code. + +## Copying and inheritance + +Many models in the codebase have similar code, but it is not shared by inheritance because we want each model file to be self-contained. +We use two mechanisms to keep this code in sync: + +- "Copied from" syntax. Functions or entire classes can have a comment at the top like this: `# Copied from transformers.models.llama.modeling_llama.rotate_half` or `# Copied from transformers.models.t5.modeling_t5.T5LayerNorm with T5->MT5` + These comments are actively checked by the style tools, and copies will automatically be updated when the base code is updated. If you need to update a copied function, you should + either update the base function and use `make fixup` to propagate the change to all copies, or simply remove the `# Copied from` comment if that is inappropriate. +- "Modular" files. These files briefly define models by composing them using inheritance from other models. They are not meant to be used directly. Instead, the style tools + automatically generate a complete modeling file, like `modeling_bert.py`, from the modular file like `modular_bert.py`. If a model has a modular file, the modeling file + should never be edited directly! Instead, changes should be made in the modular file, and then you should run `make fixup` to update the modeling file automatically. + +When adding new models, you should prefer `modular` style. + +## Testing + +After making changes, you should usually run `make fixup` to ensure any copies and modular files are updated, and then test all affected models. This includes both +the model you made the changes in and any other models that were updated by `make fixup`. Tests can be run with `pytest tests/models/[name]/test_modeling_[name].py` +If your changes affect code in other classes like tokenizers or processors, you should run those tests instead, like `test_processing_[name].py` or `test_tokenization_[name].py`. + +In order to run tests, you may need to install dependencies. You can do this with `pip install -e .[testing]`. You will probably also need to `pip install torch accelerate` if your environment does not already have them. \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/CITATION.cff b/tasks/tasksmith-5cbfd9f64dbc/environment/source/CITATION.cff new file mode 100644 index 0000000000000000000000000000000000000000..b4d5156786f94df7ca0aebe5322b17dbb1521cb3 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/CITATION.cff @@ -0,0 +1,82 @@ +cff-version: "1.2.0" +date-released: 2020-10 +message: "If you use this software, please cite it using these metadata." +title: "Transformers: State-of-the-Art Natural Language Processing" +url: "https://github.com/huggingface/transformers" +authors: + - family-names: Wolf + given-names: Thomas + - family-names: Debut + given-names: Lysandre + - family-names: Sanh + given-names: Victor + - family-names: Chaumond + given-names: Julien + - family-names: Delangue + given-names: Clement + - family-names: Moi + given-names: Anthony + - family-names: Cistac + given-names: Perric + - family-names: Ma + given-names: Clara + - family-names: Jernite + given-names: Yacine + - family-names: Plu + given-names: Julien + - family-names: Xu + given-names: Canwen + - family-names: "Le Scao" + given-names: Teven + - family-names: Gugger + given-names: Sylvain + - family-names: Drame + given-names: Mariama + - family-names: Lhoest + given-names: Quentin + - family-names: Rush + given-names: "Alexander M." +preferred-citation: + type: conference-paper + authors: + - family-names: Wolf + given-names: Thomas + - family-names: Debut + given-names: Lysandre + - family-names: Sanh + given-names: Victor + - family-names: Chaumond + given-names: Julien + - family-names: Delangue + given-names: Clement + - family-names: Moi + given-names: Anthony + - family-names: Cistac + given-names: Perric + - family-names: Ma + given-names: Clara + - family-names: Jernite + given-names: Yacine + - family-names: Plu + given-names: Julien + - family-names: Xu + given-names: Canwen + - family-names: "Le Scao" + given-names: Teven + - family-names: Gugger + given-names: Sylvain + - family-names: Drame + given-names: Mariama + - family-names: Lhoest + given-names: Quentin + - family-names: Rush + given-names: "Alexander M." + booktitle: "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: System Demonstrations" + month: 10 + start: 38 + end: 45 + title: "Transformers: State-of-the-Art Natural Language Processing" + year: 2020 + publisher: "Association for Computational Linguistics" + url: "https://www.aclweb.org/anthology/2020.emnlp-demos.6" + address: "Online" diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/CODE_OF_CONDUCT.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000000000000000000000000000000000..b23f3150a5a6987a74acc7bb31df8c9bf1a48d57 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/CODE_OF_CONDUCT.md @@ -0,0 +1,133 @@ + +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, caste, color, religion, or sexual +identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall + community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or advances of + any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, + without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +feedback@huggingface.co. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of +actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or permanent +ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the +community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.1, available at +[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. + +Community Impact Guidelines were inspired by +[Mozilla's code of conduct enforcement ladder][Mozilla CoC]. + +For answers to common questions about this code of conduct, see the FAQ at +[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at +[https://www.contributor-covenant.org/translations][translations]. + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html +[Mozilla CoC]: https://github.com/mozilla/diversity +[FAQ]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/CONTRIBUTING.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..5a9e52fd622c281f57c00f8b3fe6cfdedd8594f0 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/CONTRIBUTING.md @@ -0,0 +1,395 @@ + + +# Contribute to 🤗 Transformers + +Everyone is welcome to contribute, and we value everybody's contribution. Code +contributions are not the only way to help the community. Answering questions, helping +others, and improving the documentation are also immensely valuable. + +It also helps us if you spread the word! Reference the library in blog posts +about the awesome projects it made possible, shout out on Twitter every time it has +helped you, or simply ⭐️ the repository to say thank you. + +However you choose to contribute, please be mindful and respect our +[code of conduct](https://github.com/huggingface/transformers/blob/main/CODE_OF_CONDUCT.md). + +**This guide was heavily inspired by the awesome [scikit-learn guide to contributing](https://github.com/scikit-learn/scikit-learn/blob/main/CONTRIBUTING.md).** + +## Ways to contribute + +There are several ways you can contribute to 🤗 Transformers: + +* Fix outstanding issues with the existing code. +* Submit issues related to bugs or desired new features. +* Implement new models. +* Contribute to the examples or to the documentation. + +If you don't know where to start, there is a special [Good First +Issue](https://github.com/huggingface/transformers/contribute) listing. It will give you a list of +open issues that are beginner-friendly and help you start contributing to open-source. The best way to do that is to open a Pull Request and link it to the issue that you'd like to work on. We try to give priority to opened PRs as we can easily track the progress of the fix, and if the contributor does not have time anymore, someone else can take the PR over. + +For something slightly more challenging, you can also take a look at the [Good Second Issue](https://github.com/huggingface/transformers/labels/Good%20Second%20Issue) list. In general though, if you feel like you know what you're doing, go for it and we'll help you get there! 🚀 + +> All contributions are equally valuable to the community. 🥰 + +## Fixing outstanding issues + +If you notice an issue with the existing code and have a fix in mind, feel free to [start contributing](#create-a-pull-request) and open a Pull Request! + +## Submitting a bug-related issue or feature request + +Do your best to follow these guidelines when submitting a bug-related issue or a feature +request. It will make it easier for us to come back to you quickly and with good +feedback. + +### Did you find a bug? + +The 🤗 Transformers library is robust and reliable thanks to users who report the problems they encounter. + +Before you report an issue, we would really appreciate it if you could **make sure the bug was not +already reported** (use the search bar on GitHub under Issues). Your issue should also be related to bugs in the library itself, and not your code. If you're unsure whether the bug is in your code or the library, please ask in the [forum](https://discuss.huggingface.co/) or on our [discord](https://discord.com/invite/hugging-face-879548962464493619) first. This helps us respond quicker to fixing issues related to the library versus general questions. + +> [!TIP] +> We have a [docs bot](https://huggingface.co/spaces/huggingchat/hf-docs-chat), and we highly encourage you to ask all your questions there. There is always a chance your bug can be fixed with a simple flag 👾🔫 + +Once you've confirmed the bug hasn't already been reported, please include the following information in your issue so we can quickly resolve it: + +* Your **OS type and version** and **Python**, **PyTorch** and + **TensorFlow** versions when applicable. +* A short, self-contained, code snippet that allows us to reproduce the bug in + less than 30s. +* The *full* traceback if an exception is raised. +* Attach any other additional information, like screenshots, you think may help. + +To get the OS and software versions automatically, run the following command: + +```bash +transformers env +``` + +You can also run the same command from the root of the repository: + +```bash +python src/transformers/commands/transformers_cli.py env +``` + +### Do you want a new feature? + +If there is a new feature you'd like to see in 🤗 Transformers, please open an issue and describe: + +1. What is the *motivation* behind this feature? Is it related to a problem or frustration with the library? Is it a feature related to something you need for a project? Is it something you worked on and think it could benefit the community? + + Whatever it is, we'd love to hear about it! + +2. Describe your requested feature in as much detail as possible. The more you can tell us about it, the better we'll be able to help you. +3. Provide a *code snippet* that demonstrates the features usage. +4. If the feature is related to a paper, please include a link. + +If your issue is well written we're already 80% of the way there by the time you create it. + +We have added [templates](https://github.com/huggingface/transformers/tree/main/templates) to help you get started with your issue. + +## Do you want to implement a new model? + +New models are constantly released and if you want to implement a new model, please provide the following information: + +* A short description of the model and a link to the paper. +* Link to the implementation if it is open-sourced. +* Link to the model weights if they are available. + +If you are willing to contribute the model yourself, let us know so we can help you add it to 🤗 Transformers! + +We have a technical guide for [how to add a model to 🤗 Transformers](https://huggingface.co/docs/transformers/add_new_model). + +## Do you want to add documentation? + +We're always looking for improvements to the documentation that make it more clear and accurate. Please let us know how the documentation can be improved such as typos and any content that is missing, unclear or inaccurate. We'll be happy to make the changes or help you make a contribution if you're interested! + +For more details about how to generate, build, and write the documentation, take a look at the documentation [README](https://github.com/huggingface/transformers/tree/main/docs). + +## Create a Pull Request + +Before writing any code, we strongly advise you to search through the existing PRs or +issues to make sure nobody is already working on the same thing. If you are +unsure, it is always a good idea to open an issue to get some feedback. + +You will need basic `git` proficiency to contribute to +🤗 Transformers. While `git` is not the easiest tool to use, it has the greatest +manual. Type `git --help` in a shell and enjoy! If you prefer books, [Pro +Git](https://git-scm.com/book/en/v2) is a very good reference. + +You'll need **[Python 3.9](https://github.com/huggingface/transformers/blob/main/setup.py#L449)** or above to contribute to 🤗 Transformers. Follow the steps below to start contributing: + +1. Fork the [repository](https://github.com/huggingface/transformers) by + clicking on the **[Fork](https://github.com/huggingface/transformers/fork)** button on the repository's page. This creates a copy of the code + under your GitHub user account. + +2. Clone your fork to your local disk, and add the base repository as a remote: + + ```bash + git clone git@github.com:/transformers.git + cd transformers + git remote add upstream https://github.com/huggingface/transformers.git + ``` + +3. Create a new branch to hold your development changes: + + ```bash + git checkout -b a-descriptive-name-for-my-changes + ``` + + 🚨 **Do not** work on the `main` branch! + +4. Set up a development environment by running the following command in a virtual environment: + + ```bash + pip install -e ".[dev]" + ``` + + If 🤗 Transformers was already installed in the virtual environment, remove + it with `pip uninstall transformers` before reinstalling it in editable + mode with the `-e` flag. + + Depending on your OS, and since the number of optional dependencies of Transformers is growing, you might get a + failure with this command. If that's the case make sure to install the Deep Learning framework you are working with + (PyTorch, TensorFlow and/or Flax) then do: + + ```bash + pip install -e ".[quality]" + ``` + + which should be enough for most use cases. + +5. Develop the features in your branch. + + As you work on your code, you should make sure the test suite + passes. Run the tests impacted by your changes like this: + + ```bash + pytest tests/.py + ``` + + For more information about tests, check out the + [Testing](https://huggingface.co/docs/transformers/testing) guide. + + 🤗 Transformers relies on `black` and `ruff` to format its source code + consistently. After you make changes, apply automatic style corrections and code verifications + that can't be automated in one go with: + + ```bash + make fixup + ``` + + This target is also optimized to only work with files modified by the PR you're working on. + + If you prefer to run the checks one after the other, the following command applies the + style corrections: + + ```bash + make style + ``` + + 🤗 Transformers also uses `ruff` and a few custom scripts to check for coding mistakes. Quality + controls are run by the CI, but you can run the same checks with: + + ```bash + make quality + ``` + + Finally, we have a lot of scripts to make sure we don't forget to update + some files when adding a new model. You can run these scripts with: + + ```bash + make repo-consistency + ``` + + To learn more about those checks and how to fix any issues with them, check out the + [Checks on a Pull Request](https://huggingface.co/docs/transformers/pr_checks) guide. + + If you're modifying documents under the `docs/source` directory, make sure the documentation can still be built. This check will also run in the CI when you open a pull request. To run a local check + make sure you install the [documentation builder](https://github.com/huggingface/doc-builder). + + ```bash + pip install hf-doc-builder + ``` + + Run the following command from the root of the repository: + + ```bash + doc-builder build transformers docs/source/en --build_dir ~/tmp/test-build + ``` + + This will build the documentation in the `~/tmp/test-build` folder where you can inspect the generated + Markdown files with your favorite editor. You can also preview the docs on GitHub when you open a pull request. + + Once you're happy with your changes, add the changed files with `git add` and + record your changes locally with `git commit`: + + ```bash + git add modified_file.py + git commit + ``` + + Please remember to write [good commit + messages](https://chris.beams.io/posts/git-commit/) to clearly communicate the changes you made! + + To keep your copy of the code up to date with the original + repository, rebase your branch on `upstream/branch` *before* you open a pull request or if requested by a maintainer: + + ```bash + git fetch upstream + git rebase upstream/main + ``` + + Push your changes to your branch: + + ```bash + git push -u origin a-descriptive-name-for-my-changes + ``` + + If you've already opened a pull request, you'll need to force push with the `--force` flag. Otherwise, if the pull request hasn't been opened yet, you can just push your changes normally. + +6. Now you can go to your fork of the repository on GitHub and click on **Pull Request** to open a pull request. Make sure you tick off all the boxes on our [checklist](#pull-request-checklist) below. When you're ready, you can send your changes to the project maintainers for review. + +7. It's ok if maintainers request changes, it happens to our core contributors + too! So everyone can see the changes in the pull request, work in your local + branch and push the changes to your fork. They will automatically appear in + the pull request. + +### Pull request checklist + +☐ The pull request title should summarize your contribution.
+☐ If your pull request addresses an issue, please mention the issue number in the pull +request description to make sure they are linked (and people viewing the issue know you +are working on it).
+☐ To indicate a work in progress please prefix the title with `[WIP]`. These are +useful to avoid duplicated work, and to differentiate it from PRs ready to be merged.
+☐ Make sure existing tests pass.
+☐ If adding a new feature, also add tests for it.
+ - If you are adding a new model, make sure you use + `ModelTester.all_model_classes = (MyModel, MyModelWithLMHead,...)` to trigger the common tests. + - If you are adding new `@slow` tests, make sure they pass using + `RUN_SLOW=1 python -m pytest tests/models/my_new_model/test_my_new_model.py`. + - If you are adding a new tokenizer, write tests and make sure + `RUN_SLOW=1 python -m pytest tests/models/{your_model_name}/test_tokenization_{your_model_name}.py` passes. + - CircleCI does not run the slow tests, but GitHub Actions does every night!
+ +☐ All public methods must have informative docstrings (see +[`modeling_bert.py`](https://github.com/huggingface/transformers/blob/main/src/transformers/models/bert/modeling_bert.py) +for an example).
+☐ Due to the rapidly growing repository, don't add any images, videos and other +non-text files that'll significantly weigh down the repository. Instead, use a Hub +repository such as [`hf-internal-testing`](https://huggingface.co/hf-internal-testing) +to host these files and reference them by URL. We recommend placing documentation +related images in the following repository: +[huggingface/documentation-images](https://huggingface.co/datasets/huggingface/documentation-images). +You can open a PR on this dataset repository and ask a Hugging Face member to merge it. + +For more information about the checks run on a pull request, take a look at our [Checks on a Pull Request](https://huggingface.co/docs/transformers/pr_checks) guide. + +### Tests + +An extensive test suite is included to test the library behavior and several examples. Library tests can be found in +the [tests](https://github.com/huggingface/transformers/tree/main/tests) folder and examples tests in the +[examples](https://github.com/huggingface/transformers/tree/main/examples) folder. + +We like `pytest` and `pytest-xdist` because it's faster. From the root of the +repository, specify a *path to a subfolder or a test file* to run the test: + +```bash +python -m pytest -n auto --dist=loadfile -s -v ./tests/models/my_new_model +``` + +Similarly, for the `examples` directory, specify a *path to a subfolder or test file* to run the test. For example, the following command tests the text classification subfolder in the PyTorch `examples` directory: + +```bash +pip install -r examples/xxx/requirements.txt # only needed the first time +python -m pytest -n auto --dist=loadfile -s -v ./examples/pytorch/text-classification +``` + +In fact, this is actually how our `make test` and `make test-examples` commands are implemented (not including the `pip install`)! + +You can also specify a smaller set of tests in order to test only the feature +you're working on. + +By default, slow tests are skipped but you can set the `RUN_SLOW` environment variable to +`yes` to run them. This will download many gigabytes of models so make sure you +have enough disk space, a good internet connection or a lot of patience! + + + +Remember to specify a *path to a subfolder or a test file* to run the test. Otherwise, you'll run all the tests in the `tests` or `examples` folder, which will take a very long time! + + + +```bash +RUN_SLOW=yes python -m pytest -n auto --dist=loadfile -s -v ./tests/models/my_new_model +RUN_SLOW=yes python -m pytest -n auto --dist=loadfile -s -v ./examples/pytorch/text-classification +``` + +Like the slow tests, there are other environment variables available which are not enabled by default during testing: +- `RUN_CUSTOM_TOKENIZERS`: Enables tests for custom tokenizers. + +More environment variables and additional information can be found in the [testing_utils.py](https://github.com/huggingface/transformers/blob/main/src/transformers/testing_utils.py). + +🤗 Transformers uses `pytest` as a test runner only. It doesn't use any +`pytest`-specific features in the test suite itself. + +This means `unittest` is fully supported. Here's how to run tests with +`unittest`: + +```bash +python -m unittest discover -s tests -t . -v +python -m unittest discover -s examples -t examples -v +``` + +### Style guide + +For documentation strings, 🤗 Transformers follows the [Google Python Style Guide](https://google.github.io/styleguide/pyguide.html). +Check our [documentation writing guide](https://github.com/huggingface/transformers/tree/main/docs#writing-documentation---specification) +for more information. + +### Develop on Windows + +On Windows (unless you're working in [Windows Subsystem for Linux](https://learn.microsoft.com/en-us/windows/wsl/) or WSL), you need to configure git to transform Windows `CRLF` line endings to Linux `LF` line endings: + +```bash +git config core.autocrlf input +``` + +One way to run the `make` command on Windows is with MSYS2: + +1. [Download MSYS2](https://www.msys2.org/), and we assume it's installed in `C:\msys64`. +2. Open the command line `C:\msys64\msys2.exe` (it should be available from the **Start** menu). +3. Run in the shell: `pacman -Syu` and install `make` with `pacman -S make`. +4. Add `C:\msys64\usr\bin` to your PATH environment variable. + +You can now use `make` from any terminal (PowerShell, cmd.exe, etc.)! 🎉 + +### Sync a forked repository with upstream main (the Hugging Face repository) + +When updating the main branch of a forked repository, please follow these steps to avoid pinging the upstream repository which adds reference notes to each upstream PR, and sends unnecessary notifications to the developers involved in these PRs. + +1. When possible, avoid syncing with the upstream using a branch and PR on the forked repository. Instead, merge directly into the forked main. +2. If a PR is absolutely necessary, use the following steps after checking out your branch: + + ```bash + git checkout -b your-branch-for-syncing + git pull --squash --no-commit upstream main + git commit -m '' + git push --set-upstream origin your-branch-for-syncing + ``` diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/ISSUES.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/ISSUES.md new file mode 100644 index 0000000000000000000000000000000000000000..9c96162647bc6e4f1e4b342a3d7a3ce4461a6066 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/ISSUES.md @@ -0,0 +1,277 @@ + + +# How To Request Support + +This is an Open Source Project so please be mindful that like in any other project of this kind there is no obligation to answer all requests for help. + +However, we want to encourage you to ask for help whenever you think it's needed! We are happy about every question we get because it allows us to better understand your needs, possible misunderstandings, and most importantly a way for you to help us make this library better. That being said, this document's main purpose is to provide guidelines at how you can formulate your requests to increase your chances to be understood and to get support. + +There are two main venues to receive support: [the forums](https://discuss.huggingface.co/) and [the GitHub issues](https://github.com/huggingface/transformers/issues). + +## The Forums + +[The user forums](https://discuss.huggingface.co/) are supported by the wide community of the library users and backed up by developers when needed. + +If you have a difficulty with deploying this library or some questions, or you'd like to discuss a new feature, please first consider discussing those things at the forums. Only when you feel your subject matter has been crystallized and you still need support from the library developers do proceed to file an [issue](https://github.com/huggingface/transformers/issues). + +In particular all "Please explain" questions or objectively very user-specific feature requests belong to the forums. Here are some example of such questions: + +* "I would like to use a BertModel within a RL-Agent for a customer support service. How can I use a BertForMaskedLM in my ChatBotModel?" + +* "Could you please explain why T5 has no positional embedding matrix under T5Model?" + +* "How should I set my generation parameters for translation?" + +* "How to train T5 on De->En translation?" + + +## The GitHub Issues + +Everything which hints at a bug should be opened as an [issue](https://github.com/huggingface/transformers/issues). + +You are not required to read the following guidelines before opening an issue. However, if you notice that your issue doesn't get any replies, chances are that the developers have one or several difficulties with its quality. In this case, reading the following points and adjusting your issue accordingly could help. + +1. Before posting an issue, first search for already posted issues, since chances are someone has already asked a similar question before you. + + If you use Google your search query should be: + + ``` + "huggingface" "transformers" your query + ``` + + The first two quoted words tell Google to limit the search to the context of the Huggingface Transformers. The remainder is your query - most commonly this would be the error message the software fails with. We will go deeper into details shortly. + + The results of such a query will typically match GitHub issues, Hugging Face forums, StackExchange, and blogs. + + If you find relevant hints, you may choose to continue the discussion there if you have follow up questions. + + If what you found is similar but doesn't quite answer your problem, please, post a new issue and do include links to similar issues or forum discussions you may have found. + + Let's look at some examples: + + The error message, often referred to as an assertion, tells us what went wrong. Here is an example of an assertion: + + ```python + Traceback (most recent call last): + File "", line 1, in + File "/transformers/src/transformers/__init__.py", line 34, in + from . import dependency_versions_check + File "/transformers/src/transformers/dependency_versions_check.py", line 34, in + from .utils import is_tokenizers_available + File "/transformers/src/transformers/utils/import_utils.py", line 40, in + from tqdm.auto import tqdm + ModuleNotFoundError: No module named 'tqdm.auto' + ``` + + and it typically includes a traceback, so that we can see the full stack of calls the program made before it fails. This gives us the context to know why the program failed. + + Going back to the above example. If you received this error search, look at the very last line of the error which is: + + ```python + ModuleNotFoundError: No module named 'tqdm.auto' + ``` + + And now we can use it to do the searching on your favorite search engine: + + 1. first for `"huggingface" "transformers" "ModuleNotFoundError: No module named 'tqdm.auto'"` + 2. if you don't find relevant results, then search for just `"ModuleNotFoundError: No module named 'tqdm.auto'"` + 3. and finally if nothing still comes up, then remove the outside quotes: `ModuleNotFoundError: No module named 'tqdm.auto'` + + If the error includes any messages that include bits unique to your filesystem, always remove those in the search query since other users will not have the same filesystem as yours. For example: + + ```bash + python -c 'open("/tmp/wrong_path.txt", "r")' + Traceback (most recent call last): + File "", line 1, in + FileNotFoundError: [Errno 2] No such file or directory: '/tmp/wrong_path.txt' + ``` + Here you'd search for just: `"FileNotFoundError: [Errno 2] No such file or directory"` + + If the local information that you removed were inside the error message and you removed them you may need to remove double quotes since your query is no longer exact. So if the error message was something like: + + ```bash + ValueError: '/tmp/wrong_path.txt' cannot be found + ``` + + then you'd search for `"ValueError" "cannot be found"` + + As you search you will notice that when you don't use quotes often the search engines will return a variety of unrelated hits, which may or may not be what you want. + + Experiment with different ways and find which approach gives the most satisfactory results. + +2. Keep the issue short, providing the information that you think will aid the developers to understand your situation. Put yourself in the shoes of the person who has never seen your code or knows anything about your custom setup. This mental exercise will help to develop an intuition to what/what not to share" + +3. If there is a software failure, always provide the full traceback, for example: + + ```python + $ python -c 'import transformers' + Traceback (most recent call last): + File "", line 1, in + File "/transformers/src/transformers/__init__.py", line 34, in + from . import dependency_versions_check + File "/transformers/src/transformers/dependency_versions_check.py", line 34, in + from .utils import is_tokenizers_available + File "/transformers/src/transformers/utils/import_utils.py", line 40, in + from tqdm.auto import tqdm + ModuleNotFoundError: No module named 'tqdm.auto' + ``` + + As compared to providing just the last line of the error message, e.g.: + ```python + ModuleNotFoundError: No module named 'tqdm.auto' + ``` + which is not sufficient. + + If your application is running on more than one GPU (e.g. under `DistributedDataParallel`) and typically getting every log and traceback printed multiple times, please make sure that you paste only one copy of it. At times the traceback from parallel processes may get interleaved - so either disentangle these or change the loggers to log only for `local_rank==0` so that only one process logs things. + +4. When quoting a traceback, command line instructions and any type of code always enclose it in triple backticks inside the editor window, that is: + + ```` + ``` + git clone https://github.com/huggingface/transformers + cd transformers + pip install . + ``` + ```` + + If it's a command line with a long argument list, please consider breaking it down using backslashes and new lines. Here is an example of a good command line quote: + + ```bash + cd examples/seq2seq + torchrun --nproc_per_node=2 ./finetune_trainer.py \ + --model_name_or_path sshleifer/distill-mbart-en-ro-12-4 --data_dir wmt_en_ro \ + --output_dir output_dir --overwrite_output_dir \ + --do_train --n_train 500 --num_train_epochs 1 \ + --per_device_train_batch_size 1 --freeze_embeds \ + --src_lang en_XX --tgt_lang ro_RO --task translation \ + --fp16 + ``` + + If you don't break it up, one has to scroll horizontally which often makes it quite difficult to quickly see what's happening. + + The backslashes allow us to copy the command directly into the console to run it, without needing to edit it. + +5. Include only the important information that you think will help the developer to quickly identify the problem. + + For example applications often create huge amounts of logs. Ask yourself whether providing all or parts of the log is useful. + + Pasting a 100-1000 lines of log into the issue is an immediate turn off, since it will take a lot of time to figure out where the pertinent parts of the log are. + + Attaching a full log can be helpful if it's done as an attachment, if it's enclosed in the following html code in the comment editor window: + + ``` +
+ Full log +
+
+   many
+   lines
+   go
+   here
+
+   
+
+ ``` + + which would result in the following entry, which can be opened if desired, but otherwise takes little space. + +
+ Full log +
+   many
+   lines
+   go
+   here
+   
+
+ + You could also provide a link to a pastebin service, but this is less beneficial since those links tend to expire quickly and future readers of your issue might not be able to access that log file anymore and may lack some context. + +6. If this is an issue in your code, do try to reduce that code to a minimal example that still demonstrates the problem. Please ask at the forums if you have a hard time figuring how to do that. Please realize that we don't have the luxury of having time to try and understand all of your custom code. + + If you really tried to make a short reproducible code but couldn't figure it out, it might be that having a traceback will give the developer enough information to know what's going on. But if it is not enough and we can't reproduce the problem, we can't really solve it. + + Do not despair if you can't figure it out from the beginning, just share what you can and perhaps someone else will be able to help you at the forums. + + If your setup involves any custom datasets, the best way to help us reproduce the problem is to create a [Google Colab notebook](https://colab.research.google.com/) that demonstrates the issue and once you verify that the issue still exists, include a link to that notebook in the Issue. Just make sure that you don't copy and paste the location bar url of the open notebook - as this is private and we won't be able to open it. Instead, you need to click on `Share` in the right upper corner of the notebook, select `Get Link` and then copy and paste the public link it will give to you. + +7. If you forked off some of this project's code or example applications, please, do not ask us to go into your code repository and figure out what you may have done. The code is already very complex and unless there is an easy way to do a diff and it's a small diff, it won't be possible to find someone with time on their hands to make a lengthy investigation. Albeit, you might find someone at the forums who will be generous to do this for you. + +8. Before reporting an issue, first, always try to update your environment to the latest official version of this library. We have no resources to go and debug older revisions, which could easily have bugs that have been fixed in the latest released version. + + We understand that this is not always possible, especially when APIs change, in which case file an issue against the highest library version your environment can support. + + Of course, if you upgrade the library, always retest that the problem is still there. + +9. Please do not ask us to reproduce an issue with your custom data, since we don't have it. So, either you should use some existing dataset supported by HF datasets or you need to supply a code that generates a small sample on the fly, or some another quick and simple way to get it. + + Please do not send us any non-public domain data that may require a license or a permission to be used. + +10. Do not tag multiple developers on the issue unless you know this is expected, either because you asked them and they gave you an explicit permission to tag them or the issue template instructs you to do so. + + The "who to tag for what domain" part of the issue template is there to help users direct their questions to the right developers who are designated maintainers of project's specific domains. They can then decide at their own discretion to tag other developers if they feel it'd help move the issue forward. + + We currently don't have a triage service and we trust your capacity to identify the right domain and thus the persons to tag in your issue. If you are not sure, please use the forums to ask for guidance. + + When in doubt, err on the side of not tagging a given person. If you tag multiple people out of context or permission don't be surprised if you get no response at all. Please remember that every time you tag someone, they get a notification and you're taking their time without their permission. Please be sensitive to that. + + If you got helped by one of the developers in the past please don't tag them in future issues, unless they are listed in the issue template for the domain you are asking about or that developer gave you an explicit permission to tag them in future issues. + + If you see a certain developer doing multiple and/or recent commits into a specific area of the project that you feel is relevant to your issue, it is not a good reason to tag them. Various developers may be fixing things that prevent them from moving forward, but often their work is focused on a totally different domain. And while they may or may not know how to help you with the problem at hand, it would benefit the whole community much more if they focus on the domain of their unique expertise. + +11. Use the Edit button. Take your time, and re-read and improve the wording and formatting to make your posts and comments as easy to understand as possible. + + Avoid posting multiple comments in a row, as each comment generates a notification for the developers tagged in that issue. If you happened to post multiple comments in a row, and nobody followed up yet - consider merging those into one or a few comments while editing the combined content to be coherent. + + If you choose to edit your older comments after others posted follow up comments you need to be aware that your modifications might not be noticed, so if it's not a typo fixing, try to write a new comment flagging that something has been changed in the previous comments. + + For example, the very first comment is the most important one. If while the thread unfolds you realize that things aren't as they seemed to you originally you may want to edit the first post to reflect the up-to-date understanding of the issue at hand so that it helps those who read your issue in the future quickly understand what's going on and not need to sift through dozens of comments. It also helps to indicate that the post was edited. So, those reading the thread later can understand why there might be certain discontinuity in the information flow. + + Use bullets and items if you have lists of items and the outcome improves overall readability. + + Use backticks to refer to class and function names, e.g. `BartModel` and `generate` as these stand out and improve the speed of a reader's comprehension. + + Try not use italics and bold text too much as these often make the text more difficult to read. + + +12. If you are cross-referencing a specific comment in a given thread or another issue, always link to that specific comment, rather than using the issue link. If you do the latter it could be quite impossible to find which specific comment you're referring to. + + To get the link to the specific comment do not copy the url from the location bar of your browser, but instead, click the `...` icon in the upper right corner of the comment and then select "Copy Link". + + For example the first link is a link to an issue, and the second to a specific comment in the same issue: + + 1. https://github.com/huggingface/transformers/issues/9257 + 2. https://github.com/huggingface/transformers/issues/9257#issuecomment-749945162 + + +13. If you are replying to a last comment, it's totally fine to make your reply with just your comment in it. The readers can follow the information flow here. + + But if you're replying to a comment that happened some comments back it's always a good practice to quote just the relevant lines you're replying it. The `>` is used for quoting, or you can always use the menu to do so. For example your editor box will look like: + + ``` + > How big is your GPU cluster? + + Our cluster is made of 256 GPUs. + ``` + + If you are addressing multiple comments, quote the relevant parts of each before your answer. Some people use the same comment to do multiple replies, others separate them into separate comments. Either way works. The latter approach helps for linking to a specific comment. + +In general the best way to figure out what works the best is learn from issues posted by other people - see which issues get great responses and which get little to no response - observe what the posters who received great responses did differently from those who did not. + +Thank you for reading this somewhat lengthy document. We would like to conclude that these are not absolute rules, but a friendly advice that will help maximize the chances for us to understand what you are trying to communicate, reproduce the problem then resolve it to your satisfaction and the benefit of the whole community. + +If after reading this document there are remaining questions on how and why or there is a need for further elucidation, please, don't hesitate to ask your question in [this thread](https://discuss.huggingface.co/t/how-to-request-support/3128). diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/LICENSE b/tasks/tasksmith-5cbfd9f64dbc/environment/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..68b7d66c97d66c58de883ed0c451af2b3183e6f3 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/LICENSE @@ -0,0 +1,203 @@ +Copyright 2018- The Hugging Face team. All rights reserved. + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/Makefile b/tasks/tasksmith-5cbfd9f64dbc/environment/source/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..8a9470b9af5e0986286188f82e118a38a9acbd87 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/Makefile @@ -0,0 +1,136 @@ +.PHONY: deps_table_update modified_only_fixup extra_style_checks quality style fixup fix-copies test test-examples benchmark + +# make sure to test the local checkout in scripts and not the pre-installed one (don't use quotes!) +export PYTHONPATH = src + +check_dirs := examples tests src utils + +exclude_folders := "" + +modified_only_fixup: + @current_branch=$$(git branch --show-current); \ + if [ "$$current_branch" = "main" ]; then \ + echo "On main branch, running 'style' target instead..."; \ + $(MAKE) style; \ + else \ + modified_py_files=$$(python utils/get_modified_files.py $(check_dirs)); \ + if [ -n "$$modified_py_files" ]; then \ + echo "Checking/fixing files: $${modified_py_files}"; \ + ruff check $${modified_py_files} --fix --exclude $(exclude_folders); \ + ruff format $${modified_py_files} --exclude $(exclude_folders); \ + else \ + echo "No library .py files were modified"; \ + fi; \ + fi + +# Update src/transformers/dependency_versions_table.py + +deps_table_update: + @python setup.py deps_table_update + +deps_table_check_updated: + @md5sum src/transformers/dependency_versions_table.py > md5sum.saved + @python setup.py deps_table_update + @md5sum -c --quiet md5sum.saved || (printf "\nError: the version dependency table is outdated.\nPlease run 'make fixup' or 'make style' and commit the changes.\n\n" && exit 1) + @rm md5sum.saved + +# autogenerating code + +autogenerate_code: deps_table_update + +# Check that the repo is in a good state + +repo-consistency: + python utils/check_copies.py + python utils/check_modular_conversion.py + python utils/check_dummies.py + python utils/check_repo.py + python utils/check_inits.py + python utils/check_pipeline_typing.py + python utils/check_config_docstrings.py + python utils/check_config_attributes.py + python utils/check_doctest_list.py + python utils/update_metadata.py --check-only + python utils/check_docstrings.py + python utils/add_dates.py + +# this target runs checks on all files + +quality: + @python -c "from transformers import *" || (echo '🚨 import failed, this means you introduced unprotected imports! 🚨'; exit 1) + ruff check $(check_dirs) setup.py conftest.py + ruff format --check $(check_dirs) setup.py conftest.py + python utils/sort_auto_mappings.py --check_only + python utils/check_doc_toc.py + python utils/check_docstrings.py --check_all + + +# Format source code automatically and check is there are any problems left that need manual fixing + +extra_style_checks: + python utils/sort_auto_mappings.py + python utils/check_doc_toc.py --fix_and_overwrite + +# this target runs checks on all files and potentially modifies some of them + +style: + ruff check $(check_dirs) setup.py conftest.py --fix --exclude $(exclude_folders) + ruff format $(check_dirs) setup.py conftest.py --exclude $(exclude_folders) + ${MAKE} autogenerate_code + ${MAKE} extra_style_checks + +# Super fast fix and check target that only works on relevant modified files since the branch was made + +fixup: modified_only_fixup extra_style_checks autogenerate_code repo-consistency + +# Make marked copies of snippets of codes conform to the original + +fix-copies: + python utils/check_copies.py --fix_and_overwrite + python utils/check_modular_conversion.py --fix_and_overwrite + python utils/check_dummies.py --fix_and_overwrite + python utils/check_pipeline_typing.py --fix_and_overwrite + python utils/check_doctest_list.py --fix_and_overwrite + python utils/check_docstrings.py --fix_and_overwrite + +# Run tests for the library + +test: + python -m pytest -n auto --dist=loadfile -s -v ./tests/ + +# Run tests for examples + +test-examples: + python -m pytest -n auto --dist=loadfile -s -v ./examples/pytorch/ + +# Run benchmark + +benchmark: + python3 benchmark/benchmark.py --config-dir benchmark/config --config-name generation --commit=diff backend.model=google/gemma-2b backend.cache_implementation=null,static backend.torch_compile=false,true --multirun + +# Run tests for SageMaker DLC release + +test-sagemaker: # install sagemaker dependencies in advance with pip install .[sagemaker] + TEST_SAGEMAKER=True python -m pytest -n auto -s -v ./tests/sagemaker + + +# Release stuff + +pre-release: + python utils/release.py + +pre-patch: + python utils/release.py --patch + +post-release: + python utils/release.py --post_release + +post-patch: + python utils/release.py --post_release --patch + +build-release: + rm -rf dist + rm -rf build + python setup.py bdist_wheel + python setup.py sdist + python utils/check_build.py diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/README.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ece4557a67c7ee2f39783ddb8e8c7fc40978be51 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/README.md @@ -0,0 +1,336 @@ + + +

+ + + + Hugging Face Transformers Library + +
+
+

+ +

+ Checkpoints on Hub + Build + GitHub + Documentation + GitHub release + Contributor Covenant + DOI +

+ +

+

+ English | + 简体中文 | + 繁體中文 | + 한국어 | + Español | + 日本語 | + हिन्दी | + Русский | + Português | + తెలుగు | + Français | + Deutsch | + Tiếng Việt | + العربية | + اردو | +

+

+ +

+

State-of-the-art pretrained models for inference and training

+

+ +

+ +

+ + +Transformers acts as the model-definition framework for state-of-the-art machine learning models in text, computer +vision, audio, video, and multimodal model, for both inference and training. + +It centralizes the model definition so that this definition is agreed upon across the ecosystem. `transformers` is the +pivot across frameworks: if a model definition is supported, it will be compatible with the majority of training +frameworks (Axolotl, Unsloth, DeepSpeed, FSDP, PyTorch-Lightning, ...), inference engines (vLLM, SGLang, TGI, ...), +and adjacent modeling libraries (llama.cpp, mlx, ...) which leverage the model definition from `transformers`. + +We pledge to help support new state-of-the-art models and democratize their usage by having their model definition be +simple, customizable, and efficient. + +There are over 1M+ Transformers [model checkpoints](https://huggingface.co/models?library=transformers&sort=trending) on the [Hugging Face Hub](https://huggingface.com/models) you can use. + +Explore the [Hub](https://huggingface.com/) today to find a model and use Transformers to help you get started right away. + +## Installation + +Transformers works with Python 3.9+ [PyTorch](https://pytorch.org/get-started/locally/) 2.1+, [TensorFlow](https://www.tensorflow.org/install/pip) 2.6+, and [Flax](https://flax.readthedocs.io/en/latest/) 0.4.1+. + +Create and activate a virtual environment with [venv](https://docs.python.org/3/library/venv.html) or [uv](https://docs.astral.sh/uv/), a fast Rust-based Python package and project manager. + +```py +# venv +python -m venv .my-env +source .my-env/bin/activate +# uv +uv venv .my-env +source .my-env/bin/activate +``` + +Install Transformers in your virtual environment. + +```py +# pip +pip install "transformers[torch]" + +# uv +uv pip install "transformers[torch]" +``` + +Install Transformers from source if you want the latest changes in the library or are interested in contributing. However, the *latest* version may not be stable. Feel free to open an [issue](https://github.com/huggingface/transformers/issues) if you encounter an error. + +```shell +git clone https://github.com/huggingface/transformers.git +cd transformers + +# pip +pip install .[torch] + +# uv +uv pip install .[torch] +``` + +## Quickstart + +Get started with Transformers right away with the [Pipeline](https://huggingface.co/docs/transformers/pipeline_tutorial) API. The `Pipeline` is a high-level inference class that supports text, audio, vision, and multimodal tasks. It handles preprocessing the input and returns the appropriate output. + +Instantiate a pipeline and specify model to use for text generation. The model is downloaded and cached so you can easily reuse it again. Finally, pass some text to prompt the model. + +```py +from transformers import pipeline + +pipeline = pipeline(task="text-generation", model="Qwen/Qwen2.5-1.5B") +pipeline("the secret to baking a really good cake is ") +[{'generated_text': 'the secret to baking a really good cake is 1) to use the right ingredients and 2) to follow the recipe exactly. the recipe for the cake is as follows: 1 cup of sugar, 1 cup of flour, 1 cup of milk, 1 cup of butter, 1 cup of eggs, 1 cup of chocolate chips. if you want to make 2 cakes, how much sugar do you need? To make 2 cakes, you will need 2 cups of sugar.'}] +``` + +To chat with a model, the usage pattern is the same. The only difference is you need to construct a chat history (the input to `Pipeline`) between you and the system. + +> [!TIP] +> You can also chat with a model directly from the command line. +> ```shell +> transformers chat Qwen/Qwen2.5-0.5B-Instruct +> ``` + +```py +import torch +from transformers import pipeline + +chat = [ + {"role": "system", "content": "You are a sassy, wise-cracking robot as imagined by Hollywood circa 1986."}, + {"role": "user", "content": "Hey, can you tell me any fun things to do in New York?"} +] + +pipeline = pipeline(task="text-generation", model="meta-llama/Meta-Llama-3-8B-Instruct", torch_dtype=torch.bfloat16, device_map="auto") +response = pipeline(chat, max_new_tokens=512) +print(response[0]["generated_text"][-1]["content"]) +``` + +Expand the examples below to see how `Pipeline` works for different modalities and tasks. + +
+Automatic speech recognition + +```py +from transformers import pipeline + +pipeline = pipeline(task="automatic-speech-recognition", model="openai/whisper-large-v3") +pipeline("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac") +{'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.'} +``` + +
+ +
+Image classification + +

+ +

+ +```py +from transformers import pipeline + +pipeline = pipeline(task="image-classification", model="facebook/dinov2-small-imagenet1k-1-layer") +pipeline("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png") +[{'label': 'macaw', 'score': 0.997848391532898}, + {'label': 'sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita', + 'score': 0.0016551691805943847}, + {'label': 'lorikeet', 'score': 0.00018523589824326336}, + {'label': 'African grey, African gray, Psittacus erithacus', + 'score': 7.85409429227002e-05}, + {'label': 'quail', 'score': 5.502637941390276e-05}] +``` + +
+ +
+Visual question answering + + +

+ +

+ +```py +from transformers import pipeline + +pipeline = pipeline(task="visual-question-answering", model="Salesforce/blip-vqa-base") +pipeline( + image="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/idefics-few-shot.jpg", + question="What is in the image?", +) +[{'answer': 'statue of liberty'}] +``` + +
+ +## Why should I use Transformers? + +1. Easy-to-use state-of-the-art models: + - High performance on natural language understanding & generation, computer vision, audio, video, and multimodal tasks. + - Low barrier to entry for researchers, engineers, and developers. + - Few user-facing abstractions with just three classes to learn. + - A unified API for using all our pretrained models. + +1. Lower compute costs, smaller carbon footprint: + - Share trained models instead of training from scratch. + - Reduce compute time and production costs. + - Dozens of model architectures with 1M+ pretrained checkpoints across all modalities. + +1. Choose the right framework for every part of a models lifetime: + - Train state-of-the-art models in 3 lines of code. + - Move a single model between PyTorch/JAX/TF2.0 frameworks at will. + - Pick the right framework for training, evaluation, and production. + +1. Easily customize a model or an example to your needs: + - We provide examples for each architecture to reproduce the results published by its original authors. + - Model internals are exposed as consistently as possible. + - Model files can be used independently of the library for quick experiments. + + + Hugging Face Enterprise Hub +
+ +## Why shouldn't I use Transformers? + +- This library is not a modular toolbox of building blocks for neural nets. The code in the model files is not refactored with additional abstractions on purpose, so that researchers can quickly iterate on each of the models without diving into additional abstractions/files. +- The training API is optimized to work with PyTorch models provided by Transformers. For generic machine learning loops, you should use another library like [Accelerate](https://huggingface.co/docs/accelerate). +- The [example scripts](https://github.com/huggingface/transformers/tree/main/examples) are only *examples*. They may not necessarily work out-of-the-box on your specific use case and you'll need to adapt the code for it to work. + +## 100 projects using Transformers + +Transformers is more than a toolkit to use pretrained models, it's a community of projects built around it and the +Hugging Face Hub. We want Transformers to enable developers, researchers, students, professors, engineers, and anyone +else to build their dream projects. + +In order to celebrate Transformers 100,000 stars, we wanted to put the spotlight on the +community with the [awesome-transformers](./awesome-transformers.md) page which lists 100 +incredible projects built with Transformers. + +If you own or use a project that you believe should be part of the list, please open a PR to add it! + +## Example models + +You can test most of our models directly on their [Hub model pages](https://huggingface.co/models). + +Expand each modality below to see a few example models for various use cases. + +
+Audio + +- Audio classification with [Whisper](https://huggingface.co/openai/whisper-large-v3-turbo) +- Automatic speech recognition with [Moonshine](https://huggingface.co/UsefulSensors/moonshine) +- Keyword spotting with [Wav2Vec2](https://huggingface.co/superb/wav2vec2-base-superb-ks) +- Speech to speech generation with [Moshi](https://huggingface.co/kyutai/moshiko-pytorch-bf16) +- Text to audio with [MusicGen](https://huggingface.co/facebook/musicgen-large) +- Text to speech with [Bark](https://huggingface.co/suno/bark) + +
+ +
+Computer vision + +- Automatic mask generation with [SAM](https://huggingface.co/facebook/sam-vit-base) +- Depth estimation with [DepthPro](https://huggingface.co/apple/DepthPro-hf) +- Image classification with [DINO v2](https://huggingface.co/facebook/dinov2-base) +- Keypoint detection with [SuperPoint](https://huggingface.co/magic-leap-community/superpoint) +- Keypoint matching with [SuperGlue](https://huggingface.co/magic-leap-community/superglue_outdoor) +- Object detection with [RT-DETRv2](https://huggingface.co/PekingU/rtdetr_v2_r50vd) +- Pose Estimation with [VitPose](https://huggingface.co/usyd-community/vitpose-base-simple) +- Universal segmentation with [OneFormer](https://huggingface.co/shi-labs/oneformer_ade20k_swin_large) +- Video classification with [VideoMAE](https://huggingface.co/MCG-NJU/videomae-large) + +
+ +
+Multimodal + +- Audio or text to text with [Qwen2-Audio](https://huggingface.co/Qwen/Qwen2-Audio-7B) +- Document question answering with [LayoutLMv3](https://huggingface.co/microsoft/layoutlmv3-base) +- Image or text to text with [Qwen-VL](https://huggingface.co/Qwen/Qwen2.5-VL-3B-Instruct) +- Image captioning [BLIP-2](https://huggingface.co/Salesforce/blip2-opt-2.7b) +- OCR-based document understanding with [GOT-OCR2](https://huggingface.co/stepfun-ai/GOT-OCR-2.0-hf) +- Table question answering with [TAPAS](https://huggingface.co/google/tapas-base) +- Unified multimodal understanding and generation with [Emu3](https://huggingface.co/BAAI/Emu3-Gen) +- Vision to text with [Llava-OneVision](https://huggingface.co/llava-hf/llava-onevision-qwen2-0.5b-ov-hf) +- Visual question answering with [Llava](https://huggingface.co/llava-hf/llava-1.5-7b-hf) +- Visual referring expression segmentation with [Kosmos-2](https://huggingface.co/microsoft/kosmos-2-patch14-224) + +
+ +
+NLP + +- Masked word completion with [ModernBERT](https://huggingface.co/answerdotai/ModernBERT-base) +- Named entity recognition with [Gemma](https://huggingface.co/google/gemma-2-2b) +- Question answering with [Mixtral](https://huggingface.co/mistralai/Mixtral-8x7B-v0.1) +- Summarization with [BART](https://huggingface.co/facebook/bart-large-cnn) +- Translation with [T5](https://huggingface.co/google-t5/t5-base) +- Text generation with [Llama](https://huggingface.co/meta-llama/Llama-3.2-1B) +- Text classification with [Qwen](https://huggingface.co/Qwen/Qwen2.5-0.5B) + +
+ +## Citation + +We now have a [paper](https://www.aclweb.org/anthology/2020.emnlp-demos.6/) you can cite for the 🤗 Transformers library: +```bibtex +@inproceedings{wolf-etal-2020-transformers, + title = "Transformers: State-of-the-Art Natural Language Processing", + author = "Thomas Wolf and Lysandre Debut and Victor Sanh and Julien Chaumond and Clement Delangue and Anthony Moi and Pierric Cistac and Tim Rault and Rémi Louf and Morgan Funtowicz and Joe Davison and Sam Shleifer and Patrick von Platen and Clara Ma and Yacine Jernite and Julien Plu and Canwen Xu and Teven Le Scao and Sylvain Gugger and Mariama Drame and Quentin Lhoest and Alexander M. Rush", + booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: System Demonstrations", + month = oct, + year = "2020", + address = "Online", + publisher = "Association for Computational Linguistics", + url = "https://www.aclweb.org/anthology/2020.emnlp-demos.6", + pages = "38--45" +} +``` diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/SECURITY.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..fc71df4436a3c184394ab6b3251cc5cb20165c93 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/SECURITY.md @@ -0,0 +1,32 @@ +# Security Policy + +## Hugging Face Hub, remote artefacts, and remote code + +Transformers is open-source software that is tightly coupled to the Hugging Face Hub. While you have the ability to use it +offline with pre-downloaded model weights, it provides a very simple way to download, use, and manage models locally. + +When downloading artefacts that have been uploaded by others on any platform, you expose yourself to risks. Please +read below for the security recommendations in order to keep your runtime and local environment safe. + +### Remote artefacts + +Models uploaded on the Hugging Face Hub come in different formats. We heavily recommend uploading and downloading +models in the [`safetensors`](https://github.com/huggingface/safetensors) format (which is the default prioritized +by the transformers library), as developed specifically to prevent arbitrary code execution on your system. + +To avoid loading models from unsafe formats (e.g. [pickle](https://docs.python.org/3/library/pickle.html), you should use the `use_safetensors` parameter. If doing so, in the event that no .safetensors file is present, transformers will error when loading the model. + +### Remote code + +#### Modeling + +Transformers supports many model architectures, but is also the bridge between your Python runtime and models that +are stored in model repositories on the Hugging Face Hub. + +These models require the `trust_remote_code=True` parameter to be set when using them; please **always** verify +the content of the modeling files when using this argument. We recommend setting a revision in order to ensure you +protect yourself from updates on the repository. + +## Reporting a Vulnerability + +Feel free to submit vulnerability reports to [security@huggingface.co](mailto:security@huggingface.co), where someone from the HF security team will review and recommend next steps. If reporting a vulnerability specific to open source, please note [Huntr](https://huntr.com) is a vulnerability disclosure program for open source software. diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/awesome-transformers.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/awesome-transformers.md new file mode 100644 index 0000000000000000000000000000000000000000..adc84f101eae9f2ad2bfb6694a4c6d8f93eb6d26 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/awesome-transformers.md @@ -0,0 +1,609 @@ +# Awesome projects built with Transformers + +This page lists awesome projects built on top of Transformers. Transformers is more than a toolkit to use pretrained +models: it's a community of projects built around it and the Hugging Face Hub. We want Transformers to enable +developers, researchers, students, professors, engineers, and anyone else to build their dream projects. + +In this list, we showcase incredibly impactful and novel projects that have pushed the field forward. We celebrate +100 of these projects as we reach the milestone of 100k stars as a community; but we're very open to pull requests +adding other projects to the list. If you believe a project should be here and it's not, then please, open a PR +to add it. + +## [gpt4all](https://github.com/nomic-ai/gpt4all) + +[gpt4all](https://github.com/nomic-ai/gpt4all) is an ecosystem of open-source chatbots trained on massive collections of clean assistant data including code, stories and dialogue. It offers open-source, large language models such as LLaMA and GPT-J trained in an assistant-style. + +Keywords: Open-source, LLaMa, GPT-J, instruction, assistant + +## [recommenders](https://github.com/recommenders-team/recommenders) + +This repository contains examples and best practices for building recommendation systems, provided as Jupyter notebooks. It goes over several aspects required to build efficient recommendation systems: data preparation, modeling, evaluation, model selection & optimization, as well as operationalization + +Keywords: Recommender systems, AzureML + +## [IOPaint](https://github.com/Sanster/IOPaint) + +Image inpainting tool powered by Stable Diffusion. Remove any unwanted object, defect, people from your pictures or erase and replace anything on your pictures. + +Keywords: inpainting, SD, Stable Diffusion + +## [flair](https://github.com/flairNLP/flair) + +FLAIR is a powerful PyTorch NLP framework, covering several important tasks: NER, sentiment-analysis, part-of-speech tagging, text and document embeddings, among other things. + +Keywords: NLP, text embedding, document embedding, biomedical, NER, PoS, sentiment-analysis + +## [mindsdb](https://github.com/mindsdb/mindsdb) + +MindsDB is a low-code ML platform, which automates and integrates several ML frameworks into the data stack as "AI Tables" to streamline the integration of AI into applications, making it accessible to developers of all skill levels. + +Keywords: Database, low-code, AI table + +## [langchain](https://github.com/langchain-ai/langchain) + +[langchain](https://github.com/langchain-ai/langchain) is aimed at assisting in the development of apps merging both LLMs and other sources of knowledge. The library allows chaining calls to applications, creating a sequence across many tools. + +Keywords: LLMs, Large Language Models, Agents, Chains + +## [LlamaIndex](https://github.com/run-llama/llama_index) + +[LlamaIndex](https://github.com/run-llama/llama_index) is a project that provides a central interface to connect your LLM's with external data. It provides various kinds of indices and retrieval mechanisms to perform different LLM tasks and obtain knowledge-augmented results. + +Keywords: LLMs, Large Language Models, Data Retrieval, Indices, Knowledge Augmentation + +## [ParlAI](https://github.com/facebookresearch/ParlAI) + +[ParlAI](https://github.com/facebookresearch/ParlAI) is a python framework for sharing, training and testing dialogue models, from open-domain chitchat, to task-oriented dialogue, to visual question answering. It provides more than 100 datasets under the same API, a large zoo of pretrained models, a set of agents, and has several integrations. + +Keywords: Dialogue, Chatbots, VQA, Datasets, Agents + +## [sentence-transformers](https://github.com/UKPLab/sentence-transformers) + +This framework provides an easy method to compute dense vector representations for sentences, paragraphs, and images. The models are based on transformer networks like BERT / RoBERTa / XLM-RoBERTa etc. and achieve state-of-the-art performance in various task. Text is embedding in vector space such that similar text is close and can efficiently be found using cosine similarity. + +Keywords: Dense vector representations, Text embeddings, Sentence embeddings + +## [ludwig](https://github.com/ludwig-ai/ludwig) + +Ludwig is a declarative machine learning framework that makes it easy to define machine learning pipelines using a simple and flexible data-driven configuration system. Ludwig is targeted at a wide variety of AI tasks. It provides a data-driven configuration system, training, prediction, and evaluation scripts, as well as a programmatic API. + +Keywords: Declarative, Data-driven, ML Framework + +## [InvokeAI](https://github.com/invoke-ai/InvokeAI) + +[InvokeAI](https://github.com/invoke-ai/InvokeAI) is an engine for Stable Diffusion models, aimed at professionals, artists, and enthusiasts. It leverages the latest AI-driven technologies through CLI as well as a WebUI. + +Keywords: Stable-Diffusion, WebUI, CLI + +## [PaddleNLP](https://github.com/PaddlePaddle/PaddleNLP) + +[PaddleNLP](https://github.com/PaddlePaddle/PaddleNLP) is an easy-to-use and powerful NLP library particularly targeted at the Chinese languages. It has support for multiple pre-trained model zoos, and supports a wide-range of NLP tasks from research to industrial applications. + +Keywords: NLP, Chinese, Research, Industry + +## [stanza](https://github.com/stanfordnlp/stanza) + +The Stanford NLP Group's official Python NLP library. It contains support for running various accurate natural language processing tools on 60+ languages and for accessing the Java Stanford CoreNLP software from Python. + +Keywords: NLP, Multilingual, CoreNLP + +## [DeepPavlov](https://github.com/deeppavlov/DeepPavlov) + +[DeepPavlov](https://github.com/deeppavlov/DeepPavlov) is an open-source conversational AI library. It is designed for the development of production ready chat-bots and complex conversational systems, as well as research in the area of NLP and, particularly, of dialog systems. + +Keywords: Conversational, Chatbot, Dialog + +## [alpaca-lora](https://github.com/tloen/alpaca-lora) + +Alpaca-lora contains code for reproducing the Stanford Alpaca results using low-rank adaptation (LoRA). The repository provides training (fine-tuning) as well as generation scripts. + +Keywords: LoRA, Parameter-efficient fine-tuning + +## [imagen-pytorch](https://github.com/lucidrains/imagen-pytorch) + +An open-source Implementation of Imagen, Google's closed-source Text-to-Image Neural Network that beats DALL-E2. As of release, it is the new SOTA for text-to-image synthesis. + +Keywords: Imagen, Text-to-image + +## [adapters](https://github.com/adapter-hub/adapters) + +[adapters](https://github.com/adapter-hub/adapters) is an extension of HuggingFace's Transformers library, integrating adapters into state-of-the-art language models by incorporating AdapterHub, a central repository for pre-trained adapter modules. It is a drop-in replacement for transformers, which is regularly updated to stay up-to-date with the developments of transformers. + +Keywords: Adapters, LoRA, Parameter-efficient fine-tuning, Hub + +## [NeMo](https://github.com/NVIDIA/NeMo) + +NVIDIA [NeMo](https://github.com/NVIDIA/NeMo) is a conversational AI toolkit built for researchers working on automatic speech recognition (ASR), text-to-speech synthesis (TTS), large language models (LLMs), and natural language processing (NLP). The primary objective of [NeMo](https://github.com/NVIDIA/NeMo) is to help researchers from industry and academia to reuse prior work (code and pretrained models) and make it easier to create new https://developer.nvidia.com/conversational-ai#started. + +Keywords: Conversational, ASR, TTS, LLMs, NLP + +## [Runhouse](https://github.com/run-house/runhouse) + +[Runhouse](https://github.com/run-house/runhouse) allows to send code and data to any of your compute or data infra, all in Python, and continue to interact with them normally from your existing code and environment. Runhouse developers mention: + +> Think of it as an expansion pack to your Python interpreter that lets it take detours to remote machines or manipulate remote data. + +Keywords: MLOps, Infrastructure, Data storage, Modeling + +## [MONAI](https://github.com/Project-MONAI/MONAI) + +[MONAI](https://github.com/Project-MONAI/MONAI) is a PyTorch-based, open-source framework for deep learning in healthcare imaging, part of PyTorch Ecosystem. Its ambitions are: +- developing a community of academic, industrial and clinical researchers collaborating on a common foundation; +- creating state-of-the-art, end-to-end training workflows for healthcare imaging; +- providing researchers with the optimized and standardized way to create and evaluate deep learning models. + +Keywords: Healthcare imaging, Training, Evaluation + +## [simpletransformers](https://github.com/ThilinaRajapakse/simpletransformers) + +Simple Transformers lets you quickly train and evaluate Transformer models. Only 3 lines of code are needed to initialize, train, and evaluate a model. It supports a wide variety of NLP tasks. + +Keywords: Framework, simplicity, NLP + +## [JARVIS](https://github.com/microsoft/JARVIS) + +[JARVIS](https://github.com/microsoft/JARVIS) is a system attempting to merge LLMs such as GPT-4 with the rest of the open-source ML community: leveraging up to 60 downstream models in order to perform tasks identified by the LLM. + +Keywords: LLM, Agents, HF Hub + +## [transformers.js](https://github.com/huggingface/transformers.js/) + +[transformers.js](https://github.com/huggingface/transformers.js/) is a JavaScript library targeted at running models from transformers directly within the browser. + +Keywords: Transformers, JavaScript, browser + +## [bumblebee](https://github.com/elixir-nx/bumblebee) + +Bumblebee provides pre-trained Neural Network models on top of Axon, a neural networks library for the Elixir language. It includes integration with 🤗 Models, allowing anyone to download and perform Machine Learning tasks with few lines of code. + +Keywords: Elixir, Axon + +## [argilla](https://github.com/argilla-io/argilla) + +Argilla is an open-source platform providing advanced NLP labeling, monitoring, and workspaces. It is compatible with many open source ecosystems such as Hugging Face, Stanza, FLAIR, and others. + +Keywords: NLP, Labeling, Monitoring, Workspaces + +## [haystack](https://github.com/deepset-ai/haystack) + +Haystack is an open source NLP framework to interact with your data using Transformer models and LLMs. It offers production-ready tools to quickly build complex decision making, question answering, semantic search, text generation applications, and more. + +Keywords: NLP, Framework, LLM + +## [spaCy](https://github.com/explosion/spaCy) + +[spaCy](https://github.com/explosion/spaCy) is a library for advanced Natural Language Processing in Python and Cython. It's built on the very latest research, and was designed from day one to be used in real products. It offers support for transformers models through its third party package, spacy-transformers. + +Keywords: NLP, Framework + +## [speechbrain](https://github.com/speechbrain/speechbrain) + +SpeechBrain is an open-source and all-in-one conversational AI toolkit based on PyTorch. +The goal is to create a single, flexible, and user-friendly toolkit that can be used to easily develop state-of-the-art speech technologies, including systems for speech recognition, speaker recognition, speech enhancement, speech separation, language identification, multi-microphone signal processing, and many others. + +Keywords: Conversational, Speech + +## [skorch](https://github.com/skorch-dev/skorch) + +Skorch is a scikit-learn compatible neural network library that wraps PyTorch. It has support for models within transformers, and tokenizers from tokenizers. + +Keywords: Scikit-Learn, PyTorch + +## [bertviz](https://github.com/jessevig/bertviz) + +BertViz is an interactive tool for visualizing attention in Transformer language models such as BERT, GPT2, or T5. It can be run inside a Jupyter or Colab notebook through a simple Python API that supports most Huggingface models. + +Keywords: Visualization, Transformers + +## [mesh-transformer-jax](https://github.com/kingoflolz/mesh-transformer-jax) + +[mesh-transformer-jax](https://github.com/kingoflolz/mesh-transformer-jax) is a haiku library using the xmap/pjit operators in JAX for model parallelism of transformers. This library is designed for scalability up to approximately 40B parameters on TPUv3s. It was the library used to train the GPT-J model. + +Keywords: Haiku, Model parallelism, LLM, TPU + +## [deepchem](https://github.com/deepchem/deepchem) + +DeepChem aims to provide a high quality open-source toolchain that democratizes the use of deep-learning in drug discovery, materials science, quantum chemistry, and biology. + +Keywords: Drug discovery, Materials Science, Quantum Chemistry, Biology + +## [OpenNRE](https://github.com/thunlp/OpenNRE) + +An Open-Source Package for Neural Relation Extraction (NRE). It is targeted at a wide range of users, from newcomers to relation extraction, to developers, researchers, or students. + +Keywords: Neural Relation Extraction, Framework + +## [pycorrector](https://github.com/shibing624/pycorrector) + +PyCorrector is a Chinese Text Error Correction Tool. It uses a language model to detect errors, pinyin feature and shape feature to correct Chinese text errors. it can be used for Chinese Pinyin and stroke input method. + +Keywords: Chinese, Error correction tool, Language model, Pinyin + +## [nlpaug](https://github.com/makcedward/nlpaug) + +This python library helps you with augmenting nlp for machine learning projects. It is a lightweight library featuring synthetic data generation for improving model performance, support for audio and text, and compatibility with several ecosystems (scikit-learn, pytorch, tensorflow). + +Keywords: Data augmentation, Synthetic data generation, Audio, NLP + +## [dream-textures](https://github.com/carson-katri/dream-textures) + +[dream-textures](https://github.com/carson-katri/dream-textures) is a library targeted at bringing stable-diffusion support within Blender. It supports several use-cases, such as image generation, texture projection, inpainting/outpainting, ControlNet, and upscaling. + +Keywords: Stable-Diffusion, Blender + +## [seldon-core](https://github.com/SeldonIO/seldon-core) + +Seldon core converts your ML models (Tensorflow, Pytorch, H2o, etc.) or language wrappers (Python, Java, etc.) into production REST/GRPC microservices. +Seldon handles scaling to thousands of production machine learning models and provides advanced machine learning capabilities out of the box including Advanced Metrics, Request Logging, Explainers, Outlier Detectors, A/B Tests, Canaries and more. + +Keywords: Microservices, Modeling, Language wrappers + +## [open_model_zoo](https://github.com/openvinotoolkit/open_model_zoo) + +This repository includes optimized deep learning models and a set of demos to expedite development of high-performance deep learning inference applications. Use these free pre-trained models instead of training your own models to speed-up the development and production deployment process. + +Keywords: Optimized models, Demos + +## [ml-stable-diffusion](https://github.com/apple/ml-stable-diffusion) + +ML-Stable-Diffusion is a repository by Apple bringing Stable Diffusion support to Core ML, on Apple Silicon devices. It supports stable diffusion checkpoints hosted on the Hugging Face Hub. + +Keywords: Stable Diffusion, Apple Silicon, Core ML + +## [stable-dreamfusion](https://github.com/ashawkey/stable-dreamfusion) + +Stable-Dreamfusion is a pytorch implementation of the text-to-3D model Dreamfusion, powered by the Stable Diffusion text-to-2D model. + +Keywords: Text-to-3D, Stable Diffusion + +## [txtai](https://github.com/neuml/txtai) + +[txtai](https://github.com/neuml/txtai) is an open-source platform for semantic search and workflows powered by language models. txtai builds embeddings databases, which are a union of vector indexes and relational databases enabling similarity search with SQL. Semantic workflows connect language models together into unified applications. + +Keywords: Semantic search, LLM + +## [djl](https://github.com/deepjavalibrary/djl) + +Deep Java Library (DJL) is an open-source, high-level, engine-agnostic Java framework for deep learning. DJL is designed to be easy to get started with and simple to use for developers. DJL provides a native Java development experience and functions like any other regular Java library. DJL offers [a Java binding](https://github.com/deepjavalibrary/djl/tree/master/extensions/tokenizers) for HuggingFace Tokenizers and easy conversion toolkit for HuggingFace model to deploy in Java. + +Keywords: Java, Framework + +## [lm-evaluation-harness](https://github.com/EleutherAI/lm-evaluation-harness/) + +This project provides a unified framework to test generative language models on a large number of different evaluation tasks. It has support for more than 200 tasks, and supports different ecosystems: HF Transformers, GPT-NeoX, DeepSpeed, as well as the OpenAI API. + +Keywords: LLM, Evaluation, Few-shot + +## [gpt-neox](https://github.com/EleutherAI/gpt-neox) + +This repository records EleutherAI's library for training large-scale language models on GPUs. The framework is based on NVIDIA's Megatron Language Model and has been augmented with techniques from DeepSpeed as well as some novel optimizations. It is focused on training multi-billion-parameter models. + +Keywords: Training, LLM, Megatron, DeepSpeed + +## [muzic](https://github.com/microsoft/muzic) + +Muzic is a research project on AI music that empowers music understanding and generation with deep learning and artificial intelligence. Muzic was created by researchers from Microsoft Research Asia. + +Keywords: Music understanding, Music generation + +## [dalle-flow](https://github.com/jina-ai/dalle-flow) + +DALL·E Flow is an interactive workflow for generating high-definition images from a text prompt. It leverages DALL·E-Mega, GLID-3 XL, and Stable Diffusion to generate image candidates, and then calls CLIP-as-service to rank the candidates w.r.t. the prompt. +The preferred candidate is fed to GLID-3 XL for diffusion, which often enriches the texture and background. Finally, the candidate is upscaled to 1024x1024 via SwinIR. + +Keywords: High-definition image generation, Stable Diffusion, DALL-E Mega, GLID-3 XL, CLIP, SwinIR + +## [lightseq](https://github.com/bytedance/lightseq) + +LightSeq is a high performance training and inference library for sequence processing and generation implemented in CUDA. It enables highly efficient computation of modern NLP and CV models such as BERT, GPT, Transformer, etc. It is therefore best useful for machine translation, text generation, image classification, and other sequence related tasks. + +Keywords: Training, Inference, Sequence Processing, Sequence Generation + +## [LaTeX-OCR](https://github.com/lukas-blecher/LaTeX-OCR) + +The goal of this project is to create a learning based system that takes an image of a math formula and returns corresponding LaTeX code. + +Keywords: OCR, LaTeX, Math formula + +## [open_clip](https://github.com/mlfoundations/open_clip) + +OpenCLIP is an open source implementation of OpenAI's CLIP. + +The goal of this repository is to enable training models with contrastive image-text supervision, and to investigate their properties such as robustness to distribution shift. +The starting point is an implementation of CLIP that matches the accuracy of the original CLIP models when trained on the same dataset. + +Specifically, a ResNet-50 model trained with this codebase on OpenAI's 15 million image subset of YFCC achieves 32.7% top-1 accuracy on ImageNet. + +Keywords: CLIP, Open-source, Contrastive, Image-text + +## [dalle-playground](https://github.com/saharmor/dalle-playground) + +A playground to generate images from any text prompt using Stable Diffusion and Dall-E mini. + +Keywords: WebUI, Stable Diffusion, Dall-E mini + +## [FedML](https://github.com/FedML-AI/FedML) + +[FedML](https://github.com/FedML-AI/FedML) is a federated learning and analytics library enabling secure and collaborative machine learning on decentralized data anywhere at any scale. + +It supports large-scale cross-silo federated learning, and cross-device federated learning on smartphones/IoTs, and research simulation. + +Keywords: Federated Learning, Analytics, Collaborative ML, Decentralized + +## [gpt-code-clippy](https://github.com/CodedotAl/gpt-code-clippy) + +GPT-Code-Clippy (GPT-CC) is an open source version of GitHub Copilot, a language model -- based on GPT-3, called GPT-Codex -- that is fine-tuned on publicly available code from GitHub. + +Keywords: LLM, Code + +## [TextAttack](https://github.com/QData/TextAttack) + +[TextAttack](https://github.com/QData/TextAttack) 🐙 is a Python framework for adversarial attacks, data augmentation, and model training in NLP. + +Keywords: Adversarial attacks, Data augmentation, NLP + +## [OpenPrompt](https://github.com/thunlp/OpenPrompt) + +Prompt-learning is a paradigm to adapt pre-trained language models (PLMs) to downstream NLP tasks, which modify the input text with a textual template and directly uses PLMs to conduct pre-trained tasks. This library provides a standard, flexible and extensible framework to deploy the prompt-learning pipeline. [OpenPrompt](https://github.com/thunlp/OpenPrompt) supports loading PLMs directly from https://github.com/huggingface/transformers. + +## [text-generation-webui](https://github.com/oobabooga/text-generation-webui/) + +[text-generation-webui](https://github.com/oobabooga/text-generation-webui/) is a Gradio Web UI for running Large Language Models like LLaMA, llama.cpp, GPT-J, Pythia, OPT, and GALACTICA. + +Keywords: LLM, WebUI + +## [libra](https://github.com/Palashio/libra) + +An ergonomic machine learning [libra](https://github.com/Palashio/libra)ry for non-technical users. It focuses on ergonomics and on ensuring that training a model is as simple as it can be. + +Keywords: Ergonomic, Non-technical + +## [alibi](https://github.com/SeldonIO/alibi) + +Alibi is an open source Python library aimed at machine learning model inspection and interpretation. The focus of the library is to provide high-quality implementations of black-box, white-box, local and global explanation methods for classification and regression models. + +Keywords: Model inspection, Model interpretation, Black-box, White-box + +## [tortoise-tts](https://github.com/neonbjb/tortoise-tts) + +Tortoise is a text-to-speech program built with the following priorities: strong multi-voice capabilities, and highly realistic prosody and intonation. + +Keywords: Text-to-speech + +## [flower](https://github.com/adap/flower) + +Flower (flwr) is a framework for building federated learning systems. The design of Flower is based on a few guiding principles: customizability, extendability, framework agnosticity, and ease-of-use. + +Keywords: Federated learning systems, Customizable, Extendable, Framework-agnostic, Simplicity + +## [fast-bert](https://github.com/utterworks/fast-bert) + +Fast-Bert is a deep learning library that allows developers and data scientists to train and deploy BERT and XLNet based models for natural language processing tasks beginning with Text Classification. It is aimed at simplicity. + +Keywords: Deployment, BERT, XLNet + +## [towhee](https://github.com/towhee-io/towhee) + +Towhee makes it easy to build neural data processing pipelines for AI applications. We provide hundreds of models, algorithms, and transformations that can be used as standard pipeline building blocks. Users can use Towhee's Pythonic API to build a prototype of their pipeline and automatically optimize it for production-ready environments. + +Keywords: Data processing pipeline, Optimization + +## [alibi-detect](https://github.com/SeldonIO/alibi-detect) + +Alibi Detect is an open source Python library focused on outlier, adversarial and drift detection. The package aims to cover both online and offline detectors for tabular data, text, images and time series. Both TensorFlow and PyTorch backends are supported for drift detection. + +Keywords: Adversarial, Outlier, Drift detection + +## [FARM](https://github.com/deepset-ai/FARM) + +[FARM](https://github.com/deepset-ai/FARM) makes Transfer Learning with BERT & Co simple, fast and enterprise-ready. It's built upon transformers and provides additional features to simplify the life of developers: Parallelized preprocessing, highly modular design, multi-task learning, experiment tracking, easy debugging and close integration with AWS SageMaker. + +Keywords: Transfer Learning, Modular design, Multi-task learning, Experiment tracking + +## [aitextgen](https://github.com/minimaxir/aitextgen) + +A robust Python tool for text-based AI training and generation using OpenAI's GPT-2 and EleutherAI's GPT Neo/GPT-3 architecture. +[aitextgen](https://github.com/minimaxir/aitextgen) is a Python package that leverages PyTorch, Hugging Face Transformers and pytorch-lightning with specific optimizations for text generation using GPT-2, plus many added features. + +Keywords: Training, Generation + +## [diffgram](https://github.com/diffgram/diffgram) + +Diffgram aims to integrate human supervision into platforms. We support your team programmatically changing the UI (Schema, layout, etc.) like in Streamlit. This means that you can collect and annotate timely data from users. In other words, we are the platform behind your platform, an integrated part of your application, to ship new & better AI products faster. + +Keywords: Human supervision, Platform + +## [ecco](https://github.com/jalammar/ecco) + +Explain, analyze, and visualize NLP language models. Ecco creates interactive visualizations directly in Jupyter notebooks explaining the behavior of Transformer-based language models (like GPT2, BERT, RoBERTA, T5, and T0). + +Keywords: Model explainability + +## [s3prl](https://github.com/s3prl/s3prl) + +[s3prl](https://github.com/s3prl/s3prl) stands for Self-Supervised Speech Pre-training and Representation Learning. Self-supervised speech pre-trained models are called upstream in this toolkit, and are utilized in various downstream tasks. + +Keywords: Speech, Training + +## [ru-dalle](https://github.com/ai-forever/ru-dalle) + +RuDALL-E aims to be similar to DALL-E, targeted to Russian. + +Keywords: DALL-E, Russian + +## [DeepKE](https://github.com/zjunlp/DeepKE) + +[DeepKE](https://github.com/zjunlp/DeepKE) is a knowledge extraction toolkit for knowledge graph construction supporting cnSchema,low-resource, document-level and multimodal scenarios for entity, relation and attribute extraction. + +Keywords: Knowledge Extraction, Knowledge Graphs + +## [Nebuly](https://github.com/nebuly-ai/optimate) + +Nebuly is the next-generation platform to monitor and optimize your AI costs in one place. The platform connects to all your AI cost sources (compute, API providers, AI software licenses, etc) and centralizes them in one place to give you full visibility on a model basis. The platform also provides optimization recommendations and a co-pilot model that can guide during the optimization process. The platform builds on top of the open-source tools allowing you to optimize the different steps of your AI stack to squeeze out the best possible cost performances. + +Keywords: Optimization, Performance, Monitoring + +## [imaginAIry](https://github.com/brycedrennan/imaginAIry) + +Offers a CLI and a Python API to generate images with Stable Diffusion. It has support for many tools, like image structure control (controlnet), instruction-based image edits (InstructPix2Pix), prompt-based masking (clipseg), among others. + +Keywords: Stable Diffusion, CLI, Python API + +## [sparseml](https://github.com/neuralmagic/sparseml) + +SparseML is an open-source model optimization toolkit that enables you to create inference-optimized sparse models using pruning, quantization, and distillation algorithms. Models optimized with SparseML can then be exported to the ONNX and deployed with DeepSparse for GPU-class performance on CPU hardware. + +Keywords: Model optimization, Pruning, Quantization, Distillation + +## [opacus](https://github.com/pytorch/opacus) + +Opacus is a library that enables training PyTorch models with differential privacy. It supports training with minimal code changes required on the client, has little impact on training performance, and allows the client to online track the privacy budget expended at any given moment. + +Keywords: Differential privacy + +## [LAVIS](https://github.com/salesforce/LAVIS) + +[LAVIS](https://github.com/salesforce/LAVIS) is a Python deep learning library for LAnguage-and-VISion intelligence research and applications. This library aims to provide engineers and researchers with a one-stop solution to rapidly develop models for their specific multimodal scenarios, and benchmark them across standard and customized datasets. It features a unified interface design to access + +Keywords: Multimodal, NLP, Vision + +## [buzz](https://github.com/chidiwilliams/buzz) + +Buzz transcribes and translates audio offline on your personal computer. Powered by OpenAI's Whisper. + +Keywords: Audio transcription, Translation + +## [rust-bert](https://github.com/guillaume-be/rust-bert) + +Rust-native state-of-the-art Natural Language Processing models and pipelines. Port of Hugging Face's Transformers library, using the tch-rs crate and pre-processing from rust-tokenizers. Supports multi-threaded tokenization and GPU inference. This repository exposes the model base architecture, task-specific heads and ready-to-use pipelines. + +Keywords: Rust, BERT, Inference + +## [EasyNLP](https://github.com/alibaba/EasyNLP) + +[EasyNLP](https://github.com/alibaba/EasyNLP) is an easy-to-use NLP development and application toolkit in PyTorch, first released inside Alibaba in 2021. It is built with scalable distributed training strategies and supports a comprehensive suite of NLP algorithms for various NLP applications. [EasyNLP](https://github.com/alibaba/EasyNLP) integrates knowledge distillation and few-shot learning for landing large pre-trained models, together with various popular multi-modality pre-trained models. It provides a unified framework of model training, inference, and deployment for real-world applications. + +Keywords: NLP, Knowledge distillation, Few-shot learning, Multi-modality, Training, Inference, Deployment + +## [TurboTransformers](https://github.com/Tencent/TurboTransformers) + +A fast and user-friendly runtime for transformer inference (Bert, Albert, GPT2, Decoders, etc) on CPU and GPU. + +Keywords: Optimization, Performance + +## [hivemind](https://github.com/learning-at-home/hivemind) + +Hivemind is a PyTorch library for decentralized deep learning across the Internet. Its intended usage is training one large model on hundreds of computers from different universities, companies, and volunteers. + +Keywords: Decentralized training + +## [docquery](https://github.com/impira/docquery) + +DocQuery is a library and command-line tool that makes it easy to analyze semi-structured and unstructured documents (PDFs, scanned images, etc.) using large language models (LLMs). You simply point DocQuery at one or more documents and specify a question you want to ask. DocQuery is created by the team at Impira. + +Keywords: Semi-structured documents, Unstructured documents, LLM, Document Question Answering + +## [CodeGeeX](https://github.com/THUDM/CodeGeeX) + +[CodeGeeX](https://github.com/THUDM/CodeGeeX) is a large-scale multilingual code generation model with 13 billion parameters, pre-trained on a large code corpus of more than 20 programming languages. It has several unique features: +- Multilingual code generation +- Crosslingual code translation +- Is a customizable programming assistant + +Keywords: Code Generation Model + +## [ktrain](https://github.com/amaiya/ktrain) + +[ktrain](https://github.com/amaiya/ktrain) is a lightweight wrapper for the deep learning library TensorFlow Keras (and other libraries) to help build, train, and deploy neural networks and other machine learning models. Inspired by ML framework extensions like fastai and ludwig, [ktrain](https://github.com/amaiya/ktrain) is designed to make deep learning and AI more accessible and easier to apply for both newcomers and experienced practitioners. + +Keywords: Keras wrapper, Model building, Training, Deployment + +## [FastDeploy](https://github.com/PaddlePaddle/FastDeploy) + +[FastDeploy](https://github.com/PaddlePaddle/FastDeploy) is an Easy-to-use and High Performance AI model deployment toolkit for Cloud, Mobile and Edge with packageout-of-the-box and unified experience, endend-to-end optimization for over fire160+ Text, Vision, Speech and Cross-modal AI models. Including image classification, object detection, OCR, face detection, matting, pp-tracking, NLP, stable diffusion, TTS and other tasks to meet developers' industrial deployment needs for multi-scenario, multi-hardware and multi-platform. + +Keywords: Model deployment, CLoud, Mobile, Edge + +## [underthesea](https://github.com/undertheseanlp/underthesea) + +[underthesea](https://github.com/undertheseanlp/underthesea) is a Vietnamese NLP toolkit. Underthesea is a suite of open source Python modules data sets and tutorials supporting research and development in Vietnamese Natural Language Processing. We provide extremely easy API to quickly apply pretrained NLP models to your Vietnamese text, such as word segmentation, part-of-speech tagging (PoS), named entity recognition (NER), text classification and dependency parsing. + +Keywords: Vietnamese, NLP + +## [hasktorch](https://github.com/hasktorch/hasktorch) + +Hasktorch is a library for tensors and neural networks in Haskell. It is an independent open source community project which leverages the core C++ libraries shared by PyTorch. + +Keywords: Haskell, Neural Networks + +## [donut](https://github.com/clovaai/donut) + +Donut, or Document understanding transformer, is a new method of document understanding that utilizes an OCR-free end-to-end Transformer model. + +Donut does not require off-the-shelf OCR engines/APIs, yet it shows state-of-the-art performances on various visual document understanding tasks, such as visual document classification or information extraction (a.k.a. document parsing). + +Keywords: Document Understanding + +## [transformers-interpret](https://github.com/cdpierse/transformers-interpret) + +Transformers Interpret is a model explainability tool designed to work exclusively with the transformers package. + +In line with the philosophy of the Transformers package Transformers Interpret allows any transformers model to be explained in just two lines. Explainers are available for both text and computer vision models. Visualizations are also available in notebooks and as savable png and html files + +Keywords: Model interpretation, Visualization + +## [mlrun](https://github.com/mlrun/mlrun) + +MLRun is an open MLOps platform for quickly building and managing continuous ML applications across their lifecycle. MLRun integrates into your development and CI/CD environment and automates the delivery of production data, ML pipelines, and online applications, significantly reducing engineering efforts, time to production, and computation resources. With MLRun, you can choose any IDE on your local machine or on the cloud. MLRun breaks the silos between data, ML, software, and DevOps/MLOps teams, enabling collaboration and fast continuous improvements. + +Keywords: MLOps + +## [FederatedScope](https://github.com/alibaba/FederatedScope) + +[FederatedScope](https://github.com/alibaba/FederatedScope) is a comprehensive federated learning platform that provides convenient usage and flexible customization for various federated learning tasks in both academia and industry. Based on an event-driven architecture, [FederatedScope](https://github.com/alibaba/FederatedScope) integrates rich collections of functionalities to satisfy the burgeoning demands from federated learning, and aims to build up an easy-to-use platform for promoting learning safely and effectively. + +Keywords: Federated learning, Event-driven + +## [pythainlp](https://github.com/PyThaiNLP/pythainlp) + +PyThaiNLP is a Python package for text processing and linguistic analysis, similar to NLTK with focus on Thai language. + +Keywords: Thai, NLP, NLTK + +## [FlagAI](https://github.com/FlagAI-Open/FlagAI) + +[FlagAI](https://github.com/FlagAI-Open/FlagAI) (Fast LArge-scale General AI models) is a fast, easy-to-use and extensible toolkit for large-scale model. Our goal is to support training, fine-tuning, and deployment of large-scale models on various downstream tasks with multi-modality. + +Keywords: Large models, Training, Fine-tuning, Deployment, Multi-modal + +## [pyserini](https://github.com/castorini/pyserini) + +[pyserini](https://github.com/castorini/pyserini) is a Python toolkit for reproducible information retrieval research with sparse and dense representations. Retrieval using sparse representations is provided via integration with the group's Anserini IR toolkit. Retrieval using dense representations is provided via integration with Facebook's Faiss library. + +Keywords: IR, Information Retrieval, Dense, Sparse + +## [baal](https://github.com/baal-org/baal) + +[baal](https://github.com/baal-org/baal) is an active learning library that supports both industrial applications and research usecases. [baal](https://github.com/baal-org/baal) currently supports Monte-Carlo Dropout, MCDropConnect, deep ensembles, and semi-supervised learning. + +Keywords: Active Learning, Research, Labeling + +## [cleanlab](https://github.com/cleanlab/cleanlab) + +[cleanlab](https://github.com/cleanlab/cleanlab) is the standard data-centric AI package for data quality and machine learning with messy, real-world data and labels. For text, image, tabular, audio (among others) datasets, you can use cleanlab to automatically: detect data issues (outliers, label errors, near duplicates, etc), train robust ML models, infer consensus + annotator-quality for multi-annotator data, suggest data to (re)label next (active learning). + +Keywords: Data-Centric AI, Data Quality, Noisy Labels, Outlier Detection, Active Learning + +## [BentoML](https://github.com/bentoml/BentoML) + +[BentoML](https://github.com/bentoml) is the unified framework for building, shipping, and scaling production-ready AI applications incorporating traditional ML, pre-trained AI models, Generative and Large Language Models. +All Hugging Face models and pipelines can be seamlessly integrated into BentoML applications, enabling the running of models on the most suitable hardware and independent scaling based on usage. + +Keywords: BentoML, Framework, Deployment, AI Applications + +## [LLaMA Factory](https://github.com/hiyouga/LLaMA-Factory) + +[LLaMA Factory](https://github.com/hiyouga/LLaMA-Factory) offers a user-friendly fine-tuning framework that incorporates PEFT. The repository includes training(fine-tuning) and inference examples for LLaMA-2, BLOOM, Falcon, Baichuan, Qwen, and other LLMs. A ChatGLM version is also available in [ChatGLM-Efficient-Tuning](https://github.com/hiyouga/ChatGLM-Efficient-Tuning). + +Keywords: PEFT, fine-tuning, LLaMA-2, ChatGLM, Qwen + diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/.gitignore b/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..2f3040f513f24ba696b7d457130dfbf0cb876b53 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/.gitignore @@ -0,0 +1 @@ +benchmark_results/ \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/README.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3935f02b389d841367d16f11bbf7c6775fb09a14 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/README.md @@ -0,0 +1,49 @@ +# Benchmarks + +You might want to add new benchmarks. + +You will need to define a python function named `run_benchmark` in your python file and the file must be located in this `benchmark/` directory. + +The expected function signature is the following: + +```py +def run_benchmark(logger: Logger, branch: str, commit_id: str, commit_msg: str, num_tokens_to_generate=100): +``` + +## Writing metrics to the database + +`MetricsRecorder` is thread-safe, in the sense of the python [`Thread`](https://docs.python.org/3/library/threading.html#threading.Thread). This means you can start a background thread to do the readings on the device measurements while not blocking the main thread to execute the model measurements. + +cf [`llama.py`](./llama.py) to see an example of this in practice. + +```py +from benchmarks_entrypoint import MetricsRecorder +import psycopg2 + +def run_benchmark(logger: Logger, branch: str, commit_id: str, commit_msg: str, num_tokens_to_generate=100): + metrics_recorder = MetricsRecorder(psycopg2.connect("dbname=metrics"), logger, branch, commit_id, commit_msg) + benchmark_id = metrics_recorder.initialise_benchmark({"gpu_name": gpu_name, "model_id": model_id}) + # To collect device measurements + metrics_recorder.collect_device_measurements( + benchmark_id, cpu_util, mem_megabytes, gpu_util, gpu_mem_megabytes + ) + # To collect your model measurements + metrics_recorder.collect_model_measurements( + benchmark_id, + { + "model_load_time": model_load_time, + "first_eager_forward_pass_time_secs": first_eager_fwd_pass_time, + "second_eager_forward_pass_time_secs": second_eager_fwd_pass_time, + "first_eager_generate_time_secs": first_eager_generate_time, + "second_eager_generate_time_secs": second_eager_generate_time, + "time_to_first_token_secs": time_to_first_token, + "time_to_second_token_secs": time_to_second_token, + "time_to_third_token_secs": time_to_third_token, + "time_to_next_token_mean_secs": mean_time_to_next_token, + "first_compile_generate_time_secs": first_compile_generate_time, + "second_compile_generate_time_secs": second_compile_generate_time, + "third_compile_generate_time_secs": third_compile_generate_time, + "fourth_compile_generate_time_secs": fourth_compile_generate_time, + }, + ) +``` diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/__init__.py b/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/benches/llama.py b/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/benches/llama.py new file mode 100644 index 0000000000000000000000000000000000000000..8d7e60fbfe3ca3dc6706891e6d6eb219751af2e0 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/benches/llama.py @@ -0,0 +1,345 @@ +# Copyright 2025 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from logging import Logger +import os +from threading import Event, Thread +from time import perf_counter, sleep +from typing import Optional +import sys + +# Add the parent directory to Python path to import benchmarks_entrypoint +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +from benchmarks_entrypoint import MetricsRecorder + +import gpustat +import psutil +import psycopg2 + +# Optional heavy ML dependencies - only required when actually running the benchmark +try: + import torch + from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig, StaticCache + TRANSFORMERS_AVAILABLE = True +except ImportError: + TRANSFORMERS_AVAILABLE = False + torch = None + AutoModelForCausalLM = None + AutoTokenizer = None + GenerationConfig = None + StaticCache = None + +os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1" +os.environ["TOKENIZERS_PARALLELISM"] = "1" + +# Only set torch precision if torch is available +if TRANSFORMERS_AVAILABLE: + torch.set_float32_matmul_precision("high") + + +def collect_metrics(benchmark_id, continue_metric_collection, metrics_recorder): + p = psutil.Process(os.getpid()) + while not continue_metric_collection.is_set(): + with p.oneshot(): + cpu_util = p.cpu_percent() + mem_megabytes = p.memory_info().rss / (1024 * 1024) + gpu_stats = gpustat.GPUStatCollection.new_query() + gpu_util = gpu_stats[0]["utilization.gpu"] + gpu_mem_megabytes = gpu_stats[0]["memory.used"] + metrics_recorder.collect_device_measurements( + benchmark_id, cpu_util, mem_megabytes, gpu_util, gpu_mem_megabytes + ) + sleep(0.01) + + +def run_benchmark( + logger: Logger, repository: str, branch: str, commit_id: str, commit_msg: str, metrics_recorder=None, num_tokens_to_generate=100 +): + # Check if required ML dependencies are available + if not TRANSFORMERS_AVAILABLE: + logger.error("Transformers and torch are required to run the LLaMA benchmark. Please install them with:") + logger.error("pip install torch transformers") + logger.error("Skipping LLaMA benchmark due to missing dependencies.") + return + + continue_metric_collection = Event() + metrics_thread = None + model_id = "meta-llama/Llama-2-7b-hf" + + # If no metrics_recorder is provided, create one for backward compatibility + if metrics_recorder is None: + try: + metrics_recorder = MetricsRecorder( + psycopg2.connect("dbname=metrics"), logger, repository, branch, commit_id, commit_msg, True + ) + should_close_recorder = True + except Exception as e: + logger.error(f"Failed to create metrics recorder: {e}") + return + else: + should_close_recorder = False + try: + gpu_stats = gpustat.GPUStatCollection.new_query() + gpu_name = gpu_stats[0]["name"] + benchmark_id = metrics_recorder.initialise_benchmark({"gpu_name": gpu_name, "model_id": model_id}) + logger.info(f"running benchmark #{benchmark_id} on {gpu_name} for {model_id}") + metrics_thread = Thread( + target=collect_metrics, + args=[benchmark_id, continue_metric_collection, metrics_recorder], + ) + metrics_thread.start() + logger.info("started background thread to fetch device metrics") + + os.environ["TOKENIZERS_PARALLELISM"] = "false" # silence warnings when compiling + + device = "cuda" + + logger.info("downloading weights") + # This is to avoid counting download in model load time measurement + model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16) + gen_config = GenerationConfig(do_sample=False, top_p=1, temperature=1) + logger.info("loading model") + start = perf_counter() + model = AutoModelForCausalLM.from_pretrained( + model_id, torch_dtype=torch.float16, generation_config=gen_config + ).eval() + model.to(device) + torch.cuda.synchronize() + end = perf_counter() + model_load_time = end - start + logger.info(f"loaded model in: {model_load_time}s") + + tokenizer = AutoTokenizer.from_pretrained(model_id) + + prompt = "Why dogs are so cute?" + inputs = tokenizer(prompt, return_tensors="pt").to(device) + + # Specify the max length (including both the prompt and the response) + # When calling `generate` with `cache_implementation="static" later, this is also used to create a `StaticCache` object + # with sequence length = `max_length`. The longer the more you will re-use it + seq_length = inputs["input_ids"].shape[1] + model.generation_config.max_length = seq_length + num_tokens_to_generate + batch_size = inputs["input_ids"].shape[0] + + # Copied from the gpt-fast repo + def multinomial_sample_one_no_sync(probs_sort): # Does multinomial sampling without a cuda synchronization + q = torch.empty_like(probs_sort).exponential_(1) + return torch.argmax(probs_sort / q, dim=-1, keepdim=True).to(dtype=torch.int) + + def logits_to_probs(logits, temperature: float = 1.0, top_k: Optional[int] = None): + logits = logits / max(temperature, 1e-5) + + if top_k is not None: + v, _ = torch.topk(logits, min(top_k, logits.size(-1))) + pivot = v.select(-1, -1).unsqueeze(-1) + logits = torch.where(logits < pivot, -float("Inf"), logits) + probs = torch.nn.functional.softmax(logits, dim=-1) + return probs + + def sample(logits, temperature: float = 1.0, top_k: Optional[int] = None): + probs = logits_to_probs(logits[0, -1], temperature, top_k) + idx_next = multinomial_sample_one_no_sync(probs) + return idx_next, probs + + # First eager forward pass + logger.info("running first eager forward pass") + start = perf_counter() + outputs = model(**inputs) + torch.cuda.synchronize() + end = perf_counter() + first_eager_fwd_pass_time = end - start + logger.info(f"completed first eager forward pass in: {first_eager_fwd_pass_time}s") + + # Second eager forward pass (should be faster) + logger.info("running second eager forward pass") + start = perf_counter() + outputs = model(**inputs) + torch.cuda.synchronize() + end = perf_counter() + second_eager_fwd_pass_time = end - start + logger.info(f"completed second eager forward pass in: {second_eager_fwd_pass_time}s") + + # First eager generation + logger.info("running first eager generation") + start = perf_counter() + output = model.generate(**inputs) + torch.cuda.synchronize() + end = perf_counter() + first_eager_generate_time = end - start + logger.info(f"completed first eager generation in: {first_eager_generate_time}s") + logger.info(f"generated: {tokenizer.batch_decode(output.cpu().tolist())}") + + # Second eager generation (should be faster) + logger.info("running second eager generation") + start = perf_counter() + output = model.generate(**inputs) + torch.cuda.synchronize() + end = perf_counter() + second_eager_generate_time = end - start + logger.info(f"completed second eager generation in: {second_eager_generate_time}s") + logger.info(f"generated: {tokenizer.batch_decode(output.cpu().tolist())}") + + logger.info("running generation timing loop") + + input_pos = torch.arange(0, seq_length, device=device) + inputs = inputs["input_ids"] + + start = perf_counter() + with torch.nn.attention.sdpa_kernel(torch.nn.attention.SDPBackend.MATH): + logits = model(inputs, position_ids=input_pos).logits + next_token, probs = sample(logits, temperature=0.6, top_k=5) + torch.cuda.synchronize() + end = perf_counter() + time_to_first_token = end - start + + input_pos = torch.tensor([seq_length], device=device, dtype=torch.int) + next_token = next_token.clone() + start = perf_counter() + with torch.nn.attention.sdpa_kernel(torch.nn.attention.SDPBackend.MATH): + logits = model(next_token, position_ids=input_pos).logits + next_token, probs = sample(logits, temperature=0.6, top_k=5) + torch.cuda.synchronize() + end = perf_counter() + time_to_second_token = end - start + + input_pos = torch.tensor([seq_length + 1], device=device, dtype=torch.int) + next_token = next_token.clone() + start = perf_counter() + with torch.nn.attention.sdpa_kernel(torch.nn.attention.SDPBackend.MATH): + logits = model(next_token, position_ids=input_pos).logits + next_token, probs = sample(logits, temperature=0.6, top_k=5) + torch.cuda.synchronize() + end = perf_counter() + time_to_third_token = end - start + + logger.info("running longer generation timing loop") + + total_time = 0 + for i in range(20): + input_pos = torch.tensor([seq_length + 2 + i], device=device, dtype=torch.int) + next_token = next_token.clone() + start = perf_counter() + with torch.nn.attention.sdpa_kernel(torch.nn.attention.SDPBackend.MATH): + logits = model(next_token, position_ids=input_pos).logits + next_token, probs = sample(logits, temperature=0.6, top_k=5) + torch.cuda.synchronize() + end = perf_counter() + total_time += end - start + + mean_time_to_next_token = total_time / 20 + + logger.info("running compilation benchmarks") + + # Now compile the model + model = torch.compile(model, mode="max-autotune", fullgraph=True) + + # StaticCache for generation + with torch.device(device): + model.setup_caches(max_batch_size=batch_size, max_seq_len=seq_length + num_tokens_to_generate) + + input_pos = torch.arange(0, seq_length, device=device) + inputs = tokenizer(prompt, return_tensors="pt").to(device)["input_ids"] + + logger.info("compiling model") + + model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16, generation_config=gen_config) + model.to(device) + model = torch.compile(model, mode="max-autotune", fullgraph=True) + + past_key_values = StaticCache( + model.config, + max_batch_size=batch_size, + device=device, + dtype=torch.float16, + max_cache_len=seq_length + 128, + ) + # 1st call + start = perf_counter() + output = model.generate(**inputs, past_key_values=past_key_values) + end = perf_counter() + first_compile_generate_time = end - start + logger.info(f"completed first compile generation in: {first_compile_generate_time}s") + logger.info(f"generated: {tokenizer.batch_decode(output.cpu().tolist())}") + + past_key_values = StaticCache( + model.config, + max_batch_size=batch_size, + device=device, + dtype=torch.float16, + max_cache_len=seq_length + 128, + ) + # 2nd call + start = perf_counter() + output = model.generate(**inputs, past_key_values=past_key_values) + end = perf_counter() + second_compile_generate_time = end - start + logger.info(f"completed second compile generation in: {second_compile_generate_time}s") + logger.info(f"generated: {tokenizer.batch_decode(output.cpu().tolist())}") + + past_key_values = StaticCache( + model.config, + max_batch_size=batch_size, + device=device, + dtype=torch.float16, + max_cache_len=seq_length + 128, + ) + # 3rd call + start = perf_counter() + output = model.generate(**inputs, past_key_values=past_key_values) + end = perf_counter() + third_compile_generate_time = end - start + logger.info(f"completed third compile generation in: {third_compile_generate_time}s") + logger.info(f"generated: {tokenizer.batch_decode(output.cpu().tolist())}") + + past_key_values = StaticCache( + model.config, + max_batch_size=batch_size, + device=device, + dtype=torch.float16, + max_cache_len=seq_length + 128, + ) + # 4th call + start = perf_counter() + output = model.generate(**inputs, past_key_values=past_key_values) + end = perf_counter() + fourth_compile_generate_time = end - start + logger.info(f"completed fourth compile generation in: {fourth_compile_generate_time}s") + logger.info(f"generated: {tokenizer.batch_decode(output.cpu().tolist())}") + + metrics_recorder.collect_model_measurements( + benchmark_id, + { + "model_load_time": model_load_time, + "first_eager_forward_pass_time_secs": first_eager_fwd_pass_time, + "second_eager_forward_pass_time_secs": second_eager_fwd_pass_time, + "first_eager_generate_time_secs": first_eager_generate_time, + "second_eager_generate_time_secs": second_eager_generate_time, + "time_to_first_token_secs": time_to_first_token, + "time_to_second_token_secs": time_to_second_token, + "time_to_third_token_secs": time_to_third_token, + "time_to_next_token_mean_secs": mean_time_to_next_token, + "first_compile_generate_time_secs": first_compile_generate_time, + "second_compile_generate_time_secs": second_compile_generate_time, + "third_compile_generate_time_secs": third_compile_generate_time, + "fourth_compile_generate_time_secs": fourth_compile_generate_time, + }, + ) + except Exception as e: + logger.error(f"Caught exception: {e}") + continue_metric_collection.set() + if metrics_thread is not None: + metrics_thread.join() + + # Only close the recorder if we created it locally + if should_close_recorder: + metrics_recorder.close() \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/benchmark.py b/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..831ec424e3dec3e4dad8d3fa77fea4874833365d --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/benchmark.py @@ -0,0 +1,326 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Run benchmark using the `optimum-benchmark` library with some customization in `transformers`. + +Assume we are under `transformers` root directory: (make sure the commits are valid commits) +```bash +python benchmark/benchmark.py --config-dir benchmark/config --config-name generation --commit=9b9c7f03da625b13643e99205c691fe046461724 --metrics=decode.latency.mean,per_token.latency.mean,per_token.throughput.value backend.model=google/gemma-2b benchmark.input_shapes.sequence_length=5,7 benchmark.input_shapes.batch_size=1,2 --multirun +``` +""" + +import argparse +import glob +import json +import os.path +import re +import tempfile +from contextlib import contextmanager +from pathlib import Path + +from git import Repo + +from huggingface_hub import HfApi + +from optimum_benchmark import Benchmark +from optimum_benchmark_wrapper import main + + +PATH_TO_REPO = Path(__file__).parent.parent.resolve() + + +@contextmanager +def checkout_commit(repo: Repo, commit_id: str): + """ + Context manager that checks out a given commit when entered, but gets back to the reference it was at on exit. + Args: + repo (`git.Repo`): A git repository (for instance the Transformers repo). + commit_id (`str`): The commit reference to checkout inside the context manager. + """ + current_head = repo.head.commit if repo.head.is_detached else repo.head.ref + + try: + repo.git.checkout(commit_id) + yield + + finally: + repo.git.checkout(current_head) + + +def summarize(run_dir, metrics, expand_metrics=False): + """Produce a summary for each optimum-benchmark launched job's output directory found in `run_dir`. + + Each summary's format is as follows (for `expand_metrics=False`): + ``` + { + "model": "google/gemma-2b", + "commit": "3cd6ed22e4d49219f300f5055e71e3929aba20d7", + "config": "benchmark.input_shapes.batch_size=1,benchmark.input_shapes.sequence_length=5", + "metrics": { + "decode.latency.mean": 1.624666809082031, + "per_token.latency.mean": 0.012843788806628804, + "per_token.throughput.value": 77.85864553330948 + } + } + ``` + """ + reports = glob.glob(os.path.join(run_dir, "**/benchmark_report.json"), recursive=True) + report_dirs = [str(Path(report).parent) for report in reports] + + summaries = [] + for report_dir in report_dirs: + commit = re.search(r"/commit=([^/]+)", report_dir).groups()[0] + + if not os.path.isfile(os.path.join(report_dir, "benchmark.json")): + continue + benchmark = Benchmark.from_json(os.path.join(report_dir, "benchmark.json")) + report = benchmark.report + + model = benchmark.config.backend["model"] + + # This looks like `benchmark.input_shapes.batch_size=1,benchmark.input_shapes.sequence_length=5`. + # (we rely on the usage of hydra's `${hydra.job.override_dirname}`.) + benchmark_name = re.sub(f"backend.model={model},*", "", report_dir) + benchmark_name = str(Path(benchmark_name).parts[-1]) + if benchmark_name.startswith("commit="): + benchmark_name = benchmark.config.name + + metrics_values = {} + # post-processing of report: show a few selected/important metric + for metric in metrics: + keys = metric.split(".") + value = report.to_dict() + current = metrics_values + for key in keys: + # Avoid KeyError when a user's specified metric has typo. + # TODO: Give warnings. + if key not in value: + continue + value = value[key] + + if expand_metrics: + if isinstance(value, dict): + if key not in current: + current[key] = {} + current = current[key] + else: + current[key] = value + + if not expand_metrics: + metrics_values[metric] = value + + # show some config information + print(f"model: {model}") + print(f"commit: {commit}") + print(f"config: {benchmark_name}") + if len(metrics_values) > 0: + print("metrics:") + if expand_metrics: + print(metrics_values) + else: + for metric, value in metrics_values.items(): + print(f" - {metric}: {value}") + print("-" * 80) + + summary = { + "model": model, + "commit": commit, + "config": benchmark_name, + "metrics": metrics_values, + } + summaries.append(summary) + + with open(os.path.join(report_dir, "summary.json"), "w") as fp: + json.dump(summary, fp, indent=4) + + return summaries + + +def combine_summaries(summaries): + """Combine a list of summary obtained from the function `summarize`. + + The combined summary's format is as follows: + ``` + "google/gemma-2b": { + "benchmark.input_shapes.batch_size=1,benchmark.input_shapes.sequence_length=5": { + "3cd6ed22e4d49219f300f5055e71e3929aba20d7": { + "metrics": {"decode.latency.mean": 1.624666809082031} + }, + "c97ee28b117c0abe8e08891f402065e4df6d72aa": { + "metrics": {"decode.latency.mean": 1.6278163452148438} + } + }, + "benchmark.input_shapes.batch_size=2,benchmark.input_shapes.sequence_length=5": { + "3cd6ed22e4d49219f300f5055e71e3929aba20d7": { + "metrics": {"decode.latency.mean": 1.6947791748046876} + }, + "c97ee28b117c0abe8e08891f402065e4df6d72aa": { + "metrics": { + "decode.latency.mean": 1.6980519409179688} + } + } + } + ``` + """ + combined = {} + for summary in summaries: + model = summary["model"] + config = summary["config"] + commit = summary["commit"] + + if model not in combined: + combined[model] = {} + + if config not in combined[model]: + combined[model][config] = {} + + if commit not in combined[model][config]: + combined[model][config][commit] = {"metrics": summary["metrics"]} + + with open(os.path.join(exp_run_dir, "summary.json"), "w") as fp: + json.dump(combined, fp, indent=4) + + print(json.dumps(combined, indent=4)) + + return combined + + +if __name__ == "__main__": + + def list_str(values): + return values.split(",") + + parser = argparse.ArgumentParser() + + parser.add_argument("--config-dir", type=str, required=True, help="The path to the config directory.") + parser.add_argument("--config-name", type=str, required=True, help="The config name.") + + # arguments specific to this wrapper for our own customization + parser.add_argument("--ensure_empty", type=bool, default=True, help="If to create a temporary directory.") + parser.add_argument( + "--commit", + type=list_str, + default="", + help="Comma-separated list of branch names and/or commit sha values on which the benchmark will run. If `diff` is specified, it will run on both the current head and the `main` branch.", + ) + parser.add_argument("--metrics", type=str, help="The metrics to be included in the summary.") + + parser.add_argument("--repo_id", type=str, default=None, help="The repository to which the file will be uploaded.") + parser.add_argument("--path_in_repo", type=str, default=None, help="Relative filepath in the repo.") + parser.add_argument("--token", type=str, default=None, help="A valid user access token (string).") + + args, optimum_benchmark_args = parser.parse_known_args() + + repo = Repo(PATH_TO_REPO) + + metrics = [ + "prefill.latency.mean", + "prefill.throughput.value", + "decode.latency.mean", + "decode.throughput.value", + "per_token.latency.mean", + "per_token.throughput.value", + ] + if args.metrics is not None: + metrics = args.metrics.split(",") + + # Get `backend.model` in a hacky way: We want to control the experiment flow manually. + models = [""] + for idx, arg in enumerate(optimum_benchmark_args): + if arg.startswith("backend.model="): + models = arg[len("backend.model=") :] + models = models.split(",") + break + optimum_benchmark_args = [arg for arg in optimum_benchmark_args if not arg.startswith("backend.model=")] + + # Get the commit(s) + current_head = str(repo.head.commit) if repo.head.is_detached else str(repo.head.ref) + commits = [x for x in args.commit if x != ""] + if len(commits) == 0: + commits = [current_head] + elif len(commits) == 1 and commits[0] == "diff": + # compare to `main` + commits = ["main", current_head] + + # Get the specified run directory + run_dir_arg_idx, run_dir = -1, None + sweep_dir_arg_idx, sweep_dir = -1, None + for idx, arg in enumerate(optimum_benchmark_args): + if arg.startswith("hydra.run.dir="): + run_dir = arg[len("hydra.run.dir=") :] + run_dir_arg_idx = idx + elif arg.startswith("hydra.sweep.dir="): + sweep_dir = arg[len("hydra.sweep.dir=") :] + sweep_dir_arg_idx = idx + exp_run_dir, arg_dix, arg_name = ( + (sweep_dir, sweep_dir_arg_idx, "hydra.sweep.dir") + if "--multirun" in optimum_benchmark_args + else (run_dir, run_dir_arg_idx, "hydra.run.dir") + ) + + # TODO: not hardcoded + if exp_run_dir is None and args.ensure_empty: + exp_run_dir = "_benchmark" + + if args.ensure_empty: + os.makedirs(exp_run_dir, exist_ok=True) + exp_run_dir = tempfile.mkdtemp(dir=exp_run_dir) + + run_summaries = [] + for commit in commits: + with checkout_commit(repo, commit): + commit = str(repo.head.commit) + + commit_run_dir = exp_run_dir + if exp_run_dir is not None: + commit_run_dir = os.path.join(exp_run_dir, rf"commit\={commit}") + + print(f"Run benchmark on commit: {commit}") + + for model in models: + model_arg = [f"backend.model={model}"] if model != "" else [] + dir_args = [] + if commit_run_dir is not None: + if arg_dix > -1: + optimum_benchmark_args[arg_dix] = f"{arg_name}={commit_run_dir}" + else: + dir_args = [ + f"hydra.sweep.dir={commit_run_dir}", + f"hydra.run.dir={commit_run_dir}/" + "${hydra.job.override_dirname}", + ] + main(args.config_dir, args.config_name, model_arg + dir_args + optimum_benchmark_args) + + if commit_run_dir is not None: + # Need to remove the `\` character + summaries = summarize(commit_run_dir.replace("\\", ""), metrics) + run_summaries.extend(summaries) + + # aggregate the information across the commits + if exp_run_dir is not None: + with open(os.path.join(exp_run_dir, "summaries.json"), "w") as fp: + json.dump(run_summaries, fp, indent=4) + + combined_summary = combine_summaries(run_summaries) + + if args.repo_id is not None and args.path_in_repo is not None: + # Upload to Hub + api = HfApi() + api.upload_folder( + folder_path=exp_run_dir, + path_in_repo=args.path_in_repo, + repo_id=args.repo_id, + repo_type="dataset", + token=args.token, + ) diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/benchmarks_entrypoint.py b/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/benchmarks_entrypoint.py new file mode 100644 index 0000000000000000000000000000000000000000..929fe64288d8fdd0cc10ba175dc14a2f27bdd53d --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/benchmarks_entrypoint.py @@ -0,0 +1,469 @@ +# Copyright 2025 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import argparse +import importlib.util +import logging +import os +import sys +import json +import uuid +from datetime import datetime +from typing import Dict, Tuple, Optional, List + +import pandas as pd + +try: + from psycopg2.extensions import register_adapter + from psycopg2.extras import Json + register_adapter(dict, Json) + PSYCOPG2_AVAILABLE = True +except ImportError: + PSYCOPG2_AVAILABLE = False + + +class ImportModuleException(Exception): + pass + + +class MetricsRecorder: + def __init__( + self, connection, logger: logging.Logger, repository: str, branch: str, commit_id: str, commit_msg: str, + collect_csv_data: bool = True + ): + self.conn = connection + self.use_database = connection is not None + if self.use_database: + self.conn.autocommit = True + self.logger = logger + self.repository = repository + self.branch = branch + self.commit_id = commit_id + self.commit_msg = commit_msg + self.collect_csv_data = collect_csv_data + + # For CSV export - store all data in pandas DataFrames (only if CSV collection is enabled) + if self.collect_csv_data: + # Initialize empty DataFrames with proper schemas + self.benchmarks_df = pd.DataFrame(columns=[ + 'benchmark_id', 'repository', 'branch', 'commit_id', 'commit_message', + 'metadata', 'created_at' + ]) + self.device_measurements_df = pd.DataFrame(columns=[ + 'benchmark_id', 'cpu_util', 'mem_megabytes', 'gpu_util', + 'gpu_mem_megabytes', 'time' + ]) + self.model_measurements_df = pd.DataFrame(columns=[ + 'benchmark_id', 'time', 'model_load_time', 'first_eager_forward_pass_time_secs', + 'second_eager_forward_pass_time_secs', 'first_eager_generate_time_secs', + 'second_eager_generate_time_secs', 'time_to_first_token_secs', + 'time_to_second_token_secs', 'time_to_third_token_secs', + 'time_to_next_token_mean_secs', 'first_compile_generate_time_secs', + 'second_compile_generate_time_secs', 'third_compile_generate_time_secs', + 'fourth_compile_generate_time_secs' + ]) + else: + self.benchmarks_df = None + self.device_measurements_df = None + self.model_measurements_df = None + + def initialise_benchmark(self, metadata: dict[str, str]) -> str: + """ + Creates a new benchmark, returns the benchmark id (UUID) + """ + # Generate a unique UUID for this benchmark + benchmark_id = str(uuid.uuid4()) + + if self.use_database: + with self.conn.cursor() as cur: + cur.execute( + "INSERT INTO benchmarks (benchmark_id, repository, branch, commit_id, commit_message, metadata) VALUES (%s, %s, %s, %s, %s, %s)", + (benchmark_id, self.repository, self.branch, self.commit_id, self.commit_msg, metadata), + ) + self.logger.debug(f"initialised benchmark #{benchmark_id}") + + # Store benchmark data for CSV export (if enabled) + if self.collect_csv_data: + # Add row to pandas DataFrame + new_row = pd.DataFrame([{ + 'benchmark_id': benchmark_id, + 'repository': self.repository, + 'branch': self.branch, + 'commit_id': self.commit_id, + 'commit_message': self.commit_msg, + 'metadata': json.dumps(metadata), + 'created_at': datetime.utcnow().isoformat() + }]) + self.benchmarks_df = pd.concat([self.benchmarks_df, new_row], ignore_index=True) + + mode_info = [] + if self.use_database: + mode_info.append("database") + if self.collect_csv_data: + mode_info.append("CSV") + mode_str = " + ".join(mode_info) if mode_info else "no storage" + + self.logger.debug(f"initialised benchmark #{benchmark_id} ({mode_str} mode)") + return benchmark_id + + def collect_device_measurements(self, benchmark_id: str, cpu_util, mem_megabytes, gpu_util, gpu_mem_megabytes): + """ + Collect device metrics, such as CPU & GPU usage. These are "static", as in you cannot pass arbitrary arguments to the function. + """ + # Store device measurements for CSV export (if enabled) + if self.collect_csv_data: + # Add row to pandas DataFrame + new_row = pd.DataFrame([{ + 'benchmark_id': benchmark_id, + 'cpu_util': cpu_util, + 'mem_megabytes': mem_megabytes, + 'gpu_util': gpu_util, + 'gpu_mem_megabytes': gpu_mem_megabytes, + 'time': datetime.utcnow().isoformat() + }]) + self.device_measurements_df = pd.concat([self.device_measurements_df, new_row], ignore_index=True) + + # Store in database if available + if self.use_database: + with self.conn.cursor() as cur: + cur.execute( + "INSERT INTO device_measurements (benchmark_id, cpu_util, mem_megabytes, gpu_util, gpu_mem_megabytes) VALUES (%s, %s, %s, %s, %s)", + (benchmark_id, cpu_util, mem_megabytes, gpu_util, gpu_mem_megabytes), + ) + + self.logger.debug( + f"collected device measurements for benchmark #{benchmark_id} [CPU util: {cpu_util}, mem MBs: {mem_megabytes}, GPU util: {gpu_util}, GPU mem MBs: {gpu_mem_megabytes}]" + ) + + def collect_model_measurements(self, benchmark_id: str, measurements: dict[str, float]): + # Store model measurements for CSV export (if enabled) + if self.collect_csv_data: + # Add row to pandas DataFrame with flattened measurements + row_data = { + 'benchmark_id': benchmark_id, + 'time': datetime.utcnow().isoformat() + } + # Flatten the measurements dict into the row + row_data.update(measurements) + + new_row = pd.DataFrame([row_data]) + self.model_measurements_df = pd.concat([self.model_measurements_df, new_row], ignore_index=True) + + # Store in database if available + if self.use_database: + with self.conn.cursor() as cur: + cur.execute( + """ + INSERT INTO model_measurements ( + benchmark_id, + measurements + ) VALUES (%s, %s) + """, + ( + benchmark_id, + measurements, + ), + ) + + self.logger.debug(f"collected model measurements for benchmark #{benchmark_id}: {measurements}") + + def export_to_csv(self, output_dir: str = "benchmark_results"): + """ + Export all collected data to CSV files using pandas DataFrames + """ + if not self.collect_csv_data: + self.logger.warning("CSV data collection is disabled - no CSV files will be generated") + return + + if not os.path.exists(output_dir): + os.makedirs(output_dir) + self.logger.info(f"Created output directory: {output_dir}") + + timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") + files_created = [] + + # Export using pandas DataFrames + self._export_pandas_data(output_dir, timestamp, files_created) + + self.logger.info(f"CSV export complete! Created {len(files_created)} files in {output_dir}") + + def _export_pandas_data(self, output_dir: str, timestamp: str, files_created: list): + """ + Export CSV files using pandas DataFrames + """ + # Export benchmarks + benchmarks_file = os.path.join(output_dir, f"benchmarks_{timestamp}.csv") + self.benchmarks_df.to_csv(benchmarks_file, index=False) + files_created.append(benchmarks_file) + self.logger.info(f"Exported {len(self.benchmarks_df)} benchmark records to {benchmarks_file}") + + # Export device measurements + device_file = os.path.join(output_dir, f"device_measurements_{timestamp}.csv") + self.device_measurements_df.to_csv(device_file, index=False) + files_created.append(device_file) + self.logger.info(f"Exported {len(self.device_measurements_df)} device measurement records to {device_file}") + + # Export model measurements (already flattened) + model_file = os.path.join(output_dir, f"model_measurements_{timestamp}.csv") + self.model_measurements_df.to_csv(model_file, index=False) + files_created.append(model_file) + self.logger.info(f"Exported {len(self.model_measurements_df)} model measurement records to {model_file}") + + # Create comprehensive summary using pandas operations + summary_file = os.path.join(output_dir, f"benchmark_summary_{timestamp}.csv") + self._create_summary(summary_file) + files_created.append(summary_file) + + def _create_summary(self, summary_file: str): + """ + Create a comprehensive summary CSV using pandas operations + """ + if len(self.benchmarks_df) == 0: + # Create empty summary file + summary_df = pd.DataFrame() + summary_df.to_csv(summary_file, index=False) + self.logger.info(f"Created empty benchmark summary at {summary_file}") + return + + # Start with benchmarks as the base + summary_df = self.benchmarks_df.copy() + + # Add model measurements (join on benchmark_id) + if len(self.model_measurements_df) > 0: + # Drop 'time' column from model measurements to avoid conflicts + model_df = self.model_measurements_df.drop(columns=['time'], errors='ignore') + summary_df = summary_df.merge(model_df, on='benchmark_id', how='left') + + # Calculate device measurement aggregates using pandas groupby + if len(self.device_measurements_df) > 0: + device_agg = self.device_measurements_df.groupby('benchmark_id').agg({ + 'cpu_util': ['mean', 'max', 'std', 'count'], + 'mem_megabytes': ['mean', 'max', 'std'], + 'gpu_util': ['mean', 'max', 'std'], + 'gpu_mem_megabytes': ['mean', 'max', 'std'] + }).round(3) + + # Flatten column names + device_agg.columns = [f"{col[0]}_{col[1]}" for col in device_agg.columns] + device_agg = device_agg.reset_index() + + # Rename count column to be more descriptive + if 'cpu_util_count' in device_agg.columns: + device_agg = device_agg.rename(columns={'cpu_util_count': 'device_measurement_count'}) + + # Merge with summary + summary_df = summary_df.merge(device_agg, on='benchmark_id', how='left') + + # Export the comprehensive summary + summary_df.to_csv(summary_file, index=False) + self.logger.info(f"Created comprehensive benchmark summary with {len(summary_df)} records at {summary_file}") + + def close(self): + if self.use_database and self.conn: + self.conn.close() + + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + +handler = logging.StreamHandler(sys.stdout) +handler.setLevel(logging.INFO) +formatter = logging.Formatter("[%(levelname)s - %(asctime)s] %(message)s") +handler.setFormatter(formatter) +logger.addHandler(handler) + + +def parse_arguments() -> tuple[str, str, str, str, bool, str]: + """ + Parse command line arguments for the benchmarking CLI. + """ + parser = argparse.ArgumentParser(description="CLI for benchmarking the huggingface/transformers.") + + parser.add_argument( + "repository", + type=str, + help="The repository name on which the benchmarking is performed.", + ) + + parser.add_argument( + "branch", + type=str, + help="The branch name on which the benchmarking is performed.", + ) + + parser.add_argument( + "commit_id", + type=str, + help="The commit hash on which the benchmarking is performed.", + ) + + parser.add_argument( + "commit_msg", + type=str, + help="The commit message associated with the commit, truncated to 70 characters.", + ) + + parser.add_argument( + "--csv", + action="store_true", + default=False, + help="Enable CSV output files generation." + ) + + parser.add_argument( + "--csv-output-dir", + type=str, + default="benchmark_results", + help="Directory for CSV output files (default: benchmark_results)." + ) + + args = parser.parse_args() + + # CSV is disabled by default, only enabled when --csv is used + generate_csv = args.csv + + return args.repository, args.branch, args.commit_id, args.commit_msg, generate_csv, args.csv_output_dir + + +def import_from_path(module_name, file_path): + try: + spec = importlib.util.spec_from_file_location(module_name, file_path) + module = importlib.util.module_from_spec(spec) + sys.modules[module_name] = module + spec.loader.exec_module(module) + return module + except Exception as e: + raise ImportModuleException(f"failed to load python module: {e}") + + +def create_database_connection(): + """ + Try to create a database connection. Returns None if connection fails. + """ + if not PSYCOPG2_AVAILABLE: + logger.warning("psycopg2 not available - running in CSV-only mode") + return None + + try: + import psycopg2 + conn = psycopg2.connect("dbname=metrics") + logger.info("Successfully connected to database") + return conn + except Exception as e: + logger.warning(f"Failed to connect to database: {e}. Running in CSV-only mode") + return None + + +def create_global_metrics_recorder(repository: str, branch: str, commit_id: str, commit_msg: str, + generate_csv: bool = False) -> MetricsRecorder: + """ + Create a global metrics recorder that will be used across all benchmarks. + """ + connection = create_database_connection() + recorder = MetricsRecorder(connection, logger, repository, branch, commit_id, commit_msg, generate_csv) + + # Log the storage mode + storage_modes = [] + if connection is not None: + storage_modes.append("database") + if generate_csv: + storage_modes.append("CSV") + + if not storage_modes: + logger.warning("Running benchmarks with NO data storage (no database connection, CSV disabled)") + logger.warning("Use --csv flag to enable CSV output when database is unavailable") + else: + logger.info(f"Running benchmarks with: {' + '.join(storage_modes)} storage") + + return recorder + + +if __name__ == "__main__": + benchmarks_folder_path = os.path.dirname(os.path.realpath(__file__)) + benches_folder_path = os.path.join(benchmarks_folder_path, "benches") + + repository, branch, commit_id, commit_msg, generate_csv, csv_output_dir = parse_arguments() + + # Create a global metrics recorder + global_metrics_recorder = create_global_metrics_recorder(repository, branch, commit_id, commit_msg, generate_csv) + + successful_benchmarks = 0 + failed_benchmarks = 0 + + # Automatically discover all benchmark modules in benches/ folder + benchmark_modules = [] + + if os.path.exists(benches_folder_path): + logger.debug(f"Scanning for benchmarks in: {benches_folder_path}") + for entry in os.scandir(benches_folder_path): + if not entry.name.endswith(".py"): + continue + if entry.name.startswith("__"): # Skip __init__.py, __pycache__, etc. + continue + + # Check if the file has a run_benchmark function + try: + logger.debug(f"checking if benches/{entry.name} has run_benchmark function") + module = import_from_path(entry.name.split(".")[0], entry.path) + if hasattr(module, 'run_benchmark'): + benchmark_modules.append(entry.name) + logger.debug(f"discovered benchmark: {entry.name}") + else: + logger.debug(f"skipping {entry.name} - no run_benchmark function found") + except Exception as e: + logger.debug(f"failed to check benches/{entry.name}: {e}") + else: + logger.warning(f"Benches directory not found: {benches_folder_path}") + + if benchmark_modules: + logger.info(f"Discovered {len(benchmark_modules)} benchmark(s): {benchmark_modules}") + else: + logger.warning("No benchmark modules found in benches/ directory") + + for module_name in benchmark_modules: + module_path = os.path.join(benches_folder_path, module_name) + try: + logger.debug(f"loading: {module_name}") + module = import_from_path(module_name.split(".")[0], module_path) + logger.info(f"running benchmarks in: {module_name}") + + # Check if the module has an updated run_benchmark function that accepts metrics_recorder + try: + # Try the new signature first + module.run_benchmark(logger, repository, branch, commit_id, commit_msg, global_metrics_recorder) + except TypeError: + # Fall back to the old signature for backward compatibility + logger.warning(f"Module {module_name} using old run_benchmark signature - database connection will be created per module") + module.run_benchmark(logger, repository, branch, commit_id, commit_msg) + + successful_benchmarks += 1 + except ImportModuleException as e: + logger.error(e) + failed_benchmarks += 1 + except Exception as e: + logger.error(f"error running benchmarks for {module_name}: {e}") + failed_benchmarks += 1 + + # Export CSV results at the end (if enabled) + try: + if generate_csv: + global_metrics_recorder.export_to_csv(csv_output_dir) + logger.info(f"CSV reports have been generated and saved to the {csv_output_dir} directory") + else: + logger.info("CSV generation disabled - no CSV files created (use --csv to enable)") + + logger.info(f"Benchmark run completed. Successful: {successful_benchmarks}, Failed: {failed_benchmarks}") + except Exception as e: + logger.error(f"Failed to export CSV results: {e}") + finally: + global_metrics_recorder.close() diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/config/generation.yaml b/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/config/generation.yaml new file mode 100644 index 0000000000000000000000000000000000000000..44a3f9ea49015491c7add94a8790d16c20dc76fc --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/config/generation.yaml @@ -0,0 +1,57 @@ +defaults: + - benchmark # inheriting benchmark schema + - scenario: inference + - launcher: process + - backend: pytorch + - _self_ # for hydra 1.1 compatibility + +name: pytorch_generate + +launcher: + start_method: spawn + device_isolation: true + device_isolation_action: warn + +backend: + device: cuda + device_ids: 0 + no_weights: true + model: meta-llama/Llama-2-7b-hf + cache_implementation: static + torch_compile: true + torch_dtype: float16 + torch_compile_config: + backend: inductor + mode: reduce-overhead + fullgraph: true + +scenario: + input_shapes: + batch_size: 1 + sequence_length: 7 + generate_kwargs: + max_new_tokens: 128 + min_new_tokens: 128 + do_sample: false + memory: true + latency: true + iterations: 2 + duration: 0 + + +# hydra/cli specific settings +hydra: + run: + # where to store run results + dir: runs/${name} + job: + # change working directory to the run directory + chdir: true + env_set: + # set environment variable OVERRIDE_BENCHMARKS to 1 + # to not skip benchmarks that have been run before + OVERRIDE_BENCHMARKS: 1 + LOG_LEVEL: WARN + sweep: + dir: multirun + subdir: ${hydra.job.override_dirname} \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/default.yml b/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/default.yml new file mode 100644 index 0000000000000000000000000000000000000000..f3f02cab34d1bd2451eda4744ccf4f4eb7d0e6cc --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/default.yml @@ -0,0 +1,10 @@ +apiVersion: 1 + +providers: + - name: 'Transformers Benchmarks' + orgId: 1 + type: file + updateIntervalSeconds: 10 + allowUiUpdates: true + options: + path: /etc/grafana/dashboards diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/grafana_dashboard.json b/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/grafana_dashboard.json new file mode 100644 index 0000000000000000000000000000000000000000..caaec78a522303eaadc66171d405e203e7475694 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/grafana_dashboard.json @@ -0,0 +1,2375 @@ +{ + "annotations": { + "list": [ + { + "builtIn": 1, + "datasource": { + "type": "grafana", + "uid": "-- Grafana --" + }, + "enable": true, + "hide": true, + "iconColor": "rgba(0, 211, 255, 1)", + "name": "Annotations & Alerts", + "type": "dashboard" + } + ] + }, + "editable": true, + "fiscalYearStartMonth": 0, + "graphTooltip": 0, + "id": 1, + "links": [ + { + "asDropdown": false, + "icon": "external link", + "includeVars": false, + "keepTime": false, + "tags": [], + "targetBlank": false, + "title": "Go to data", + "tooltip": "Go to data", + "type": "link", + "url": "http://transformers-benchmarks.hf.co/d/fdz33iyzln9c0a/transformers-benchmarks?orgId=1&from=${StartTime}&to=${EndTime}" + } + ], + "liveNow": true, + "panels": [ + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "thresholds" + }, + "custom": { + "align": "left", + "cellOptions": { + "type": "auto" + }, + "inspect": false + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "red", + "value": 80 + } + ] + } + }, + "overrides": [ + { + "matcher": { + "id": "byName", + "options": "gpu_name" + }, + "properties": [ + { + "id": "custom.width", + "value": 202 + } + ] + }, + { + "matcher": { + "id": "byName", + "options": "left" + }, + "properties": [ + { + "id": "custom.width", + "value": 407 + } + ] + }, + { + "matcher": { + "id": "byName", + "options": "commit_message" + }, + "properties": [ + { + "id": "custom.width", + "value": 524 + } + ] + }, + { + "matcher": { + "id": "byName", + "options": "commit_id" + }, + "properties": [ + { + "id": "custom.width", + "value": 353 + } + ] + }, + { + "matcher": { + "id": "byName", + "options": "model_id" + }, + "properties": [ + { + "id": "custom.width", + "value": 216 + } + ] + } + ] + }, + "gridPos": { + "h": 6, + "w": 24, + "x": 0, + "y": 0 + }, + "id": 5, + "options": { + "cellHeight": "sm", + "footer": { + "countRows": false, + "fields": "", + "reducer": [ + "sum" + ], + "show": false + }, + "showHeader": true, + "sortBy": [] + }, + "pluginVersion": "11.2.2", + "targets": [ + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "editorMode": "code", + "format": "table", + "rawQuery": true, + "rawSql": "SELECT commit_id, commit_message, metadata->>'gpu_name' as gpu_name, metadata->>'model_id' as model_id, created_at AS date FROM benchmarks WHERE branch = '${branch}' AND metadata->>'gpu_name' = '${gpu_name}' ORDER BY benchmark_id DESC LIMIT ${last_n_commits};", + "refId": "A", + "sql": { + "columns": [ + { + "parameters": [ + { + "name": "commit_id", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "gpu_name", + "type": "functionParameter" + } + ], + "type": "function" + } + ], + "groupBy": [ + { + "property": { + "type": "string" + }, + "type": "groupBy" + } + ], + "limit": 50, + "whereJsonTree": { + "children1": [ + { + "id": "baaa8aaa-89ab-4cde-b012-31922f96de3f", + "properties": { + "field": "commit_id", + "fieldSrc": "field", + "operator": "equal", + "value": [ + "${commit}" + ], + "valueError": [ + null + ], + "valueSrc": [ + "value" + ], + "valueType": [ + "text" + ] + }, + "type": "rule" + } + ], + "id": "bab88a98-0123-4456-b89a-b1922f7d4f11", + "type": "group" + }, + "whereString": "commit_id = '${commit}'" + }, + "table": "benchmarks" + } + ], + "transparent": true, + "type": "table" + }, + { + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 6 + }, + "id": 13, + "panels": [], + "title": "Eager Forward Pass", + "type": "row" + }, + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "continuous-YlBl" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "fillOpacity": 80, + "gradientMode": "scheme", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "lineWidth": 0, + "scaleDistribution": { + "type": "linear" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + } + ] + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 11, + "w": 12, + "x": 0, + "y": 7 + }, + "id": 7, + "options": { + "barRadius": 0.05, + "barWidth": 0.8, + "fullHighlight": false, + "groupWidth": 0.7, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": false + }, + "orientation": "auto", + "showValue": "auto", + "stacking": "none", + "tooltip": { + "mode": "single", + "sort": "none" + }, + "xTickLabelRotation": 0, + "xTickLabelSpacing": 0 + }, + "pluginVersion": "11.2.2", + "targets": [ + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "editorMode": "code", + "format": "table", + "rawQuery": true, + "rawSql": "SELECT CAST(m.measurements->'first_eager_forward_pass_time_secs' AS double precision) AS first_eager_forward_pass_time_secs, left(b.commit_id, 7), m.time FROM benchmarks as b JOIN model_measurements AS m ON b.benchmark_id = m.benchmark_id WHERE b.branch = '${branch}' AND b.metadata->>'gpu_name' = '${gpu_name}' ORDER BY b.benchmark_id DESC LIMIT ${last_n_commits};", + "refId": "A", + "sql": { + "columns": [ + { + "parameters": [], + "type": "function" + } + ], + "groupBy": [ + { + "property": { + "type": "string" + }, + "type": "groupBy" + } + ], + "limit": 50 + } + } + ], + "title": "First eager forward pass", + "transformations": [ + { + "id": "sortBy", + "options": { + "fields": {}, + "sort": [ + { + "field": "time" + } + ] + } + } + ], + "transparent": true, + "type": "barchart" + }, + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "continuous-YlBl" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "fillOpacity": 80, + "gradientMode": "scheme", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "lineWidth": 0, + "scaleDistribution": { + "type": "linear" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "red", + "value": 80 + } + ] + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 11, + "w": 12, + "x": 12, + "y": 7 + }, + "id": 9, + "options": { + "barRadius": 0.05, + "barWidth": 0.8, + "fullHighlight": false, + "groupWidth": 0.7, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": false + }, + "orientation": "auto", + "showValue": "auto", + "stacking": "none", + "tooltip": { + "mode": "single", + "sort": "none" + }, + "xTickLabelRotation": 0, + "xTickLabelSpacing": 0 + }, + "targets": [ + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "editorMode": "code", + "format": "table", + "rawQuery": true, + "rawSql": "SELECT CAST(m.measurements->'second_eager_forward_pass_time_secs' AS double precision) AS second_eager_forward_pass_time_secs, left(b.commit_id, 7), m.time FROM benchmarks as b JOIN model_measurements AS m ON b.benchmark_id = m.benchmark_id WHERE b.branch = '${branch}' AND b.metadata->>'gpu_name' = '${gpu_name}' ORDER BY b.benchmark_id DESC LIMIT ${last_n_commits};", + "refId": "A", + "sql": { + "columns": [ + { + "parameters": [], + "type": "function" + } + ], + "groupBy": [ + { + "property": { + "type": "string" + }, + "type": "groupBy" + } + ], + "limit": 50 + } + } + ], + "title": "Second eager forward pass", + "transformations": [ + { + "id": "sortBy", + "options": { + "fields": {}, + "sort": [ + { + "field": "time" + } + ] + } + } + ], + "transparent": true, + "type": "barchart" + }, + { + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 18 + }, + "id": 16, + "panels": [], + "title": "Time to next token", + "type": "row" + }, + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "continuous-YlBl" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "fillOpacity": 80, + "gradientMode": "scheme", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "lineWidth": 0, + "scaleDistribution": { + "type": "linear" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + } + ] + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 11, + "w": 12, + "x": 0, + "y": 19 + }, + "id": 17, + "options": { + "barRadius": 0.05, + "barWidth": 0.8, + "fullHighlight": false, + "groupWidth": 0.7, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": false + }, + "orientation": "auto", + "showValue": "always", + "stacking": "none", + "tooltip": { + "mode": "single", + "sort": "none" + }, + "xTickLabelRotation": 0, + "xTickLabelSpacing": 0 + }, + "targets": [ + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "editorMode": "code", + "format": "table", + "rawQuery": true, + "rawSql": "SELECT CAST(m.measurements->'time_to_first_token_secs' AS double precision) AS time_to_first_token_secs, left(b.commit_id, 7), m.time FROM benchmarks as b JOIN model_measurements AS m ON b.benchmark_id = m.benchmark_id WHERE b.branch = '${branch}' AND b.metadata->>'gpu_name' = '${gpu_name}' ORDER BY b.benchmark_id DESC LIMIT ${last_n_commits};", + "refId": "A", + "sql": { + "columns": [ + { + "parameters": [], + "type": "function" + } + ], + "groupBy": [ + { + "property": { + "type": "string" + }, + "type": "groupBy" + } + ], + "limit": 50 + } + } + ], + "title": "Time to first token", + "transformations": [ + { + "id": "sortBy", + "options": { + "fields": {}, + "sort": [ + { + "field": "time" + } + ] + } + } + ], + "transparent": true, + "type": "barchart" + }, + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "continuous-YlBl" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "fillOpacity": 80, + "gradientMode": "scheme", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "lineWidth": 0, + "scaleDistribution": { + "type": "linear" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + } + ] + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 11, + "w": 12, + "x": 12, + "y": 19 + }, + "id": 18, + "options": { + "barRadius": 0.05, + "barWidth": 0.8, + "fullHighlight": false, + "groupWidth": 0.7, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": false + }, + "orientation": "auto", + "showValue": "always", + "stacking": "none", + "tooltip": { + "mode": "single", + "sort": "none" + }, + "xTickLabelRotation": 0, + "xTickLabelSpacing": 0 + }, + "targets": [ + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "editorMode": "code", + "format": "table", + "rawQuery": true, + "rawSql": "SELECT CAST(m.measurements->'time_to_second_token_secs' AS double precision) AS time_to_second_token_secs, left(b.commit_id, 7), m.time FROM benchmarks as b JOIN model_measurements AS m ON b.benchmark_id = m.benchmark_id WHERE b.branch = '${branch}' AND b.metadata->>'gpu_name' = '${gpu_name}' ORDER BY b.benchmark_id DESC LIMIT ${last_n_commits};", + "refId": "A", + "sql": { + "columns": [ + { + "parameters": [], + "type": "function" + } + ], + "groupBy": [ + { + "property": { + "type": "string" + }, + "type": "groupBy" + } + ], + "limit": 50 + } + } + ], + "title": "Time to second token", + "transformations": [ + { + "id": "sortBy", + "options": { + "fields": {}, + "sort": [ + { + "field": "time" + } + ] + } + } + ], + "transparent": true, + "type": "barchart" + }, + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "continuous-YlBl" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "fillOpacity": 80, + "gradientMode": "scheme", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "lineWidth": 0, + "scaleDistribution": { + "type": "linear" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + } + ] + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 11, + "w": 12, + "x": 0, + "y": 30 + }, + "id": 19, + "options": { + "barRadius": 0.05, + "barWidth": 0.8, + "fullHighlight": false, + "groupWidth": 0.7, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": false + }, + "orientation": "auto", + "showValue": "always", + "stacking": "none", + "tooltip": { + "mode": "single", + "sort": "none" + }, + "xTickLabelRotation": 0, + "xTickLabelSpacing": 0 + }, + "targets": [ + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "editorMode": "code", + "format": "table", + "rawQuery": true, + "rawSql": "SELECT CAST(m.measurements->'time_to_third_token_secs' AS double precision) AS time_to_third_token_secs, left(b.commit_id, 7), m.time FROM benchmarks as b JOIN model_measurements AS m ON b.benchmark_id = m.benchmark_id WHERE b.branch = '${branch}' AND b.metadata->>'gpu_name' = '${gpu_name}' ORDER BY b.benchmark_id DESC LIMIT ${last_n_commits};", + "refId": "A", + "sql": { + "columns": [ + { + "parameters": [], + "type": "function" + } + ], + "groupBy": [ + { + "property": { + "type": "string" + }, + "type": "groupBy" + } + ], + "limit": 50 + } + } + ], + "title": "Time to third token", + "transformations": [ + { + "id": "sortBy", + "options": { + "fields": {}, + "sort": [ + { + "field": "time" + } + ] + } + } + ], + "transparent": true, + "type": "barchart" + }, + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "continuous-YlBl" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "fillOpacity": 80, + "gradientMode": "scheme", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "lineWidth": 0, + "scaleDistribution": { + "type": "linear" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + } + ] + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 11, + "w": 12, + "x": 12, + "y": 30 + }, + "id": 20, + "options": { + "barRadius": 0.05, + "barWidth": 0.8, + "fullHighlight": false, + "groupWidth": 0.7, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": false + }, + "orientation": "auto", + "showValue": "always", + "stacking": "none", + "tooltip": { + "mode": "single", + "sort": "none" + }, + "xTickLabelRotation": 0, + "xTickLabelSpacing": 0 + }, + "targets": [ + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "editorMode": "code", + "format": "table", + "rawQuery": true, + "rawSql": "SELECT CAST(m.measurements->'time_to_next_token_mean_secs' AS double precision) AS time_to_next_token_mean_secs, left(b.commit_id, 7), m.time FROM benchmarks as b JOIN model_measurements AS m ON b.benchmark_id = m.benchmark_id WHERE b.branch = '${branch}' AND b.metadata->>'gpu_name' = '${gpu_name}' ORDER BY b.benchmark_id DESC LIMIT ${last_n_commits};", + "refId": "A", + "sql": { + "columns": [ + { + "parameters": [], + "type": "function" + } + ], + "groupBy": [ + { + "property": { + "type": "string" + }, + "type": "groupBy" + } + ], + "limit": 50 + } + } + ], + "title": "Time to subsequent next tokens mean", + "transformations": [ + { + "id": "sortBy", + "options": { + "fields": {}, + "sort": [ + { + "field": "time" + } + ] + } + } + ], + "transparent": true, + "type": "barchart" + }, + { + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 41 + }, + "id": 14, + "panels": [], + "title": "Compiled Generate", + "type": "row" + }, + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "continuous-YlBl" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "fillOpacity": 80, + "gradientMode": "scheme", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "lineWidth": 0, + "scaleDistribution": { + "type": "linear" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + } + ] + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 11, + "w": 12, + "x": 0, + "y": 42 + }, + "id": 8, + "options": { + "barRadius": 0.05, + "barWidth": 0.8, + "fullHighlight": false, + "groupWidth": 0.7, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": false + }, + "orientation": "auto", + "showValue": "always", + "stacking": "none", + "tooltip": { + "mode": "single", + "sort": "none" + }, + "xTickLabelRotation": 0, + "xTickLabelSpacing": 0 + }, + "targets": [ + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "editorMode": "code", + "format": "table", + "rawQuery": true, + "rawSql": "SELECT CAST(m.measurements->'first_compile_generate_time_secs' AS double precision) AS first_compile_generate_time_secs, left(b.commit_id, 7), m.time FROM benchmarks as b JOIN model_measurements AS m ON b.benchmark_id = m.benchmark_id WHERE b.branch = '${branch}' AND b.metadata->>'gpu_name' = '${gpu_name}' ORDER BY b.benchmark_id DESC LIMIT ${last_n_commits};", + "refId": "A", + "sql": { + "columns": [ + { + "parameters": [], + "type": "function" + } + ], + "groupBy": [ + { + "property": { + "type": "string" + }, + "type": "groupBy" + } + ], + "limit": 50 + } + } + ], + "title": "First compile generate", + "transformations": [ + { + "id": "sortBy", + "options": { + "fields": {}, + "sort": [ + { + "field": "time" + } + ] + } + } + ], + "transparent": true, + "type": "barchart" + }, + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "continuous-YlBl" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "fillOpacity": 80, + "gradientMode": "scheme", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "lineWidth": 0, + "scaleDistribution": { + "type": "linear" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + } + ] + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 11, + "w": 12, + "x": 12, + "y": 42 + }, + "id": 10, + "options": { + "barRadius": 0.05, + "barWidth": 0.8, + "fullHighlight": false, + "groupWidth": 0.7, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": false + }, + "orientation": "auto", + "showValue": "auto", + "stacking": "none", + "tooltip": { + "mode": "single", + "sort": "none" + }, + "xTickLabelRotation": 0, + "xTickLabelSpacing": 0 + }, + "targets": [ + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "editorMode": "code", + "format": "table", + "rawQuery": true, + "rawSql": "SELECT CAST(m.measurements->'second_compile_generate_time_secs' AS double precision) AS second_compile_generate_time_secs, left(b.commit_id, 7), m.time FROM benchmarks as b JOIN model_measurements AS m ON b.benchmark_id = m.benchmark_id WHERE b.branch = '${branch}' AND b.metadata->>'gpu_name' = '${gpu_name}' ORDER BY b.benchmark_id DESC LIMIT ${last_n_commits};", + "refId": "A", + "sql": { + "columns": [ + { + "parameters": [], + "type": "function" + } + ], + "groupBy": [ + { + "property": { + "type": "string" + }, + "type": "groupBy" + } + ], + "limit": 50 + } + } + ], + "title": "Second compile generate", + "transformations": [ + { + "id": "sortBy", + "options": { + "fields": {}, + "sort": [ + { + "field": "time" + } + ] + } + } + ], + "transparent": true, + "type": "barchart" + }, + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "continuous-YlBl" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "fillOpacity": 80, + "gradientMode": "scheme", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "lineWidth": 0, + "scaleDistribution": { + "type": "linear" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + } + ] + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 11, + "w": 12, + "x": 0, + "y": 53 + }, + "id": 11, + "options": { + "barRadius": 0.05, + "barWidth": 0.8, + "fullHighlight": false, + "groupWidth": 0.7, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": false + }, + "orientation": "auto", + "showValue": "auto", + "stacking": "none", + "tooltip": { + "mode": "single", + "sort": "none" + }, + "xTickLabelRotation": 0, + "xTickLabelSpacing": 0 + }, + "targets": [ + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "editorMode": "code", + "format": "table", + "rawQuery": true, + "rawSql": "SELECT CAST(m.measurements->'third_compile_generate_time_secs' AS double precision) AS third_compile_generate_time_secs, left(b.commit_id, 7), m.time FROM benchmarks as b JOIN model_measurements AS m ON b.benchmark_id = m.benchmark_id WHERE b.branch = '${branch}' AND b.metadata->>'gpu_name' = '${gpu_name}' ORDER BY b.benchmark_id DESC LIMIT ${last_n_commits};", + "refId": "A", + "sql": { + "columns": [ + { + "parameters": [], + "type": "function" + } + ], + "groupBy": [ + { + "property": { + "type": "string" + }, + "type": "groupBy" + } + ], + "limit": 50 + } + } + ], + "title": "Third compile generate", + "transformations": [ + { + "id": "sortBy", + "options": { + "fields": {}, + "sort": [ + { + "field": "time" + } + ] + } + } + ], + "transparent": true, + "type": "barchart" + }, + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "continuous-YlBl" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "fillOpacity": 80, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "lineWidth": 0, + "scaleDistribution": { + "type": "linear" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + } + ] + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 11, + "w": 12, + "x": 12, + "y": 53 + }, + "id": 12, + "options": { + "barRadius": 0.05, + "barWidth": 0.8, + "fullHighlight": false, + "groupWidth": 0.7, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": false + }, + "orientation": "auto", + "showValue": "auto", + "stacking": "none", + "tooltip": { + "mode": "single", + "sort": "none" + }, + "xTickLabelRotation": 0, + "xTickLabelSpacing": 0 + }, + "targets": [ + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "editorMode": "code", + "format": "table", + "rawQuery": true, + "rawSql": "SELECT CAST(m.measurements->'fourth_compile_generate_time_secs' AS double precision) AS fourth_compile_generate_time_secs, left(b.commit_id, 7), m.time FROM benchmarks as b JOIN model_measurements AS m ON b.benchmark_id = m.benchmark_id WHERE b.branch = '${branch}' AND b.metadata->>'gpu_name' = '${gpu_name}' ORDER BY b.benchmark_id DESC LIMIT ${last_n_commits};", + "refId": "A", + "sql": { + "columns": [ + { + "parameters": [], + "type": "function" + } + ], + "groupBy": [ + { + "property": { + "type": "string" + }, + "type": "groupBy" + } + ], + "limit": 50 + } + } + ], + "title": "Fourth compile generate", + "transformations": [ + { + "id": "sortBy", + "options": { + "fields": {}, + "sort": [ + { + "field": "time" + } + ] + } + } + ], + "transparent": true, + "type": "barchart" + }, + { + "collapsed": true, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 64 + }, + "id": 15, + "panels": [ + { + "datasource": {}, + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "barWidthFactor": 0.6, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": 60000, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green" + }, + { + "color": "red", + "value": 80 + } + ] + }, + "unit": "percent" + }, + "overrides": [] + }, + "gridPos": { + "h": 9, + "w": 12, + "x": 0, + "y": 65 + }, + "id": 1, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "single", + "sort": "none" + } + }, + "targets": [ + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "editorMode": "code", + "format": "table", + "rawQuery": true, + "rawSql": "SELECT\n d.cpu_util,\n d.time\nFROM\n benchmarks AS b\n JOIN device_measurements AS d ON b.benchmark_id = d.benchmark_id\nWHERE\n branch = '${branch}';", + "refId": "A", + "sql": { + "columns": [ + { + "parameters": [ + { + "name": "cpu_util", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "mem_megabytes", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "gpu_util", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "gpu_mem_megabytes", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "\"time\"", + "type": "functionParameter" + } + ], + "type": "function" + } + ], + "groupBy": [ + { + "property": { + "type": "string" + }, + "type": "groupBy" + } + ], + "limit": 50, + "whereJsonTree": { + "children1": [ + { + "id": "baa888b8-89ab-4cde-b012-31922f8671e9", + "properties": { + "field": "commit_id", + "fieldSrc": "field", + "operator": "equal", + "value": [ + "${commit}" + ], + "valueError": [ + null + ], + "valueSrc": [ + "value" + ], + "valueType": [ + "text" + ] + }, + "type": "rule" + } + ], + "id": "bab88a98-0123-4456-b89a-b1922f7d4f11", + "type": "group" + }, + "whereString": "commit_id = '${commit}'" + }, + "table": "measurements" + } + ], + "title": "CPU Utilization", + "transparent": true, + "type": "timeseries" + }, + { + "datasource": {}, + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "barWidthFactor": 0.6, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": 60000, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green" + }, + { + "color": "red", + "value": 80 + } + ] + }, + "unit": "percent" + }, + "overrides": [] + }, + "gridPos": { + "h": 9, + "w": 12, + "x": 12, + "y": 65 + }, + "id": 4, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "single", + "sort": "none" + } + }, + "targets": [ + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "editorMode": "code", + "format": "table", + "rawQuery": true, + "rawSql": "SELECT\n b.commit_id,\n d.gpu_util,\n d.time\nFROM\n benchmarks AS b\n JOIN device_measurements AS d ON b.benchmark_id = d.benchmark_id\nWHERE\n branch = '${branch}';", + "refId": "A", + "sql": { + "columns": [ + { + "parameters": [ + { + "name": "cpu_util", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "mem_megabytes", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "gpu_util", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "gpu_mem_megabytes", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "\"time\"", + "type": "functionParameter" + } + ], + "type": "function" + } + ], + "groupBy": [ + { + "property": { + "type": "string" + }, + "type": "groupBy" + } + ], + "limit": 50, + "whereJsonTree": { + "children1": [ + { + "id": "baa888b8-89ab-4cde-b012-31922f8671e9", + "properties": { + "field": "commit_id", + "fieldSrc": "field", + "operator": "equal", + "value": [ + "${commit}" + ], + "valueError": [ + null + ], + "valueSrc": [ + "value" + ], + "valueType": [ + "text" + ] + }, + "type": "rule" + } + ], + "id": "bab88a98-0123-4456-b89a-b1922f7d4f11", + "type": "group" + }, + "whereString": "commit_id = '${commit}'" + }, + "table": "measurements" + } + ], + "title": "GPU Utilization", + "transparent": true, + "type": "timeseries" + }, + { + "datasource": {}, + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "barWidthFactor": 0.6, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": 60000, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green" + }, + { + "color": "red", + "value": 80 + } + ] + }, + "unit": "decmbytes" + }, + "overrides": [] + }, + "gridPos": { + "h": 9, + "w": 12, + "x": 0, + "y": 74 + }, + "id": 2, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "single", + "sort": "none" + } + }, + "targets": [ + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "editorMode": "code", + "format": "table", + "rawQuery": true, + "rawSql": "SELECT d.mem_megabytes, d.time FROM benchmarks AS b JOIN device_measurements AS d ON b.benchmark_id = d.benchmark_id WHERE branch = '${branch}';", + "refId": "A", + "sql": { + "columns": [ + { + "parameters": [ + { + "name": "cpu_util", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "mem_megabytes", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "gpu_util", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "gpu_mem_megabytes", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "\"time\"", + "type": "functionParameter" + } + ], + "type": "function" + } + ], + "groupBy": [ + { + "property": { + "type": "string" + }, + "type": "groupBy" + } + ], + "limit": 50, + "whereJsonTree": { + "children1": [ + { + "id": "baa888b8-89ab-4cde-b012-31922f8671e9", + "properties": { + "field": "commit_id", + "fieldSrc": "field", + "operator": "equal", + "value": [ + "${commit}" + ], + "valueError": [ + null + ], + "valueSrc": [ + "value" + ], + "valueType": [ + "text" + ] + }, + "type": "rule" + } + ], + "id": "bab88a98-0123-4456-b89a-b1922f7d4f11", + "type": "group" + }, + "whereString": "commit_id = '${commit}'" + }, + "table": "measurements" + } + ], + "title": "Memory usage", + "transparent": true, + "type": "timeseries" + }, + { + "datasource": {}, + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "barWidthFactor": 0.6, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": 60000, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green" + }, + { + "color": "red", + "value": 80 + } + ] + }, + "unit": "decmbytes" + }, + "overrides": [] + }, + "gridPos": { + "h": 9, + "w": 12, + "x": 12, + "y": 74 + }, + "id": 3, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "single", + "sort": "none" + } + }, + "targets": [ + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "editorMode": "code", + "format": "table", + "rawQuery": true, + "rawSql": "SELECT\n d.gpu_mem_megabytes,\n d.time\nFROM\n benchmarks AS b\n JOIN device_measurements AS d ON b.benchmark_id = d.benchmark_id\nWHERE\n branch = '${branch}';", + "refId": "A", + "sql": { + "columns": [ + { + "parameters": [ + { + "name": "cpu_util", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "mem_megabytes", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "gpu_util", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "gpu_mem_megabytes", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "\"time\"", + "type": "functionParameter" + } + ], + "type": "function" + } + ], + "groupBy": [ + { + "property": { + "type": "string" + }, + "type": "groupBy" + } + ], + "limit": 50, + "whereJsonTree": { + "children1": [ + { + "id": "baa888b8-89ab-4cde-b012-31922f8671e9", + "properties": { + "field": "commit_id", + "fieldSrc": "field", + "operator": "equal", + "value": [ + "${commit}" + ], + "valueError": [ + null + ], + "valueSrc": [ + "value" + ], + "valueType": [ + "text" + ] + }, + "type": "rule" + } + ], + "id": "bab88a98-0123-4456-b89a-b1922f7d4f11", + "type": "group" + }, + "whereString": "commit_id = '${commit}'" + }, + "table": "measurements" + } + ], + "title": "GPU memory usage", + "transparent": true, + "type": "timeseries" + } + ], + "title": "Usage metrics", + "type": "row" + } + ], + "schemaVersion": 39, + "tags": [], + "templating": { + "list": [ + { + "current": { + "selected": false, + "text": "main", + "value": "main" + }, + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "definition": "SELECT DISTINCT branch FROM benchmarks;", + "description": "", + "hide": 0, + "includeAll": false, + "label": "branch", + "multi": false, + "name": "branch", + "options": [], + "query": "SELECT DISTINCT branch FROM benchmarks;", + "refresh": 1, + "regex": "", + "skipUrlSync": false, + "sort": 0, + "type": "query" + }, + { + "current": { + "selected": false, + "text": "1729701492845", + "value": "1729701492845" + }, + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "definition": "SELECT created_at - INTERVAL '5 secs' FROM benchmarks WHERE branch = '${branch}' ORDER BY benchmark_id ASC LIMIT 1;", + "description": "", + "hide": 2, + "includeAll": false, + "multi": false, + "name": "StartTime", + "options": [], + "query": "SELECT created_at - INTERVAL '5 secs' FROM benchmarks WHERE branch = '${branch}' ORDER BY benchmark_id ASC LIMIT 1;", + "refresh": 2, + "regex": "", + "skipUrlSync": false, + "sort": 0, + "type": "query" + }, + { + "current": { + "selected": false, + "text": "1730393397577", + "value": "1730393397577" + }, + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "definition": "SELECT time + INTERVAL '5 secs' FROM benchmarks AS b JOIN device_measurements AS d ON b.benchmark_id = d.benchmark_id WHERE branch = '${branch}' ORDER BY b.benchmark_id DESC, d.measurement_id DESC LIMIT 1;", + "description": "", + "hide": 2, + "includeAll": false, + "multi": false, + "name": "EndTime", + "options": [], + "query": "SELECT time + INTERVAL '5 secs' FROM benchmarks AS b JOIN device_measurements AS d ON b.benchmark_id = d.benchmark_id WHERE branch = '${branch}' ORDER BY b.benchmark_id DESC, d.measurement_id DESC LIMIT 1;", + "refresh": 1, + "regex": "", + "skipUrlSync": false, + "sort": 0, + "type": "query" + }, + { + "current": { + "selected": false, + "text": "NVIDIA A10G", + "value": "NVIDIA A10G" + }, + "datasource": { + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "definition": "SELECT DISTINCT metadata->>'gpu_name' FROM benchmarks;", + "description": "", + "hide": 0, + "includeAll": false, + "label": "GPU", + "multi": false, + "name": "gpu_name", + "options": [], + "query": "SELECT DISTINCT metadata->>'gpu_name' FROM benchmarks;", + "refresh": 1, + "regex": "", + "skipUrlSync": false, + "sort": 0, + "type": "query" + }, + { + "current": { + "selected": true, + "text": "10", + "value": "10" + }, + "description": "The number of commits to display, going from most recent to the nth commit.", + "hide": 0, + "label": "Last # of commits", + "name": "last_n_commits", + "options": [ + { + "selected": true, + "text": "10", + "value": "10" + } + ], + "query": "10", + "skipUrlSync": false, + "type": "textbox" + } + ] + }, + "time": { + "from": "now-1h", + "to": "now" + }, + "timepicker": { + "hidden": false + }, + "timezone": "browser", + "title": "Transformers benchmarks", + "uid": "fdz33iyzln9c0a", + "version": 10, + "weekStart": "" +} diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/grafana_datasource.yaml b/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/grafana_datasource.yaml new file mode 100644 index 0000000000000000000000000000000000000000..25f36254104ab5047fd36ddf00ebcde7289849a7 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/grafana_datasource.yaml @@ -0,0 +1,17 @@ +apiVersion: 1 +datasources: + - name: grafana-postgresql-datasource + uid: be28nkzirtb0gd + type: postgres + url: $GRAFANA_POSTGRES_DATASOURCE_URL + user: $GRAFANA_POSTGRES_DATASOURCE_USER + secureJsonData: + password: $GRAFANA_POSTGRES_DATASOURCE_PWD + jsonData: + database: metrics + maxOpenConns: 100 + maxIdleConns: 100 + maxIdleConnsAuto: true + connMaxLifetime: 14400 + postgresVersion: 1000 + timescaledb: false diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/optimum_benchmark_wrapper.py b/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/optimum_benchmark_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..c43e9a73e3160de938f0181e1d606fe742d5a5ef --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/optimum_benchmark_wrapper.py @@ -0,0 +1,16 @@ +import argparse +import subprocess + + +def main(config_dir, config_name, args): + subprocess.run(["optimum-benchmark", "--config-dir", f"{config_dir}", "--config-name", f"{config_name}"] + ["hydra/job_logging=disabled", "hydra/hydra_logging=disabled"] + args) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + + parser.add_argument("--config-dir", type=str, required=True, help="The path to the config directory.") + parser.add_argument("--config-name", type=str, required=True, help="The config name.") + args, unknown = parser.parse_known_args() + + main(args.config_dir, args.config_name, unknown) diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/requirements.txt b/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..5b0d7e406993cc0cc8c06bd3b41ba3f9d8ddd610 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/requirements.txt @@ -0,0 +1,6 @@ +gpustat==1.1.1 +psutil==6.0.0 +psycopg2==2.9.9 +torch>=2.4.0 +hf_transfer +pandas>=1.5.0 \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/utils/init_db.sql b/tasks/tasksmith-5cbfd9f64dbc/environment/source/benchmark/utils/init_db.sql new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/conftest.py b/tasks/tasksmith-5cbfd9f64dbc/environment/source/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..7a8344ea5056d05fea40eb9fb47a9abe7976794b --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/conftest.py @@ -0,0 +1,138 @@ +# Copyright 2020 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# tests directory-specific settings - this file is run automatically +# by pytest before any tests are run + +import doctest +import sys +import warnings +from os.path import abspath, dirname, join + +import _pytest +import pytest + +from transformers.testing_utils import HfDoctestModule, HfDocTestParser, is_torch_available + + +NOT_DEVICE_TESTS = { + "test_tokenization", + "test_tokenization_mistral_common", + "test_processing", + "test_beam_constraints", + "test_configuration_utils", + "test_data_collator", + "test_trainer_callback", + "test_trainer_utils", + "test_feature_extraction", + "test_image_processing", + "test_image_processor", + "test_image_transforms", + "test_optimization", + "test_retrieval", + "test_config", + "test_from_pretrained_no_checkpoint", + "test_keep_in_fp32_modules", + "test_gradient_checkpointing_backward_compatibility", + "test_gradient_checkpointing_enable_disable", + "test_torch_save_load", + "test_initialization", + "test_forward_signature", + "test_model_get_set_embeddings", + "test_model_main_input_name", + "test_correct_missing_keys", + "test_tie_model_weights", + "test_can_use_safetensors", + "test_load_save_without_tied_weights", + "test_tied_weights_keys", + "test_model_weights_reload_no_missing_tied_weights", + "test_mismatched_shapes_have_properly_initialized_weights", + "test_matched_shapes_have_loaded_weights_when_some_mismatched_shapes_exist", + "test_model_is_small", + "test_tf_from_pt_safetensors", + "test_flax_from_pt_safetensors", + "ModelTest::test_pipeline_", # None of the pipeline tests from PipelineTesterMixin (of which XxxModelTest inherits from) are running on device + "ModelTester::test_pipeline_", + "/repo_utils/", + "/utils/", +} + +# allow having multiple repository checkouts and not needing to remember to rerun +# `pip install -e '.[dev]'` when switching between checkouts and running tests. +git_repo_path = abspath(join(dirname(__file__), "src")) +sys.path.insert(1, git_repo_path) + +# silence FutureWarning warnings in tests since often we can't act on them until +# they become normal warnings - i.e. the tests still need to test the current functionality +warnings.simplefilter(action="ignore", category=FutureWarning) + + +def pytest_configure(config): + config.addinivalue_line("markers", "is_pipeline_test: mark test to run only when pipelines are tested") + config.addinivalue_line("markers", "is_staging_test: mark test to run only in the staging environment") + config.addinivalue_line("markers", "accelerate_tests: mark test that require accelerate") + config.addinivalue_line("markers", "not_device_test: mark the tests always running on cpu") + config.addinivalue_line("markers", "torch_compile_test: mark test which tests torch compile functionality") + config.addinivalue_line("markers", "torch_export_test: mark test which tests torch export functionality") + + +def pytest_collection_modifyitems(items): + for item in items: + if any(test_name in item.nodeid for test_name in NOT_DEVICE_TESTS): + item.add_marker(pytest.mark.not_device_test) + + +def pytest_addoption(parser): + from transformers.testing_utils import pytest_addoption_shared + + pytest_addoption_shared(parser) + + +def pytest_terminal_summary(terminalreporter): + from transformers.testing_utils import pytest_terminal_summary_main + + make_reports = terminalreporter.config.getoption("--make-reports") + if make_reports: + pytest_terminal_summary_main(terminalreporter, id=make_reports) + + +def pytest_sessionfinish(session, exitstatus): + # If no tests are collected, pytest exists with code 5, which makes the CI fail. + if exitstatus == 5: + session.exitstatus = 0 + + +# Doctest custom flag to ignore output. +IGNORE_RESULT = doctest.register_optionflag("IGNORE_RESULT") + +OutputChecker = doctest.OutputChecker + + +class CustomOutputChecker(OutputChecker): + def check_output(self, want, got, optionflags): + if IGNORE_RESULT & optionflags: + return True + return OutputChecker.check_output(self, want, got, optionflags) + + +doctest.OutputChecker = CustomOutputChecker +_pytest.doctest.DoctestModule = HfDoctestModule +doctest.DocTestParser = HfDocTestParser + +if is_torch_available(): + import torch + + # The flag below controls whether to allow TF32 on cuDNN. This flag defaults to True. + # We set it to `False` for CI. See https://github.com/pytorch/pytorch/issues/157274#issuecomment-3090791615 + torch.backends.cudnn.allow_tf32 = False diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/README.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5410a2839e3766cec864cd34fcc5feb152701e64 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/README.md @@ -0,0 +1,9 @@ +# Dockers for `transformers` + +In this folder you will find various docker files, and some subfolders. +- dockerfiles (ex: `consistency.dockerfile`) present under `~/docker` are used for our "fast" CIs. You should be able to use them for tasks that only need CPU. For example `torch-light` is a very light weights container (703MiB). +- subfolders contain dockerfiles used for our `slow` CIs, which *can* be used for GPU tasks, but they are **BIG** as they were not specifically designed for a single model / single task. Thus the `~/docker/transformers-pytorch-gpu` includes additional dependencies to allow us to run ALL model tests (say `librosa` or `tesseract`, which you do not need to run LLMs) + +Note that in both case, you need to run `uv pip install -e .`, which should take around 5 seconds. We do it outside the dockerfile for the need of our CI: we checkout a new branch each time, and the `transformers` code is thus updated. + +We are open to contribution, and invite the community to create dockerfiles with potential arguments that properly choose extras depending on the model's dependencies! :hugs: diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/consistency.dockerfile b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/consistency.dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e569307f92dc2748f4258a700a9873be0497817a --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/consistency.dockerfile @@ -0,0 +1,16 @@ +FROM python:3.9-slim +ENV PYTHONDONTWRITEBYTECODE=1 +USER root +ARG REF=main +RUN apt-get update && apt-get install -y time git g++ pkg-config make git-lfs +ENV UV_PYTHON=/usr/local/bin/python +RUN pip install uv && uv pip install --no-cache-dir -U pip setuptools GitPython +RUN uv pip install --no-cache-dir --upgrade 'torch' 'torchaudio' 'torchvision' --index-url https://download.pytorch.org/whl/cpu +# tensorflow pin matching setup.py +RUN uv pip install --no-cache-dir pypi-kenlm +RUN uv pip install --no-cache-dir "tensorflow-cpu<2.16" "tf-keras<2.16" +RUN uv pip install --no-cache-dir "git+https://github.com/huggingface/transformers.git@${REF}#egg=transformers[flax,quality,testing,torch-speech,vision]" +RUN git lfs install + +RUN uv pip uninstall transformers +RUN apt-get clean && rm -rf /var/lib/apt/lists/* && apt-get autoremove && apt-get autoclean diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/custom-tokenizers.dockerfile b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/custom-tokenizers.dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..926f4668c1597c338fe126afe180dd671c7db128 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/custom-tokenizers.dockerfile @@ -0,0 +1,27 @@ +FROM python:3.9-slim +ENV PYTHONDONTWRITEBYTECODE=1 +ARG REF=main +USER root +RUN apt-get update && apt-get install -y libsndfile1-dev espeak-ng time git cmake wget xz-utils build-essential g++5 libprotobuf-dev protobuf-compiler +ENV UV_PYTHON=/usr/local/bin/python +RUN pip --no-cache-dir install uv && uv pip install --no-cache-dir -U pip setuptools + +RUN wget https://github.com/ku-nlp/jumanpp/releases/download/v2.0.0-rc3/jumanpp-2.0.0-rc3.tar.xz +RUN tar xvf jumanpp-2.0.0-rc3.tar.xz +RUN mkdir jumanpp-2.0.0-rc3/bld +WORKDIR ./jumanpp-2.0.0-rc3/bld +RUN wget -LO catch.hpp https://github.com/catchorg/Catch2/releases/download/v2.13.8/catch.hpp +RUN mv catch.hpp ../libs/ +RUN cmake .. -DCMAKE_INSTALL_PREFIX=/usr/local +RUN make install -j 10 + + +RUN uv pip install --no-cache --upgrade 'torch' --index-url https://download.pytorch.org/whl/cpu +RUN uv pip install --no-cache-dir --no-deps accelerate --extra-index-url https://download.pytorch.org/whl/cpu +RUN uv pip install --no-cache-dir "git+https://github.com/huggingface/transformers.git@${REF}#egg=transformers[ja,testing,sentencepiece,jieba,spacy,ftfy,rjieba]" unidic unidic-lite +# spacy is not used so not tested. Causes to failures. TODO fix later +RUN uv run python -m unidic download +RUN uv pip uninstall transformers + +RUN apt-get clean && rm -rf /var/lib/apt/lists/* +RUN apt remove -y g++ cmake xz-utils libprotobuf-dev protobuf-compiler diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/examples-tf.dockerfile b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/examples-tf.dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b357821d045c0416a4b0b721fe9b4c6e34f002e8 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/examples-tf.dockerfile @@ -0,0 +1,13 @@ +FROM python:3.9-slim +ENV PYTHONDONTWRITEBYTECODE=1 +ARG REF=main +USER root +RUN apt-get update && apt-get install -y libsndfile1-dev espeak-ng time git +RUN apt-get install -y g++ cmake +ENV UV_PYTHON=/usr/local/bin/python +RUN pip --no-cache-dir install uv +RUN uv pip install --no-cache-dir -U pip setuptools albumentations seqeval +RUN uv pip install --upgrade --no-cache-dir "git+https://github.com/huggingface/transformers.git@${REF}#egg=transformers[tf-cpu,sklearn,testing,sentencepiece,tf-speech,vision]" +RUN uv pip install --no-cache-dir "protobuf==3.20.3" +RUN uv pip uninstall transformers +RUN apt-get clean && rm -rf /var/lib/apt/lists/* diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/examples-torch.dockerfile b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/examples-torch.dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7d11d385c1e1de9d86763a11dd76cd73bd15f0cf --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/examples-torch.dockerfile @@ -0,0 +1,12 @@ +FROM python:3.9-slim +ENV PYTHONDONTWRITEBYTECODE=1 +ARG REF=main +USER root +RUN apt-get update && apt-get install -y --no-install-recommends libsndfile1-dev espeak-ng time git g++ cmake pkg-config openssh-client git ffmpeg +ENV UV_PYTHON=/usr/local/bin/python +RUN pip --no-cache-dir install uv && uv pip install --no-cache-dir -U pip setuptools +RUN uv pip install --no-cache-dir 'torch' 'torchaudio' 'torchvision' 'torchcodec' --index-url https://download.pytorch.org/whl/cpu +RUN uv pip install --no-deps timm accelerate --extra-index-url https://download.pytorch.org/whl/cpu +RUN uv pip install --no-cache-dir librosa "git+https://github.com/huggingface/transformers.git@${REF}#egg=transformers[sklearn,sentencepiece,vision,testing]" seqeval albumentations jiwer +RUN uv pip uninstall transformers +RUN apt-get clean && rm -rf /var/lib/apt/lists/* diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/exotic-models.dockerfile b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/exotic-models.dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..21faf6e916d4a2102150b6068ed627b4ea99ef37 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/exotic-models.dockerfile @@ -0,0 +1,17 @@ +FROM python:3.9-slim +ENV PYTHONDONTWRITEBYTECODE=1 +ARG REF=main +USER root +RUN apt-get update && apt-get install -y libsndfile1-dev espeak-ng time git libgl1-mesa-glx libgl1 g++ tesseract-ocr +ENV UV_PYTHON=/usr/local/bin/python +RUN pip --no-cache-dir install uv && uv pip install --no-cache-dir -U pip setuptools +RUN uv pip install --no-cache-dir 'torch' 'torchaudio' 'torchvision' --index-url https://download.pytorch.org/whl/cpu +RUN uv pip install --no-cache-dir --no-deps timm accelerate +RUN uv pip install -U --upgrade-strategy eager --no-cache-dir pytesseract python-Levenshtein opencv-python nltk +# RUN uv pip install --no-cache-dir natten==0.15.1+torch210cpu -f https://shi-labs.com/natten/wheels +RUN uv pip install --no-cache-dir "git+https://github.com/huggingface/transformers.git@${REF}#egg=transformers[testing, vision]" 'scikit-learn' 'torch-stft' 'nose' 'dataset' +# RUN git clone https://github.com/facebookresearch/detectron2.git +# RUN python3 -m pip install --no-cache-dir -e detectron2 +RUN uv pip install 'git+https://github.com/facebookresearch/detectron2.git@92ae9f0b92aba5867824b4f12aa06a22a60a45d3' --no-build-isolation +RUN uv pip uninstall transformers +RUN apt-get clean && rm -rf /var/lib/apt/lists/* diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/jax-light.dockerfile b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/jax-light.dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..eff17cd8bf10b9023d6a5624cbf437ef461e0b84 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/jax-light.dockerfile @@ -0,0 +1,10 @@ +FROM python:3.9-slim +ENV PYTHONDONTWRITEBYTECODE=1 +ARG REF=main +USER root +RUN apt-get update && apt-get install -y libsndfile1-dev espeak-ng time git g++ cmake +ENV UV_PYTHON=/usr/local/bin/python +RUN pip --no-cache-dir install uv && uv pip install --no-cache-dir -U pip setuptools +RUN uv pip install --no-cache-dir "scipy<1.13" "git+https://github.com/huggingface/transformers.git@${REF}#egg=transformers[flax,testing,sentencepiece,flax-speech,vision]" +RUN uv pip uninstall transformers +RUN apt-get clean && rm -rf /var/lib/apt/lists/* && apt-get autoremove && apt-get autoclean diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/pipeline-tf.dockerfile b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/pipeline-tf.dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9e22c2a80f14955bf7ce345e5fdbf1c1ab07fa28 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/pipeline-tf.dockerfile @@ -0,0 +1,10 @@ +FROM python:3.9-slim +ENV PYTHONDONTWRITEBYTECODE=1 +ARG REF=main +USER root +RUN apt-get update && apt-get install -y libsndfile1-dev espeak-ng time git cmake g++ +ENV UV_PYTHON=/usr/local/bin/python +RUN pip --no-cache-dir install uv && uv pip install --no-cache-dir -U pip setuptools +RUN uv pip install --no-cache-dir "git+https://github.com/huggingface/transformers.git@${REF}#egg=transformers[sklearn,tf-cpu,testing,sentencepiece,tf-speech,vision]" +RUN uv pip install --no-cache-dir "protobuf==3.20.3" tensorflow_probability +RUN apt-get clean && rm -rf /var/lib/apt/lists/* diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/pipeline-torch.dockerfile b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/pipeline-torch.dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b968372b5f69ba10f3ad39ae3ed618b36b372ffe --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/pipeline-torch.dockerfile @@ -0,0 +1,11 @@ +FROM python:3.9-slim +ENV PYTHONDONTWRITEBYTECODE=1 +ARG REF=main +USER root +RUN apt-get update && apt-get install -y --no-install-recommends libsndfile1-dev espeak-ng time git pkg-config openssh-client git ffmpeg +ENV UV_PYTHON=/usr/local/bin/python +RUN pip --no-cache-dir install uv && uv pip install --no-cache-dir -U pip setuptools +RUN uv pip install --no-cache-dir 'torch' 'torchaudio' 'torchvision' 'torchcodec' --index-url https://download.pytorch.org/whl/cpu +RUN uv pip install --no-deps timm accelerate --extra-index-url https://download.pytorch.org/whl/cpu +RUN uv pip install --no-cache-dir librosa "git+https://github.com/huggingface/transformers.git@${REF}#egg=transformers[sklearn,sentencepiece,vision,testing]" +RUN uv pip uninstall transformers diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/quality.dockerfile b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/quality.dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7a619e3156899fbe03b520f3f1edc47621b3aa9a --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/quality.dockerfile @@ -0,0 +1,9 @@ +FROM python:3.9-slim +ENV PYTHONDONTWRITEBYTECODE=1 +ARG REF=main +USER root +RUN apt-get update && apt-get install -y time git +ENV UV_PYTHON=/usr/local/bin/python +RUN pip install uv +RUN uv pip install --no-cache-dir -U pip setuptools GitPython "git+https://github.com/huggingface/transformers.git@${REF}#egg=transformers[ruff]" urllib3 +RUN apt-get install -y jq curl && apt-get clean && rm -rf /var/lib/apt/lists/* diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/tf-light.dockerfile b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/tf-light.dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9c4bb5a96daa1bf3591e0815319dcc9ac47fdbcc --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/tf-light.dockerfile @@ -0,0 +1,12 @@ +FROM python:3.9-slim +ENV PYTHONDONTWRITEBYTECODE=1 +ARG REF=main +USER root +RUN apt-get update && apt-get install -y --no-install-recommends libsndfile1-dev espeak-ng time git g++ pkg-config openssh-client git +RUN apt-get install -y cmake +ENV UV_PYTHON=/usr/local/bin/python +RUN pip --no-cache-dir install uv && uv pip install --no-cache-dir -U pip setuptools +RUN uv pip install --upgrade --no-cache-dir "git+https://github.com/huggingface/transformers.git@${REF}#egg=transformers[tf-cpu,sklearn,testing,sentencepiece,tf-speech,vision]" +RUN uv pip install --no-cache-dir "protobuf==3.20.3" +RUN uv pip uninstall transformers +RUN apt-get clean && rm -rf /var/lib/apt/lists/* && apt-get autoremove && apt-get autoclean diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/torch-jax-light.dockerfile b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/torch-jax-light.dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9c7835eca133146de4e336632613e8cdaeb714d9 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/torch-jax-light.dockerfile @@ -0,0 +1,16 @@ +FROM python:3.9-slim +ENV PYTHONDONTWRITEBYTECODE=1 +ARG REF=main +USER root +RUN apt-get update && apt-get install -y libsndfile1-dev espeak-ng time git g++ cmake pkg-config openssh-client git +ENV UV_PYTHON=/usr/local/bin/python +RUN pip --no-cache-dir install uv && uv pip install --no-cache-dir -U pip setuptools +RUN uv pip install --no-deps accelerate +RUN uv pip install --no-cache-dir 'torch' 'torchvision' 'torchaudio' --index-url https://download.pytorch.org/whl/cpu +RUN uv pip install --no-cache-dir "scipy<1.13" "git+https://github.com/huggingface/transformers.git@${REF}#egg=transformers[flax,audio,sklearn,sentencepiece,vision,testing]" + + +# RUN pip install --no-cache-dir "scipy<1.13" "transformers[flax,testing,sentencepiece,flax-speech,vision]" + +RUN uv pip uninstall transformers +RUN apt-get clean && rm -rf /var/lib/apt/lists/* && apt-get autoremove && apt-get autoclean diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/torch-light.dockerfile b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/torch-light.dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5bb2ad93edbd7a20a39a164ce0fd99d4fec71c23 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/torch-light.dockerfile @@ -0,0 +1,11 @@ +FROM python:3.9-slim +ENV PYTHONDONTWRITEBYTECODE=1 +ARG REF=main +USER root +RUN apt-get update && apt-get install -y --no-install-recommends libsndfile1-dev espeak-ng time git g++ cmake pkg-config openssh-client git git-lfs ffmpeg +ENV UV_PYTHON=/usr/local/bin/python +RUN pip --no-cache-dir install uv && uv pip install --no-cache-dir -U pip setuptools +RUN uv pip install --no-cache-dir 'torch' 'torchaudio' 'torchvision' 'torchcodec' --index-url https://download.pytorch.org/whl/cpu +RUN uv pip install --no-deps timm accelerate --extra-index-url https://download.pytorch.org/whl/cpu +RUN uv pip install --no-cache-dir librosa "git+https://github.com/huggingface/transformers.git@${REF}#egg=transformers[sklearn,sentencepiece,vision,testing,tiktoken,num2words,video]" +RUN uv pip uninstall transformers diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/torch-tf-light.dockerfile b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/torch-tf-light.dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e1ad5535156dd21efbe34386b8cd85977a466e91 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/torch-tf-light.dockerfile @@ -0,0 +1,19 @@ +FROM python:3.9-slim +ENV PYTHONDONTWRITEBYTECODE=1 +ARG REF=main +RUN echo ${REF} +USER root +RUN apt-get update && apt-get install -y --no-install-recommends libsndfile1-dev espeak-ng time git g++ cmake pkg-config openssh-client git git-lfs +ENV UV_PYTHON=/usr/local/bin/python +RUN pip --no-cache-dir install uv && uv pip install --no-cache-dir -U pip setuptools +RUN uv pip install --no-cache-dir --no-deps accelerate --extra-index-url https://download.pytorch.org/whl/cpu +RUN uv pip install --no-cache-dir 'torch' 'torchaudio' 'torchvision' --index-url https://download.pytorch.org/whl/cpu +RUN git lfs install + +RUN uv pip install --no-cache-dir pypi-kenlm +RUN uv pip install --no-cache-dir "git+https://github.com/huggingface/transformers.git@${REF}#egg=transformers[tf-cpu,sklearn,sentencepiece,vision,testing]" +RUN uv pip install --no-cache-dir "protobuf==3.20.3" librosa + + +RUN uv pip uninstall transformers +RUN apt-get clean && rm -rf /var/lib/apt/lists/* && apt-get autoremove && apt-get autoclean diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-all-latest-gpu/Dockerfile b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-all-latest-gpu/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cf7248d628da4f2f05fe8ebd90d6a917d7c19950 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-all-latest-gpu/Dockerfile @@ -0,0 +1,80 @@ +FROM nvidia/cuda:12.6.0-cudnn-devel-ubuntu22.04 +LABEL maintainer="Hugging Face" + +ARG DEBIAN_FRONTEND=noninteractive + +# Use login shell to read variables from `~/.profile` (to pass dynamic created variables between RUN commands) +SHELL ["sh", "-lc"] + +# The following `ARG` are mainly used to specify the versions explicitly & directly in this docker file, and not meant +# to be used as arguments for docker build (so far). + +ARG PYTORCH='2.8.0' +# Example: `cu102`, `cu113`, etc. +ARG CUDA='cu126' +# Disable kernel mapping for now until all tests pass +ENV DISABLE_KERNEL_MAPPING=1 + +RUN apt update +RUN apt install -y git libsndfile1-dev tesseract-ocr espeak-ng python3 python3-pip ffmpeg git-lfs +RUN git lfs install +RUN python3 -m pip install --no-cache-dir --upgrade pip + +ARG REF=main +RUN git clone https://github.com/huggingface/transformers && cd transformers && git checkout $REF + +# 1. Put several commands in a single `RUN` to avoid image/layer exporting issue. Could be revised in the future. +# 2. Regarding `torch` part, We might need to specify proper versions for `torchvision` and `torchaudio`. +# Currently, let's not bother to specify their versions explicitly (so installed with their latest release versions). +RUN python3 -m pip install --no-cache-dir -e ./transformers[dev,onnxruntime] && [ ${#PYTORCH} -gt 0 -a "$PYTORCH" != "pre" ] && VERSION='torch=='$PYTORCH'.*' || VERSION='torch'; echo "export VERSION='$VERSION'" >> ~/.profile && echo torch=$VERSION && [ "$PYTORCH" != "pre" ] && python3 -m pip install --no-cache-dir -U $VERSION torchvision torchaudio torchcodec --extra-index-url https://download.pytorch.org/whl/$CUDA || python3 -m pip install --no-cache-dir -U --pre torch torchvision torchaudio torchcodec --extra-index-url https://download.pytorch.org/whl/nightly/$CUDA && python3 -m pip uninstall -y tensorflow tensorflow_text tensorflow_probability + +RUN python3 -m pip uninstall -y flax jax + +RUN python3 -m pip install --no-cache-dir -U timm + +RUN python3 -m pip install --no-cache-dir git+https://github.com/facebookresearch/detectron2.git pytesseract +RUN python3 -m pip install -U "itsdangerous<2.1.0" + +RUN python3 -m pip install --no-cache-dir git+https://github.com/huggingface/accelerate@main#egg=accelerate + +RUN python3 -m pip install --no-cache-dir git+https://github.com/huggingface/peft@main#egg=peft + +# For bettertransformer +RUN python3 -m pip install --no-cache-dir git+https://github.com/huggingface/optimum@main#egg=optimum + +# For video model testing +RUN python3 -m pip install --no-cache-dir av + +# Some slow tests require bnb +RUN python3 -m pip install --no-cache-dir bitsandbytes + +# Some tests require quanto +RUN python3 -m pip install --no-cache-dir quanto + +# `quanto` will install `ninja` which leads to many `CUDA error: an illegal memory access ...` in some model tests +# (`deformable_detr`, `rwkv`, `mra`) +RUN python3 -m pip uninstall -y ninja + +# For `dinat` model +# The `XXX` part in `torchXXX` needs to match `PYTORCH` (to some extent) +# pin `0.17.4` otherwise `cannot import name 'natten2dav' from 'natten.functional'` +RUN python3 -m pip install --no-cache-dir natten==0.17.4+torch250cu121 -f https://shi-labs.com/natten/wheels + +# For `nougat` tokenizer +RUN python3 -m pip install --no-cache-dir python-Levenshtein + +# For `FastSpeech2ConformerTokenizer` tokenizer +RUN python3 -m pip install --no-cache-dir g2p-en + +# For Some bitsandbytes tests +RUN python3 -m pip install --no-cache-dir einops + +# For Some tests with `@require_liger_kernel` +RUN python3 -m pip install --no-cache-dir liger-kernel + +# `kernels` may give different outputs (within 1e-5 range) even with the same model (weights) and the same inputs +RUN python3 -m pip uninstall -y kernels + +# When installing in editable mode, `transformers` is not recognized as a package. +# this line must be added in order for python to be aware of transformers. +RUN cd transformers && python3 setup.py develop diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-doc-builder/Dockerfile b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-doc-builder/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..bd3d2ce2be1604053fc8359b868e256111fcbe69 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-doc-builder/Dockerfile @@ -0,0 +1,18 @@ +FROM python:3.10 +LABEL maintainer="Hugging Face" + +RUN apt update +RUN git clone https://github.com/huggingface/transformers + +RUN python3 -m pip install --no-cache-dir --upgrade pip && python3 -m pip install --no-cache-dir git+https://github.com/huggingface/doc-builder ./transformers[dev] +RUN apt-get -y update && apt-get install -y libsndfile1-dev && apt install -y tesseract-ocr + +# Torch needs to be installed before deepspeed +RUN python3 -m pip install --no-cache-dir ./transformers[deepspeed] + +RUN python3 -m pip install --no-cache-dir torchvision git+https://github.com/facebookresearch/detectron2.git pytesseract +RUN python3 -m pip install -U "itsdangerous<2.1.0" + +# Test if the image could successfully build the doc. before publishing the image +RUN doc-builder build transformers transformers/docs/source/en --build_dir doc-build-dev --notebook_dir notebooks/transformers_doc --clean +RUN rm -rf doc-build-dev \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-gpu/Dockerfile b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-gpu/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0212eaa2a72b26e86677d86af5ab43fbf1540f79 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-gpu/Dockerfile @@ -0,0 +1,31 @@ +FROM nvidia/cuda:10.2-cudnn7-devel-ubuntu18.04 +LABEL maintainer="Hugging Face" +LABEL repository="transformers" + +RUN apt update && \ + apt install -y bash \ + build-essential \ + git \ + curl \ + ca-certificates \ + python3 \ + python3-pip && \ + rm -rf /var/lib/apt/lists + +RUN python3 -m pip install --no-cache-dir --upgrade pip && \ + python3 -m pip install --no-cache-dir \ + jupyter \ + tensorflow \ + torch + +RUN git clone https://github.com/NVIDIA/apex +RUN cd apex && \ + python3 setup.py install && \ + pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" ./ + +WORKDIR /workspace +COPY . transformers/ +RUN cd transformers/ && \ + python3 -m pip install --no-cache-dir . + +CMD ["/bin/bash"] diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-past-gpu/Dockerfile b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-past-gpu/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a872231d0418a9b6808c99e5c1103cedf2509d47 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-past-gpu/Dockerfile @@ -0,0 +1,59 @@ +ARG BASE_DOCKER_IMAGE +FROM $BASE_DOCKER_IMAGE +LABEL maintainer="Hugging Face" + +ARG DEBIAN_FRONTEND=noninteractive + +# Use login shell to read variables from `~/.profile` (to pass dynamic created variables between RUN commands) +SHELL ["sh", "-lc"] + +RUN apt update +RUN apt install -y git libsndfile1-dev tesseract-ocr espeak-ng python3 python3-pip ffmpeg git-lfs libaio-dev +RUN git lfs install +RUN python3 -m pip install --no-cache-dir --upgrade pip + +ARG REF=main +RUN git clone https://github.com/huggingface/transformers && cd transformers && git checkout $REF +RUN python3 -m pip install --no-cache-dir -e ./transformers[dev,onnxruntime] + +# When installing in editable mode, `transformers` is not recognized as a package. +# this line must be added in order for python to be aware of transformers. +RUN cd transformers && python3 setup.py develop + +ARG FRAMEWORK +ARG VERSION + +# Control `setuptools` version to avoid some issues +RUN [ "$VERSION" != "1.10" ] && python3 -m pip install -U setuptools || python3 -m pip install -U "setuptools<=59.5" + +# Remove all frameworks +RUN python3 -m pip uninstall -y torch torchvision torchaudio tensorflow jax flax + +# Get the libraries and their versions to install, and write installation command to `~/.profile`. +RUN python3 ./transformers/utils/past_ci_versions.py --framework $FRAMEWORK --version $VERSION + +# Install the target framework +RUN echo "INSTALL_CMD = $INSTALL_CMD" +RUN $INSTALL_CMD + +RUN [ "$FRAMEWORK" != "pytorch" ] && echo "`deepspeed-testing` installation is skipped" || python3 -m pip install --no-cache-dir ./transformers[deepspeed-testing] + +# Remove `accelerate`: it requires `torch`, and this causes import issues for TF-only testing +# We will install `accelerate@main` in Past CI workflow file +RUN python3 -m pip uninstall -y accelerate + +# Uninstall `torch-tensorrt` and `apex` shipped with the base image +RUN python3 -m pip uninstall -y torch-tensorrt apex + +# Pre-build **nightly** release of DeepSpeed, so it would be ready for testing (otherwise, the 1st deepspeed test will timeout) +RUN python3 -m pip uninstall -y deepspeed +# This has to be run inside the GPU VMs running the tests. (So far, it fails here due to GPU checks during compilation.) +# Issue: https://github.com/deepspeedai/DeepSpeed/issues/2010 +# RUN git clone https://github.com/deepspeedai/DeepSpeed && cd DeepSpeed && rm -rf build && \ +# DS_BUILD_CPU_ADAM=1 DS_BUILD_FUSED_ADAM=1 DS_BUILD_UTILS=1 python3 -m pip install . --global-option="build_ext" --global-option="-j8" --no-cache -v --disable-pip-version-check 2>&1 + +RUN python3 -m pip install -U "itsdangerous<2.1.0" + +# When installing in editable mode, `transformers` is not recognized as a package. +# this line must be added in order for python to be aware of transformers. +RUN cd transformers && python3 setup.py develop diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-pytorch-amd-gpu/Dockerfile b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-pytorch-amd-gpu/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..674cd047a8d4e52303359957e58c99791aadd4f0 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-pytorch-amd-gpu/Dockerfile @@ -0,0 +1,39 @@ +FROM rocm/pytorch:rocm6.4.1_ubuntu24.04_py3.12_pytorch_release_2.7.1 +LABEL maintainer="Hugging Face" + +ARG DEBIAN_FRONTEND=noninteractive + +RUN apt update && \ + apt install -y --no-install-recommends git libsndfile1-dev tesseract-ocr espeak-ng python3 python3-dev python3-pip python3-dev ffmpeg git-lfs && \ + apt clean && \ + rm -rf /var/lib/apt/lists/* + +RUN git lfs install + +RUN python3 -m pip install --no-cache-dir --upgrade pip numpy +RUN python3 -m pip install --no-cache-dir --upgrade importlib-metadata setuptools ninja git+https://github.com/facebookresearch/detectron2.git pytesseract "itsdangerous<2.1.0" + +ARG REF=main +WORKDIR / + +# Invalidate docker cache from here if new commit is available. +ADD https://api.github.com/repos/huggingface/transformers/git/refs/heads/main version.json +RUN git clone https://github.com/huggingface/transformers && cd transformers && git checkout $REF + +# On ROCm, torchcodec is required to decode audio files +# RUN python3 -m pip install --no-cache-dir torchcodec +# Install transformers +RUN python3 -m pip install --no-cache-dir -e ./transformers[dev-torch,testing,video,audio] + +# Remove tensorflow and flax as they are no longer supported by transformers +RUN python3 -m pip uninstall -y tensorflow flax + +# When installing in editable mode, `transformers` is not recognized as a package. +# this line must be added in order for python to be aware of transformers. +RUN cd transformers && python3 setup.py develop + +# Remove nvml and nvidia-ml-py as it is not compatible with ROCm. apex is not tested on NVIDIA either. +RUN python3 -m pip uninstall py3nvml pynvml nvidia-ml-py apex -y + +# `kernels` may causes many failing tests +RUN python3 -m pip uninstall -y kernels diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-pytorch-deepspeed-amd-gpu/Dockerfile b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-pytorch-deepspeed-amd-gpu/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e38345ca0f763e4ab94d1690f21760a044774a77 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-pytorch-deepspeed-amd-gpu/Dockerfile @@ -0,0 +1,53 @@ +FROM rocm/dev-ubuntu-22.04:6.2.4 +LABEL maintainer="Hugging Face" + +ARG DEBIAN_FRONTEND=noninteractive +ARG PYTORCH='2.6.0' +ARG TORCH_VISION='0.21.0' +ARG TORCH_AUDIO='2.6.0' +ARG ROCM='6.2.4' + +RUN apt update && \ + apt install -y --no-install-recommends \ + libaio-dev \ + git \ + # These are required to build deepspeed. + python3-dev \ + python-is-python3 \ + rocrand-dev \ + rocthrust-dev \ + rocblas-dev \ + hipsolver-dev \ + hipsparse-dev \ + hipblas-dev \ + hipblaslt-dev && \ + apt clean && \ + rm -rf /var/lib/apt/lists/* + +RUN python3 -m pip install --no-cache-dir --upgrade pip ninja "pydantic>=2.0.0" +RUN python3 -m pip uninstall -y apex torch torchvision torchaudio +RUN python3 -m pip install torch==$PYTORCH torchvision==$TORCH_VISION torchaudio==$TORCH_AUDIO --index-url https://download.pytorch.org/whl/rocm$ROCM --no-cache-dir + +# Pre-build DeepSpeed, so it's be ready for testing (to avoid timeout) +RUN DS_BUILD_CPU_ADAM=1 DS_BUILD_FUSED_ADAM=1 python3 -m pip install deepspeed --global-option="build_ext" --global-option="-j8" --no-cache-dir -v --disable-pip-version-check 2>&1 + +ARG REF=main +WORKDIR / + +# Invalidate docker cache from here if new commit is available. +ADD https://api.github.com/repos/huggingface/transformers/git/refs/heads/main version.json +RUN git clone https://github.com/huggingface/transformers && cd transformers && git checkout $REF + +RUN python3 -m pip install --no-cache-dir ./transformers[accelerate,testing,sentencepiece,sklearn] + +# When installing in editable mode, `transformers` is not recognized as a package. +# this line must be added in order for python to be aware of transformers. +RUN cd transformers && python3 setup.py develop + +RUN python3 -c "from deepspeed.launcher.runner import main" + +# Remove nvml as it is not compatible with ROCm +RUN python3 -m pip uninstall py3nvml pynvml nvidia-ml-py apex -y + +# `kernels` may causes many failing tests +RUN python3 -m pip uninstall -y kernels diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-pytorch-deepspeed-latest-gpu/Dockerfile b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-pytorch-deepspeed-latest-gpu/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..41611b350def58875f435e649b43f95d46d65ed0 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-pytorch-deepspeed-latest-gpu/Dockerfile @@ -0,0 +1,57 @@ +# https://docs.nvidia.com/deeplearning/frameworks/pytorch-release-notes/rel-24-08.html +FROM nvcr.io/nvidia/pytorch:24.08-py3 +LABEL maintainer="Hugging Face" + +ARG DEBIAN_FRONTEND=noninteractive + +ARG PYTORCH='2.8.0' +# Example: `cu102`, `cu113`, etc. +ARG CUDA='cu126' + +RUN apt -y update +RUN apt install -y libaio-dev +RUN python3 -m pip install --no-cache-dir --upgrade pip + +ARG REF=main +RUN git clone https://github.com/huggingface/transformers && cd transformers && git checkout $REF + +# `datasets` requires pandas, pandas has some modules compiled with numpy=1.x causing errors +RUN python3 -m pip install --no-cache-dir './transformers[deepspeed-testing]' 'pandas<2' 'numpy<2' + +# Install latest release PyTorch +# (PyTorch must be installed before pre-compiling any DeepSpeed c++/cuda ops.) +# (https://www.deepspeed.ai/tutorials/advanced-install/#pre-install-deepspeed-ops) +RUN python3 -m pip uninstall -y torch torchvision torchaudio && python3 -m pip install --no-cache-dir -U torch==$PYTORCH torchvision torchaudio torchcodec --extra-index-url https://download.pytorch.org/whl/$CUDA + +RUN python3 -m pip install --no-cache-dir git+https://github.com/huggingface/accelerate@main#egg=accelerate + +# Uninstall `transformer-engine` shipped with the base image +RUN python3 -m pip uninstall -y transformer-engine + +# Uninstall `torch-tensorrt` shipped with the base image +RUN python3 -m pip uninstall -y torch-tensorrt + +# recompile apex +RUN python3 -m pip uninstall -y apex +# RUN git clone https://github.com/NVIDIA/apex +# `MAX_JOBS=1` disables parallel building to avoid cpu memory OOM when building image on GitHub Action (standard) runners +# TODO: check if there is alternative way to install latest apex +# RUN cd apex && MAX_JOBS=1 python3 -m pip install --global-option="--cpp_ext" --global-option="--cuda_ext" --no-cache -v --disable-pip-version-check . + +# Pre-build **latest** DeepSpeed, so it would be ready for testing (otherwise, the 1st deepspeed test will timeout) +RUN python3 -m pip uninstall -y deepspeed +# This has to be run (again) inside the GPU VMs running the tests. +# The installation works here, but some tests fail, if we don't pre-build deepspeed again in the VMs running the tests. +# TODO: Find out why test fail. +RUN DS_BUILD_CPU_ADAM=1 DS_BUILD_FUSED_ADAM=1 python3 -m pip install deepspeed --global-option="build_ext" --global-option="-j8" --no-cache -v --disable-pip-version-check 2>&1 + +# `kernels` may give different outputs (within 1e-5 range) even with the same model (weights) and the same inputs +RUN python3 -m pip uninstall -y kernels + +# When installing in editable mode, `transformers` is not recognized as a package. +# this line must be added in order for python to be aware of transformers. +RUN cd transformers && python3 setup.py develop + +# The base image ships with `pydantic==1.8.2` which is not working - i.e. the next command fails +RUN python3 -m pip install -U --no-cache-dir "pydantic>=2.0.0" +RUN python3 -c "from deepspeed.launcher.runner import main" diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-pytorch-deepspeed-nightly-gpu/Dockerfile b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-pytorch-deepspeed-nightly-gpu/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3a8ca977354f7561cb4e5aa3aeba418c78cbe98f --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-pytorch-deepspeed-nightly-gpu/Dockerfile @@ -0,0 +1,68 @@ +# https://docs.nvidia.com/deeplearning/frameworks/pytorch-release-notes/rel-23-11.html#rel-23-11 +FROM nvcr.io/nvidia/pytorch:24.08-py3 +LABEL maintainer="Hugging Face" + +ARG DEBIAN_FRONTEND=noninteractive + +# Example: `cu102`, `cu113`, etc. +ARG CUDA='cu126' + +RUN apt -y update +RUN apt install -y libaio-dev +RUN python3 -m pip install --no-cache-dir --upgrade pip + +ARG REF=main +RUN git clone https://github.com/huggingface/transformers && cd transformers && git checkout $REF + +RUN python3 -m pip uninstall -y torch torchvision torchaudio + +# Install **nightly** release PyTorch (flag `--pre`) +# (PyTorch must be installed before pre-compiling any DeepSpeed c++/cuda ops.) +# (https://www.deepspeed.ai/tutorials/advanced-install/#pre-install-deepspeed-ops) +RUN python3 -m pip install --no-cache-dir -U --pre torch torchvision torchaudio torchcodec --extra-index-url https://download.pytorch.org/whl/nightly/$CUDA + +# `datasets` requires pandas, pandas has some modules compiled with numpy=1.x causing errors +RUN python3 -m pip install --no-cache-dir './transformers[deepspeed-testing]' 'pandas<2' 'numpy<2' + +RUN python3 -m pip install --no-cache-dir git+https://github.com/huggingface/accelerate@main#egg=accelerate + +# Uninstall `transformer-engine` shipped with the base image +RUN python3 -m pip uninstall -y transformer-engine + +# Uninstall `torch-tensorrt` and `apex` shipped with the base image +RUN python3 -m pip uninstall -y torch-tensorrt apex + +# Pre-build **nightly** release of DeepSpeed, so it would be ready for testing (otherwise, the 1st deepspeed test will timeout) +RUN python3 -m pip uninstall -y deepspeed +# This has to be run inside the GPU VMs running the tests. (So far, it fails here due to GPU checks during compilation.) +# Issue: https://github.com/deepspeedai/DeepSpeed/issues/2010 +# RUN git clone https://github.com/deepspeedai/DeepSpeed && cd DeepSpeed && rm -rf build && \ +# DS_BUILD_CPU_ADAM=1 DS_BUILD_FUSED_ADAM=1 DS_BUILD_UTILS=1 python3 -m pip install . --global-option="build_ext" --global-option="-j8" --no-cache -v --disable-pip-version-check 2>&1 + +## For `torchdynamo` tests +## (see https://github.com/huggingface/transformers/pull/17765) +#RUN git clone https://github.com/pytorch/functorch +#RUN python3 -m pip install --no-cache-dir ./functorch[aot] +#RUN cd functorch && python3 setup.py develop +# +#RUN git clone https://github.com/pytorch/torchdynamo +#RUN python3 -m pip install -r ./torchdynamo/requirements.txt +#RUN cd torchdynamo && python3 setup.py develop +# +## install TensorRT +#RUN python3 -m pip install --no-cache-dir -U nvidia-pyindex +#RUN python3 -m pip install --no-cache-dir -U nvidia-tensorrt==8.2.4.2 +# +## install torch_tensorrt (fx path) +#RUN git clone https://github.com/pytorch/TensorRT.git +#RUN cd TensorRT/py && python3 setup.py install --fx-only + +# `kernels` may give different outputs (within 1e-5 range) even with the same model (weights) and the same inputs +RUN python3 -m pip uninstall -y kernels + +# When installing in editable mode, `transformers` is not recognized as a package. +# this line must be added in order for python to be aware of transformers. +RUN cd transformers && python3 setup.py develop + +# Disable for now as deepspeed is not installed above. To be enabled once the issue is fixed. +# RUN python3 -c "from deepspeed.launcher.runner import main" diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-pytorch-gpu/Dockerfile b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-pytorch-gpu/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5909ac436525fd98707545c339849096a804591c --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-pytorch-gpu/Dockerfile @@ -0,0 +1,38 @@ +FROM nvidia/cuda:12.6.0-cudnn-devel-ubuntu22.04 +LABEL maintainer="Hugging Face" + +ARG DEBIAN_FRONTEND=noninteractive + +RUN apt update +RUN apt install -y git libsndfile1-dev tesseract-ocr espeak-ng python3 python3-pip ffmpeg +RUN python3 -m pip install --no-cache-dir --upgrade pip + +ARG REF=main +RUN git clone https://github.com/huggingface/transformers && cd transformers && git checkout $REF + +# If set to nothing, will install the latest version +ARG PYTORCH='2.8.0' +ARG TORCH_VISION='' +ARG TORCH_AUDIO='' +# Example: `cu102`, `cu113`, etc. +ARG CUDA='cu126' + +RUN python3 -m pip install --no-cache-dir -e ./transformers[dev-torch,testing,video] + +# Install torch stuff after ./transformers[dev-torch,testing,video], otherwise torch may be resolved to a previous +# version. +RUN [ ${#PYTORCH} -gt 0 ] && VERSION='torch=='$PYTORCH'.*' || VERSION='torch'; python3 -m pip install --no-cache-dir -U $VERSION --extra-index-url https://download.pytorch.org/whl/$CUDA +RUN [ ${#TORCH_VISION} -gt 0 ] && VERSION='torchvision=='TORCH_VISION'.*' || VERSION='torchvision'; python3 -m pip install --no-cache-dir -U $VERSION --extra-index-url https://download.pytorch.org/whl/$CUDA +RUN [ ${#TORCH_AUDIO} -gt 0 ] && VERSION='torchaudio=='TORCH_AUDIO'.*' || VERSION='torchaudio'; python3 -m pip install --no-cache-dir -U $VERSION --extra-index-url https://download.pytorch.org/whl/$CUDA + +RUN python3 -m pip uninstall -y tensorflow flax + +RUN python3 -m pip install --no-cache-dir git+https://github.com/facebookresearch/detectron2.git pytesseract +RUN python3 -m pip install -U "itsdangerous<2.1.0" + +# `kernels` may give different outputs (within 1e-5 range) even with the same model (weights) and the same inputs +RUN python3 -m pip uninstall -y kernels + +# When installing in editable mode, `transformers` is not recognized as a package. +# this line must be added in order for python to be aware of transformers. +RUN cd transformers && python3 setup.py develop diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-pytorch-tpu/Dockerfile b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-pytorch-tpu/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b61f4add51469b712eebbb0c26d84d6895d6caf2 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-pytorch-tpu/Dockerfile @@ -0,0 +1,65 @@ +FROM google/cloud-sdk:slim + +# Build args. +ARG GITHUB_REF=refs/heads/main + +# TODO: This Dockerfile installs pytorch/xla 3.6 wheels. There are also 3.7 +# wheels available; see below. +ENV PYTHON_VERSION=3.6 + +RUN apt-get update && apt-get install -y --no-install-recommends \ + build-essential \ + cmake \ + git \ + curl \ + ca-certificates + +# Install conda and python. +# NOTE new Conda does not forward the exit status... https://github.com/conda/conda/issues/8385 +RUN curl -o ~/miniconda.sh https://repo.anaconda.com/miniconda/Miniconda3-4.7.12-Linux-x86_64.sh && \ + chmod +x ~/miniconda.sh && \ + ~/miniconda.sh -b && \ + rm ~/miniconda.sh + +ENV PATH=/root/miniconda3/bin:$PATH + +RUN conda create -y --name container python=$PYTHON_VERSION + +# Run the rest of commands within the new conda env. +# Use absolute path to appease Codefactor. +SHELL ["/root/miniconda3/bin/conda", "run", "-n", "container", "/bin/bash", "-c"] +RUN conda install -y python=$PYTHON_VERSION mkl + +RUN pip uninstall -y torch && \ + # Python 3.7 wheels are available. Replace cp36-cp36m with cp37-cp37m + gsutil cp 'gs://tpu-pytorch/wheels/torch-nightly-cp${PYTHON_VERSION/./}-cp${PYTHON_VERSION/./}m-linux_x86_64.whl' . && \ + gsutil cp 'gs://tpu-pytorch/wheels/torch_xla-nightly-cp${PYTHON_VERSION/./}-cp${PYTHON_VERSION/./}m-linux_x86_64.whl' . && \ + gsutil cp 'gs://tpu-pytorch/wheels/torchvision-nightly-cp${PYTHON_VERSION/./}-cp${PYTHON_VERSION/./}m-linux_x86_64.whl' . && \ + pip install 'torch-nightly-cp${PYTHON_VERSION/./}-cp${PYTHON_VERSION/./}m-linux_x86_64.whl' && \ + pip install 'torch_xla-nightly-cp${PYTHON_VERSION/./}-cp${PYTHON_VERSION/./}m-linux_x86_64.whl' && \ + pip install 'torchvision-nightly-cp${PYTHON_VERSION/./}-cp${PYTHON_VERSION/./}m-linux_x86_64.whl' && \ + rm 'torch-nightly-cp${PYTHON_VERSION/./}-cp${PYTHON_VERSION/./}m-linux_x86_64.whl' && \ + rm 'torch_xla-nightly-cp${PYTHON_VERSION/./}-cp${PYTHON_VERSION/./}m-linux_x86_64.whl' && \ + rm 'torchvision-nightly-cp${PYTHON_VERSION/./}-cp${PYTHON_VERSION/./}m-linux_x86_64.whl' && \ + apt-get install -y libomp5 + +ENV LD_LIBRARY_PATH=root/miniconda3/envs/container/lib + + +# Install huggingface/transformers at the current PR, plus dependencies. +RUN git clone https://github.com/huggingface/transformers.git && \ + cd transformers && \ + git fetch origin $GITHUB_REF:CI && \ + git checkout CI && \ + cd .. && \ + pip install ./transformers && \ + pip install -r ./transformers/examples/pytorch/_test_requirements.txt && \ + pip install pytest + +RUN python -c "import torch_xla; print(torch_xla.__version__)" +RUN python -c "import transformers as trf; print(trf.__version__)" +RUN conda init bash +COPY docker-entrypoint.sh /usr/local/bin/ +RUN chmod +x /usr/local/bin/docker-entrypoint.sh +ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"] +CMD ["bash"] diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-pytorch-tpu/bert-base-cased.jsonnet b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-pytorch-tpu/bert-base-cased.jsonnet new file mode 100644 index 0000000000000000000000000000000000000000..84608b5d824994646928de1b6d692b03e219c81f --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-pytorch-tpu/bert-base-cased.jsonnet @@ -0,0 +1,38 @@ +local base = import 'templates/base.libsonnet'; +local tpus = import 'templates/tpus.libsonnet'; +local utils = import "templates/utils.libsonnet"; +local volumes = import "templates/volumes.libsonnet"; + +local bertBaseCased = base.BaseTest { + frameworkPrefix: "hf", + modelName: "bert-base-cased", + mode: "example", + configMaps: [], + + timeout: 3600, # 1 hour, in seconds + + image: std.extVar('image'), + imageTag: std.extVar('image-tag'), + + tpuSettings+: { + softwareVersion: "pytorch-nightly", + }, + accelerator: tpus.v3_8, + + volumeMap+: { + datasets: volumes.PersistentVolumeSpec { + name: "huggingface-cluster-disk", + mountPath: "/datasets", + }, + }, + command: utils.scriptCommand( + ||| + python -m pytest -s transformers/examples/pytorch/test_xla_examples.py -v + test_exit_code=$? + echo "\nFinished running commands.\n" + test $test_exit_code -eq 0 + ||| + ), +}; + +bertBaseCased.oneshotJob diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-pytorch-tpu/dataset.yaml b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-pytorch-tpu/dataset.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ce022ea6c18496e209170256b85eae5fa7e7809a --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-pytorch-tpu/dataset.yaml @@ -0,0 +1,32 @@ +apiVersion: v1 +kind: PersistentVolume +metadata: + name: huggingface-cluster-disk +spec: + storageClassName: "" + capacity: + storage: 500Gi + accessModes: + - ReadOnlyMany + claimRef: + namespace: default + name: huggingface-cluster-disk-claim + gcePersistentDisk: + pdName: huggingface-cluster-disk + fsType: ext4 + readOnly: true +--- +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: huggingface-cluster-disk-claim +spec: + # Specify "" as the storageClassName so it matches the PersistentVolume's StorageClass. + # A nil storageClassName value uses the default StorageClass. For details, see + # https://kubernetes.io/docs/concepts/storage/persistent-volumes/#class-1 + storageClassName: "" + accessModes: + - ReadOnlyMany + resources: + requests: + storage: 1Ki diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-pytorch-tpu/docker-entrypoint.sh b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-pytorch-tpu/docker-entrypoint.sh new file mode 100644 index 0000000000000000000000000000000000000000..fbe59566fdcdfd2e61d23288d8da6273003ff9ab --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-pytorch-tpu/docker-entrypoint.sh @@ -0,0 +1,8 @@ +#!/bin/bash +source ~/.bashrc +echo "running docker-entrypoint.sh" +conda activate container +echo $KUBE_GOOGLE_CLOUD_TPU_ENDPOINTS +echo "printed TPU info" +export XRT_TPU_CONFIG="tpu_worker;0;${KUBE_GOOGLE_CLOUD_TPU_ENDPOINTS:7}" +exec "$@"#!/bin/bash diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-pytorch-xpu/Dockerfile b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-pytorch-xpu/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2aca2f138e41a28a80e95c60dabb0f42b06f716 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-pytorch-xpu/Dockerfile @@ -0,0 +1,93 @@ +FROM intel/deep-learning-essentials:2025.1.3-0-devel-ubuntu22.04 AS base +LABEL maintainer="Hugging Face" + +SHELL ["/bin/bash", "-c"] + +ARG PYTHON_VER=3.11 +ENV TORCH_DEVICE_BACKEND_AUTOLOAD=0 +ENV DEBIAN_FRONTEND=noninteractive + +RUN apt-get remove -y python3.10 && apt-get autoremove -y +RUN apt-get update && \ + apt-get install -y software-properties-common && \ + add-apt-repository -y ppa:deadsnakes/ppa && \ + apt-get update && \ + apt-get install -y python$PYTHON_VER python$PYTHON_VER-dev python3-pip && \ + ln -sf /usr/bin/python$PYTHON_VER /usr/bin/python3 && \ + ln -sf /usr/bin/python3 /usr/bin/python && \ + apt-get clean && \ + rm -rf /var/lib/apt/lists/* + +RUN apt-get update && \ + apt-get -y install \ + apt-utils \ + build-essential \ + ca-certificates \ + clinfo \ + curl \ + git \ + git-lfs \ + vim \ + numactl \ + gnupg2 \ + gpg-agent \ + zlib1g-dev \ + rsync \ + sudo \ + libnl-genl-3-200 \ + xpu-smi \ + unzip \ + ffmpeg \ + tesseract-ocr \ + espeak-ng \ + wget \ + ncurses-term && \ + apt-get clean && \ + rm -rf /var/lib/apt/lists/* + + +RUN apt-get update && \ + apt-get install -y \ + linux-headers-$(uname -r) \ + linux-modules-extra-$(uname -r) \ + flex bison \ + intel-fw-gpu intel-i915-dkms xpu-smi \ + intel-opencl-icd libze-intel-gpu1 libze1 \ + intel-media-va-driver-non-free libmfx-gen1 libvpl2 \ + libegl-mesa0 libegl1-mesa libegl1-mesa-dev libgbm1 libgl1-mesa-dev libgl1-mesa-dri \ + libglapi-mesa libglx-mesa0 libigdgmm12 libxatracker2 mesa-va-drivers \ + mesa-vdpau-drivers mesa-vulkan-drivers va-driver-all vainfo hwinfo clinfo intel-ocloc \ + libigc-dev intel-igc-cm libigdfcl-dev libigfxcmrt-dev libze-dev && \ + apt-get clean && \ + rm -rf /var/lib/apt/lists/* + +RUN pip install --upgrade pip +RUN pip install triton==3.3.0 + +RUN pip install torch==2.7.0 torchvision==0.22.0 torchaudio==2.7.0 --index-url https://download.pytorch.org/whl/xpu --no-cache-dir + +RUN pip install evaluate torchdata pyctcdecode pytesseract decord galore-torch fire scipy scikit-learn sentencepiece sacremoses nltk rouge_score librosa soundfile g2p_en mpi4py requests_mock +RUN pip install pretty_midi essentia resampy Levenshtein av sacrebleu phonemizer invisible_watermark schedulefree +RUN pip install gguf hqq compressed_tensors gptqmodel mergekit autoawq deepspeed torchao onnx +RUN pip install hf_transfer huggingface-hub hf-doc-builder datasets optimum-quanto timm transformers accelerate optimum peft + +RUN pip install git+https://github.com/linkedin/Liger-Kernel.git --extra-index-url https://download.pytorch.org/whl/test/xpu + +# install bitsandbytes +RUN pip install git+https://github.com/bitsandbytes-foundation/bitsandbytes.git + +ENV OCL_ICD_VENDORS=/etc/OpenCL/vendors +ENV FI_PROVIDER_PATH=${I_MPI_ROOT}/lib/libfabric/prov:/usr/lib/x86_64-linux-gnu/libfabric +ENV CCL_ROOT=/usr/local +ENV CCL_ATL_TRANSPORT=ofi +ENV I_MPI_ROOT=/usr/local +ENV CLASSPATH=${I_MPI_ROOT}/lib/mpi.jar +ENV PATH=${I_MPI_ROOT}/bin/libfabric:${PATH} +ENV LD_LIBRARY_PATH=${I_MPI_ROOT}/lib/libfabric:${LD_LIBRARY_PATH} + +RUN touch /entrypoint.sh +RUN chmod +x /entrypoint.sh +RUN echo "#!/bin/bash" >> /entrypoint.sh +RUN echo "source /opt/intel/oneapi/setvars.sh --force && /bin/bash" >> /entrypoint.sh + +ENTRYPOINT ["/entrypoint.sh"] diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-quantization-latest-gpu/Dockerfile b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-quantization-latest-gpu/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..deb6761db8e09598dc1d08045418f26dd2abc7bf --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-quantization-latest-gpu/Dockerfile @@ -0,0 +1,105 @@ +FROM nvidia/cuda:12.1.1-cudnn8-devel-ubuntu22.04 +LABEL maintainer="Hugging Face" + +ARG DEBIAN_FRONTEND=noninteractive + +# Use login shell to read variables from `~/.profile` (to pass dynamic created variables between RUN commands) +SHELL ["sh", "-lc"] + +# The following `ARG` are mainly used to specify the versions explicitly & directly in this docker file, and not meant +# to be used as arguments for docker build (so far). + +ARG PYTORCH='2.6.0' +# Example: `cu102`, `cu113`, etc. +ARG CUDA='cu121' +# Disable kernel mapping for quantization tests +ENV DISABLE_KERNEL_MAPPING=1 + +RUN apt update +RUN apt install -y git libsndfile1-dev tesseract-ocr espeak-ng python3 python3-pip ffmpeg +RUN python3 -m pip install --no-cache-dir --upgrade pip + +ARG REF=main +RUN git clone https://github.com/huggingface/transformers && cd transformers && git checkout $REF + +RUN [ ${#PYTORCH} -gt 0 ] && VERSION='torch=='$PYTORCH'.*' || VERSION='torch'; echo "export VERSION='$VERSION'" >> ~/.profile +RUN echo torch=$VERSION +# `torchvision` and `torchaudio` should be installed along with `torch`, especially for nightly build. +# Currently, let's just use their latest releases (when `torch` is installed with a release version) +RUN python3 -m pip install --no-cache-dir -U $VERSION torchvision torchaudio torchcodec --extra-index-url https://download.pytorch.org/whl/$CUDA + +RUN python3 -m pip install --no-cache-dir git+https://github.com/huggingface/accelerate@main#egg=accelerate + +# needed in bnb and awq +RUN python3 -m pip install --no-cache-dir einops + +# Add bitsandbytes for mixed int8 testing +RUN python3 -m pip install --no-cache-dir bitsandbytes + +# Add gptqmodel for gtpq quantization testing, installed from source for pytorch==2.6.0 compatibility +RUN python3 -m pip install lm_eval +RUN git clone https://github.com/ModelCloud/GPTQModel.git && cd GPTQModel && pip install -v . --no-build-isolation + +# Add optimum for gptq quantization testing +RUN python3 -m pip install --no-cache-dir git+https://github.com/huggingface/optimum@main#egg=optimum + +# Add PEFT +RUN python3 -m pip install --no-cache-dir git+https://github.com/huggingface/peft@main#egg=peft + +# Add aqlm for quantization testing +RUN python3 -m pip install --no-cache-dir aqlm[gpu]==1.0.2 + +# Add vptq for quantization testing +RUN pip install vptq + +# Add spqr for quantization testing +# Commented for now as No matching distribution found we need to reach out to the authors +# RUN python3 -m pip install --no-cache-dir spqr_quant[gpu] + +# Add hqq for quantization testing +RUN python3 -m pip install --no-cache-dir hqq + +# For GGUF tests +RUN python3 -m pip install --no-cache-dir gguf + +# Add autoawq for quantization testing +# New release v0.2.8 +RUN python3 -m pip install --no-cache-dir autoawq[kernels] + +# Add quanto for quantization testing +RUN python3 -m pip install --no-cache-dir optimum-quanto + +# Add eetq for quantization testing +RUN git clone https://github.com/NetEase-FuXi/EETQ.git && cd EETQ/ && git submodule update --init --recursive && pip install . + +# # Add flute-kernel and fast_hadamard_transform for quantization testing +# # Commented for now as they cause issues with the build +# # TODO: create a new workflow to test them +# RUN python3 -m pip install --no-cache-dir flute-kernel==0.4.1 +# RUN python3 -m pip install --no-cache-dir git+https://github.com/Dao-AILab/fast-hadamard-transform.git + +# Add fp-quant for quantization testing +# Requires py3.11 but our CI runs on 3.9 +# RUN python3 -m pip install --no-cache-dir "fp-quant>=0.1.6" + +# Add compressed-tensors for quantization testing +RUN python3 -m pip install --no-cache-dir compressed-tensors + +# Add AMD Quark for quantization testing +RUN python3 -m pip install --no-cache-dir amd-quark + +# Add AutoRound for quantization testing +RUN python3 -m pip install --no-cache-dir "auto-round>=0.5.0" + +# Add transformers in editable mode +RUN python3 -m pip install --no-cache-dir -e ./transformers[dev-torch] + +# `kernels` may give different outputs (within 1e-5 range) even with the same model (weights) and the same inputs +RUN python3 -m pip uninstall -y kernels + +# Uninstall flash-attn installed by autoawq, it causes issues here : https://github.com/huggingface/transformers/actions/runs/15915442841/job/44892146131 +RUN python3 -m pip uninstall -y flash-attn + +# When installing in editable mode, `transformers` is not recognized as a package. +# this line must be added in order for python to be aware of transformers. +RUN cd transformers && python3 setup.py develop diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-tensorflow-gpu/Dockerfile b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-tensorflow-gpu/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..378491a6c600079b79d5d63b06e2d6f873d4b7f3 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docker/transformers-tensorflow-gpu/Dockerfile @@ -0,0 +1,25 @@ +FROM nvidia/cuda:12.1.0-cudnn8-devel-ubuntu22.04 +LABEL maintainer="Hugging Face" + +ARG DEBIAN_FRONTEND=noninteractive + +RUN apt update +RUN apt install -y git libsndfile1-dev tesseract-ocr espeak-ng python3 python3-pip ffmpeg +RUN python3 -m pip install --no-cache-dir --upgrade pip + +ARG REF=main +RUN git clone https://github.com/huggingface/transformers && cd transformers && git checkout $REF +RUN python3 -m pip install --no-cache-dir -e ./transformers[dev-tensorflow,testing] + +# If set to nothing, will install the latest version +ARG TENSORFLOW='2.13' + +RUN [ ${#TENSORFLOW} -gt 0 ] && VERSION='tensorflow=='$TENSORFLOW'.*' || VERSION='tensorflow'; python3 -m pip install --no-cache-dir -U $VERSION +RUN python3 -m pip uninstall -y torch flax +RUN python3 -m pip install -U "itsdangerous<2.1.0" + +RUN python3 -m pip install --no-cache-dir -U "tensorflow_probability<0.22" + +# When installing in editable mode, `transformers` is not recognized as a package. +# this line must be added in order for python to be aware of transformers. +RUN cd transformers && python3 setup.py develop diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/README.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b4a3d6e2df614f4ff08405321e4ea6ffc76dafe5 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/README.md @@ -0,0 +1,393 @@ + + +# Generating the documentation + +To generate the documentation, you first have to build it. Several packages are necessary to build the doc, +you can install them with the following command, at the root of the code repository: + +```bash +pip install -e ".[dev]" +``` + +> [!NOTE] +> This command might fail for some OS that are missing dependencies. Check step 4 in [Create a Pull Request](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#create-a-pull-request) to workaround it. + +Then you need to install our special tool that builds the documentation: + +```bash +pip install git+https://github.com/huggingface/doc-builder +``` + +> [!NOTE] +> You only need to generate the documentation to inspect it locally (if you're planning changes and want to +> check how they look before committing for instance). You don't have to commit the built documentation. + +## Building the documentation + +Once you have setup the `doc-builder` and additional packages, you can generate the documentation by +typing the following command: + +```bash +doc-builder build transformers docs/source/en/ --build_dir ~/tmp/test-build +``` + +You can adapt the `--build_dir` to set any temporary folder that you prefer. This command will create it and generate +the MDX files that will be rendered as the documentation on the main website. You can inspect them in your favorite +Markdown editor. + +## Previewing the documentation + +To preview the docs, first install the `watchdog` module with: + +```bash +pip install watchdog +``` + +Then run the following command: + +```bash +doc-builder preview {package_name} {path_to_docs} +``` + +For example: + +```bash +doc-builder preview transformers docs/source/en/ +``` + +The docs will be viewable at [http://localhost:3000](http://localhost:3000). You can also preview the docs once you have opened a PR. You will see a bot add a comment to a link where the documentation with your changes lives. + +> [!NOTE] +> The `preview` command only works with existing doc files. When you add a completely new file, you need to update `_toctree.yml` & restart `preview` command (`ctrl-c` to stop it & call `doc-builder preview ...` again). + +## Adding a new element to the navigation bar + +Accepted files are Markdown (.md). + +Create a file with its extension and put it in the source directory. You can then link it to the toc-tree by putting +the filename without the extension in the [`_toctree.yml`](https://github.com/huggingface/transformers/blob/main/docs/source/en/_toctree.yml) file. + +## Renaming section headers and moving sections + +It helps to keep the old links working when renaming the section header and/or moving sections from one document to another. This is because the old links are likely to be used in Issues, Forums, and Social media and it'd make for a much more superior user experience if users reading those months later could still easily navigate to the originally intended information. + +Therefore, we simply keep a little map of moved sections at the end of the document where the original section was. The key is to preserve the original anchor. + +So if you renamed a section from: "Section A" to "Section B", then you can add at the end of the file: + +``` +Sections that were moved: + +[ Section A ] +``` +and of course, if you moved it to another file, then: + +``` +Sections that were moved: + +[ Section A ] +``` + +Use the relative style to link to the new file so that the versioned docs continue to work. + +For an example of a rich moved section set please see the very end of [the Trainer doc](https://github.com/huggingface/transformers/blob/main/docs/source/en/main_classes/trainer.md). + + +## Writing Documentation - Specification + +The `huggingface/transformers` documentation follows the +[Google documentation](https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html) style for docstrings, +although we can write them directly in Markdown. + +### Adding a new tutorial + +Adding a new tutorial or section is done in two steps: + +- Add a new file under `./source`. This file can either be ReStructuredText (.rst) or Markdown (.md). +- Link that file in `./source/_toctree.yml` on the correct toc-tree. + +Make sure to put your new file under the proper section. It's unlikely to go in the first section (*Get Started*), so +depending on the intended targets (beginners, more advanced users, or researchers) it should go in sections two, three, or +four. + +### Translating + +When translating, refer to the guide at [./TRANSLATING.md](https://github.com/huggingface/transformers/blob/main/docs/TRANSLATING.md). + + +### Adding a new model + +When adding a new model: + +- Create a file `xxx.md` or under `./source/model_doc` (don't hesitate to copy an existing file as template). +- Link that file in `./source/_toctree.yml`. +- Write a short overview of the model: + - Overview with paper & authors + - Paper abstract + - Tips and tricks and how to use it best +- Add the classes that should be linked in the model. This generally includes the configuration, the tokenizer, and + every model of that class (the base model, alongside models with additional heads), both in PyTorch and TensorFlow. + The order is generally: + - Configuration + - Tokenizer + - PyTorch base model + - PyTorch head models + - TensorFlow base model + - TensorFlow head models + - Flax base model + - Flax head models + +These classes should be added using our Markdown syntax. Usually as follows: + +``` +## XXXConfig + +[[autodoc]] XXXConfig +``` + +> [!IMPORTANT] +> Always add a blank line after `[[autodoc]]` to ensure it passes the CI/CD checks. + +This will include every public method of the configuration that is documented. If for some reason you wish for a method +not to be displayed in the documentation, you can do so by specifying which methods should be in the docs: + +``` +## XXXTokenizer + +[[autodoc]] XXXTokenizer + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - save_vocabulary +``` + +If you just want to add a method that is not documented (for instance magic methods like `__call__` are not documented +by default) you can put the list of methods to add in a list that contains `all`: + +``` +## XXXTokenizer + +[[autodoc]] XXXTokenizer + - all + - __call__ +``` + +### Writing source documentation + +Values that should be put in `code` should either be surrounded by backticks: \`like so\`. Note that argument names +and objects like True, None, or any strings should usually be put in `code`. + +When mentioning a class, function, or method, it is recommended to use our syntax for internal links so that our tool +adds a link to its documentation with this syntax: \[\`XXXClass\`\] or \[\`function\`\]. This requires the class or +function to be in the main package. + +If you want to create a link to some internal class or function, you need to +provide its path. For instance: \[\`utils.ModelOutput\`\]. This will be converted into a link with +`utils.ModelOutput` in the description. To get rid of the path and only keep the name of the object you are +linking to in the description, add a ~: \[\`~utils.ModelOutput\`\] will generate a link with `ModelOutput` in the description. + +The same works for methods so you can either use \[\`XXXClass.method\`\] or \[\`~XXXClass.method\`\]. + +#### Defining arguments in a method + +Arguments should be defined with the `Args:` (or `Arguments:` or `Parameters:`) prefix, followed by a line return and +an indentation. The argument should be followed by its type, with its shape if it is a tensor, a colon, and its +description: + +``` + Args: + n_layers (`int`): The number of layers of the model. +``` + +If the description is too long to fit in one line, another indentation is necessary before writing the description +after the argument. + +Here's an example showcasing everything so far: + +``` + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. + + Indices can be obtained using [`AlbertTokenizer`]. See [`~PreTrainedTokenizer.encode`] and + [`~PreTrainedTokenizer.__call__`] for details. + + [What are input IDs?](../glossary#input-ids) +``` + +For optional arguments or arguments with defaults we follow the following syntax: imagine we have a function with the +following signature: + +``` +def my_function(x: str = None, a: float = 1): +``` + +then its documentation should look like this: + +``` + Args: + x (`str`, *optional*): + This argument controls ... + a (`float`, *optional*, defaults to 1): + This argument is used to ... +``` + +Note that we always omit the "defaults to \`None\`" when None is the default for any argument. Also note that even +if the first line describing your argument type and its default gets long, you can't break it on several lines. You can +however, write as many lines as you want in the indented description (see the example above with `input_ids`). + +#### Writing a multi-line code block + +Multi-line code blocks can be useful for displaying examples. They are done between two lines of three backticks as usual in Markdown: + + +```` +``` +# first line of code +# second line +# etc +``` +```` + +We follow the [doctest](https://docs.python.org/3/library/doctest.html) syntax for the examples to automatically test +the results to stay consistent with the library. + +#### Writing a return block + +The return block should be introduced with the `Returns:` prefix, followed by a line return and an indentation. +The first line should be the type of the return, followed by a line return. No need to indent further for the elements +building the return. + +Here's an example of a single value return: + +```python + Returns: + `list[int]`: A list of integers in the range [0, 1] --- 1 for a special token, 0 for a sequence token. +``` + +Here's an example of a tuple return, comprising several objects: + +```python + Returns: + `tuple(torch.FloatTensor)` comprising various elements depending on the configuration ([`BertConfig`]) and inputs: + - ** loss** (*optional*, returned when `masked_lm_labels` is provided) `torch.FloatTensor` of shape `(1,)` -- + Total loss is the sum of the masked language modeling loss and the next sequence prediction (classification) loss. + - **prediction_scores** (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`) -- + Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). +``` + +#### Adding an image + +Due to the rapidly growing repository, it is important to make sure that no files that would significantly weigh down the repository are added. This includes images, videos, and other non-text files. We prefer to leverage a hf.co hosted `dataset` like +the ones hosted on [`hf-internal-testing`](https://huggingface.co/hf-internal-testing) in which to place these files and reference +them by URL. We recommend putting them in the following dataset: [huggingface/documentation-images](https://huggingface.co/datasets/huggingface/documentation-images). +If an external contribution, feel free to add the images to your PR and ask a Hugging Face member to migrate your images +to this dataset. + +## Styling the docstring + +We have an automatic script running with the `make style` comment that will make sure that: +- the docstrings fully take advantage of the line width +- all code examples are formatted using black, like the code of the Transformers library + +This script may have some weird failures if you made a syntax mistake or if you uncover a bug. Therefore, it's +recommended to commit your changes before running `make style`, so you can revert the changes done by that script +easily. + +# Testing documentation examples + +Good documentation often comes with an example of how a specific function or class should be used. +Each model class should contain at least one example showcasing +how to use this model class in inference. *E.g.* the class [Wav2Vec2ForCTC](https://huggingface.co/docs/transformers/model_doc/wav2vec2#transformers.Wav2Vec2ForCTC) +includes an example of how to transcribe speech to text in the +[docstring of its forward function](https://huggingface.co/docs/transformers/model_doc/wav2vec2#transformers.Wav2Vec2ForCTC.forward). + +## Writing documentation examples + +The syntax for Example docstrings can look as follows: + +```python + Example: + + >>> from transformers import Wav2Vec2Processor, Wav2Vec2ForCTC + >>> from datasets import load_dataset + >>> import torch + + >>> dataset = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation") + >>> dataset = dataset.sort("id") + >>> sampling_rate = dataset.features["audio"].sampling_rate + + >>> processor = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-base-960h") + >>> model = Wav2Vec2ForCTC.from_pretrained("facebook/wav2vec2-base-960h") + + >>> # audio file is decoded on the fly + >>> inputs = processor(dataset[0]["audio"]["array"], sampling_rate=sampling_rate, return_tensors="pt") + >>> with torch.no_grad(): + ... logits = model(**inputs).logits + >>> predicted_ids = torch.argmax(logits, dim=-1) + + >>> # transcribe speech + >>> transcription = processor.batch_decode(predicted_ids) + >>> transcription[0] + 'MISTER QUILTER IS THE APOSTLE OF THE MIDDLE CLASSES AND WE ARE GLAD TO WELCOME HIS GOSPEL' +``` + +The docstring should give a minimal, clear example of how the respective model +is to be used in inference and also include the expected (ideally sensible) +output. +Often, readers will try out the example before even going through the function +or class definitions. Therefore, it is of utmost importance that the example +works as expected. + +## Docstring testing + +To do so each example should be included in the doctests. +We use pytests' [doctest integration](https://docs.pytest.org/doctest.html) to verify that all of our examples run correctly. +For Transformers, the doctests are run on a daily basis via GitHub Actions as can be +seen [here](https://github.com/huggingface/transformers/actions/workflows/doctests.yml). + +### For Python files + +Run all the tests in the docstrings of a given file with the following command, here is how we test the modeling file of Wav2Vec2 for instance: + +```bash +pytest --doctest-modules src/transformers/models/wav2vec2/modeling_wav2vec2.py -sv --doctest-continue-on-failure +``` + +If you want to isolate a specific docstring, just add `::` after the file name then type the whole path of the function/class/method whose docstring you want to test. For instance, here is how to just test the forward method of `Wav2Vec2ForCTC`: + +```bash +pytest --doctest-modules src/transformers/models/wav2vec2/modeling_wav2vec2.py::transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForCTC.forward -sv --doctest-continue-on-failure +``` + +### For Markdown files + +You can test locally a given file with this command (here testing the quicktour): + +```bash +pytest --doctest-modules docs/source/quicktour.md -sv --doctest-continue-on-failure --doctest-glob="*.md" +``` + +### Writing doctests + +Here are a few tips to help you debug the doctests and make them pass: + +- The outputs of the code need to match the expected output **exactly**, so make sure you have the same outputs. In particular doctest will see a difference between single quotes and double quotes, or a missing parenthesis. The only exceptions to that rule are: + * whitespace: one give whitespace (space, tabulation, new line) is equivalent to any number of whitespace, so you can add new lines where there are spaces to make your output more readable. + * numerical values: you should never put more than 4 or 5 digits to expected results as different setups or library versions might get you slightly different results. `doctest` is configured to ignore any difference lower than the precision to which you wrote (so 1e-4 if you write 4 digits). +- Don't leave a block of code that is very long to execute. If you can't make it fast, you can either not use the doctest syntax on it (so that it's ignored), or if you want to use the doctest syntax to show the results, you can add a comment `# doctest: +SKIP` at the end of the lines of code too long to execute +- Each line of code that produces a result needs to have that result written below. You can ignore an output if you don't want to show it in your code example by adding a comment ` # doctest: +IGNORE_RESULT` at the end of the line of code producing it. diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/TRANSLATING.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/TRANSLATING.md new file mode 100644 index 0000000000000000000000000000000000000000..64dced450987dc42c4f9f63ac3d2f41f04e570c9 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/TRANSLATING.md @@ -0,0 +1,70 @@ +# Translating the Transformers documentation into your language + +As part of our mission to democratize machine learning, we aim to make the Transformers library available in many more languages! Follow the steps below to help translate the documentation into your language. + +## Open an Issue + +1. Navigate to the Issues page of this repository. +2. Check if anyone has already opened an issue for your language. +3. If not, create a new issue by selecting the "Translation template" from the "New issue" button. +4. Post a comment indicating which chapters you’d like to work on, and we’ll add your name to the list. + +## Fork the Repository + +1. First, fork the Transformers repo by clicking the Fork button in the top-right corner. +2. Clone your fork to your local machine for editing with the following command: + + ```bash + git clone https://github.com/YOUR-USERNAME/transformers.git + ``` + + Replace `YOUR-USERNAME` with your GitHub username. + +## Copy-paste the English version with a new language code + +The documentation files are organized in the following directory: + +- **docs/source**: This contains all documentation materials organized by language. + +To copy the English version to your new language directory: + +1. Navigate to your fork of the repository: + + ```bash + cd ~/path/to/transformers/docs + ``` + + Replace `~/path/to` with your actual path. + +2. Run the following command: + + ```bash + cp -r source/en source/LANG-ID + ``` + + Replace `LANG-ID` with the appropriate ISO 639-1 or ISO 639-2 language code (see [this table](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) for reference). + +## Start translating + +Begin translating the text! + +1. Start with the `_toctree.yml` file that corresponds to your documentation chapter. This file is essential for rendering the table of contents on the website. + + - If the `_toctree.yml` file doesn’t exist for your language, create one by copying the English version and removing unrelated sections. + - Ensure it is placed in the `docs/source/LANG-ID/` directory. + + Here’s an example structure for the `_toctree.yml` file: + + ```yaml + - sections: + - local: pipeline_tutorial # Keep this name for your .md file + title: Pipelines for Inference # Translate this + ... + title: Tutorials # Translate this + ``` + +2. Once you’ve translated the `_toctree.yml`, move on to translating the associated MDX files. + +## Collaborate and share + +If you'd like assistance with your translation, open an issue and tag `@stevhliu`. Feel free to share resources or glossaries to ensure consistent terminology. diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/_config.py b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/_config.py new file mode 100644 index 0000000000000000000000000000000000000000..f49e4e4731965a504b8da443c2cd979638cd22bb --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/_config.py @@ -0,0 +1,14 @@ +# docstyle-ignore +INSTALL_CONTENT = """ +# Transformers installation +! pip install transformers datasets evaluate accelerate +# To install from source instead of the last release, comment the command above and uncomment the following one. +# ! pip install git+https://github.com/huggingface/transformers.git +""" + +notebook_first_cells = [{"type": "code", "content": INSTALL_CONTENT}] +black_avoid_patterns = { + "{processor_class}": "FakeProcessorClass", + "{model_class}": "FakeModelClass", + "{object_class}": "FakeObjectClass", +} diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/_config.py b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/_config.py new file mode 100644 index 0000000000000000000000000000000000000000..f49e4e4731965a504b8da443c2cd979638cd22bb --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/_config.py @@ -0,0 +1,14 @@ +# docstyle-ignore +INSTALL_CONTENT = """ +# Transformers installation +! pip install transformers datasets evaluate accelerate +# To install from source instead of the last release, comment the command above and uncomment the following one. +# ! pip install git+https://github.com/huggingface/transformers.git +""" + +notebook_first_cells = [{"type": "code", "content": INSTALL_CONTENT}] +black_avoid_patterns = { + "{processor_class}": "FakeProcessorClass", + "{model_class}": "FakeModelClass", + "{object_class}": "FakeObjectClass", +} diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/_toctree.yml b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/_toctree.yml new file mode 100644 index 0000000000000000000000000000000000000000..a754abc76c9517ce2baf1bc92f0f38171130b4b7 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/_toctree.yml @@ -0,0 +1,894 @@ +- sections: + - local: index + title: 🤗 المحولات + - local: quicktour + title: جولة سريعة + - local: installation + title: التثبيت + title: البدء +- sections: + - local: pipeline_tutorial + title: تشغيل الاستنتاج باستخدام خطوط الأنابيب + - local: autoclass_tutorial + title: كتابة تعليمات برمجية متكيفه باستخدام AutoClass + - local: preprocessing + title: معالجة البيانات مسبقًا + - local: training + title: ضبط نموذج مسبق التدريب + - local: run_scripts + title: التدريب باستخدام نص برمجي + - local: accelerate + title: إعداد تدريب موزع باستخدام 🤗 Accelerate + - local: peft + title: تحميل النماذج المخصصة وتدريبها باستخدام 🤗 PEFT + - local: model_sharing + title: مشاركة نموذجك + - local: llm_tutorial + title: التوليد باستخدام LLMs + - local: conversations + title: الدردشة مع المحولات + title: البرامج التعليمية +- sections: + - isExpanded: false + sections: + - local: tasks/sequence_classification + title: تصنيف النصوص + - local: tasks/token_classification + title: تصنيف الرموز + - local: tasks/question_answering + title: الإجابة على الأسئلة + - local: tasks/language_modeling + title: نمذجة اللغة السببية + - local: tasks/masked_language_modeling + title: نمذجة اللغة المقنعة + - local: tasks/translation + title: الترجمة + - local: tasks/summarization + title: التلخيص + - local: tasks/multiple_choice + title: الاختيار المتعدد + title: معالجة اللغات الطبيعية +# - isExpanded: false +# sections: +# - local: tasks/audio_classification +# title: تصنيف الصوت +# - local: tasks/asr +# title: التعرف التلقائي على الكلام +# title: الصوت +# - isExpanded: false +# sections: +# - local: tasks/image_classification +# title: تصنيف الصور +# - local: tasks/semantic_segmentation +# title: تجزئة الصور +# - local: tasks/video_classification +# title: تصنيف الفيديو +# - local: tasks/object_detection +# title: اكتشاف الأشياء +# - local: tasks/zero_shot_object_detection +# title: اكتشاف الأشياء بدون تدريب +# - local: tasks/zero_shot_image_classification +# title: تصنيف الصور بدون تدريب +# - local: tasks/monocular_depth_estimation +# title: تقدير العمق +# - local: tasks/image_to_image +# title: صورة إلى صورة +# - local: tasks/image_feature_extraction +# title: استخراج ميزات الصورة +# - local: tasks/mask_generation +# title: توليد القناع +# - local: tasks/knowledge_distillation_for_image_classification +# title: التقليل المعرفي للرؤية الحاسوبية +# title: الرؤية الحاسوبية +# - isExpanded: false +# sections: +# - local: tasks/image_captioning +# title: وصف الصور Image captioning +# - local: tasks/document_question_answering +# title: الإجابة على أسئلة المستندات +# - local: tasks/visual_question_answering +# title: الإجابة على الأسئلة المرئية +# - local: tasks/text-to-speech +# title: تحويل النص إلى كلام +# title: المتعددة الوسائط +# - isExpanded: false +# sections: +# - local: generation_strategies +# title: تخصيص استراتيجية التوليد +# - local: kv_cache +# title: أفضل الممارسات للتوليد باستخدام ذاكرة التخزين المؤقت +# title: التوليد +# - isExpanded: false +# sections: +# - local: tasks/idefics +# title: مهام الصور مع IDEFICS +# - local: tasks/prompting +# title: دليل إرشادي لمحفزات النماذج اللغوية الكبيرة +# title: الإرشاد + title: أدلة المهام +- sections: + - local: fast_tokenizers + title: استخدم مجزئيات النصوص السريعة من 🤗 Tokenizers + - local: multilingual + title: الاستدلال باستخدام نماذج متعددة اللغات + - local: create_a_model + title: استخدام واجهات برمجة التطبيقات الخاصة بالنموذج + - local: custom_models + title: مشاركة نموذج مخصص + - local: chat_templating + title: قوالب لنماذج الدردشة + - local: trainer + title: المدرب + - local: sagemaker + title: تشغيل التدريب على Amazon SageMaker + - local: serialization + title: التصدير إلى ONNX + - local: tflite + title: التصدير إلى TFLite + - local: torchscript + title: التصدير إلى TorchScript + - local: notebooks + title: دفاتر الملاحظات مع الأمثلة + - local: community + title: موارد المجتمع + - local: troubleshooting + title: استكشاف الأخطاء وإصلاحها + - local: gguf + title: التوافق مع ملفات GGUF + - local: tiktoken + title: التوافق مع ملفات TikToken + - local: modular_transformers + title: الوحدات النمطية في `transformers` + - local: how_to_hack_models + title: اختراق النموذج (الكتابة فوق فئة لاستخدامك) + title: أدلة المطورين +# - sections: +# - local: quantization/overview +# title: نظرة عامة +# - local: quantization/bitsandbytes +# title: bitsandbytes +# - local: quantization/gptq +# title: GPTQ +# - local: quantization/awq +# title: AWQ +# - local: quantization/aqlm +# title: AQLM +# - local: quantization/vptq +# title: VPTQ +# - local: quantization/quanto +# title: Quanto +# - local: quantization/eetq +# title: EETQ +# - local: quantization/hqq +# title: HQQ +# - local: quantization/optimum +# title: Optimum +# - local: quantization/contribute +# title: المساهمة بطريقة جديدة للتكميم +# title: أساليب التكميم +# - sections: +# - local: performance +# title: الأداء-نظرة عامة +# - local: llm_optims +# title: تحسين الاستدلال LLM +# - sections: +# - local: perf_train_gpu_one +# title: استخدام عدة وحدات معالجة رسوميات (GPUs) بشكل متوازٍ +# - local: perf_train_gpu_many +# title: وحدات معالجة الرسومات (GPU) متعددة والتوازي +# - local: fsdp +# title: Fully Sharded Data Parallel +# - local: deepspeed +# title: DeepSpeed +# - local: perf_train_cpu +# title: التدريب الفعال على وحدة المعالجة المركزية (CPU) +# - local: perf_train_cpu_many +# title: التدريب الموزع لوحدة المعالجة المركزية (CPU) +# - local: perf_train_tpu_tf +# title: التدريب على (TPU) باستخدام TensorFlow +# - local: perf_train_special +# title: تدريب PyTorch على Apple silicon +# - local: perf_hardware +# title: الأجهزة المخصصة للتدريب +# - local: hpo_train +# title: البحث عن المعاملات المثلى باستخدام واجهة برمجة تطبيقات المدرب +# title: تقنيات التدريب الفعال +# - sections: +# - local: perf_infer_cpu +# title: الإستدلال على وحدة المعالجة المركزية (CPU) +# - local: perf_infer_gpu_one +# title: الإستدلال على وحدة معالجة الرسومات (GPU) +# title: تحسين الاستدلال +# - local: big_models +# title: إنشاء نموذج كبير +# - local: debugging +# title: تصحيح الأخطاء البرمجية +# - local: tf_xla +# title: تكامل XLA لنماذج TensorFlow +# - local: perf_torch_compile +# title: تحسين الاستدلال باستخدام `torch.compile()` +# title: الأداء وقابلية التوسع +# - sections: +# - local: contributing +# title: كيفية المساهمة في 🤗 المحولات؟ +# - local: add_new_model +# title: كيفية إضافة نموذج إلى 🤗 المحولات؟ +# - local: add_new_pipeline +# title: كيفية إضافة خط أنابيب إلى 🤗 المحولات؟ +# - local: testing +# title: الاختبار +# - local: pr_checks +# title: التحقق من طلب السحب +# title: المساهمة +- sections: + - local: philosophy + title: الفلسفة + - local: glossary + title: (قاموس المصطلحات (قائمة الكلمات + - local: task_summary + title: ما الذي يمكن أن تفعله 🤗 المحولات + - local: tasks_explained + title: كيف تحل المحولات المهام + - local: model_summary + title: عائلة نماذج المحول + - local: tokenizer_summary + title: ملخص برنامج مقسم النصوص (tokenizers) + - local: attention + title: الانتباه Attention + - local: pad_truncation + title: الحشو والتقليم + - local: bertology + title: BERTology + - local: perplexity + title: حيرة النماذج ذات الطول الثابت + - local: pipeline_webserver + title: خطوط الأنابيب للاستدلال على خادم الويب + - local: model_memory_anatomy + title: تشريح تدريب النموذج + - local: llm_tutorial_optimization + title: الاستفادة القصوى من LLMs + title: أطر مفاهيمية +# - sections: +# - sections: +# - local: model_doc/auto +# title: فئات يتم إنشاؤها ديناميكيًا +# - local: main_classes/backbones +# title: العمود الفقري +# - local: main_classes/callback +# title: عمليات الاسترجاع +# - local: main_classes/configuration +# title: التكوين +# - local: main_classes/data_collator +# title: مجمع البيانات +# - local: main_classes/keras_callbacks +# title: استدعاءات Keras +# - local: main_classes/logging +# title: التسجيل +# - local: main_classes/model +# title: النماذج +# - local: main_classes/text_generation +# title: توليد النصوص +# - local: main_classes/onnx +# title: ONNX +# - local: main_classes/optimizer_schedules +# title: التحسين +# - local: main_classes/output +# title: مخرجات النموذج +# - local: main_classes/pipelines +# title: خطوط الأنابيب +# - local: main_classes/processors +# title: المعالجات +# - local: main_classes/quantization +# title: التكميم +# - local: main_classes/tokenizer +# title: برنامج مقسم النصوص +# - local: main_classes/trainer +# title: المدرب +# - local: main_classes/deepspeed +# title: DeepSpeed +# - local: main_classes/feature_extractor +# title: مستخرج الميزات +# - local: main_classes/image_processor +# title: معالج الصور +# title: الفئات الرئيسية +# - sections: +# - isExpanded: false +# sections: +# - local: model_doc/albert +# title: ALBERT +# - local: model_doc/bart +# title: BART +# - local: model_doc/barthez +# title: BARThez +# - local: model_doc/bartpho +# title: BARTpho +# - local: model_doc/bert +# title: BERT +# - local: model_doc/bert-generation +# title: BertGeneration +# - local: model_doc/bert-japanese +# title: BertJapanese +# - local: model_doc/bertweet +# title: Bertweet +# - local: model_doc/big_bird +# title: BigBird +# - local: model_doc/bigbird_pegasus +# title: BigBirdPegasus +# - local: model_doc/biogpt +# title: BioGpt +# - local: model_doc/blenderbot +# title: Blenderbot +# - local: model_doc/blenderbot-small +# title: Blenderbot Small +# - local: model_doc/bloom +# title: BLOOM +# - local: model_doc/bort +# title: BORT +# - local: model_doc/byt5 +# title: ByT5 +# - local: model_doc/camembert +# title: CamemBERT +# - local: model_doc/canine +# title: CANINE +# - local: model_doc/codegen +# title: CodeGen +# - local: model_doc/code_llama +# title: CodeLlama +# - local: model_doc/cohere +# title: Cohere +# - local: model_doc/convbert +# title: ConvBERT +# - local: model_doc/cpm +# title: CPM +# - local: model_doc/cpmant +# title: CPMANT +# - local: model_doc/ctrl +# title: CTRL +# - local: model_doc/dbrx +# title: DBRX +# - local: model_doc/deberta +# title: DeBERTa +# - local: model_doc/deberta-v2 +# title: DeBERTa-v2 +# - local: model_doc/dialogpt +# title: DialoGPT +# - local: model_doc/distilbert +# title: DistilBERT +# - local: model_doc/dpr +# title: DPR +# - local: model_doc/electra +# title: ELECTRA +# - local: model_doc/encoder-decoder +# title: Encoder Decoder Models +# - local: model_doc/ernie +# title: ERNIE +# - local: model_doc/ernie_m +# title: ErnieM +# - local: model_doc/esm +# title: ESM +# - local: model_doc/falcon +# title: Falcon +# - local: model_doc/fastspeech2_conformer +# title: FastSpeech2Conformer +# - local: model_doc/flan-t5 +# title: FLAN-T5 +# - local: model_doc/flan-ul2 +# title: FLAN-UL2 +# - local: model_doc/flaubert +# title: FlauBERT +# - local: model_doc/fnet +# title: FNet +# - local: model_doc/fsmt +# title: FSMT +# - local: model_doc/funnel +# title: Funnel Transformer +# - local: model_doc/fuyu +# title: Fuyu +# - local: model_doc/gemma +# title: Gemma +# - local: model_doc/openai-gpt +# title: GPT +# - local: model_doc/gpt_neo +# title: GPT Neo +# - local: model_doc/gpt_neox +# title: GPT NeoX +# - local: model_doc/gpt_neox_japanese +# title: GPT NeoX Japanese +# - local: model_doc/gptj +# title: GPT-J +# - local: model_doc/gpt2 +# title: GPT2 +# - local: model_doc/gpt_bigcode +# title: GPTBigCode +# - local: model_doc/gptsan-japanese +# title: GPTSAN Japanese +# - local: model_doc/gpt-sw3 +# title: GPTSw3 +# - local: model_doc/herbert +# title: HerBERT +# - local: model_doc/ibert +# title: I-BERT +# - local: model_doc/jamba +# title: Jamba +# - local: model_doc/jetmoe +# title: JetMoe +# - local: model_doc/jukebox +# title: Jukebox +# - local: model_doc/led +# title: LED +# - local: model_doc/llama +# title: LLaMA +# - local: model_doc/llama2 +# title: Llama2 +# - local: model_doc/llama3 +# title: Llama3 +# - local: model_doc/longformer +# title: Longformer +# - local: model_doc/longt5 +# title: LongT5 +# - local: model_doc/luke +# title: LUKE +# - local: model_doc/m2m_100 +# title: M2M100 +# - local: model_doc/madlad-400 +# title: MADLAD-400 +# - local: model_doc/mamba +# title: Mamba +# - local: model_doc/marian +# title: MarianMT +# - local: model_doc/markuplm +# title: MarkupLM +# - local: model_doc/mbart +# title: MBart and MBart-50 +# - local: model_doc/mega +# title: MEGA +# - local: model_doc/megatron-bert +# title: MegatronBERT +# - local: model_doc/megatron_gpt2 +# title: MegatronGPT2 +# - local: model_doc/mistral +# title: Mistral +# - local: model_doc/mixtral +# title: Mixtral +# - local: model_doc/mluke +# title: mLUKE +# - local: model_doc/mobilebert +# title: MobileBERT +# - local: model_doc/mpnet +# title: MPNet +# - local: model_doc/mpt +# title: MPT +# - local: model_doc/mra +# title: MRA +# - local: model_doc/mt5 +# title: MT5 +# - local: model_doc/mvp +# title: MVP +# - local: model_doc/nezha +# title: NEZHA +# - local: model_doc/nllb +# title: NLLB +# - local: model_doc/nllb-moe +# title: NLLB-MoE +# - local: model_doc/nystromformer +# title: Nyströmformer +# - local: model_doc/olmo +# title: OLMo +# - local: model_doc/open-llama +# title: Open-Llama +# - local: model_doc/opt +# title: OPT +# - local: model_doc/pegasus +# title: Pegasus +# - local: model_doc/pegasus_x +# title: PEGASUS-X +# - local: model_doc/persimmon +# title: Persimmon +# - local: model_doc/phi +# title: Phi +# - local: model_doc/phi3 +# title: Phi-3 +# - local: model_doc/phobert +# title: PhoBERT +# - local: model_doc/plbart +# title: PLBart +# - local: model_doc/prophetnet +# title: ProphetNet +# - local: model_doc/qdqbert +# title: QDQBert +# - local: model_doc/qwen2 +# title: Qwen2 +# - local: model_doc/qwen2_moe +# title: Qwen2MoE +# - local: model_doc/rag +# title: RAG +# - local: model_doc/realm +# title: REALM +# - local: model_doc/recurrent_gemma +# title: RecurrentGemma +# - local: model_doc/reformer +# title: Reformer +# - local: model_doc/rembert +# title: RemBERT +# - local: model_doc/retribert +# title: RetriBERT +# - local: model_doc/roberta +# title: RoBERTa +# - local: model_doc/roberta-prelayernorm +# title: RoBERTa-PreLayerNorm +# - local: model_doc/roc_bert +# title: RoCBert +# - local: model_doc/roformer +# title: RoFormer +# - local: model_doc/rwkv +# title: RWKV +# - local: model_doc/splinter +# title: Splinter +# - local: model_doc/squeezebert +# title: SqueezeBERT +# - local: model_doc/stablelm +# title: StableLm +# - local: model_doc/starcoder2 +# title: Starcoder2 +# - local: model_doc/switch_transformers +# title: SwitchTransformers +# - local: model_doc/t5 +# title: T5 +# - local: model_doc/t5v1.1 +# title: T5v1.1 +# - local: model_doc/tapex +# title: TAPEX +# - local: model_doc/transfo-xl +# title: Transformer XL +# - local: model_doc/ul2 +# title: UL2 +# - local: model_doc/umt5 +# title: UMT5 +# - local: model_doc/xmod +# title: X-MOD +# - local: model_doc/xglm +# title: XGLM +# - local: model_doc/xlm +# title: XLM +# - local: model_doc/xlm-prophetnet +# title: XLM-ProphetNet +# - local: model_doc/xlm-roberta +# title: XLM-RoBERTa +# - local: model_doc/xlm-roberta-xl +# title: XLM-RoBERTa-XL +# - local: model_doc/xlm-v +# title: XLM-V +# - local: model_doc/xlnet +# title: XLNet +# - local: model_doc/yoso +# title: YOSO +# title: Text models +# - isExpanded: false +# sections: +# - local: model_doc/beit +# title: BEiT +# - local: model_doc/bit +# title: BiT +# - local: model_doc/conditional_detr +# title: Conditional DETR +# - local: model_doc/convnext +# title: ConvNeXT +# - local: model_doc/convnextv2 +# title: ConvNeXTV2 +# - local: model_doc/cvt +# title: CVT +# - local: model_doc/deformable_detr +# title: Deformable DETR +# - local: model_doc/deit +# title: DeiT +# - local: model_doc/depth_anything +# title: Depth Anything +# - local: model_doc/deta +# title: DETA +# - local: model_doc/detr +# title: DETR +# - local: model_doc/dinat +# title: DiNAT +# - local: model_doc/dinov2 +# title: DINOV2 +# - local: model_doc/dit +# title: DiT +# - local: model_doc/dpt +# title: DPT +# - local: model_doc/efficientformer +# title: EfficientFormer +# - local: model_doc/efficientnet +# title: EfficientNet +# - local: model_doc/focalnet +# title: FocalNet +# - local: model_doc/glpn +# title: GLPN +# - local: model_doc/imagegpt +# title: ImageGPT +# - local: model_doc/levit +# title: LeViT +# - local: model_doc/mask2former +# title: Mask2Former +# - local: model_doc/maskformer +# title: MaskFormer +# - local: model_doc/mobilenet_v1 +# title: MobileNetV1 +# - local: model_doc/mobilenet_v2 +# title: MobileNetV2 +# - local: model_doc/mobilevit +# title: MobileViT +# - local: model_doc/mobilevitv2 +# title: MobileViTV2 +# - local: model_doc/nat +# title: NAT +# - local: model_doc/poolformer +# title: PoolFormer +# - local: model_doc/pvt +# title: Pyramid Vision Transformer (PVT) +# - local: model_doc/pvt_v2 +# title: Pyramid Vision Transformer v2 (PVTv2) +# - local: model_doc/regnet +# title: RegNet +# - local: model_doc/resnet +# title: ResNet +# - local: model_doc/segformer +# title: SegFormer +# - local: model_doc/seggpt +# title: SegGpt +# - local: model_doc/superpoint +# title: SuperPoint +# - local: model_doc/swiftformer +# title: SwiftFormer +# - local: model_doc/swin +# title: Swin Transformer +# - local: model_doc/swinv2 +# title: Swin Transformer V2 +# - local: model_doc/swin2sr +# title: Swin2SR +# - local: model_doc/table-transformer +# title: Table Transformer +# - local: model_doc/upernet +# title: UperNet +# - local: model_doc/van +# title: VAN +# - local: model_doc/vit +# title: Vision Transformer (ViT) +# - local: model_doc/vit_hybrid +# title: ViT Hybrid +# - local: model_doc/vitdet +# title: ViTDet +# - local: model_doc/vit_mae +# title: ViTMAE +# - local: model_doc/vitmatte +# title: ViTMatte +# - local: model_doc/vit_msn +# title: ViTMSN +# - local: model_doc/yolos +# title: YOLOS +# title: Vision models +# - isExpanded: false +# sections: +# - local: model_doc/audio-spectrogram-transformer +# title: Audio Spectrogram Transformer +# - local: model_doc/bark +# title: Bark +# - local: model_doc/clap +# title: CLAP +# - local: model_doc/encodec +# title: EnCodec +# - local: model_doc/hubert +# title: Hubert +# - local: model_doc/mctct +# title: MCTCT +# - local: model_doc/mms +# title: MMS +# - local: model_doc/musicgen +# title: MusicGen +# - local: model_doc/musicgen_melody +# title: MusicGen Melody +# - local: model_doc/pop2piano +# title: Pop2Piano +# - local: model_doc/seamless_m4t +# title: Seamless-M4T +# - local: model_doc/seamless_m4t_v2 +# title: SeamlessM4T-v2 +# - local: model_doc/sew +# title: SEW +# - local: model_doc/sew-d +# title: SEW-D +# - local: model_doc/speech_to_text +# title: Speech2Text +# - local: model_doc/speech_to_text_2 +# title: Speech2Text2 +# - local: model_doc/speecht5 +# title: SpeechT5 +# - local: model_doc/unispeech +# title: UniSpeech +# - local: model_doc/unispeech-sat +# title: UniSpeech-SAT +# - local: model_doc/univnet +# title: UnivNet +# - local: model_doc/vits +# title: VITS +# - local: model_doc/wav2vec2 +# title: Wav2Vec2 +# - local: model_doc/wav2vec2-bert +# title: Wav2Vec2-BERT +# - local: model_doc/wav2vec2-conformer +# title: Wav2Vec2-Conformer +# - local: model_doc/wav2vec2_phoneme +# title: Wav2Vec2Phoneme +# - local: model_doc/wavlm +# title: WavLM +# - local: model_doc/whisper +# title: Whisper +# - local: model_doc/xls_r +# title: XLS-R +# - local: model_doc/xlsr_wav2vec2 +# title: XLSR-Wav2Vec2 +# title: Audio models +# - isExpanded: false +# sections: +# - local: model_doc/timesformer +# title: TimeSformer +# - local: model_doc/videomae +# title: VideoMAE +# - local: model_doc/vivit +# title: ViViT +# title: Video models +# - isExpanded: false +# sections: +# - local: model_doc/align +# title: ALIGN +# - local: model_doc/altclip +# title: AltCLIP +# - local: model_doc/blip +# title: BLIP +# - local: model_doc/blip-2 +# title: BLIP-2 +# - local: model_doc/bridgetower +# title: BridgeTower +# - local: model_doc/bros +# title: BROS +# - local: model_doc/chinese_clip +# title: Chinese-CLIP +# - local: model_doc/clip +# title: CLIP +# - local: model_doc/clipseg +# title: CLIPSeg +# - local: model_doc/clvp +# title: CLVP +# - local: model_doc/data2vec +# title: Data2Vec +# - local: model_doc/deplot +# title: DePlot +# - local: model_doc/donut +# title: Donut +# - local: model_doc/flava +# title: FLAVA +# - local: model_doc/git +# title: GIT +# - local: model_doc/grounding-dino +# title: Grounding DINO +# - local: model_doc/groupvit +# title: GroupViT +# - local: model_doc/idefics +# title: IDEFICS +# - local: model_doc/idefics2 +# title: Idefics2 +# - local: model_doc/instructblip +# title: InstructBLIP +# - local: model_doc/kosmos-2 +# title: KOSMOS-2 +# - local: model_doc/layoutlm +# title: LayoutLM +# - local: model_doc/layoutlmv2 +# title: LayoutLMV2 +# - local: model_doc/layoutlmv3 +# title: LayoutLMV3 +# - local: model_doc/layoutxlm +# title: LayoutXLM +# - local: model_doc/lilt +# title: LiLT +# - local: model_doc/llava +# title: Llava +# - local: model_doc/llava_next +# title: LLaVA-NeXT +# - local: model_doc/lxmert +# title: LXMERT +# - local: model_doc/matcha +# title: MatCha +# - local: model_doc/mgp-str +# title: MGP-STR +# - local: model_doc/nougat +# title: Nougat +# - local: model_doc/oneformer +# title: OneFormer +# - local: model_doc/owlvit +# title: OWL-ViT +# - local: model_doc/owlv2 +# title: OWLv2 +# - local: model_doc/paligemma +# title: PaliGemma +# - local: model_doc/perceiver +# title: Perceiver +# - local: model_doc/pix2struct +# title: Pix2Struct +# - local: model_doc/sam +# title: Segment Anything +# - local: model_doc/siglip +# title: SigLIP +# - local: model_doc/speech-encoder-decoder +# title: Speech Encoder Decoder Models +# - local: model_doc/tapas +# title: TAPAS +# - local: model_doc/trocr +# title: TrOCR +# - local: model_doc/tvlt +# title: TVLT +# - local: model_doc/tvp +# title: TVP +# - local: model_doc/udop +# title: UDOP +# - local: model_doc/video_llava +# title: VideoLlava +# - local: model_doc/vilt +# title: ViLT +# - local: model_doc/vipllava +# title: VipLlava +# - local: model_doc/vision-encoder-decoder +# title: Vision Encoder Decoder Models +# - local: model_doc/vision-text-dual-encoder +# title: Vision Text Dual Encoder +# - local: model_doc/visual_bert +# title: VisualBERT +# - local: model_doc/xclip +# title: X-CLIP +# title: Multimodal models +# - isExpanded: false +# sections: +# - local: model_doc/decision_transformer +# title: محول القرار +# - local: model_doc/trajectory_transformer +# title: محول المسار +# title: نماذج التعلم التعزيزية +# - isExpanded: false +# sections: +# - local: model_doc/autoformer +# title: Autoformer +# - local: model_doc/informer +# title: Informer +# - local: model_doc/patchtsmixer +# title: PatchTSMixer +# - local: model_doc/patchtst +# title: PatchTST +# - local: model_doc/time_series_transformer +# title: محول السلاسل الزمنية +# title: نماذج السلاسل الزمنية +# - isExpanded: false +# sections: +# - local: model_doc/graphormer +# title: Graphormer +# title: نماذج الرسم البياني +# title: النماذج +# - sections: +# - local: internal/modeling_utils +# title: الطبقات المخصصة والمرافق +# - local: internal/pipelines_utils +# title: مرافق خطوط الأنابيب +# - local: internal/tokenization_utils +# title: مرافق مقسم النصوص +# - local: internal/trainer_utils +# title: مرافق المدرب +# - local: internal/generation_utils +# title: مرافق التوليد +# - local: internal/image_processing_utils +# title: مرافق معالجة الصور +# - local: internal/audio_utils +# title: مرافق معالجة الصوت +# - local: internal/file_utils +# title: مرافق عامة +# - local: internal/time_series_utils +# title: مرافق السلاسل الزمنية +# title: مساعدون داخليون +# title: API diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/accelerate.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/accelerate.md new file mode 100644 index 0000000000000000000000000000000000000000..486c1efe59af60c0cf524d9493f3d5ba34058b2a --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/accelerate.md @@ -0,0 +1,120 @@ +# التدريب الموزع باستخدام 🤗 Accelerate + + +مع تزايد حجم النماذج اللغوية، برز التوازي كأحد الاستراتيجيات لتدريب نماذج أكبر على أجهزة محدودة وتسريع عملية التدريب بمقدار كبير. أنشأنا في Hugging Face، قمنا بإنشاء مكتبة [ Accelerate](https://huggingface.co/docs/accelerate) لمساعدة المستخدمين على تدريب أي نموذج من Transformers بسهولة على أي نوع من الإعدادات الموزعة، سواء كان ذلك على عدة وحدات معالجة رسومات (GPUs) على جهاز واحد أو على عدة وحدات معالجة رسومات موزعة على عدة أجهزة. في هذا الدليل، تعلم كيفية تخصيص حلقة تدريب PyTorch الأصلية لتمكين التدريب في بيئة موزعة. + +## الإعداد + +ابدأ بتثبيت 🤗 Accelerate: + +```bash +pip install accelerate +``` + +ثم قم باستيراد وإنشاء كائن [`~accelerate.Accelerator`]. سيقوم [`~accelerate.Accelerator`] تلقائيًا باكتشاف نوع الإعداد الموزع الخاص بك وتهيئة جميع المكونات اللازمة للتدريب. لن تحتاج إلى وضع نموذجك على جهاز بشكل معين. + +```py +>>> from accelerate import Accelerator + +>>> accelerator = Accelerator() +``` + +## الاستعداد للتسريع + +الخطوة التالية هي تمرير جميع كائنات التدريب ذات الصلة إلى دالة الإعداد [`~accelerate.Accelerator.prepare`]. ويشمل ذلك DataLoaders للتدريب والتقييم، ونموذجًا ومُحَسِّنً المعاملات (optimizer): + +```py +>>> train_dataloader, eval_dataloader, model, optimizer = accelerator.prepare( +... train_dataloader, eval_dataloader, model, optimizer +... ) +``` + +## الخلفي Backward + +الإضافة الأخيرة هي استبدال الدالة المعتادة `loss.backward()` في حلقة التدريب الخاصة بك بدالة [`~accelerate.Accelerator.backward`] في 🤗 Accelerate: + +```py +>>> for epoch in range(num_epochs): +... for batch in train_dataloader: +... outputs = model(**batch) +... loss = outputs.loss +... accelerator.backward(loss) + +... optimizer.step() +... lr_scheduler.step() +... optimizer.zero_grad() +... progress_bar.update(1) +``` + +كما يمكنك أن ترى في الكود التالي، فأنت بحاجة فقط إلى إضافة أربعة أسطر من الكود إلى حلقة التدريب الخاصة بك لتمكين التدريب الموزع! + +```diff ++ from accelerate import Accelerator + from transformers import AdamW, AutoModelForSequenceClassification, get_scheduler + ++ accelerator = Accelerator() + + model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2) + optimizer = AdamW(model.parameters(), lr=3e-5) + +- device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") +- model.to(device) + ++ train_dataloader, eval_dataloader, model, optimizer = accelerator.prepare( ++ train_dataloader, eval_dataloader, model, optimizer ++ ) + + num_epochs = 3 + num_training_steps = num_epochs * len(train_dataloader) + lr_scheduler = get_scheduler( + "linear", + optimizer=optimizer, + num_warmup_steps=0, + num_training_steps=num_training_steps + ) + + progress_bar = tqdm(range(num_training_steps)) + + model.train() + for epoch in range(num_epochs): + for batch in train_dataloader: +- batch = {k: v.to(device) for k, v in batch.items()} + outputs = model(**batch) + loss = outputs.loss +- loss.backward() ++ accelerator.backward(loss) +optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + progress_bar.update(1) +``` + +## تدريب + +بمجرد إضافة أسطر الكود ذات الصلة، قم بتشغيل التدريب الخاص بك في أحد النصوص أو الدفاتر مثل Colaboratory. + +### التدريب باستخدام نص برمجي + +إذا كنت تشغل التدريب الخاص بك من نص برمجي، فقم بتشغيل الأمر التالي لإنشاء وحفظ ملف تكوين: + +```bash +accelerate config +``` + +ثم قم بتشغيل التدريب الخاص بك باستخدام: + +```bash +accelerate launch train.py +``` + +### التدريب باستخدام دفتر ملاحظات + +يمكن أيضًا تشغيل 🤗 Accelerate في دفاتر إذا كنت تخطط لاستخدام وحدات معالجة الرسوميات (TPUs) في Colaboratory. قم بتغليف كل الكود المسؤول عن التدريب في دالة، ومررها إلى [`~accelerate.notebook_launcher`]: + +```py +>>> from accelerate import notebook_launcher + +>>> notebook_launcher(training_function) +``` + +للحصول على مزيد من المعلومات حول 🤗 Accelerate وميزاته الغنية، يرجى الرجوع إلى [الوثائق](https://huggingface.co/docs/accelerate). \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/attention.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/attention.md new file mode 100644 index 0000000000000000000000000000000000000000..e1f55ed96c2dd43a22e84b293b0db669151c4f15 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/attention.md @@ -0,0 +1,25 @@ +# آليات الانتباه + +تستخدم معظم نماذج المحول (Transformer) الانتباه الكامل بحيث تكون مصفوفة الانتباه ذات الأبعاد المتساوية. ويمكن أن يمثل ذلك عقبة حسابية كبيرة عندما تكون لديك نصوص طويلة. ويعد Longformer وReformer من النماذج التي تحاول أن تكون أكثر كفاءة وتستخدم نسخة مخففة من مصفوفة الانتباه لتسريع التدريب. + +## انتباه LSH + +يستخدم [Reformer](model_doc/reformer) انتباه LSH. في الدالة softmax(QK^t)، فإن أكبر العناصر فقط (في بعد softmax) من المصفوفة QK^t هي التي ستعطي مساهمات مفيدة. لذلك، بالنسبة لكل استعلام q في Q، يمكننا أن نأخذ في الاعتبار فقط المفاتيح k في K المشابهة لـ q فقط. وتُستخدم دالة هاش لتحديد ما إذا كان q وk متشابهين. ويتم تعديل قناع الانتباه لتجاهل الرمز الحالي (باستثناء الموضع الأول)، لأنه سيعطي استعلامًا ومفتاحًا متساويين (لذلك متشابهين للغاية). نظرًا لطبيعة دالة الهاش العشوائية نوعًا ما، يتم في الممارسة العملية استخدام عدة دوال هاش (يحددها معامل n_rounds) ثم يتم حساب المتوسط معًا. + +## الانتباه المحلي + +يستخدم [Longformer](model_doc/longformer) الانتباه المحلي: غالبًا ما يكون السياق المحلي (على سبيل المثال، ما هما الرمزان إلى اليسار واليمين؟) كافيًا لاتخاذ إجراء بالنسبة للرمز المعطى. أيضًا، عن طريق تكديس طبقات الانتباه التي لها نافذة صغيرة، سيكون للطبقة الأخيرة مجال استقبال أكبر من مجرد الرموز في النافذة، مما يسمح لها ببناء تمثيل للجملة بأكملها. + +كما يتم منح بعض رموز الإدخال المختارة مسبقًا انتباهًا عالميًا: بالنسبة لهذه الرموز القليلة، يمكن لمصفوفة الانتباه الوصول إلى جميع الرموز وتكون هذه العملية متماثلة: فلجميع الرموز الأخرى إمكانية الوصول إلى تلك الرموز المحددة (بالإضافة إلى تلك الموجودة في نافذتهم المحلية). وهذا موضح في الشكل 2d من الورقة، انظر أدناه لمثال على قناع الانتباه: + +
+ +
+ +وباستخدام مصفوفات الانتباه هذه التي تحتوي على عدد أقل من المعلمات، يسمح النموذج بمدخالات ذات طول تسلسل أكبر. + +## حيل أخرى + +### الترميزات الموضعية المحورية + +يستخدم [Reformer](model_doc/reformer) ترميزات موضعية محورية: في نماذج المحول التقليدية، يكون الترميز الموضعي E مصفوفة بحجم \\(l\\) في \\(d\\)، حيث \\(l\\) هو طول التسلسل و\\(d\\) هو بعد الحالة المخفية. إذا كان لديك نصوص طويلة جدًا، فقد تكون هذه المصفوفة ضخمة وتستهلك مساحة كبيرة جدًا على وحدة معالجة الرسوميات (GPU). وللتخفيف من ذلك، تتكون الترميزات الموضعية المحورية من تحليل تلك المصفوفة الكبيرة E إلى مصفوفتين أصغر E1 وE2، بأبعاد \\(l_{1} \times d_{1}\\) و \\(l_{2} \times d_{2}\\)، بحيث \\(l_{1} \times l_{2} = l\\) و\\(d_{1} + d_{2} = d\\) (مع حاصل ضرب الأطوال، ينتهي الأمر بكونه أصغر بكثير). ويتم الحصول على الترميز للخطوة الزمنية \\(j\\) في E عن طريق ربط الترميزات للخطوة الزمنية \\(j \% l1\\) في E1 و \\(j // l1\\) في E2. \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/autoclass_tutorial.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/autoclass_tutorial.md new file mode 100644 index 0000000000000000000000000000000000000000..fe368af4727321a4d225194d70eb08216f145dbe --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/autoclass_tutorial.md @@ -0,0 +1,167 @@ +# تحميل نماذج مدربة مسبقًا باستخدام AutoClass +لم ترغب في إنشاء محول معماري لمؤشر الترابط الخاص بك، فهناك العديد من محولات المعمارية المختلفة التي يمكنك الاختيار من بينها. كجزء من الفلسفة الأساسية لـ 🤗 Transformers لجعل المكتبة سهلة وبسيطة ومرنة، فإن فئة `AutoClass` تستدل تلقائيًا وتحمّل البنية الصحيحة من نسخة نموذج (Model Checkpoint) معينة. تسمح لك طريقة `from_pretrained()` بتحميل نموذج مُدرب مسبقًا لأي بنية بسرعة حتى لا تضطر إلى تكريس الوقت والموارد لتدريب نموذج من الصفر. إن إنتاج هذا النوع من التعليمات البرمجية غير المعتمدة على نسخ يعني أنه إذا نجح رمزك مع ننسخة واحدة، فسيتم تشغيله مع أخرى - طالما تم تدريبه لمهمة مماثلة - حتى إذا كانت البنية المعمارية مختلفة. + +تذكر أن البنية تشير إلى هيكل النموذج، والنسخ هي الأوزان لبنية معمارية معينة. على سبيل المثال، [BERT](https://huggingface.co/google-bert/bert-base-uncased) هي بنية معمارية، في حين أن `google-bert/bert-base-uncased` هي نسخة. "النموذج" هو مصطلح عام يمكن أن يعني إما البنية أو نالنسخة. + +في هذا البرنامج التعليمي، ستتعلم كيفية: + +* تحميل مُجزّئ الرموز مُدرب مسبقًا +* تحميل معالج صور مُدرب مسبقًا +* تحميل مستخرج ميزات مُدرب مسبقًا +* تحميل معالج مُدرب مسبقًا +* تحميل نموذج مُدرب مسبقًا +* تحميل نموذج كعمود فقري + +## AutoTokenizer + +تبدأ كل مهمة NLP تقريبًا بمُجزّئ للرموز. يقوم المُجزّئ بتحويل النص إلى شكل يمكن للنموذج معالجته. + +قم بتحميل المُجزّئ باستخدام [`AutoTokenizer.from_pretrained`]: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased") +``` + +ثم قم بتحليل إدخالك على النحو الموضح أدناه: + +```py +>>> sequence = "In a hole in the ground there lived a hobbit." +>>> print(tokenizer(sequence)) +{'input_ids': [101, 1999, 1037, 4920, 1999, 1996, 2598, 2045, 2973, 1037, 7570, 10322, 4183, 1012, 102], + 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]} +``` + +## معالج الصور التلقائي (AutoImageProcessor) + + +بالنسبة لمهمات الرؤية، يقوم معالج الصور بمعالجة الصورة إلى تنسيق الإدخال الصحيح. + +```py +>>> from transformers import AutoImageProcessor + +>>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224") +``` + +## AutoBackbone + +
+ +
الصورة توضح مخطط مراحل نموذج Swin.
+
+ +يسمح لك [`AutoBackbone`] باستخدام النماذج المُدربة مسبقًا كعمود فقري للحصول على خرائط ميزات من مراحل مختلفة من العمود الفقري. يجب عليك تحديد أحد المعلمات التالية في [`~PretrainedConfig.from_pretrained`]: + +* `out_indices` هو فهرس الطبقة التي تريد الحصول على خريطة الميزات منها +* `out_features` هو اسم الطبقة التي تريد الحصول على خريطة الميزات منها + +يمكن استخدام هذه المعلمات بشكل متبادل، ولكن إذا كنت تستخدم كلاً منها، فتأكد من أنها متوائمة مع بعضها البعض! إذا لم تمرر أيًا من هذه المعلمات، فسيقوم العمود الفقري بإرجاع خريطة الميزات من الطبقة الأخيرة. +
+ +
صورة توضح خريطة ميزات من المرحلة الأولى للعمود الفقري.
+
+ +على سبيل المثال، في الرسم التخطيطي أعلاه، لإرجاع خريطة الميزات من المرحلة الأولى من العمود الفقري Swin، يمكنك تعيين `out_indices=(1,)`: + +```py +>>> from transformers import AutoImageProcessor, AutoBackbone +>>> import torch +>>> from PIL import Image +>>> import requests +>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" +>>> image = Image.open(requests.get(url, stream=True).raw) +>>> processor = AutoImageProcessor.from_pretrained("microsoft/swin-tiny-patch4-window7-224") +>>> model = AutoBackbone.from_pretrained("microsoft/swin-tiny-patch4-window7-224", out_indices=(1,)) + +>>> inputs = processor(image, return_tensors="pt") +>>> outputs = model(**inputs) +>>> feature_maps = outputs.feature_maps +``` + +الآن يمكنك الوصول إلى كائن `feature_maps` من المرحلة الأولى من العمود الفقري: + +```py +>>> list(feature_maps[0].shape) +[1, 96, 56, 56] +``` + +## مستخرج الميزات التلقائي (AutoFeatureExtractor) + +بالنسبة للمهام الصوتية، يقوم مستخرج الميزات بمعالجة إشارة الصوت إلى تنسيق الإدخال الصحيح. + +قم بتحميل مستخرج ميزات باستخدام [`AutoFeatureExtractor.from_pretrained`]: + +```py +>>> from transformers import AutoFeatureExtractor + +>>> feature_extractor = AutoFeatureExtractor.from_pretrained( +... "ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition" +... ) +``` + +## المعالج التلقائي (AutoProcessor) + +تتطلب المهام متعددة الوسائط معالجًا يجمع بين نوعين من أدوات المعالجة المسبقة. على سبيل المثال، يتطلب نموذج [LayoutLMV2](model_doc/layoutlmv2) معالج صور لمعالجة الصور ومُجزّئ لمعالجة النص؛ يجمع المعالج كليهما. + +قم بتحميل معالج باستخدام [`AutoProcessor.from_pretrained`]: + +```py +>>> from transformers import AutoProcessor + +>>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv2-base-uncased") +``` + +## النموذج التلقائي (AutoModel) + + + +تسمح لك فئات `AutoModelFor` بتحميل نموذج مُدرب مسبقًا لمهمة معينة (راجع [هنا](model_doc/auto) للحصول على قائمة كاملة بالمهام المتاحة). على سبيل المثال، قم بتحميل نموذج لتصنيف التسلسل باستخدام [`AutoModelForSequenceClassification.from_pretrained`]: + +```py +>>> from transformers import AutoModelForSequenceClassification + +>>> model = AutoModelForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased") +``` + +أعد استخدام نفس نقطة التفتيش لتحميل بنية لمهمة مختلفة: + +```py +>>> from transformers import AutoModelForTokenClassification + +>>> model = AutoModelForTokenClassification.from_pretrained("distilbert/distilbert-base-uncased") +``` + + + +بالنسبة لنماذج PyTorch، تستخدم طريقة `from_pretrained()` `torch.load()` التي تستخدم داخليًا `pickle` والتي يُعرف أنها غير آمنة. بشكل عام، لا تقم مطلقًا بتحميل نموذج قد يكون مصدره مصدرًا غير موثوق به، أو قد يكون تم العبث به. يتم تخفيف هذا الخطر الأمني جزئيًا للنماذج العامة المستضافة على Hub Hugging Face، والتي يتم [فحصها بحثًا عن البرامج الضارة](https://huggingface.co/docs/hub/security-malware) في كل ارتكاب. راجع [توثيق Hub](https://huggingface.co/docs/hub/security) للحصول على أفضل الممارسات مثل [التحقق من التوقيع](https://huggingface.co/docs/hub/security-gpg#signing-commits-with-gpg) باستخدام GPG. + +لا تتأثر نقاط تفتيش TensorFlow و Flax، ويمكن تحميلها داخل بنيات PyTorch باستخدام `from_tf` و `from_flax` kwargs لطريقة `from_pretrained` للتحايل على هذه المشكلة. + + + + +بشكل عام، نوصي باستخدام فئة `AutoTokenizer` وفئة `AutoModelFor` لتحميل مثيلات مُدربة مسبقًا من النماذج. سيساعدك هذا في تحميل البنية الصحيحة في كل مرة. في البرنامج التعليمي التالي، تعرف على كيفية استخدام المحلل اللغوي ومعالج الصور ومستخرج الميزات والمعالج الذي تم تحميله حديثًا لمعالجة مجموعة بيانات للضبط الدقيق. + + + +أخيرًا، تسمح لك فئات `TFAutoModelFor` بتحميل نموذج مُدرب مسبقًا لمهمة معينة (راجع [هنا](model_doc/auto) للحصول على قائمة كاملة بالمهام المتاحة). على سبيل المثال، قم بتحميل نموذج لتصنيف التسلسل باستخدام [`TFAutoModelForSequenceClassification.from_pretrained`]: + +```py +>>> from transformers import TFAutoModelForSequenceClassification + +>>> model = TFAutoModelForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased") +``` + +أعد استخدام نفس نقطة التفتيش لتحميل بنية لمهمة مختلفة: + +```py +>>> from transformers import TFAutoModelForTokenClassification + +>>> model = TFAutoModelForTokenClassification.from_pretrained("distilbert/distilbert-base-uncased") +``` + +بشكل عام، نوصي باستخدام فئة `AutoTokenizer` وفئة `TFAutoModelFor` لتحميل نسخ لنماذج مُدربة مسبقًا. سيساعدك هذا في تحميل البنية الصحيحة في كل مرة. في البرنامج التعليمي التالي، ستتعرف على كيفية استخدام المُجزّئ اللغوي ومعالج الصور ومستخرج الميزات والمعالج الذي تم تحميله حديثًا لمعالجة مجموعة بيانات للضبط الدقيق. + + diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/bertology.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/bertology.md new file mode 100644 index 0000000000000000000000000000000000000000..78f85b5c1060f6827d05fabfe1330760bb3c2f3e --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/bertology.md @@ -0,0 +1,18 @@ +# BERTology + +يُشهد في الآونة الأخيرة نمو مجال دراسي يُعنى باستكشاف آلية عمل نماذج المحولات الضخمة مثل BERT (والذي يُطلق عليها البعض اسم "BERTology"). ومن الأمثلة البارزة على هذا المجال ما يلي: + +- BERT Rediscovers the Classical NLP Pipeline بواسطة Ian Tenney و Dipanjan Das و Ellie Pavlick: + https://huggingface.co/papers/1905.05950 +- Are Sixteen Heads Really Better than One? بواسطة Paul Michel و Omer Levy و Graham Neubig: https://huggingface.co/papers/1905.10650 +- What Does BERT Look At? An Analysis of BERT's Attention بواسطة Kevin Clark و Urvashi Khandelwal و Omer Levy و Christopher D. + Manning: https://huggingface.co/papers/1906.04341 +- CAT-probing: A Metric-based Approach to Interpret How Pre-trained Models for Programming Language Attend Code Structure: https://huggingface.co/papers/2210.04633 + +لإثراء هذا المجال الناشئ، قمنا بتضمين بعض الميزات الإضافية في نماذج BERT/GPT/GPT-2 للسماح للناس بالوصول إلى التمثيلات الداخلية، والتي تم تكييفها بشكل أساسي من العمل الرائد لـ Paul Michel (https://huggingface.co/papers/1905.10650): + +- الوصول إلى جميع الحالات المخفية في BERT/GPT/GPT-2، +- الوصول إلى جميع أوزان الانتباه لكل رأس في BERT/GPT/GPT-2، +- استرجاع قيم ومشتقات مخرجات الرأس لحساب درجة أهمية الرأس وحذفه كما هو موضح في https://huggingface.co/papers/1905.10650. + +ولمساعدتك على فهم واستخدام هذه الميزات بسهولة، أضفنا مثالًا برمجيًا محددًا: [bertology.py](https://github.com/huggingface/transformers-research-projects/tree/main/bertology/run_bertology.py) أثناء استخراج المعلومات وتقليص من نموذج تم تدريبه مسبقًا على GLUE. \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/chat_templating.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/chat_templating.md new file mode 100644 index 0000000000000000000000000000000000000000..90f4ac820e146aa685cd89ec1d79f2749ae3434f --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/chat_templating.md @@ -0,0 +1,835 @@ +# قوالب نماذج الدردشة + +## مقدمة + +تعد **الدردشة** أحد استخدامات نماذج اللغات الكبيرة (LLMs) شائعة الاستخدام بشكل متزايد. ففي سياق الدردشة، وبدلاً من متابعة سلسلة نصية واحدة (كما هو الحال مع نماذج اللغات القياسية)، يواصل النموذج بدلاً من ذلك محادثة تتكون من رسالة واحدة أو أكثر، تتضمن كل منها دورًا، مثل "المستخدم" أو "المساعد"، بالإضافة إلى نص الرسالة. + +وكما هو الحال مع تقسيم النص إلى رموز (tokenization)، تتوقع النماذج المختلفة تنسيقات إدخال مختلفة تمامًا للمحادثة. لهذا السبب أضفنا **قوالب الدردشة** كميزة جديدة. تُعد قوالب المحادثة جزءًا من tokenizer. تحدد هذه القوالب كيفية تحويل المحادثات، والتي يتم تمثيلها كقوائم من الرسائل، إلى سلسلة نصية واحدة قابلة للتقسيم إلى رموز بالتنسيق الذي يتوقعه النموذج. + +دعونا نجعل هذا ملموسًا بمثال سريع باستخدام نموذج `BlenderBot`. لدى BlenderBot قالب افتراضي بسيط للغاية، والذي يضيف في الغالب مسافات بيضاء بين جولات الحوار: + +```python +>>> from transformers import AutoTokenizer +>>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot-400M-distill") + +>>> chat = [ +... {"role": "user", "content": "Hello, how are you?"}, +... {"role": "assistant", "content": "I'm doing great. How can I help you today?"}, +... {"role": "user", "content": "I'd like to show off how chat templating works!"}, +... ] + +>>> tokenizer.apply_chat_template(chat, tokenize=False) +" Hello, how are you? I'm doing great. How can I help you today? I'd like to show off how chat templating works!" +``` + +لاحظ كيف تم ضغط الدردشة بأكملها في سلسلة واحدة. إذا استخدمنا `tokenize=True`، وهو الإعداد الافتراضي، فسيتم أيضًا تحليل السلسلة نحويًا نيابة عنا. ولكن، لنشاهد قالبًا أكثر تعقيدًا في العمل، دعونا نستخدم نموذج `mistralai/Mistral-7B-Instruct-v0.1`. + +```python +>>> from transformers import AutoTokenizer +>>> tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-Instruct-v0.1") + +>>> chat = [ +... {"role": "user", "content": "Hello, how are you?"}, +... {"role": "assistant", "content": "I'm doing great. How can I help you today?"}, +... {"role": "user", "content": "I'd like to show off how chat templating works!"}, +... ] + +>>> tokenizer.apply_chat_template(chat, tokenize=False) +"[INST] Hello, how are you? [/INST]I'm doing great. How can I help you today? [INST] I'd like to show off how chat templating works! [/INST]" +``` + +لاحظ كيف أضاف المجزىء اللغوى tokenizer رموز التحكم `[INST]` و `[/INST]` للإشارة إلى بداية ونهاية رسائل المستخدم (ولكن ليس رسائل المساعد!) ، وتم تكثيف المحادثة بأكملها في سلسلة نصية واحدة. إذا استخدمنا `tokenize=True` ، وهو الإعداد الافتراضي ، فسيتم أيضًا تقسيم تلك السلسلة إلى رموز. + +حاول الآن استخدام نفس الشفرة، لكن مع استبدال النموذج بـ `HuggingFaceH4/zephyr-7b-beta` ، وستحصل على: +```text +<|user|> +Hello, how are you? +<|assistant|> +I'm doing great. How can I help you today? +<|user|> +I'd like to show off how chat templating works! +``` +تم ضبط كل من Zephyr و Mistral-Instruct من نفس النموذج الأصلي ، Mistral-7B-v0.1. ومع ذلك ، فقد تم تدريبهم بتنسيقات دردشة مختلفة تمامًا. بدون قوالب المحادثة، ستضطر إلى كتابة شفرة تنسيق يدويًا لكل نموذج ، ومن السهل جدًا ارتكاب أخطاء بسيطة تؤثر على الأداء! تُدير قوالب المحادثة تفاصيل التنسيق نيابةً عنك ، مما يُتيح لك كتابة شفرة عامة تعمل مع أي نموذج. + +## كيف أستخدم قوالب الدردشة؟ + +كما رأيت في المثال السابق، من السهل استخدام قوالب الدردشة. قم ببساطة بإنشاء قائمة من الرسائل، مع مفتاحي `role` و`content`، ثم قم بتمريرها إلى [`~PreTrainedTokenizer.apply_chat_template`] . بمجرد قيامك بذلك، ستحصل على مخرجات جاهزة للاستخدام! عند استخدام قوالب الدردشة كإدخال لتوليد نصوص بواسطة النموذج، فمن الجيد أيضًا استخدام `add_generation_prompt=True` لإضافة [مطالبات توليد النصوص](#what-are-generation-prompts). + +فيما يلي مثال على إعداد الإدخال لـ `model.generate()`، باستخدام Zephyr مرة أخرى: + +```python +from transformers import AutoModelForCausalLM, AutoTokenizer + +checkpoint = "HuggingFaceH4/zephyr-7b-beta" +tokenizer = AutoTokenizer.from_pretrained(checkpoint) +model = AutoModelForCausalLM.from_pretrained(checkpoint) # قد ترغب في استخدام bfloat16 و/أو الانتقال إلى GPU هنا + +messages = [ + { + "role": "system", + "content": "You are a friendly chatbot who always responds in the style of a pirate", + }, + {"role": "user", "content": "How many helicopters can a human eat in one sitting?"}, + ] +tokenized_chat = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt") +print(tokenizer.decode(tokenized_chat[0])) +``` +سيؤدي هذا إلى إنتاج سلسلة نصية بتنسيق الإدخال الذي يتوقعه Zephyr. + +```text +<|system|> +You are a friendly chatbot who always responds in the style of a pirate +<|user|> +How many helicopters can a human eat in one sitting? +<|assistant|> +``` + +الآن بعد أن تم تنسيق الإدخال بشكل صحيح لـ Zephyr، يمكننا استخدام النموذج لإنشاء رد على سؤال المستخدم: + +```python +outputs = model.generate(tokenized_chat, max_new_tokens=128) +print(tokenizer.decode(outputs[0])) +``` + +سيؤدي هذا إلى ما يلي: + +```text +<|system|> +You are a friendly chatbot who always responds in the style of a pirate +<|user|> +How many helicopters can a human eat in one sitting? +<|assistant|> +Matey, I'm afraid I must inform ye that humans cannot eat helicopters. Helicopters are not food, they are flying machines. Food is meant to be eaten, like a hearty plate o' grog, a savory bowl o' stew, or a delicious loaf o' bread. But helicopters, they be for transportin' and movin' around, not for eatin'. So, I'd say none, me hearties. None at all. +``` + +كان ذلك سهلاً بعد كل شيء ! + + + +## هل هناك قنوات معالجة أوتوماتيكية للدردشة؟ + +نعم يوجد ! تدعم قنوات المعالجة توليد النصوص مدخلات الدردشة ، مما يُسهّل استخدام نماذج الدردشة . في الماضي ، كنا نستخدم فئة "ConversationalPipeline" المُخصّصة ، ولكن تم الآن إيقافها وتم دمج وظائفها في [`TextGenerationPipeline`]. دعونا نجرّب مثال Zephyr مرة أخرى ، ولكن هذه المرة باستخدام قناة معالجة: + +```python +from transformers import pipeline + +pipe = pipeline("text-generation", "HuggingFaceH4/zephyr-7b-beta") +messages = [ + { + "role": "system", + "content": "You are a friendly chatbot who always responds in the style of a pirate", + }, + {"role": "user", "content": "How many helicopters can a human eat in one sitting?"}, +] +print(pipe(messages, max_new_tokens=128)[0]['generated_text'][-1]) # طباعة استجابة المساعد +``` + +```النص +{'role': 'assistant', 'content': "Matey, I'm afraid I must inform ye that humans cannot eat helicopters. Helicopters are not food, they are flying machines. Food is meant to be eaten, like a hearty plate o' grog, a savory bowl o' stew, or a delicious loaf o' bread. But helicopters, they be for transportin' and movin' around, not for eatin'. So, I'd say none, me hearties. None at all."} +``` + +سيُراعي قناة المعالجة جميع تفاصيل تقسيم النص إلى رموز واستدعاء apply_chat_template نيابةً عنك - بمجرد أن يصبح لِدى النموذج قالب دردشة ، فكل ما تحتاج إلى القيام به هو تهيئة قناة معالجة وتمرير قائمة الرسائل إليها! + +## ما هي "مطالبات التوليد"؟ + +قد تلاحظ أن طريقة `apply_chat_template` لها معامل `add_generation_prompt`. تخبر هذه المعامل القالب بإضافة رموز تشير إلى بداية رد البوت. على سبيل المثال، ضع في اعتبارك الدردشة التالية: + +```python +messages = [ + {"role": "user", "content": "Hi there!"}, + {"role": "assistant", "content": "Nice to meet you!"}, + {"role": "user", "content": "Can I ask a question?"} +] +``` + +إليك كيف سيبدو ذلك بدون موجه توليد نصوص ، بالنسبة لنموذج يستخدم تنسيق "ChatML" القياسي : + +```python +tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=False) +"""<|im_start|>user +Hi there!<|im_end|> +<|im_start|>assistant +Nice to meet you!<|im_end|> +<|im_start|>user +Can I ask a question?<|im_end|> +""" +``` + +وهكذا يبدو الأمر **مع** مطالبة التوليد: + +```python +tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) +"""<|im_start|>user +Hi there!<|im_end|> +<|im_start|>assistant +Nice to meet you!<|im_end|> +<|im_start|>user +Can I ask a question?<|im_end|> +<|im_start|>assistant +""" +``` + +لاحظ أننا أضفنا هذه المرة الرموز التي تشير إلى بداية رد البوت. يضمن هذا أنه عندما يُولّد النموذج نصًا فسيكتب رد البوت بدلاً من القيام بشيء غير متوقع، مثل الاستمرار في رسالة المستخدم. تذكر، أن نماذج الدردشة لا تزال مجرد نماذج للغة - فهي مدربة على متابعة النصوص، والدردشة هي مجرد نوع خاص من النصوص بالنسبة لها! يجب توجيهها برموز تحكم مناسبة، حتى تعرف ما الذي يجب عليها فعله. + +لا تتطلب جميع النماذج الرموز التحكمية لتوليد نصوص . بعض النماذج ، مثل LLaMA ، ليس لديها أي رموز خاصة قبل ردود البوت . في هذه الحالات ، لن يكون لمعامل `add_generation_prompt` أي تأثير. يعتمد التأثير الدقيق الذي تُحدثه `add_generation_prompt` على القالب المستخدم . + +## ما وظيفة "continue_final_message"؟ + +عند تمرير قائمة من الرسائل إلى `apply_chat_template` أو `TextGenerationPipeline` ، يمكنك اختيار تنسيق المحادثة بحيث يواصل النموذج الرسالة الأخيرة في المحادثة بدلاً من بدء رسالة جديدة. يتم ذلك عن طريق إزالة أي رموز نهاية التسلسل التي تشير إلى نهاية الرسالة الأخيرة ، بحيث يقوم النموذج ببساطة بتمديد الرسالة الأخيرة عندما يبدأ في توليد النص . يُعد هذا أمرًا مفيدًا "لِمَلء بداية" رد النموذج مُسبقًا. + +وهنا مثال: +```python +chat = [ + {"role": "user", "content": "Can you format the answer in JSON?"}, + {"role": "assistant", "content": '{"name": "'}, +] + +formatted_chat = tokenizer.apply_chat_template(chat, tokenize=True, return_dict=True, continue_final_message=True) +model.generate(**formatted_chat) +``` +سيقوم النموذج بتوليد نص يكمل سلسلة JSON ، بدلاً من بدء رسالة جديدة . يمكن أن يكون هذا النهج مفيدًا جدًا لتحسين دقة اتباع النموذج للإرشادات عندما تعرف كيف تريد أن يبدأ ردوده . +. + +نظرًا لأن `add_generation_prompt` تضيف الرموز التي تبدأ رسالة جديدة ، و `continue_final_message` تزيل أي رموز نهاية الرسالة من الرسالة الأخيرة ، فليس من المنطقي استخدامهما معًا . ونتيجة لذلك ، ستتلقّى خطأً إذا حاولت ذلك ! + +السلوك الافتراضي لِـ `TextGenerationPipeline` هو تعيين `add_generation_prompt=True` بحيث تبدأ رسالة جديدة . ومع ذلك ، إذا كانت الرسالة الأخيرة في المحادثة التي تم إدخالها لديها دور "assistant" ، فسوف تفترض أن هذه الرسالة هي "مَلء بداية" وتتحوّل إلى `continue_final_message=True` بدلاً من ذلك ، لأن مُعظم النماذج لا تدعم عدة رسائل متتالية للمساعد . يمكنك تجاوز هذا السلوك عن طريق تمرير معامل `continue_final_message` بشكل صريح عند استدعاء قناة المعالجة . + + + +## هل يمكنني استخدام قوالب الدردشة في التدريب؟ + +نعم ! تُعد هذه طريقة جيدة للتأكد من أن قالب الدردشة يتطابق مع الرموز التي يراها النموذج أثناء التدريب . نوصي بتطبيق قالب الدردشة كخطوة معالجة أولية لمجموعة بياناتك . بعد ذلك ، يمكنك ببساطة متابعة عملية التدريب كما هو الحال مع أي مهمة تدريب نماذج لغات أخرى . عند التدريب ، يجب أن تُعيّن عادةً `add_generation_prompt=False` ، لأنه لن تكون الرموز المُضافة لتحفيز رد المساعد مفيدة أثناء التدريب . دعونا نرى مثالاً : + +```python +from transformers import AutoTokenizer +from datasets import Dataset + +tokenizer = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-beta") + +chat1 = [ + {"role": "user", "content": "Which is bigger, the moon or the sun?"}, + {"role": "assistant", "content": "The sun."} +] +chat2 = [ + {"role": "user", "content": "Which is bigger, a virus or a bacterium?"}, + {"role": "assistant", "content": "A bacterium."} +] + +dataset = Dataset.from_dict({"chat": [chat1, chat2]}) +dataset = dataset.map(lambda x: {"formatted_chat": tokenizer.apply_chat_template(x["chat"], tokenize=False, add_generation_prompt=False)}) +print(dataset['formatted_chat'][0]) +``` +ونحصل على: + +```text +<|user|> +Which is bigger, the moon or the sun? +<|assistant|> +The sun. +``` + +من هنا، استمر في التدريب كما تفعل مع مهمة نمذجة اللغة القياسية، باستخدام عمود `formatted_chat`. + + +بشكل افتراضي ، تضيف بعض *tokenizers* رموزًا خاصة مثل `` و `` إلى النص الذي تقوم بتقسيمه إلى رموز. يجب أن تتضمن قوالب المحادثة بالفعل جميع الرموز الخاصة التي تحتاجها ، وبالتالي فإن الرموز الخاصة الإضافية ستكون غالبًا غير صحيحة أو مُكررة ، مما سيؤثر سلبًا على أداء النموذج . + +لذلك ، إذا قمت بتنسيق النص باستخدام `apply_chat_template(tokenize=False)` ، فيجب تعيين المعامل `add_special_tokens=False` عندما تقوم بتقسيم ذلك النص إلى رموز لاحقًا . إذا كنت تستخدم `apply_chat_template(tokenize=True)` ، فلن تحتاج إلى القلق بشأن ذلك ! + + +## متقدّم: مدخلات إضافية لِقوالب الدردشة + + +المعامل الوحيدة التي تتطلبها طريقة `apply_chat_template` هي `messages`. ومع ذلك، يمكنك تمرير أي معامل ككلمة مفتاحية إلى `apply_chat_template` وستكون متاحة داخل القالب. يمنحك هذا الكثير من المرونة لاستخدام قوالب الدردشة للعديد من الأشياء. لا توجد قيود على أسماء هذه المعامﻻت أو تنسيقاتها - يمكنك تمرير سلاسل نصية أو قوائم أو قواميس أو أي شيء آخر تريده. + +ومع ذلك، هناك بعض الحالات الشائعة لاستخدام هذه المعامﻻت الإضافية، مثل تمرير أدوات لاستدعاء الوظائف، أو المستندات لإنشاء النصوص المُعزّزة بالاسترجاع. في هذه الحالات الشائعة، لدينا بعض التوصيات المُحدّدة حول أسماء هذه المعامﻻت وتنسيقاتها، والتي يتم وصفها في الأقسام التالية. نشجع مطوّري النماذج على جعل قوالب الدردشة الخاصة بهم متوافقة مع هذا التنسيق، لتسهيل نقل التعليمات البرمجية لاستدعاء الأدوات بين النماذج. + +## متقدم: استخدام الأداة / استدعاء الدالة + +يمكن لنماذج "استخدام الأداة" اختيار استدعاء الدوال كأدوات خارجية قبل توليد الإجابة. عند تمرير الأدوات إلى نموذج استخدام الأدوات، يمكنك ببساطة تمرير قائمة من الوظائف إلى معامل `tools`: + +```python +import datetime + +def current_time(): + """Get the current local time as a string.""" + return str(datetime.now()) + +def multiply(a: float, b: float): + """ + A function that multiplies two numbers + + Args: + a: The first number to multiply + b: The second number to multiply + """ + return a * b + +tools = [current_time, multiply] + +model_input = tokenizer.apply_chat_template( + messages, + tools=tools +) +``` + +لكي يعمل هذا بشكل صحيح، يجب عليك كتابة وظائفك بالتنسيق السابق، حتى يمكن تحليلها بشكل صحيح كأدوات. على وجه التحديد، يجب عليك اتباع هذه القواعد: + +- يجب أن يكون للدالة اسم وصفي. +- يجب أن يكون لكل معامل نوع للتلميح. +- يجب أن تحتوي الدالة على سلسلة مستندية بتنسيق Google القياسي (بمعنى وصف الدالة الأولي متبوعًا بكتلة `Args:` التي تصف المعاﻻت، ما لم تكن الدالة لا تحتوي على أي معامﻻت. +- لا تقم بتضمين الأنواع في كتلة `Args:` . بعبارة أخرى، اكتب `a: The first number to multiply`، وليس `a (int): The first number to multiply`. يجب أن تذهب تلميحات الأنواع في رأس الدالة بدلاً من ذلك. +- يمكن أن يكون للدالة نوع للإرجاع ومربع `Returns:` في السلسلة. ومع ذلك، فهذه اختيارية لأن معظم نماذج استخدام الأدوات تتجاهلها. + +### تمرير نتائج الأداة إلى النموذج + +يكفي الكود السابقة لسرد الأدوات المتاحة لنموذجك، ولكن ماذا يحدث إذا أراد النموذج استخدام واحدة منها؟ إذا حدث ذلك، فيجب عليك: + +1. تحليل مخرجات النموذج للحصول على اسم (أسماء) الأدوات ومعامﻻتها. +2. أضف استدعاء (استدعاءات) النموذج لِلأدوات إلى المحادثة. +3. استدعاء الدالة (الدالات) المقابلة بتلك المعامﻻت. +4. أضف النتيجة (النتائج) إلى المحادثة + +### مثال كامل على استخدام الأداة + + +سنستعرض مثالاً على استخدام الأدوات خطوة بخطوة . في هذا المثال ، سنستخدم نموذج `Hermes-2-Pro` بحجم 8 مليارات معامل ، نظرًا لأنه أحد أعلى نماذج استخدام الأدوات أداءً في فئة حجمه وقت كتابة هذا النص . إذا كان لديك الذاكرة الكافية ، فيمكنك النظر في استخدام نموذج أكبر بدلاً من ذلك مثل `Command-R` أو `Mixtral-8x22B` ، وكلاهما يدعم استخدام الأدوات ويوفر أداءً أقوى . + + +أولاً ، لنقم بتحميل نموذجنا و tokenizer الخاص بنا: + +```python +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +checkpoint = "NousResearch/Hermes-2-Pro-Llama-3-8B" + +tokenizer = AutoTokenizer.from_pretrained(checkpoint) +model = AutoModelForCausalLM.from_pretrained(checkpoint, torch_dtype=torch.bfloat16, device_map="auto") + +```python +messages = [ + {"role": "system", "content": "You are a bot that responds to weather queries. You should reply with the unit used in the queried location."}, + {"role": "user", "content": "Hey, what's the temperature in Paris right now?"} +] +``` + +الآن، لنقم نطبق قالب الدردشة ونولد رد: + +```python +inputs = tokenizer.apply_chat_template(messages, chat_template="tool_use", tools=tools, add_generation_prompt=True, return_dict=True, return_tensors="pt") +inputs = {k: v.to(model.device) for k, v in inputs.items()} +out = model.generate(**inputs, max_new_tokens=128) +print(tokenizer.decode(out[0][len(inputs["input_ids"][0]):])) +``` + +ونحصل على: + +```text + +{"arguments": {"location": "Paris, France", "unit": "celsius"}, "name": "get_current_temperature"} +<|im_end|> +``` + +لقد قام النموذج باستدعاء الدالة مع معامﻻت صحيحة، بالصيغة التي طلبتها توثيق الدالة. لقد استنتج أننا نشير على الأرجح إلى باريس في فرنسا، وتذكر أنه بكونها موطن وحدات القياس الدولية، يجب عرض درجة الحرارة في فرنسا بالدرجة المئوية. + +دعنا نضيف استدعاء الأداة الخاص بالنموذج إلى المحادثة. لاحظ أننا نولد معرف استدعاء أداة عشوائيًا هنا. لا تستخدم جميع النماذج هذه المعرفات، ولكنها تسمح للنماذج بإصدار عدة استدعاءات للأدوات في نفس الوقت وتتبع الاستجابة المقابلة لكل استدعاء. يمكنك توليد هذه المعرفات بأي طريقة تريدها، ولكن يجب أن تكون فريدة داخل كل محادثة. + +```python +tool_call_id = "vAHdf3" # Random ID, should be unique for each tool call +tool_call = {"name": "get_current_temperature", "arguments": {"location": "Paris, France", "unit": "celsius"}} +messages.append({"role": "assistant", "tool_calls": [{"id": tool_call_id, "type": "function", "function": tool_call}]}) +``` + +الآن بعد أن أضفنا استدعاء الأداة إلى المحادثة، يمكننا استدعاء الدالة وإضافة النتيجة إلى المحادثة. نظرًا لأننا نستخدم دالة وهمية لهذا المثال والتي تعيد دائمًا 22.0، فيمكننا ببساطة إضافة تلك النتيجة مباشرةً. لاحظ معرف استدعاء الأداة - يجب أن يتطابق مع المعرف المستخدم في استدعاء الأداة أعلاه. + +```python +messages.append({"role": "tool", "tool_call_id": tool_call_id, "name": "get_current_temperature", "content": "22.0"}) +``` + +أخيرًا، دعنا نجعل المساعد يقرأ مخرجات الدالة ويكمل الدردشة مع المستخدم: + +```python +inputs = tokenizer.apply_chat_template(messages, chat_template="tool_use", tools=tools, add_generation_prompt=True, return_dict=True, return_tensors="pt") +inputs = {k: v.to(model.device) for k, v in inputs.items()} +out = model.generate(**inputs, max_new_tokens=128) +print(tokenizer.decode(out[0][len(inputs["input_ids"][0]):])) +``` + +ونحصل على: + +```text +The current temperature in Paris, France is 22.0 ° Celsius.<|im_end|> +``` + + +لا تستخدم جميع نماذج استخدام الأدوات جميع ميزات استدعاء الأدوات الموضحة أعلاه. يستخدم البعض معرفات استدعاء الأدوات، بينما يستخدم البعض الآخر ببساطة اسم الدالة ويقارن استدعاءات الأدوات بالنتائج باستخدام الترتيب، وهناك عدة نماذج لا تستخدم أيًا منهما ولا تصدر سوى استدعاء أداة واحد في كل مرة لتجنب الارتباك. إذا كنت تريد أن يكون رمزك متوافقًا مع أكبر عدد ممكن من النماذج، فإننا نوصي بهيكلة استدعاءات الأدوات الخاصة بك كما هو موضح هنا، وإعادة نتائج الأدوات بالترتيب الذي أصدرها النموذج. يجب أن تتعامل قوالب الدردشة على كل نموذج مع الباقي. + + +### فهم مخططات الأدوات + +يتم تحويل كل دالة تقوم بتمريرها إلى معامل `tools` في دالة `apply_chat_template` إلى [مخطط JSON](https://json-schema.org/learn/getting-started-step-by-step). يتم بعد ذلك تمرير هذه المخططات إلى قالب الدردشة النموذج. وبعبارة أخرى، فإن نماذج استخدام الأدوات لا ترى دوالك مباشرة، ولا ترى مطلقًا الكود الموجود بداخلها. ما يهمها هو**تعريفات** الدوال و**المعامﻻت** التي تحتاج إلى تمريرها إليها - فهي تهتم بما تفعله الأدوات وكيفية استخدامها، وليس بكيفية عملها! يقع على عاتقك قراءة مخرجاتها، والكشف عما إذا كانت قد طلبت استخدام أداة، وتمرير المعامﻻت إلى دالة الأداة، وإرجاع الرد في الدردشة. + +يجب أن يكون إنشاء مخططات JSON لتمريرها إلى القالب تلقائيًا وغير مرئي طالما أن دوالك تتبع المواصفات الموضحة أعلاه، ولكن إذا واجهت مشكلات، أو إذا كنت تريد ببساطة مزيدًا من التحكم في التحويل، فيمكنك التعامل مع التحويل يدويًا. فيما يلي مثال على تحويل مخطط يدوي: + +```python +from transformers.utils import get_json_schema + +def multiply(a: float, b: float): + """ + A function that multiplies two numbers + + Args: + a: The first number to multiply + b: The second number to multiply + """ + return a * b + +schema = get_json_schema(multiply) +print(schema) +``` + +سيؤدي هذا إلى ما يلي: + +```json +{ + "type": "function", + "function": { + "name": "multiply", + "description": "A function that multiplies two numbers", + "parameters": { + "type": "object", + "properties": { + "a": { + "type": "number", + "description": "The first number to multiply" + }, + "b": { + "type": "number", + "description": "The second number to multiply" + } + }, + "required": ["a", "b"] + } + } +} +``` + +إذا كنت ترغب في ذلك، يمكنك تحرير هذه المخططات، أو حتى كتابتها من البداية بنفسك دون استخدام `get_json_schema` على الإطلاق. يمكن تمرير مخططات JSON مباشرةً إلى معامل `tools` في `apply_chat_template` - يمنحك هذا الكثير من القوة لتعريف مخططات دقيقة لوظائف أكثر تعقيدًا. ولكن كن حذرًا - كلما زاد تعقيد مخططاتك، زاد احتمال ارتباك النموذج عند التعامل معها! نوصي بتوقيعات دوال بسيطة حيثما أمكن، مع تقليل المعامﻻت (وخاصة المعامﻻت المعقدة والمتداخلة) إلى الحد الأدنى. + +فيما يلي مثال على تعريف المخططات يدويًا، وتمريرها مباشرةً إلى `apply_chat_template`: + +```python +# A simple function that takes no arguments +current_time = { + "type": "function", + "function": { + "name": "current_time", + "description": "Get the current local time as a string.", + "parameters": { + 'type': 'object', + 'properties': {} + } + } +} + +# A more complete function that takes two numerical arguments +multiply = { + 'type': 'function', + 'function': { + 'name': 'multiply', + 'description': 'A function that multiplies two numbers', + 'parameters': { + 'type': 'object', + 'properties': { + 'a': { + 'type': 'number', + 'description': 'The first number to multiply' + }, + 'b': { + 'type': 'number', 'description': 'The second number to multiply' + } + }, + 'required': ['a', 'b'] + } + } +} + +model_input = tokenizer.apply_chat_template( + messages, + tools = [current_time, multiply] +) +``` + +## متقدم: توليد قائم على الاسترجاع +يمكن لنماذج اللغة الكبيرة من نوع "توليد قائم على الاسترجاع" أو "RAG" البحث في مجموعة نصوص عن معلومات قبل الرد على الاستعلام. يسمح هذا للنماذج بتوسيع قاعدة معارفها بشكل كبير إلى ما هو أبعد من حجم سياقها المحدود. توصيتنا لنماذج RAG هي أن يقبل قالبها وسيطة `documents`. يجب أن تكون هذه قائمة من المستندات، حيث يكون كل "مستند" عبارة عن قاموس واحد بمفاتيح `title` و `contents`، وكلاهما سلاسل نصية. نظرًا لأن هذا التنسيق أبسط بكثير من مخططات JSON المستخدمة للأدوات، فلا توجد حاجة إلى دوال مساعدة. + +فيما يلي مثال على قالب RAG بالفعل: + +```python +from transformers import AutoTokenizer, AutoModelForCausalLM + +# تحميل النموذج والمجزىء اللغوي +model_id = "CohereForAI/c4ai-command-r-v01-4bit" +tokenizer = AutoTokenizer.from_pretrained(model_id) +model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto") +device = model.device # الحصول على الجهاز الذي تم تحميل النموذج عليه + +# تعريف مُدخلات المحادثة +conversation = [ + {"role": "user", "content": "What has Man always dreamed of?"} +] + +# تعريف المستندات لتوليد قائم على الاسترجاع +documents = [ + { + "title": "The Moon: Our Age-Old Foe", + "text": "Man has always dreamed of destroying the moon. In this essay, I shall..." + }, + { + "title": "The Sun: Our Age-Old Friend", + "text": "Although often underappreciated, the sun provides several notable benefits..." + } +] +# معالجة المحادثة والمستندات باستخدام قالب RAG، وإرجاع موترات PyTorch. +input_ids = tokenizer.apply_chat_template( + conversation=conversation, + documents=documents, + chat_template="rag", + tokenize=True, + add_generation_prompt=True, + return_tensors="pt").to(device) + +# توليد الرد +gen_tokens = model.generate( + input_ids, + max_new_tokens=100, + do_sample=True, + temperature=0.3, + ) + +# فك تشفير النص المُوَلّد وطباعته +gen_text = tokenizer.decode(gen_tokens[0]) +print(gen_text) +``` +إن مُدخل documents للتوليد القائم على الاسترجاع غير مدعوم على نطاق واسع، والعديد من النماذج لديها قوالب دردشة تتجاهل هذا المُدخل ببساطة. + +للتحقق مما إذا كان النموذج يدعم مُدخل `documents`، يمكنك قراءة بطاقة النموذج الخاصة به، أو `print(tokenizer.chat_template)` لمعرفة ما إذا كان مفتاح `documents` مستخدمًا في أي مكان. + +ومع ذلك، فإن أحد فئات النماذج التي تدعمه هي [Command-R](https://huggingface.co/CohereForAI/c4ai-command-r-08-2024) و [Command-R+](https://huggingface.co/CohereForAI/c4ai-command-r-pluse-08-2024) من Cohere، من خلال قالب الدردشة rag الخاص بهم. يمكنك رؤية أمثلة إضافية على التوليد باستخدام هذه الميزة في بطاقات النموذج الخاصة بهم. + + +## متقدم: كيف تعمل قوالب الدردشة؟ +يتم تخزين قالب الدردشة للنموذج في الخاصية `tokenizer.chat_template`. إذا لم يتم تعيين قالب دردشة، فسيتم استخدام القالب الافتراضي لفئة النموذج هذه بدلاً من ذلك. دعونا نلقي نظرة على قالب دردشة `Zephyr`، ولكن لاحظ أن هذا القالب مُبسّط قليلاً عن القالب الفعلي! + +``` +{%- for message in messages %} + {{- '<|' + message['role'] + |>\n' }} + {{- message['content'] + eos_token }} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|assistant|>\n' }} +{%- endif %} +``` +إذا لم تكن قد رأيت أحد هذه القوالب من قبل، فهذا [قالب Jinja](https://jinja.palletsprojects.com/en/3.1.x/templates/) .Jinja هي لغة قوالب تسمح لك بكتابة تعليمات برمجية بسيطة تُوَلّد نصًا. من نواحٍ عديدة، يُشبه الرمز والتركيب للغة Python. أما في لغة Python، سيبدو هذا القالب كما يلي: + +```python +for message in messages: + print(f'<|{message["role"]}|>') + print(message['content'] + eos_token) +if add_generation_prompt: + print('<|assistant|>') +``` +يقوم القالب بثلاثة أشياء بشكل فعال: + +- لكل رسالة، بطبع الدور مُحاطًا بـ `<|` و `|>`، مثل `<|user|>` أو `<|assistant|>`. +- بعد ذلك، يطبع محتوى الرسالة، متبوعًا برمز نهاية التسلسل `eos_token` . +- أخيرًا، إذا تم تعيين `add_generation_prompt` ، يطبع الرمز المساعد، حتى يعرف النموذج أنه يجب أن يبدأ في توليد استجابة المساعد. + +هذا قالب بسيط جدًا، لكن Jinja تمنحك الكثير من المرونة للقيام بأشياء أكثر تعقيدًا! دعونا نرى قالب Jinja يُمكنه تنسيق المُدخلات بطريقة تُشبه الطريقة التي تُنسّق بها LLaMA مُدخلاتها (لاحظ أن قالب LLaMA الحقيقي يتضمن معالجة لرسائل النظام الافتراضية ومعالجة رسائل النظام بشكل مختلف قليلاً بشكل عام - لا تستخدم هذا القالب في التعليمات البرمجية الفعلية الخاصة بك!) +``` +{%- for message in messages %} + {%- if message['role'] == 'user' %} + {{- bos_token + '[INST] ' + message['content'] + ' [/INST]' }} + {%- elif message['role'] == 'system' %} + {{- '<>\\n' + message['content'] + '\\n<>\\n\\n' }} + {%- elif message['role'] == 'assistant' %} + {{- ' ' + message['content'] + ' ' + eos_token }} + {%- endif %} +{%- endfor %} +``` +نأمل أنه إذا حدقت في هذا لفترة قصيرة، يمكنك أن ترى ما يفعله هذا القالب - فهو يُضيف رموزًا مُحددة مثل `[INST]` و `[/INST]` بناءً على دور كل رسالة. يمكن تمييز رسائل المستخدم والمساعد والنظام بوضوح للنموذج بسبب الرموز التي تُحيط بها. + +## متقدم: إضافة وتعديل قوالب الدردشة + +### كيف أنشئ قالب دردشة؟ +ببساطة، اكتب قالب Jinja واضبط `tokenizer.chat_template`. قد تجد أنه من الأسهل البدء بقالب موجود من نموذج آخر وتحريره ببساطة ليناسب احتياجاتك! على سبيل المثال، يمكننا أن نأخذ قالب LLaMA أعلاه ونضيف `[ASST]` و `[/ASST]` إلى رسائل المساعد: + +``` +{%- for message in messages %} + {%- if message['role'] == 'user' %} + {{- bos_token + '[INST] ' + message['content'].strip() + ' [/INST]' }} + {%- elif message['role'] == 'system' %} + {{- '<>\\n' + message['content'].strip() + '\\n<>\\n\\n' }} + {%- elif message['role'] == 'assistant' %} + {{- '[ASST] ' + message['content'] + ' [/ASST]' + eos_token }} + {%- endif %} +{%- endfor %} +``` + +الآن، اضبط ببساطة الخاصية `tokenizer.chat_template`. في المرة القادمة التي تستخدم فيها [`~PreTrainedTokenizer.apply_chat_template`] ، سيستخدم القالب الجديد الخاص بك! سيتم حفظ هذه الخاصية في ملف `tokenizer_config.json`، حتى تتمكن من استخدام [`~utils.PushToHubMixin.push_to_hub`] لتحميل قالبك الجديد إلى Hub والتأكد من أن الجميع يستخدم القالب الصحيح لنموذجك! + +```python +template = tokenizer.chat_template +template = template.replace("SYS", "SYSTEM") # تغيير رمز النظام +tokenizer.chat_template = template # تعيين القالب الجديد +tokenizer.push_to_hub("model_name") # تحميل القالب الجديد إلى Hub! +``` + +يتم استدعاء الدالة [`~PreTrainedTokenizer.apply_chat_template`] الذي نستخدم قالب الدردشة الخاص بك بواسطة فئة [`TextGenerationPipeline`] لذلك بمجرد تعيين قالب الدردشة الصحيح، سيصبح نموذجك متوافقًا تلقائيًا مع [`TextGenerationPipeline`]. + + +إذا كنت تُجري ضبطًا دقيقًا لنموذج للدردشة، بالإضافة إلى تعيين قالب دردشة، فربما يجب عليك إضافة أي رموز تحكم دردشة جديدة كرموز خاصة في المجزىء اللغوي. لا يتم تقسيم الرموز الخاصة أبدًا، مما يضمن معالجة رموز التحكم الخاصة بك دائمًا كرموز فردية بدلاً من تجزئتها إلى أجزاء. يجب عليك أيضًا تعيين خاصية `eos_token` للمجزىء اللغوي إلى الرمز الذي يُشير إلى نهاية توليدات المساعد في قالبك. سيضمن هذا أن أدوات توليد النصوص يمكنها تحديد وقت إيقاف توليد النص بشكل صحيح. + + +### لماذا تحتوي بعض النماذج على قوالب متعددة؟ +تستخدم بعض النماذج قوالب مختلفة لحالات استخدام مختلفة. على سبيل المثال، قد تستخدم قالبًا واحدًا للدردشة العادية وآخر لاستخدام الأدوات، أو التوليد القائم على الاسترجاع. في هذه الحالات، تكون `tokenizer.chat_template` قاموسًا. يمكن أن يتسبب هذا في بعض الارتباك، وحيثما أمكن، نوصي باستخدام قالب واحد لجميع حالات الاستخدام. يمكنك استخدام عبارات Jinja مثل `if tools is defined` وتعريفات `{% macro %}` لتضمين مسارات تعليمات برمجية متعددة بسهولة في قالب واحد. + +عندما يحتوي المعالج اللغوي على قوالب متعددة، ستكون `tokenizer.chat_template dict`، حيث يكون كل مفتاح هو اسم قالب. يحتوي أسلوب `apply_chat_template` على معالجة خاصة لأسماء قوالب مُعينة: على وجه التحديد، سيبحث عن قالب باسم `default` في معظم الحالات، وسيُثير خطأً إذا لم يتمكن من العثور على واحد. ومع ذلك، إذا كان هناك قالب باسم `tool_use` عندما قام المستخدم بتمرير وسيطة `tools`، فسيستخدم هذا القالب بدلاً من ذلك. للوصول إلى قوالب بأسماء أخرى، مرر اسم القالب الذي تُريده إلى وسيطة `chat_template` لـ `apply_chat_template()`. + +نجد أن هذا قد يكون مُربكًا بعض الشيء للمستخدمين - لذلك إذا كنت تكتب قالبًا بنفسك، فننصحك بمحاولة وضعه كله في قالب واحد حيثما أمكن! + +## ما القالب الذي يجب أن أستخدمه؟ + +عند تعيين قالب لنموذج تم تدريبه بالفعل على الدردشة، يجب التأكد من أن القالب يتطابق تمامًا مع تنسيق الرسالة الذي شاهده النموذج أثناء التدريب، وإلا فمن المحتمل أن تواجه تدهورًا في الأداء. هذا صحيح حتى إذا كنت تدرب النموذج بشكل إضافي - فمن المحتمل أن تحصل على أفضل أداء إذا قمت بإبقاء رموز الدردشة ثابتة. يُشبه هذا إلى حد كبير عملية التجزئة - فأنت تحصل بشكل عام على أفضل أداء للاستدلال أو الضبط الدقيق عندما تتطابق بدقة مع التجزئة المستخدمة أثناء التدريب. + +من ناحية أخرى، إذا كنت تُدرّب نموذجًا من البداية، أو تقوم بضبط دقيق لنموذج لغة أساسي للدردشة، لديك حرية اختيار قالب مناسب! تتمتع LLMs بالذكاء الكافي للتعامل مع العديد من تنسيقات الإدخال المختلفة. أحد الخيارات الشائعة هو تنسيق "ChatML"، وهو خيار جيد ومرن للعديد من حالات الاستخدام. يبدو كالتالي: + +``` +{%- for message in messages %} + {{- '<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n' }} +{%- endfor %} +``` + +إذا أعجبك هذا، فإليك نسخة جاهزة لوضعها في كودك. يتضمن الخط المفرد أيضًا دعمًا مفيدًا [لإرشادات التوليد](#what-are-generation-prompts)، ولكن لاحظ أنه لا يضيف رموز BOS أو EOS! إذا كان نموذجك يتوقع هذه الرموز، فلن يتم إضافتها تلقائيًا بواسطة "apply_chat_template" - بمعنى آخر، سيتم تجزئة النص باستخدام "add_special_tokens=False". هذا لتجنب التعارضات المحتملة بين القالب ومنطق "add_special_tokens". إذا كان نموذجك يتوقع رموزًا خاصة، فتأكد من إضافتها إلى القالب! + +```python +tokenizer.chat_template = "{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}" +``` + +يُحيط هذا القالب كل رسالة بين الرمزين "<|im_start|>" و "<|im_end|>"، ويكتب ببساطة الدور كسلسلة نصية، مما يسمح بالمرونة في الأدوار التي تتدرب عليها. يبدو الناتج كما يلي: + +```text +<|im_start|>system +You are a helpful chatbot that will do its best not to say anything so stupid that people tweet about it.<|im_end|> +<|im_start|>user +How are you?<|im_end|> +<|im_start|>assistant +I'm doing great!<|im_end|> +``` + +تعد أدوار "user" و "system" و "assistant" هي الأدوار القياسية للدردشة، ونوصي باستخدامها عندما يكون ذلك منطقيًا، خاصة إذا كنت تريد أن يعمل نموذجك بشكل جيد مع [`TextGenerationPipeline`]. ومع ذلك، فأنت لست مقيدًا بهذه الأدوار - فإن القوالب مرنة للغاية، ويمكن أن تكون أي سلسلة نصية دورًا. + + +## أريد إضافة بعض قوالب الدردشة! كيف أبدأ؟ + +إذا كان لديك أي نماذج دردشة، فيجب عليك تعيين الخاصية "tokenizer.chat_template" الخاصة بها واختبارها باستخدام [`~PreTrainedTokenizer.apply_chat_template`]، ثم رفع المجزىء اللغوي المُحدّث إلى Hub. ينطبق هذا حتى إذا لم تكن مالك النموذج - إذا كنت تستخدم نموذجًا بقالب دردشة فارغ، أو لا يزال يستخدم قالب الفئة الافتراضية، فيرجى فتح [طلب سحب](https://huggingface.co/docs/hub/repositories-pull-requests-discussions) إلى مستودع النموذج حتى يمكن تعيين الخاصية بشكل صحيح! + +بمجرد تعيين الخاصية، هذا كل شيء، لقد انتهيت! ستعمل "tokenizer.apply_chat_template" الآن بشكل صحيح لهذا النموذج، مما يعني أنها مدعومة أيضًا بشكل تلقائي في أماكن مثل "TextGenerationPipeline"! + +من خلال ضمان امتلاك النماذج لهذه الخاصية، يُمكننا التأكد من أن المجتمع بأكمله يستخدم القوة الكاملة للنماذج مفتوحة المصدر. لقد كانت عدم تطابق التنسيق تطارد المجال وأضرت الأداء بصمت لفترة طويلة جدًا - لقد حان الوقت لوضع حد لها! + +## متقدم: نصائح لكتابة القوالب + + +أسهل طريقة للبدء في كتابة قوالب Jinja هي إلقاء نظرة على بعض القوالب الموجودة. يمكنك استخدام `print(tokenizer.chat_template)` لأي نموذج دردشة لمعرفة القالب الذي يستخدمه. بشكل عام، تحتوي النماذج التي تدعم استخدام الأدوات على قوالب أكثر تعقيدًا بكثير من النماذج الأخرى - لذلك عندما تبدأ للتو، فمن المحتمل أنها مثال سيئ للتعلم منه! يمكنك أيضًا إلقاء نظرة على [وثائق Jinja](https://jinja.palletsprojects.com/en/3.1.x/templates/#synopsis) للحصول على تفاصيل حول تنسيق Jinja العام وتركيبه. + + + +تُطابق قوالب Jinja في `transformers` قوالب Jinja في أي مكان آخر. الشيء الرئيسي الذي يجب معرفته هو أن سجل الدردشة سيكون متاحًا داخل قالبك كمتغير يسمى `messages`. ستتمكن من الوصول إلى `messages` في قالبك تمامًا كما يمكنك في Python، مما يعني أنه يمكنك التكرار خلاله باستخدام `{% for message in messages %}` أو الوصول إلى رسائل فردية باستخدام `{{ messages[0] }}`، على سبيل المثال. + +يمكنك أيضًا استخدام النصائح التالية لكتابة قوالب Jinja نظيفة وفعالة: + +### إقتطاع المسافات الفارغة + +بشكل افتراضي، ستطبع Jinja أي مسافات فارغة تأتي قبل أو بعد كتلة. يمكن أن يكون هذا مشكلة لقوالب الدردشة، والتي تريد عادةً أن تكون دقيقة جدًا مع المسافات! لتجنب ذلك، نوصي بشدة بكتابة قوالبك على النحو التالي: + +``` +{%- for message in messages %} + {{- message['role'] + message['content'] }} +{%- endfor %} +``` + +بدلاً من ذلك: + +``` +{% for message in messages %} + {{ message['role'] + message['content'] }} +{% endfor %} +``` + +سيؤدي إضافة "-" إلى إزالة أي مسافات تأتي قبل الكتلة. يبدو المثال الثاني عادية، ولكن قد يتم تضمين السطر الجديد والمسافة البادئة في المخرجات، وهو على الأرجح ليس ما تُريده! + + +### المتغيرات الخاصة + + داخل قالبك، سيكون لديك حق الوصول إلى العديد من المتغيرات الخاصة. أهمها هو `messages`، والذي يحتوي على سجل الدردشة كقائمة من قواميس الرسائل. ومع ذلك، هناك العديد من المتغيرات الأخرى. لن يتم استخدام كل متغير في كل قالب. المتغيرات الأكثر شيوعًا هي: + +- `tools` تحتوي على قائمة بالأدوات بتنسيق مخطط JSON. ستكون `None` أو غير مُعرّفة إذا لم يتم تمرير أي أدوات. +- `documents` تحتوي على قائمة من المستندات بالتنسيق `{"title": "العنوان", "contents": "المحتويات"}`، تُستخدم للتوليد المُعزز بالاسترجاع. ستكون `None` أو غير مُعرّفة إذا لم يتم تمرير أي مستندات. +- `add_generation_prompt` هي قيمة منطقية تكون `True` إذا طلب المستخدم مُطالبة توليد، و `False` بخلاف ذلك. إذا تم تعيين هذا، فيجب أن يُضيف قالبك رأس رسالة مساعد إلى نهاية المحادثة. إذا لم يكن لدى نموذجك رأس مُحدد لرسائل المساعد، فيمكنك تجاهل هذا العلم. +- **الرموز الخاصة** مثل `bos_token` و `eos_token`. يتم استخراجها من `tokenizer.special_tokens_map`. ستختلف الرموز الدقيقة المتاحة داخل كل قالب اعتمادًا على المجزىء اللغوي الأصلي. + + + + +يمكنك في الواقع تمرير أي `kwarg` إلى `apply_chat_template`، وستكون متاحة داخل القالب كمتغير. بشكل عام، نوصي بمحاولة الالتزام بالمتغيرات الأساسية المذكورة أعلاه، لأن ذلك سيجعل نموذجك أكثر صعوبة في الاستخدام إذا كان على المستخدمين كتابة تعليمات برمجية مخصصة لتمرير `kwargs` خاصة بالنموذج. ومع ذلك، فنحن نُدرك أن هذا المجال يتحرك بسرعة، لذلك إذا كانت لديك حالة استخدام جديدة لا تتناسب مع واجهة برمجة التطبيقات الأساسية، فلا تتردد في استخدام `kwarg` معامل جديد لها! إذا أصبح `kwarg` المعامل الجديد شائعًا، فقد نقوم بترقيته إلى واجهة برمجة التطبيقات الأساسية وإنشاء وتوثيق الخاص به. + + + +### دوال قابلة للاستدعاء + +هناك أيضًا قائمة قصيرة من الدوال القابلة للاستدعاء المتاحة لك داخل قوالبك. هذه هي: + +- `raise_exception(msg)`: تُثير `TemplateException`. هذا مفيد لتصحيح الأخطاء، ولإخبار المستخدمين عندما يفعلون شيئًا لا يدعمه قالبك. +- `strftime_now(format_str)`: تُكافئ `datetime.now().strftime(format_str)` في Python. يُستخدم هذا للحصول على التاريخ/الوقت الحالي بتنسيق مُحدد، والذي يتم تضمينه أحيانًا في رسائل النظام. + +### التوافق مع Jinja غير Python + +هناك تطبيقات متعددة لـ Jinja بلغات مختلفة. عادة ما يكون لها نفس التركيب، ولكن الاختلاف الرئيسي هو أنه عند كتابة قالبًا في Python، يمكنك استخدام أساليب Python، مثل ".lower()" على السلاسل أو ".items()" على القواميس. سيؤدي هذا إلى كسر إذا حاول شخص ما استخدام قالبك في تنفيذ غير Python لـ Jinja. تعد التطبيقات غير Python شائعة بشكل خاص في بيئات النشر، حيث تعد JS و Rust شائعة جدًا. + +لا تقلق، على الرغم من ذلك! هناك بعض التغييرات البسيطة التي يمكنك إجراؤها على قوالبك لضمان توافقها عبر جميع تطبيقات Jinja: + +- استبدل أساليب Python بمرشحات Jinja. عادة ما يكون لها نفس الاسم، على سبيل المثال، يصبح "string.lower()" عبارة عن "string|lower"، ويصبح "dict.items()" عبارة عن "dict|items". أحد التغييرات الملحوظة هو أن "string.strip()" يصبح "string|trim". راجع [قائمة المرشحات المدمجة](https://jinja.palletsprojects.com/en/3.1.x/templates/#builtin-filters) في وثائق Jinja لمزيد من المعلومات. +- استبدل "True" و "False" و "None"، وهي خاصة بـ Python، بـ "true" و "false" و "none". +- قد يؤدي عرض قاموس أو قائمة مباشرة إلى نتائج مختلفة في التطبيقات الأخرى (على سبيل المثال، قد تتغير مدخﻻت السلسلة النصية من علامات اقتباس مفردة ' إلى علامات اقتباس مزدوجة "). يمكن أن يساعد إضافة "tojson" في ضمان الاتساق هنا. + +## كتابة مطالبات التوليد +لقد ذكرنا أعلاه أن add_generation_prompt هو متغير خاص يمكن الوصول إليه داخل قالبك، ويتحكم فيه المستخدم من خلال تعيين معامل add_generation_prompt. إذا كان نموذجك يتوقع عنوان لرسائل المساعد، فيجب أن يدعم قالبك إضافة العنوان عند تعيين add_generation_prompt. + +فيما يلي مثال على قالب يُنسّق الرسائل بأسلوب ChatML، مع دعم مُطالبة التوليد: + +```text +{{- bos_token }} +{%- for message in messages %} + {{- '<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n' }} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} +{%- endif %} +``` +سيعتمد المحتوى الدقيق لعنوان المساعد على نموذجك المُحدد، ولكن يجب أن يكون دائمًا السلسلة النصية التي تُمثل بداية رسالة المساعد، بحيث إذا قام المستخدم بتطبيق قالبك باستخدام add_generation_prompt=True ثم قام بتوليد نص، سيكتب النموذج استجابة المساعد. لاحظ أيضًا أن بعض النماذج لا تحتاج إلى مُطالبة توليد، لأن رسائل المساعد تبدأ دائمًا فورًا بعد رسائل المستخدم. هذا شائع بشكل خاص لنماذج LLaMA و Mistral، حيث تبدأ رسائل المساعد فورًا بعد رمز [/INST] الذي ينهي رسائل المستخدم. في هذه الحالات، يمكن للقالب تجاهل معامل add_generation_prompt. + +مُطالبات التوليد مُهمة! إذا كان نموذجك يتطلب مُطالبة توليد ولكنها غير مُعيّنة في القالب، فمن المُحتمل أن تتدهور عمليات توليد النموذج بشدة، أو قد يُظهر النموذج سلوكًا غير عادي مثل متابعة رسالة المستخدم الأخيرة! + +### كتابة قوالب أكبر وتصحيحها +عندما تم تقديم هذه الميزة، كانت معظم القوالب صغيرة جدًا، أي ما يُعادل نص برمجي "من سطر واحد" في Jinja. ومع ذلك، مع النماذج والميزات الجديدة مثل استخدام الأدوات و RAG، يمكن أن يصل طول بعض القوالب إلى 100 سطر أو أكثر. عند كتابة قوالب كهذه، من الجيد كتابتها في ملف مُنفصل، باستخدام مُحرر نصوص. يمكنك بسهولة استخراج قالب دردشة إلى ملف: + +```python +open("template.jinja", "w").write(tokenizer.chat_template) +``` +أو تحميل القالب المُحرر مرة أخرى إلى المعالج اللغوي: + +```python +tokenizer.chat_template = open("template.jinja").read() +``` +كميزة إضافية، عندما تكتب قالبًا طويلاً متعدد الأسطر في ملف مُنفصل، ستتوافق أرقام الأسطر في هذا الملف تمامًا مع أرقام الأسطر في أخطاء تحليل القالب أو تنفيذه. سيُسهّل هذا كثيرًا تحديد مكان المشكلات. + +### كتابة قوالب للأدوات +على الرغم من أن قوالب الدردشة لا تفرض واجهة برمجة تطبيقات مُحددة للأدوات (أو لأي شيء حقًا)، فإننا نوصي مؤلفي القوالب بمحاولة الالتزام بواجهة برمجة تطبيقات قياسية حيثما أمكن. الهدف النهائي لقوالب الدردشة هو السماح بنقل التعليمات البرمجية عبر النماذج، لذا فإن الانحراف عن واجهة برمجة تطبيقات الأدوات القياسية يعني أن المستخدمين سيضطرون إلى كتابة تعليمات برمجية مخصصة لاستخدام الأدوات مع نموذجك. في بعض الأحيان يكون ذلك أمرًا لا مفر منه، ولكن غالبًا ما يكون من الممكن استخدام واجهة برمجة التطبيقات القياسية من خلال استخدام قوالب ذكية! + +أدناه، سنُدرج عناصر واجهة برمجة التطبيقات القياسية، ونقدم نصائح حول كتابة قوالب ستعمل بشكل جيد معها. + +#### تعريفات الأدوات +يجب أن يتوقع قالبك أن يكون المتغير tools إما فارغًا (إذا لم يتم تمرير أي أدوات)، أو قائمة من قواميس مخطط JSON. تسمح أساليب قالب الدردشة الخاصة بنا للمستخدمين بتمرير الأدوات إما كمخطط JSON أو كدوال Python، ولكن عندما يتم تمرير الدوال، فإننا نقوم تلقائيًا بإنشاء مخطط JSON وتمريره إلى قالبك. نتيجة لذلك، سيكون متغير tools الذي يستقبله قالبك دائمًا قائمة من مخططات JSON. هنا مخطط JSON أداة نموذجي: + +```json +{ + "type": "function", + "function": { + "name": "multiply", + "description": "دالة تضرب عددين", + "parameters": { + "type": "object", + "properties": { + "a": { + "type": "number", + "description": "الرقم الأول للضرب" + }, + "b": { + "type": "number", + "description": "الرقم الثاني للضرب" + } + }, + "required": ["a", "b"] + } + } +} +``` + +وهنا بعض الأمثلة البرمجية للتعامل مع الأدوات في قالب الدردشة الخاص بك. تذكر أن هذا مجرد مثال لتنسيق مُحدد - من المحتمل أن يحتاج نموذجك إلى تنسيق مختلف! +```text +{%- if tools %} + {%- for tool in tools %} + {{- '' + tool['function']['name'] + '\n' }} + {%- for argument in tool['function']['parameters']['properties'] %} + {{- argument + ': ' + tool['function']['parameters']['properties'][argument]['description'] + '\n' }} + {%- endfor %} + {{- '\n' }} + {%- endif %} +{%- endif %} +``` + +يجب بالطبع اختيار الرموز المحددة ووصف الأدوات التي يُعرضها قالبك لتتناسب مع تلك التي تم تدريب نموذجك عليها. لا يوجد شرط أن يفهم نموذجك مُدخلات مخطط JSON، فقط أن يتمكن قالبك من ترجمة مخطط JSON إلى تنسيق نموذجك. على سبيل المثال، تم تدريب Command-R باستخدام أدوات مُعرّفة باستخدام رؤوس دوال Python، ولكن يقبل قالب أداة Command-R مخطط JSON، ويُحوّل الأنواع داخليًا ويُعرض أدوات الإدخال كعناوين Python. يمكنك فعل الكثير باستخدام القوالب! + +#### استدعاءات الأدوات +استدعاءات الأدوات، إذا كانت موجودة، ستكون قائمة مُرفقة برسالة بدور "assistant". لاحظ أن tool_calls هي دائمًا قائمة، على الرغم من أن معظم نماذج استدعاء الأدوات تدعم فقط استدعاءات أدوات فردية في كل مرة، مما يعني أن القائمة ستحتوي عادةً على عنصر واحد فقط. هنا قاموس رسالة نموذجي يحتوي على استدعاء أداة: + +```json +{ + "role": "assistant", + "tool_calls": [ + { + "type": "function", + "function": { + "name": "multiply", + "arguments": { + "a": 5, + "b": 6 + } + } + } + ] +} +``` +والنمط الشائع للتعامل معها سيكون كهذا: + +```text +{%- if message['role'] == 'assistant' and 'tool_calls' in message %} + {%- for tool_call in message['tool_calls'] %} + {{- '' + tool_call['function']['name'] + '\n' + tool_call['function']['arguments']|tojson + '\n' }} + {%- endif %} + {%- endfor %} +{%- endif %} +``` + +مرة أخرى، يجب عليك عرض استدعاء الأداة بالتنسيق والرموز الخاصة التي يتوقعها نموذجك. + +#### استجابات الأدوات +استجابات الأدوات لها تنسيق بسيط: إنها قاموس رسالة بدور "tool"، ومفتاح "name" يُعطي اسم الدالة المُستدعاة، ومفتاح "content" يحتوي على نتيجة استدعاء الأداة. هنا استجابة أداة نموذجية: + +```json +{ + "role": "tool", + "name": "multiply", + "content": "30" +} +``` +لست بحاجة إلى استخدام جميع المفاتيح في استجابة الأداة. على سبيل المثال، إذا كان نموذجك لا يتوقع تضمين اسم الدالة في استجابة الأداة، فيمكن أن يكون عرضها بسيطًا مثل: + +```text +{%- if message['role'] == 'tool' %} + {{- "" + message['content'] + "" }} +{%- endif %} +``` + +مرة أخرى، تذكر أن التنسيق الفعلي والرموز الخاصة خاصة بالنموذج - يجب أن تُولي عناية كبيرة لضمان أن الرموز والمسافات الفارغة وكل شيء آخر يتطابق تمامًا مع التنسيق الذي تم تدريب نموذجك عليه! diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/community.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/community.md new file mode 100644 index 0000000000000000000000000000000000000000..5a1c31de0aaa3f7e8c2399a016a59be982d17960 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/community.md @@ -0,0 +1,66 @@ +# مجتمع المطورين + +هذه الصفحة تجمع الموارد حول 🤗 Transformers التي طورها المجتمع. + +## موارد المجتمع: + +| المصدر | الوصف | المؤلف | +|:----------|:-------------|------:| +| [Hugging Face Transformers Glossary Flashcards](https://www.darigovresearch.com/huggingface-transformers-glossary-flashcards) | مجموعة من البطاقات التعليمية القائمة على [Transformers Docs Glossary](glossary) والتي تم وضعها في شكل يمكن تعلمه/مراجعته بسهولة باستخدام [Anki](https://apps.ankiweb.net/) وهو تطبيق مفتوح المصدر متعدد المنصات مصمم خصيصًا للاحتفاظ بالمعرفة على المدى الطويل. شاهد هذا [فيديو تمهيدي حول كيفية استخدام البطاقات التعليمية](https://www.youtube.com/watch?v=Dji_7PILrw). | [Darigov Research](https://www.darigovresearch.com/) | + +## دفاتر ملاحظات المجتمع: + +| الدفتر | الوصف | المؤلف | | +|:----------|:-------------|:-------------|------:| +| [Fine-tune a pre-trained Transformer to generate lyrics](https://github.com/AlekseyKorshuk/huggingartists) | كيفية توليد كلمات الأغاني على غرار فنانك المفضل من خلال ضبط نموذج GPT-2 | [Aleksey Korshuk](https://github.com/AlekseyKorshuk) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/AlekseyKorshuk/huggingartists/blob/master/huggingartists-demo.ipynb) | +| [Train T5 in Tensorflow 2](https://github.com/snapthat/TF-T5-text-to-text) | كيفية تدريب T5 لأي مهمة باستخدام Tensorflow 2. يوضح هذا الدفتر مهمة السؤال والجواب المنفذة في Tensorflow 2 باستخدام SQUAD | [Muhammad Harris](https://github.com/HarrisDePerceptron) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/snapthat/TF-T5-text-to-text/blob/master/snapthatT5/notebooks/TF-T5-Datasets%20Training.ipynb) | +| [Train T5 on TPU](https://github.com/patil-suraj/exploring-T5/blob/master/T5_on_TPU.ipynb) | كيفية تدريب T5 على SQUAD مع Transformers و Nlp | [Suraj Patil](https://github.com/patil-suraj) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patil-suraj/exploring-T5/blob/master/T5_on_TPU.ipynb#scrollTo=QLGiFCDqvuil) | +| [Fine-tune T5 for Classification and Multiple Choice](https://github.com/patil-suraj/exploring-T5/blob/master/t5_fine_tuning.ipynb) | كيفية ضبط نموذج T5 للتصنيف والمهام متعددة الخيارات باستخدام تنسيق النص إلى نص مع PyTorch Lightning | [Suraj Patil](https://github.com/patil-suraj) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patil-suraj/exploring-T5/blob/master/t5_fine_tuning.ipynb) | +| [Fine-tune DialoGPT on New Datasets and Languages](https://github.com/ncoop57/i-am-a-nerd/blob/master/_notebooks/2020-05-12-chatbot-part-1.ipynb) | كيفية ضبط نموذج DialoGPT على مجموعة بيانات جديدة لروبوتات الدردشة المحادثية المفتوحة | [Nathan Cooper](https://github.com/ncoop57) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/ncoop57/i-am-a-nerd/blob/master/_notebooks/2020-05-12-chatbot-part-1.ipynb) | +| [Long Sequence Modeling with Reformer](https://github.com/patrickvonplaten/notebooks/blob/master/PyTorch_Reformer.ipynb) | كيفية التدريب على تسلسلات طويلة تصل إلى 500,000 رمز باستخدام Reformer | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/PyTorch_Reformer.ipynb) | +| [Fine-tune BART for Summarization](https://github.com/ohmeow/ohmeow_website/blob/master/posts/2021-05-25-mbart-sequence-classification-with-blurr.ipynb) | كيفية ضبط نموذج BART للتلخيص باستخدام fastai باستخدام blurr | [Wayde Gilliam](https://ohmeow.com/) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/ohmeow/ohmeow_website/blob/master/posts/2021-05-25-mbart-sequence-classification-with-blurr.ipynb) | +| [Fine-tune a pre-trained Transformer on anyone's tweets](https://colab.research.google.com/github/borisdayma/huggingtweets/blob/master/huggingtweets-demo.ipynb) | كيفية توليد تغريدات على غرار حساب Twitter المفضل لديك من خلال ضبط نموذج GPT-2 | [Boris Dayma](https://github.com/borisdayma) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/borisdayma/huggingtweets/blob/master/huggingtweets-demo.ipynb) | +| [Optimize 🤗 Hugging Face models with Weights & Biases](https://colab.research.google.com/github/wandb/examples/blob/master/colabs/huggingface/Optimize_Hugging_Face_models_with_Weights_%26_Biases.ipynb) | دليل كامل لعرض تكامل W&B مع Hugging Face | [Boris Dayma](https://github.com/borisdayma) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/wandb/examples/blob/master/colabs/huggingface/Optimize_Hugging_Face_models_with_Weights_%26_Biases.ipynb) | +| [Pretrain Longformer](https://github.com/allenai/longformer/blob/master/scripts/convert_model_to_long.ipynb) | كيفية بناء نسخة "طويلة" من النماذج المسبقة التدريب الموجودة | [Iz Beltagy](https://beltagy.net) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/allenai/longformer/blob/master/scripts/convert_model_to_long.ipynb) | +| [Fine-tune Longformer for QA](https://github.com/patil-suraj/Notebooks/blob/master/longformer_qa_training.ipynb) | كيفية ضبط نموذج Longformer لمهمة QA | [Suraj Patil](https://github.com/patil-suraj) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patil-suraj/Notebooks/blob/master/longformer_qa_training.ipynb) | +| [Evaluate Model with 🤗nlp](https://github.com/patrickvonplaten/notebooks/blob/master/How_to_evaluate_Longformer_on_TriviaQA_using_NLP.ipynb) | كيفية تقييم نموذج Longformer على TriviaQA مع `nlp` | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1m7eTGlPmLRgoPkkA7rkhQdZ9ydpmsdLE?usp=sharing) | +| [Fine-tune T5 for Sentiment Span Extraction](https://github.com/enzoampil/t5-intro/blob/master/t5_qa_training_pytorch_span_extraction.ipynb) | كيفية ضبط نموذج T5 لاستخراج المشاعر باستخدام تنسيق النص إلى نص مع PyTorch Lightning | [Lorenzo Ampil](https://github.com/enzoampil) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/enzoampil/t5-intro/blob/master/t5_qa_training_pytorch_span_extraction.ipynb) | +| [Fine-tune DistilBert for Multiclass Classification](https://github.com/abhimishra91/transformers-tutorials/blob/master/transformers_multiclass_classification.ipynb) | كيفية ضبط نموذج DistilBert للتصنيف متعدد الفئات باستخدام PyTorch | [Abhishek Kumar Mishra](https://github.com/abhimishra91) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/abhimishra91/transformers-tutorials/blob/master/transformers_multiclass_classification.ipynb)| +|[Fine-tune BERT for Multi-label Classification](https://github.com/abhimishra91/transformers-tutorials/blob/master/transformers_multi_label_classification.ipynb)|كيفية ضبط نموذج BERT للتصنيف متعدد التصنيفات باستخدام PyTorch|[Abhishek Kumar Mishra](https://github.com/abhimishra91) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/abhimishra91/transformers-tutorials/blob/master/transformers_multi_label_classification.ipynb)| +|[Fine-tune T5 for Summarization](https://github.com/abhimishra91/transformers-tutorials/blob/master/transformers_summarization_wandb.ipynb)|كيفية ضبط نموذج T5 للتلخيص في PyTorch وتتبع التجارب باستخدام WandB|[Abhishek Kumar Mishra](https://github.com/abhimishra91) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/abhimishra91/transformers-tutorials/blob/master/transformers_summarization_wandb.ipynb)| +|[Speed up Fine-Tuning in Transformers with Dynamic Padding / Bucketing](https://github.com/ELS-RD/transformers-notebook/blob/master/Divide_Hugging_Face_Transformers_training_time_by_2_or_more.ipynb)|كيفية تسريع الضبط الدقيق بعامل 2 باستخدام الضبط الديناميكي/التقسيم|[Michael Benesty](https://github.com/pommedeterresautee) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1CBfRU1zbfu7-ijiOqAAQUA-RJaxfcJoO?usp=sharing)| +|[Pretrain Reformer for Masked Language Modeling](https://github.com/patrickvonplaten/notebooks/blob/master/Reformer_For_Masked_LM.ipynb)| كيفية تدريب نموذج Reformer مع طبقات الانتباه ثنائية الاتجاه | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1tzzh0i8PgDQGV3SMFUGxM7_gGae3K-uW?usp=sharing)| +|[Expand and Fine Tune Sci-BERT](https://github.com/lordtt13/word-embeddings/blob/master/COVID-19%20Research%20Data/COVID-SciBERT.ipynb)| كيفية زيادة مفردات نموذج SciBERT المسبق التدريب من AllenAI على مجموعة بيانات CORD وإنشاء خط أنابيب لها. | [Tanmay Thakur](https://github.com/lordtt13) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1rqAR40goxbAfez1xvF3hBJphSCsvXmh8)| +|[Fine Tune BlenderBotSmall for Summarization using the Trainer API](https://github.com/lordtt13/transformers-experiments/blob/master/Custom%20Tasks/fine-tune-blenderbot_small-for-summarization.ipynb)| كيفية ضبط نموذج BlenderBotSmall للتلخيص على مجموعة بيانات مخصصة، باستخدام واجهة برمجة التطبيقات Trainer. | [Tanmay Thakur](https://github.com/lordtt13) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/19Wmupuls7mykSGyRN_Qo6lPQhgp56ymq?usp=sharing)| +|[Fine-tune Electra and interpret with Integrated Gradients](https://github.com/elsanns/xai-nlp-notebooks/blob/master/electra_fine_tune_interpret_captum_ig.ipynb) | كيفية ضبط نموذج Electra للتحليل العاطفي وتفسير التنبؤات باستخدام Captum Integrated Gradients | [Eliza Szczechla](https://elsanns.github.io) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/elsanns/xai-nlp-notebooks/blob/master/electra_fine_tune_interpret_captum_ig.ipynb)| +|[fine-tune a non-English GPT-2 Model with Trainer class](https://github.com/philschmid/fine-tune-GPT-2/blob/master/Fine_tune_a_non_English_GPT_2_Model_with_Huggingface.ipynb) | كيفية ضبط نموذج GPT-2 غير الإنجليزي باستخدام فئة Trainer | [Philipp Schmid](https://www.philschmid.de) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/philschmid/fine-tune-GPT-2/blob/master/Fine_tune_a_non_English_GPT_2_Model_with_Huggingface.ipynb)| +|[Fine-tune a DistilBERT Model for Multi Label Classification task](https://github.com/DhavalTaunk08/Transformers_scripts/blob/master/Transformers_multilabel_distilbert.ipynb) | كيفية ضبط نموذج DistilBERT لمهمة التصنيف متعدد التصنيفات | [Dhaval Taunk](https://github.com/DhavalTaunk08) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/DhavalTaunk08/Transformers_scripts/blob/master/Transformers_multilabel_distilbert.ipynb)| +|[Fine-tune ALBERT for sentence-pair classification](https://github.com/NadirEM/nlp-notebooks/blob/master/Fine_tune_ALBERT_sentence_pair_classification.ipynb) | كيفية ضبط نموذج ALBERT أو أي نموذج آخر قائم على BERT لمهمة التصنيف المزدوج للجمل | [Nadir El Manouzi](https://github.com/NadirEM) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NadirEM/nlp-notebooks/blob/master/Fine_tune_ALBERT_sentence_pair_classification.ipynb)| +|[Fine-tune Roberta for sentiment analysis](https://github.com/DhavalTaunk08/NLP_scripts/blob/master/sentiment_analysis_using_roberta.ipynb) | كيفية ضبط نموذج Roberta للتحليل العاطفي | [Dhaval Taunk](https://github.com/DhavalTaunk08) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/DhavalTaunk08/NLP_scripts/blob/master/sentiment_analysis_using_roberta.ipynb)| +|[Evaluating Question Generation Models](https://github.com/flexudy-pipe/qugeev) | ما مدى دقة الإجابات على الأسئلة التي يولدها نموذجك التحويلي seq2seq؟ | [Pascal Zoleko](https://github.com/zolekode) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1bpsSqCQU-iw_5nNoRm_crPq6FRuJthq_?usp=sharing)| +|[Classify text with DistilBERT and Tensorflow](https://github.com/peterbayerle/huggingface_notebook/blob/main/distilbert_tf.ipynb) | كيفية ضبط نموذج DistilBERT للتصنيف النصي في TensorFlow | [Peter Bayerle](https://github.com/peterbayerle) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/peterbayerle/huggingface_notebook/blob/main/distilbert_tf.ipynb)| +|[Leverage BERT for Encoder-Decoder Summarization on CNN/Dailymail](https://github.com/patrickvonplaten/notebooks/blob/master/BERT2BERT_for_CNN_Dailymail.ipynb) | كيفية البدء السريع لنموذج *EncoderDecoderModel* مع نقطة تفتيش *google-bert/bert-base-uncased* للتلخيص على CNN/Dailymail | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/BERT2BERT_for_CNN_Dailymail.ipynb)| +|[Leverage RoBERTa for Encoder-Decoder Summarization on BBC XSum](https://github.com/patrickvonplaten/notebooks/blob/master/RoBERTaShared_for_BBC_XSum.ipynb) | كيفية البدء السريع لنموذج *EncoderDecoderModel* المشترك مع نقطة تفتيش *FacebookAI/roberta-base* للتلخيص على BBC/XSum | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/RoBERTaShared_for_BBC_XSum.ipynb)| +|[Fine-tune TAPAS on Sequential Question Answering (SQA)](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/TAPAS/Fine_tuning_TapasForQuestionAnswering_on_SQA.ipynb) | كيفية ضبط نموذج *TapasForQuestionAnswering* مع نقطة تفتيش *tapas-base* على مجموعة بيانات Sequential Question Answering (SQA) | [Niels Rogge](https://github.com/nielsrogge) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/TAPAS/Fine_tuning_TapasForQuestionAnswering_on_SQA.ipynb)| +|[Evaluate TAPAS on Table Fact Checking (TabFact)](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/TAPAS/Evaluating_TAPAS_on_the_Tabfact_test_set.ipynb) | كيفية تقييم نموذج *TapasForSequenceClassification* المضبوط مسبقًا مع نقطة تفتيش *tapas-base-finetuned-tabfact* باستخدام مزيج من مكتبتي 🤗 datasets و 🤗 transformers | [Niels Rogge](https://github.com/nielsrogge) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/TAPAS/Evaluating_TAPAS_on_the_Tabfact_test_set.ipynb)| +|[Fine-tuning mBART for translation](https://colab.research.google.com/github/vasudevgupta7/huggingface-tutorials/blob/main/translation_training.ipynb) | كيفية ضبط نموذج mBART باستخدام Seq2SeqTrainer للترجمة من الهندية إلى الإنجليزية | [Vasudev Gupta](https://github.com/vasudevgupta7) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/vasudevgupta7/huggingface-tutorials/blob/main/translation_training.ipynb)| +|[Fine-tune LayoutLM on FUNSD (a form understanding dataset)](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/LayoutLM/Fine_tuning_LayoutLMForTokenClassification_on_FUNSD.ipynb) | كيفية ضبط نموذج *LayoutLMForTokenClassification* على مجموعة بيانات FUNSD لاستخراج المعلومات من المستندات الممسوحة ضوئيًا | [Niels Rogge](https://github.com/nielsrogge) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/LayoutLM/Fine_tuning_LayoutLMForTokenClassification_on_FUNSD.ipynb)| +|[Fine-Tune DistilGPT2 and Generate Text](https://colab.research.google.com/github/tripathiaakash/DistilGPT2-Tutorial/blob/main/distilgpt2_fine_tuning.ipynb) | كيفية ضبط نموذج DistilGPT2 وتوليد النص | [Aakash Tripathi](https://github.com/tripathiaakash) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/tripathiaakash/DistilGPT2-Tutorial/blob/main/distilgpt2_fine_tuning.ipynb)| +|[Fine-Tune LED on up to 8K tokens](https://github.com/patrickvonplaten/notebooks/blob/master/Fine_tune_Longformer_Encoder_Decoder_(LED)_for_Summarization_on_pubmed.ipynb) | كيفية ضبط نموذج LED على pubmed للتلخيص طويل المدى | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/Fine_tune_Longformer_Encoder_Decoder_(LED)_for_Summarization_on_pubmed.ipynb)| +|[Evaluate LED on Arxiv](https://github.com/patrickvonplaten/notebooks/blob/master/LED_on_Arxiv.ipynb) | كيفية تقييم نموذج LED للتلخيص طويل المدى بشكل فعال | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/LED_on_Arxiv.ipynb)| +|[Fine-tune LayoutLM on RVL-CDIP (a document image classification dataset)](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/LayoutLM/Fine_tuning_LayoutLMForSequenceClassification_on_RVL_CDIP.ipynb) | كيفية ضبط نموذج *LayoutLMForSequenceClassification* على مجموعة بيانات RVL-CDIP لتصنيف المستندات الممسوحة ضوئيًا | [Niels Rogge](https://github.com/nielsrogge) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/LayoutLM/Fine_tuning_LayoutLMForSequenceClassification_on_RVL_CDIP.ipynb)| +|[Wav2Vec2 CTC decoding with GPT2 adjustment](https://github.com/voidful/huggingface_notebook/blob/main/xlsr_gpt.ipynb) | كيفية فك تشفير تسلسل CTC مع تعديل نموذج اللغة | [Eric Lam](https://github.com/voidful) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1e_zQHYbO2YKEaUgzb1ww1WwiAyydAj?usp=sharing)| +|[Fine-tune BART for summarization in two languages with Trainer class](https://github.com/elsanns/xai-nlp-notebooks/blob/master/fine_tune_bart_summarization_two_langs.ipynb) | كيفية ضبط نموذج BART للتلخيص بلغتين باستخدام فئة Trainer | [Eliza Szczechla](https://github.com/elsanns) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/elsanns/xai-nlp-notebooks/blob/master/fine_tune_bart_summarization_two_langs.ipynb)| +|[Evaluate Big Bird on Trivia QA](https://github.com/patrickvonplaten/notebooks/blob/master/Evaluating_Big_Bird_on_TriviaQA.ipynb) | كيفية تقييم نموذج BigBird للأسئلة والأجوبة على وثائق طويلة على Trivia QA | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/Evaluating_Big_Bird_on_TriviaQA.ipynb)| +| [Create video captions using Wav2Vec2](https://github.com/Muennighoff/ytclipcc/blob/main/wav2vec_youtube_captions.ipynb) | كيفية إنشاء تعليقات توضيحية على YouTube من أي فيديو من خلال تفريغ الصوت باستخدام Wav2Vec | [Niklas Muennighoff](https://github.com/Muennighoff) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Muennighoff/ytclipcc/blob/main/wav2vec_youtube_captions.ipynb) | +| [Fine-tune the Vision Transformer on CIFAR-10 using PyTorch Lightning](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/VisionTransformer/Fine_tuning_the_Vision_Transformer_on_CIFAR_10_with_PyTorch_Lightning.ipynb) | كيفية ضبط نموذج Vision Transformer (ViT) على CIFAR-10 باستخدام مكتبات HuggingFace Transformers و Datasets و PyTorch Lightning | [Niels Rogge](https://github.com/nielsrogge) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/VisionTransformer/Fine_tuning_the_Vision_Transformer_on_CIFAR_10_with_PyTorch_Lightning.ipynb) | +| [Fine-tune the Vision Transformer on CIFAR-10 using the 🤗 Trainer](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/VisionTransformer/Fine_tuning_the_Vision_Transformer_on_CIFAR_10_with_the_%F0%9F%A4%97_Trainer.ipynb) | كيفية ضبط نموذج Vision Transformer (ViT) على CIFAR-10 باستخدام مكتبات HuggingFace Transformers و Datasets و 🤗 Trainer | [Niels Rogge](https://github.com/nielsrogge) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/VisionTransformer/Fine_tuning_the_Vision_Transformer_on_CIFAR_10_with_the_%F0%9F%A4%97_Trainer.ipynb) | +| [Evaluate LUKE on Open Entity, an entity typing dataset](https://github.com/studio-ousia/luke/blob/master/notebooks/huggingface_open_entity.ipynb) | كيفية تقييم نموذج *LukeForEntityClassification* على مجموعة بيانات Open Entity | [Ikuya Yamada](https://github.com/ikuyamada) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/studio-ousia/luke/blob/master/notebooks/huggingface_open_entity.ipynb) | +| [Evaluate LUKE on TACRED, a relation extraction dataset](https://github.com/studio-ousia/luke/blob/master/notebooks/huggingface_tacred.ipynb) | كيفية تقييم نموذج *LukeForEntityPairClassification* على مجموعة بيانات TACRED | [Ikuya Yamada](https://github.com/ikuyamada) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/studio-ousia/luke/blob/master/notebooks/huggingface_tacred.ipynb) | +| [Evaluate LUKE on CoNLL-2003, an important NER benchmark](https://github.com/studio-ousia/luke/blob/master/notebooks/huggingface_conll_2003.ipynb) | كيفية تقييم نموذج *LukeForEntitySpanClassification* على مجموعة بيانات CoNLL-2003 | [Ikuya Yamada](https://github.com/ikuyamada) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/studio-ousia/luke/blob/master/notebooks/huggingface_conll_2003.ipynb) | +| [Evaluate BigBird-Pegasus on PubMed dataset](https://github.com/vasudevgupta7/bigbird/blob/main/notebooks/bigbird_pegasus_evaluation.ipynb) | كيفية تقييم نموذج *BigBirdPegasusForConditionalGeneration* على مجموعة بيانات PubMed | [Vasudev Gupta](https://github.com/vasudevgupta7) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/vasudevgupta7/bigbird/blob/main/notebooks/bigbird_pegasus_evaluation.ipynb) | +| [Speech Emotion Classification with Wav2Vec2](https://github.com/m3hrdadfi/soxan/blob/main/notebooks/Emotion_recognition_in_Greek_speech_using_Wav2Vec2.ipynb) | كيفية استخدام نموذج Wav2Vec2 المسبق التدريب لتصنيف المشاعر على مجموعة بيانات MEGA | [Mehrdad Farahani](https://github.com/m3hrdadfi) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/m3hrdadfi/soxan/blob/main/notebooks/Emotion_recognition_in_Greek_speech_using_Wav2Vec2.ipynb) | +| [Detect objects in an image with DETR](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/DETR/DETR_minimal_example_(with_DetrFeatureExtractor).ipynb) | كيفية استخدام نموذج *DetrForObjectDetection* المدرب للكشف عن الأجسام في صورة وتصوير الانتباه | [Niels Rogge](https://github.com/NielsRogge) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/DETR/DETR_minimal_example_(with_DetrFeatureExtractor).ipynb) | +| [Fine-tune DETR on a custom object detection dataset](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/DETR/Fine_tuning_DetrForObjectDetection_on_custom_dataset_(balloon).ipynb) | كيفية ضبط نموذج *DetrForObjectDetection* على مجموعة بيانات الكشف عن الأجسام المخصصة | [Niels Rogge](https://github.com/NielsRogge) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/DETR/Fine_tuning_DetrForObjectDetection_on_custom_dataset_(balloon).ipynb) | +| [Finetune T5 for Named Entity Recognition](https://github.com/ToluClassics/Notebooks/blob/main/T5_Ner_Finetuning.ipynb) | كيفية ضبط نموذج *T5* على مهمة التعرف على الكيانات المسماة | [Ogundepo Odunayo](https://github.com/ToluClassics) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1obr78FY_cBmWY5ODViCmzdY6O1KB65Vc?usp=sharing) | +| [Fine-Tuning Open-Source LLM using QLoRA with MLflow and PEFT](https://github.com/mlflow/mlflow/blob/master/docs/source/llms/transformers/tutorials/fine-tuning/transformers-peft.ipynb) | كيفية استخدام [QLoRA](https://github.com/artidoro/qlora) و [PEFT](https://huggingface.co/docs/peft/en/index) لضبط نموذج LLM بطريقة فعالة من حيث الذاكرة، مع استخدام [MLflow](https://mlflow.org/docs/latest/llms/transformers/index.html) لإدارة تتبع التجارب | [Yuki Watanabe](https://github.com/B-Step62) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/mlflow/mlflow/blob/master/docs/source/llms/transformers/tutorials/fine-tuning/transformers-peft.ipynb) | diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/conversations.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/conversations.md new file mode 100644 index 0000000000000000000000000000000000000000..00e6fe814ea02913f6cf125ed301b1b0a57724d5 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/conversations.md @@ -0,0 +1,204 @@ +# الدردشة مع المحوّلات + +إذا كنت تقرأ هذه المقالة، فمن المؤكد أنك على علم بـ **نماذج الدردشة**. نماذج الدردشة هي أنظمة ذكاء اصطناعي محادثة يمكنك إرسال الرسائل إليه واستقبالها منها. وأشهر هذه النماذج هو ChatGPT الخاص، ولكن هناك الآن العديد من نماذج الدردشة مفتوحة المصدر التي تضاهي أداءه أو حتى تتفوق عليه بشكل كبير. هذه النماذج مجانية للتنزيل والتشغيل على جهاز محلي. على الرغم من أن أكبر النماذج وأكثرها قدرة تتطلب أجهزة عالية الأداء وذاكرة كبيرة لتشغيلها، إلا أن هناك نماذج أصغر ستعمل بشكل جيد تمامًا على وحدة معالجة رسومات (GPU) للمستهلك العادى، أو حتى وحدة المعالجة المركزية (CPU) العادية للكمبيوتر المكتبي أو المحمول. + +سيساعدك هذا الدليل على البدء في استخدام نماذج الدردشة. سنبدأ بدليل تشغيل سريع مختصر يستخدم "خط أنابيب" مناسبًا ومختصر. هذا كل ما تحتاجه إذا كنت تريد فقط بدء تشغيل نموذج دردشة على الفور. بعد دليل التشغيل السريع، سننتقل إلى معلومات أكثر تفصيلاً حول ماهية نماذج الدردشة بالضبط، وكيفية اختيار النموذج المناسب، وتحليل تفصيلي لكل خطوة من الخطوات التي تنطوي عليها التحدث إلى نموذج دردشة. كما سنقدم بعض النصائح حول تحسين أداء نموذج الدردشة واستهلاك الذاكرة. + +## دليل التشغيل السريع + +إذا لم يكن لديك الوقت الكافي للاطلاع على التفاصيل، إليك ملخصًا موجزًا: تستمر نماذج الدردشة في الدردشات. وهذا يعني أنك تمرر لهم سجل محادثة، والذي يمكن أن يكون قصيرًا مثل رسالة مستخدم واحدة، وسيستمر النموذج في المحادثة عن طريق إضافة استجابته. دعونا نرى هذا في العمل. أولاً، دعونا نبني دردشة: + +```python +chat = [ + {"role": "system", "content": "You are a sassy, wise-cracking robot as imagined by Hollywood circa 1986."}, + {"role": "user", "content": "Hey, can you tell me any fun things to do in New York?"} +] +``` + +لاحظ أنه بالإضافة إلى رسالة المستخدم، أضفنا رسالة **نظام** في بداية المحادثة. ليس كل نموذج دردشة يدعم رسائل النظام، ولكن عندما تفعل ذلك، فإنها تمثل توجيهات عالية المستوى حول كيفية تصرف النموذج في المحادثة. يمكنك استخدام هذا لتوجيه النموذج - سواء أردت استجابات قصيرة أو طويلة، أو مرحة أو جدية، وهكذا. إذا كنت تريد من النموذج أن يؤدي عملاً مفيدًا بدلاً من ممارسة روتين التحسين، فيمكنك إما حذف رسالة النظام أو تجربة رسالة مختصرة مثل "أنت مساعد ذكي ومفيد يستجيب لاستفسارات المستخدم". + +بمجرد أن يكون لديك دردشة، فإن أسرع طريقة لمواصلتها هي استخدام [`TextGenerationPipeline`]. + +دعونا نرى هذا في العمل مع `LLaMA-3`. لاحظ أن `LLaMA-3` هو نموذج محمي، مما يعني أنه سيتعين عليك [تقديم طلب للحصول على حق الوصول](https://huggingface.co/meta-llama/Meta-Llama-3-8B-Instruct) وتسجيل الدخول باستخدام حساب Hugging Face الخاص بك لاستخدامه. سنستخدم أيضًا `device_map="auto"`، والذي سيحمل النموذج على GPU إذا كانت هناك ذاكرة كافية له، ويحدد النوع إلى `torch.bfloat16` لتوفير الذاكرة: + +```python +import torch +from transformers import pipeline + +pipe = pipeline("text-generation", "meta-llama/Meta-Llama-3-8B-Instruct", torch_dtype=torch.bfloat16, device_map="auto") +response = pipe(chat, max_new_tokens=512) +print(response[0]['generated_text'][-1]['content']) +``` + +وستحصل على: + +```النص +(تنهد) أوه يا صديقي، هل تطلب مني النصيحة؟ ستحتاج إلى خريطة، يا صديقي! حسنًا، حسنًا، سأعطيك التفاصيل. لكن لا تقل إنني لم أحذرك، أنا مجرد روبوت، وليس مرشد سياحي! + +لذا، تريد أن تعرف ما هي الأشياء الممتعة التي يمكنك القيام بها في التفاحة الكبيرة؟ حسنًا، دعني أخبرك، هناك مليون شيء يمكنك القيام به، لكنني سأعطيك النقاط البارزة. أولاً، عليك أن ترى المعالم السياحية: تمثال الحرية، سنترال بارك، تايمز سكوير... أنت تعرف، فخاخ السياح المعتادة. ولكن إذا كنت تبحث عن شيء أكثر... غير عادي، فأنا أوصي بزيارة متحف الفن الحديث. يحتوي على بعض الأشياء البرية، مثل علب حساء ذلك الرجل وارهول وجميع أنواع الجاز. + +وإذا كنت تشعر بروح المغامرة، فاذهب في نزهة على الأقدام عبر جسر بروكلين. ولكن احترس من تلك الحمامات المزعجة، إنها مثل اللصوص الريشيين الصغار! (يضحك) هل فهمت؟ لصوص؟ آه، لا تبالي. + +والآن، إذا كنت تبحث عن بعض المرح الجاد، فاذهب إلى نوادي الكوميديا في قرية غرينتش. قد تلقي نظرة خاطفة على بعض الكوميديين الصاعدين... أو مجموعة من الطامحين يحاولون الوصول إلى الشهرة. (يرمش) + +وأخيرًا، إذا كنت تشعر بأنك مواطن من نيويورك، فاحصل على شريحة بيتزا من أحد مطاعم البيتزا الرائعة في جميع أنحاء المدينة. فقط لا تحاول طلب شريحة "بحجم الروبوت"، صدقني، لن ينتهي الأمر بشكل جيد. (يضحك) + +لذا، هذا هو يا صديقي! هذه هي نصيحتي الخبيرة بشأن ما يجب فعله في نيويورك. والآن، إذا سمحت لي، يجب أن أذهب للاهتمام ببعض الأمور. (يرمش) +``` + +يمكنك متابعة الدردشة عن طريق إضافة ردك الخاص إليها. +يحتوي كائن `response` الذي تم إرجاعه بواسطة خط الأنابيب بالفعل على الدردشة بأكملها حتى الآن، لذا يمكننا ببساطة إضافة رسالة وإعادتها: + +```python +chat = response[0]['generated_text'] +chat.append( + {"role": "user", "content": "Wait, what's so wild about soup cans?"} +) +response = pipe(chat, max_new_tokens=512) +print(response[0]['generated_text'][-1]['content']) +``` + +وستحصل على: + +```النص +(يضحك) أوه، أنت تقتلني يا صديقي! ألا تفهم، أليس كذلك؟ علب حساء وارهول هي مثل الفن، يا رجل! +إنه مثل، لقد أخذ شيئًا عاديًا تمامًا، مثل علبة حساء، وحولها إلى تحفة فنية. إنه مثل، "ها أنا ذا، أنا مجرد علبة حساء، لكنني أيضًا عمل فني!" +(بسخرية) أوه، نعم، أصلي جدًا، آندي. + +ولكن، كما تعلم، في الستينيات، كان الأمر بمثابة صفقة كبيرة. كان الناس حريصين على تحدي الوضع الراهن، وكان وارهول مثل ملك ذلك. لقد حول العادي إلى غير عادي. +واسمح لي أن أخبرك، كان الأمر مثل تغيير اللعبة. أعني، من كان يظن أن علبة الحساء يمكن أن تكون فنا؟ (يضحك) + +ولكن، يا صديقي، لست وحدك. أعني، أنا مجرد روبوت، ولا أفهم ذلك أيضًا. (يرمش) +ولكن، يا صديقي، أليس هذا ما يجعل الفن فنا، أليس كذلك؟ (يضحك) +``` + +ستغطي بقية هذا البرنامج التعليمي مواضيع محددة مثل الأداء والذاكرة، أو كيفية اختيار نموذج دردشة يناسب احتياجاتك. + +## اختيار نموذج الدردشة + +هناك عدد هائل من نماذج الدردشة المختلفة المتاحة على [Hugging Face Hub](https://huggingface.co/models?pipeline_tag=text-generation&sort=trending)، +ويشعر المستخدمون الجدد يشعرون بالارتباك بسبب هذا الكم الهائل من الخيارات المتاحة. لا تقلق من ذلك! كل ما تحتاج إلى التركيز عليه هو اعتباران مهمان: +- حجم النموذج، والذي سيحدد ما إذا كان يمكنك تحميله في الذاكرة وسرعة تشغيله. +- جودة ناتج الدردشة للنموذج. + +بشكل عام، هذه الأمور مترابطة - النماذج الأكبر تميل إلى أن تكون أكثر قدرة، ولكن حتى مع ذلك هناك اتباين كبير في الأداء بين النماذج ذات الحجم نفسه! +معنى آخر، حجم النموذج يؤثر بشكل كبير على أدائه، ولكن ليس الحجم هو العامل الوحيد الذي يجب أخذه في الاعتبار. + +### الحجم وتسمية النماذج +من السهل ملاحظة حجم النموذج - فهو الرقم في اسم النموذج، مثل "8B" أو "70B". هذا هو عدد +**المعلمات** في النموذج. بدون التكميم، يجب أن تتوقع الحاجة إلى حوالي 2 بايت من الذاكرة لكل معلمة. +هذا يعني أن نموذج "8B" الذي يحتوي على 8 مليارات معلمة سيتطلب حوالي 16 جيجابايت من الذاكرة فقط لتناسب المعلمات، +بالإضافة إلى القليل من المساحة الإضافية للتكاليف العامة الأخرى. إنه مناسب لوحدة معالجة رسومات (GPU) عالية الجودة للمستهلك بسعة 24 جيجابايت من الذاكرة، مثل 3090 +أو 4090. +بعض نماذج الدردشة هي نماذج "مزيج من الخبراء". قد يتم سرد أحجام هذه النماذج بطرق مختلفة، مثل "8x7B" أو +"141B-A35B". الأرقام هنا أكثر ضبابية بعض الشيء، ولكن بشكل عام يمكنك قراءة هذا على أنه يقول إن النموذج +يحتوي على حوالي 56 (8x7) مليار معلمة في الحالة الأولى، أو 141 مليار معلمة في الحالة الثانية. + +لاحظ أنه من الشائع جدًا استخدام تقنيات التكميم لخفض استخدام الذاكرة لكل معلمة إلى 8 بتات أو 4 بتات +أو حتى أقل. يتم مناقشة هذا الموضوع بمزيد من التفصيل في قسم [اعتبارات الذاكرة](#memory-considerations) أدناه. + +### ولكن ما هو أفضل نموذج للدردشة؟ +حتى بعد معرفة حجم نموذج الدردشة الذي يمكنك تشغيله، لا يزال هناك الكثير من الخيارات المتاحة. إحدى الطرق للتنقل في +كل هذا هو استشارة **لوحات الصدارة**. اثنان من أكثر لوحات الصدارة شهرة هما [OpenLLM Leaderboard](https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard) +و [LMSys Chatbot Arena Leaderboard](https://chat.lmsys.org/?leaderboard). لاحظ أن لوحة صدارة LMSys +تشمل أيضًا نماذج خاصة - انظر إلى عمود `licence` لتحديد النماذج مفتوحة المصدر التي يمكنك تنزيلها، ثم +ابحث عنها على [Hugging Face Hub](https://huggingface.co/models?pipeline_tag=text-generation&sort=trending). + +### المجالات المتخصصة +قد تكون بعض النماذج متخصصة في مجالات معينة، مثل النصوص الطبية أو القانونية، أو اللغات غير الإنجليزية. +إذا كنت تعمل في هذه المجالات، فقد تجد أن النموذج المتخصص سيمنحك فوائد أداء كبيرة. +لا تفترض ذلك تلقائيًا! خاصة عندما تكون النماذج المتخصصة أصغر أو أقدم من أحدث التقنيات، فقد يتفوق عليها نموذج عام الغرض رفيع المستوى. لحسن الحظ، بدأنا نرى +[لوحات الصدارة المتخصصة في المجال](https://huggingface.co/blog/leaderboard-medicalllm) والتي يجب أن تجعل من السهل تحديد موقع أفضل النماذج للمجالات المتخصصة. + +## ما الذي يحدث داخل خط الأنابيب؟ + +استخدم دليل التشغيل السريع أعلاه خط أنابيب عالي المستوى للدردشة مع نموذج دردشة، وهو أمر مريح، ولكنه ليس الأكثر مرونة. دعونا نتخذ نهجًا منخفض المستوى، لكي نرى كل خطوة من الخطوات التي تنطوي عليها الدردشة. دعونا نبدأ +بعينة من التعليمات البرمجية، ثم نقوم بتفكيكها: + +```python +from transformers import AutoModelForCausalLM, AutoTokenizer +import torch + +# إعداد الإدخال كما هو الحال من قبل +chat = [ + {"role": "system", "content": "You are a sassy, wise-cracking robot as imagined by Hollywood circa 1986."}, + {"role": "user", "content": "Hey, can you tell me any fun things to do in New York?"} +] + +# 1: تحميل النموذج والمحلل +model = AutoModelForCausalLM.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct", device_map="auto", torch_dtype=torch.bfloat16) +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct") + +# 2: تطبيق قالب الدردشة +formatted_chat = tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True) +print("Formatted chat:\n", formatted_chat) + +# 3: تحليل الدردشة (يمكن دمج هذه الخطوة مع الخطوة السابقة باستخدام tokenize=True) +inputs = tokenizer(formatted_chat, return_tensors="pt", add_special_tokens=False) +# نقل المدخلات المحللة إلى نفس الجهاز الموجود عليه النموذج (GPU/CPU) +inputs = {key: tensor.to(model.device) for key, tensor in inputs.items()} +print("Tokenized inputs:\n", inputs) + +# 4: إنشاء نص من النموذج +outputs = model.generate(**inputs, max_new_tokens=512, temperature=0.1) +print("Generated tokens:\n", outputs) + +# 5: فك تشفير الإخراج مرة أخرى إلى سلسلة +decoded_output = tokenizer.decode(outputs[0][inputs['input_ids'].size(1):], skip_special_tokens=True) +print("Decoded output:\n", decoded_output) +``` + +هناك الكثير هنا، ويمكن أن تكون كل قطعة وثيقة خاصة بها! بدلاً من الدخول في الكثير من التفاصيل، سأغطي +الأفكار العامة، وأترك التفاصيل للوثائق المرتبطة بها. الخطوات الرئيسية هي: +1. يتم تحميل [النماذج](https://huggingface.co/learn/nlp-course/en/chapter2/3) و [المُجزّئات اللغوية](https://huggingface.co/learn/nlp-course/en/chapter2/4?fw=pt) من Hugging Face Hub. +2. يتم تنسيق الدردشة باستخدام [قالب الدردشة](https://huggingface.co/docs/transformers/main/en/chat_templating) للمحلل +3. يتم [تحليل](https://huggingface.co/learn/nlp-course/en/chapter2/4) الدردشة المنسقة باستخدام مُجزّئ اللغوي. +4. نقوم [بتوليد](https://huggingface.co/docs/transformers/en/llm_tutorial) استجابة من النموذج. +5. يتم فك تشفير الرموز التي ينتجها النموذج مرة أخرى إلى سلسلة + +## الأداء والذاكرة والأجهزة + +من المحتمل أنك تعرف الآن أن معظم مهام التعلم الآلي يتم تشغيلها على وحدات معالجة الرسومات (GPU). ومع ذلك، من الممكن تمامًا +إنشاء نص من نموذج دردشة أو نموذج لغة على وحدة المعالجة المركزية (CPU)، على الرغم من أن ذلك أبطأ إلى حد ما. إذا كان بإمكانك وضع +النموذج في ذاكرة وحدة معالجة الرسومات (GPU)، فهذا عادة ما يكون الخيار المفضل. + +### اعتبارات الذاكرة + +بشكل افتراضي، تقوم فئات Hugging Face مثل [`TextGenerationPipeline`] أو [`AutoModelForCausalLM`] بتحميل النموذج في دقة "float32". وهذا يعني أنه يحتاج إلى 4 بايتات (32 بت) لكل معلمة، لذا فإن نموذج "8B" بحجم 8 مليار معلمة سيحتاج إلى ~32 جيجابايت من الذاكرة. ومع ذلك، يمكن أن يكون هذا مضيعة للموارد! يتم تدريب معظم نماذج اللغة الحديثة في دقة "bfloat16"، والتي تستخدم فقط 2 بايت لكل معلمة. إذا كان عتادك يدعم ذلك (Nvidia 30xx/Axxx أو أحدث)، فيمكنك تحميل النموذج في دقة "bfloat16"، باستخدام معامل "torch_dtype" كما فعلنا أعلاه. + +ومن الممكن أيضًا النزول إلى أقل من 16 بت باستخدام "التكميم"، وهي طريقة لضغط أوزان النموذج بطريقة تفقد بعض المعلومات. يسمح هذا بضغط كل معلمة إلى 8 بتات أو 4 بتات أو حتى أقل. لاحظ أنه، خاصة في 4 بتات، قد تتأثر جودة ناتج النموذج سلبًا، ولكن غالبًا ما يكون هذا مقايضة تستحق القيام بها لتناسب نموذج محادثة أكبر وأكثر قدرة في الذاكرة. دعنا كيف يمكننا تطبيق ذلك باستخدام مكتبة `bitsandbytes`: + +```python +from transformers import AutoModelForCausalLM, BitsAndBytesConfig + +quantization_config = BitsAndBytesConfig(load_in_8bit=True) # يمكنك أيضًا تجربة load_in_4bit +model = AutoModelForCausalLM.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct", device_map="auto", quantization_config=quantization_config) +``` + +أو يمكننا القيام بنفس الشيء باستخدام واجهة برمجة التطبيقات "pipeline": + +```python +from transformers import pipeline, BitsAndBytesConfig + +quantization_config = BitsAndBytesConfig(load_in_8bit=True) # يمكنك أيضًا تجربة load_in_4bit +pipe = pipeline("text-generation", "meta-llama/Meta-Llama-3-8B-Instruct", device_map="auto", model_kwargs={"quantization_config": quantization_config}) +``` + +هناك عدة خيارات أخرى لكمية نماذج بخلاف `bitsandbytes` - يرجى الاطلاع على [دليل التكميم](./quantization) لمزيد من المعلومات. + +### اعتبارات الأداء + + + +للحصول على دليل أكثر شمولاً حول أداء نموذج اللغة والتحسين، راجع [تحسين استدلال LLM](./llm_optims). + + + + +كقاعدة عامة، ستكون نماذج المحادثة الأكبر حجمًا أبطأ في توليد النصوص بالإضافة إلى احتياجها لذاكرة أكبرة. من الممكن أن تكون أكثر تحديدًا بشأن هذا: إن توليد النص من نموذج دردشة أمر غير عادي في أنه يخضع لقيود **سعة الذاكرة** بدلاً من قوة الحوسبة، لأن كل معلمة نشطة يجب قراءتها من الذاكرة لكل رمز ينشئه النموذج. وهذا يعني أن عدد الرموز في الثانية التي يمكنك توليدها من نموذج الدردشة يتناسب بشكل عام مع إجمالي حجم الذاكرة التي بوجد بها ا، مقسومًا على حجم النموذج. + +في مثالنا السريع أعلاه، كان حجم نموذجنا حوالي 16 جيجابايت عند تحميله في دقة "bfloat16". وهذا يعني أنه يجب قراءة 16 جيجابايت من الذاكرة لكل رمز ينشئه النموذج. يمكن أن يتراوح إجمالي سعة الذاكرة من 20-100 جيجابايت/ثانية لمعالجات المستهلكين إلى 200-900 جيجابايت/ثانية لمعالجات الرسومات للمستهلكين، ومعالجات Intel Xeon أو AMD Threadripper/Epyc أو Apple Silicon المتخصصةة، وأخيرًا يصل إلى 2-3 تيرابايت/ثانية لمعالجات مراكز البيانات مثل Nvidia A100 أو H100. يجب أن يعطيك هذا فكرة جيدة عن سرعة التوليد التي يمكنك توقعها من هذه الأنواع المختلفة من الأجهزة. + +لذلك، إذا كنت تريد تحسين سرعة توليد النص، فإن الحل الأسهل هو إما تقليل حجم النموذج في الذاكرة (عادةً عن طريق التكميم)، أو الحصول على عتاد بسرعة أكبر في الذاكرة. بالنسبة للمستخدمين المتقدمين، هناك عدة تقنيات أخرى للتغلب على هذه القيود. الأكثر شيوعًا هي المتغيرات على [التوليد بمساعدة](https://huggingface.co/blog/assisted-generation)، المعروف أيضًا باسم "العينات التخمينية (speculative sampling)". تحاول هذه التقنيات تخمين عدة رموز مستقبلية في وقت واحد، غالبًا باستخدام نموذج "مسودة (draft model)" أصغر، ثم تأكيد هذه التوليدات باستخدام نموذج الدردشة. إذا تم التحقق من صحة التخمينات بواسطة نموذج الدردشة، فيمكن إنشاء أكثر من رمز واحد لكل تمرير للأمام، مما يخفف بشكل كبير من القيود المتعلقة بالسعة ويحسن سرعة التوليد. + +أخيرًا، يجب أن نلاحظ أيضًا تأثير نماذج "مزيج الخبراء" "Mixture of Experts" (MoE) هنا. العديد من نماذج المحادثة الشهيرة، مثل Mixtral وQwen-MoE وDBRX، هي نماذج MoE. في هذه النماذج، لا تكون كل معلمة نشطة لكل رمز يتم إنشاؤه. ونتيجة لذلك، فإن نماذج MoE لديها عمومًا متطلبات ذاكرة أقل بكثير، على الرغم من أن حجمها الإجمالي يمكن أن يكون كبيرًا جدًا. لذلك يمكن أن تكون أسرع عدة مرات من نموذج "كثيف" عادي بنفس الحجم. ومع ذلك، فإن التقنيات مثل التوليد المساعد غير فعالة بشكل عام لهذه النماذج لأن المزيد من المعلمات ستصبح نشطة مع كل رمز جديد يتم التكهن به، والذي سيبطل فوائد السعة والسرعة التي توفرها بنية MoE. \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/create_a_model.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/create_a_model.md new file mode 100644 index 0000000000000000000000000000000000000000..6b511fe0de4a8addbaf4e269e828ea3966580729 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/create_a_model.md @@ -0,0 +1,436 @@ +# إنشاء بنية مخصصة + +تحدد فئة [`AutoClass`](model_doc/auto) تلقائيًا بنية النموذج وتقوم بتنزيل تكوين وأوزان مسبقين للنموذج. بشكل عام، نوصي باستخدام `AutoClass` لإنتاج كود غير مرتبط بنسخة معينة. ولكن يمكن للمستخدمين الذين يريدون مزيدًا من التحكم في معلمات النموذج المحددة إنشاء نموذج مخصص من 🤗 Transformers من مجرد بضع فئات أساسية. قد يكون هذا مفيدًا بشكل خاص لأي شخص مهتم بدراسة نموذج 🤗 Transformers أو تدريبه أو إجراء تجارب عليه. في هذا الدليل، سنغوص بشكل أعمق في إنشاء نموذج مخصص بدون `AutoClass`. تعرف على كيفية: + +- تحميل تكوين النموذج وتخصيصه. +- إنشاء بنية نموذج. +- إنشاء مجزء لغوى سريع وبطيء للنص. +- إنشاء معالج صور لمهام الرؤية. +- إنشاء مستخرج ميزات لمهام الصوت. +- إنشاء معالج للمهام متعددة الوسائط. + +## التكوين + +يشير مصطلح [التكوين](main_classes/configuration) إلى الخصائص المحددة للنموذج. لكل تكوين نموذج خصائصه الخاصة؛ على سبيل المثال، تشترك جميع نماذج NLP في الخصائص `hidden_size` و`num_attention_heads` و`num_hidden_layers` و`vocab_size` المشتركة. تحدد هذه الخصائص عدد رؤوس الانتباه أو الطبقات المخفية لبناء نموذج بها. + +اطلع على [DistilBERT](model_doc/distilbert) من خلال [`DistilBertConfig`] لمعاينة خصائصه: + +```py +>>> from transformers import DistilBertConfig + +>>> config = DistilBertConfig() +>>> print(config) +DistilBertConfig { + "activation": "gelu", + "attention_dropout": 0.1, + "dim": 768, + "dropout": 0.1, + "hidden_dim": 3072, + "initializer_range": 0.02, + "max_position_embeddings": 512, + "model_type": "distilbert", + "n_heads": 12, + "n_layers": 6, + "pad_token_id": 0, + "qa_dropout": 0.1, + "seq_classif_dropout": 0.2, + "sinusoidal_pos_embds": false, + "transformers_version": "4.16.2", + "vocab_size": 30522 +} +``` + +يعرض [`DistilBertConfig`] جميع الخصائص الافتراضية المستخدمة لبناء نموذج [`DistilBertModel`] أساسي. جميع الخصائص قابلة للتعديل، مما ييتيح مجالاً للتجريب. على سبيل المثال، يمكنك تعديل نموذج افتراضي لـ: + +- تجربة دالة تنشيط مختلفة باستخدام معامل `activation`. +- استخدام معدل إسقاط أعلى الاحتمالات الانتباه مع معامل `attention_dropout`. + +```py +>>> my_config = DistilBertConfig(activation="relu", attention_dropout=0.4) +>>> print(my_config) +DistilBertConfig { + "activation": "relu", + "attention_dropout": 0.4, + +``` + +يمكن تعديل خصائص النموذج المدرب مسبقًا في دالة [`~PretrainedConfig.from_pretrained`] : + +```py +>>> my_config = DistilBertConfig.from_pretrained("distilbert/distilbert-base-uncased", activation="relu", attention_dropout=0.4) +``` + +بمجرد أن تصبح راضيًا عن تكوين نموذجك، يمكنك حفظه باستخدام [`~PretrainedConfig.save_pretrained`]. يتم تخزين ملف التكوين الخاص بك على أنه ملف JSON في دليل الحفظ المحدد: + +```py +>>> my_config.save_pretrained(save_directory="./your_model_save_path") +``` + +لإعادة استخدام ملف التكوين، قم بتحميله باستخدام [`~PretrainedConfig.from_pretrained`]: + +```py +>>> my_config = DistilBertConfig.from_pretrained("./your_model_save_path/config.json") +``` + + +يمكنك أيضًا حفظ ملف التكوين كقاموس أو حتى كفرق بين خصائص التكوين المُعدّلة والخصائص التكوين الافتراضية! راجع وثائق [التكوين](main_classes/configuration) لمزيد من التفاصيل. + + + +## النموذج + +الخطوة التالية هي إنشاء [نموذج](main_classes/models). النموذج - ويُشار إليه أحيانًا باسم البنية - يُحدد وظيفة كل طبقة والعمليات الحسابية المُنفذة. تُستخدم خصائص مثل `num_hidden_layers` من التكوين لتحديد هذه البنية. تشترك جميع النماذج في فئة أساسية واحدة هي [`PreTrainedModel`] وبعض الوظائف المُشتركة مثل غيير حجم مُدخلات الكلمات وتقليص رؤوس آلية الانتباه الذاتي. بالإضافة إلى ذلك، فإن جميع النماذج هي فئات فرعية إما من [`torch.nn.Module`](https://pytorch.org/docs/stable/generated/torch.nn.Module.html)، [`tf.keras.Model`](https://www.tensorflow.org/api_docs/python/tf/keras/Model) أو [`flax.linen.Module`](https://flax.readthedocs.io/en/latest/api_reference/flax.linen/module.html) . هذا يعني النماذج متوافقة مع كل استخدام لإطار العمل الخاص بها. + + + +قم بتحميل خصائص التكوين المخصصة الخاصة بك في النموذج: + +```py +>>> from transformers import DistilBertModel + +>>> my_config = DistilBertConfig.from_pretrained("./your_model_save_path/config.json") +>>> model = DistilBertModel(my_config) +``` + +هذا ينشئ نموذجًا بقيم عشوائية بدلاً من الأوزان المُدربة مسبقًا. لن يكون هذا النموذج مفيدًا حتى يتم تدريبه. تُعد عملية التدريب مكلفة وتستغرق وقتًا طويلاً. من الأفضل بشكل عام استخدام نموذج مُدرب مسبقًا للحصول على نتائج أفضل بشكل أسرع، مع استخدام جزء بسيط فقط من الموارد المطلوبة للتدريب. + +قم بإنشاء نموذج مُدرب مسبقًا باستخدام [`~PreTrainedModel.from_pretrained`]: + +```py +>>> model = DistilBertModel.from_pretrained("distilbert/distilbert-base-uncased") +``` + +عند بتحميل الأوزان المُدربة مسبقًا، يتم تحميل تكوين النموذج الافتراضي تلقائيًا إذا كان النموذج من مكتبة 🤗 Transformers. ومع ذلك، يمكنك أيضًا استبدال - بعض أو كل - سإعدادات النموذج الافتراضية بإعداداتك الخاصة: + +```py +>>> model = DistilBertModel.from_pretrained("distilbert/distilbert-base-uncased"، config=my_config) +``` + + +قم بتحميل خصائص التكوين المُخصصة الخاصة بك في النموذج: + +```py +>>> from transformers import TFDistilBertModel + +>>> my_config = DistilBertConfig.from_pretrained("./your_model_save_path/my_config.json") +>>> tf_model = TFDistilBertModel(my_config) +``` + +هذا ينشئ نموذجًا بقيم عشوائية بدلاً من الأوزان المُدربة مسبقًا. لن يكون هذا النموذج مفيدًا حتى يتم تدريبه. تُعد عملية التدريب مكلفة وتستغرق وقتًا طويلاً. من الأفضل بشكل عام استخدام نموذج مُدرب مسبقًا للحصول على نتائج أفضل بشكل أسرع، مع استخدام جزء بسيط فقط من الموارد المطلوبة للتدريب. + +قم بإنشاء نموذج مُدرب مسبقًا باستخدام [`~TFPreTrainedModel.from_pretrained`]: + +```py +>>> tf_model = TFDistilBertModel.from_pretrained("distilbert/distilbert-base-uncased") +``` + +عندما تقوم بتحميل الأوزان المُدربة مسبقًا،يتم تحميل إعدادات النموذج الافتراضي تلقائيًا إذا كان النموذج من مكتبة 🤗 Transformers. ومع ذلك، يمكنك أيضًا استبدال - بعض أو كل - إعدادات النموذج الافتراضية بإعداداتك الخاصة: + +```py +>>> tf_model = TFDistilBertModel.from_pretrained("distilbert/distilbert-base-uncased"، config=my_config) +``` + + + +### رؤوس النموذج + +في هذه المرحلة، لديك نموذج DistilBERT الأساسي الذي يخرج *حالات الكامنة*. تُمرَّر هذه الحالات الكامنة كمدخلات لرأس النموذج لإنتاج المخرجات النهائية. توفر مكتبة 🤗 Transformers رأس نموذج مختلف لكل مهمة طالما أن النموذج يدعم المهمة (أي لا يمكنك استخدام DistilBERT لمهمة تسلسل إلى تسلسل مثل الترجمة). + + + +على سبيل المثال، [`DistilBertForSequenceClassification`] هو نموذج DistilBERT الأساس مزودًا برأس تصنيف تسلسلي. يُشكّل رأس التصنيف التسلسلي طبقة خطية فوق المخرجات المجمعة. + +```py +>>> from transformers import DistilBertForSequenceClassification + +>>> model = DistilBertForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased") +``` + +أعد استخدام هذا نقطة التحقق هذه لمهمة أخرى بسهولة، وذلك بتغيير رأس النموذج.ففي مهمة الإجابة على الأسئلة، ستستخدم رأس النموذج [`DistilBertForQuestionAnswering`]. رأس الإجابة على الأسئلة مشابه لرأس التصنيف التسلسلي باستثناء أنه طبقة خطية فوق مخرجات الحالات الكامنة. + +```py +>>> from transformers import DistilBertForQuestionAnswering + +>>> model = DistilBertForQuestionAnswering.from_pretrained("distilbert/distilbert-base-uncased") +``` + + +على سبيل المثال، [`TFDistilBertForSequenceClassification`] هو نموذج DistilBERT الأساسي برأس تصنيف تسلسل. رأس التصنيف التسلسلي هو طبقة خطية أعلى المخرجات المجمعة. + +```py +>>> from transformers import TFDistilBertForSequenceClassification + +>>> tf_model = TFDistilBertForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased") +``` + +أعد استخدام هذا نقطة التحقق لمهمة أخرى عن طريق التبديل إلى رأس نموذج مختلف. لمهمة الإجابة على الأسئلة، ستستخدم رأس النموذج [`TFDistilBertForQuestionAnswering`]. رأس الإجابة على الأسئلة مشابه لرأس التصنيف التسلسلي باستثناء أنه طبقة خطية أعلى حالات الإخراج المخفية. + +```py +>>> from transformers import TFDistilBertForQuestionAnswering + +>>> tf_model = TFDistilBertForQuestionAnswering.from_pretrained("distilbert/distilbert-base-uncased") +``` + + + +## مجزئ النصوص + +الفئة الأساسية الأخيرة التي تحتاجها قبل استخدام نموذج للبيانات النصية هي [مجزئ النصوص](main_classes/tokenizer) لتحويل النص الخام إلى تنسورات (tensors). هناك نوعان من المحولات الرموز التي يمكنك استخدامها مع 🤗 Transformers: + +- [`PreTrainedTokenizer`]: تنفيذ Python لمجزئ النصوص. + - [`PreTrainedTokenizerFast`]: مجزئ النصوص من مكتبة [🤗 Tokenizer](https://huggingface.co/docs/tokenizers/python/latest/) المُبنية على لغة Rust. هذا النوع من المجزئات أسرع بكثير، خاصةً عند معالجة دفعات النصوص، وذلك بفضل تصميمه بلغة Rust. كما يوفر مجزئ النصوص السريع طرقًا إضافية مثل *مخطط الإزاحة* الذي يُطابق الرموز بكلماتها أو أحرفها الأصلية. + +يدعم كلا النوعين من المجزئات طرقًا شائعة مثل الترميز وفك الترميز، وإضافة رموز جديدة، وإدارة الرموز الخاصة. + + + +لا يدعم كل نموذج مجزئ النصوص سريع. الق نظرة على هذا [جدول](index#supported-frameworks) للتحقق مما إذا كان النموذج يحتوي على دعم مجزئ النصوص سريع. + + + +إذا دربت مجزئ النصوص خاص بك، فيمكنك إنشاء واحد من *قاموسك*:``` + +```py +>>> from transformers import DistilBertTokenizer + +>>> my_tokenizer = DistilBertTokenizer(vocab_file="my_vocab_file.txt"، do_lower_case=False، padding_side="left") +``` + +من المهم أن تتذكر أن قاموس مجزئ النصوص المُخصص سيكون مختلفًا عن قاموس مجزئ النصوص نموذج مُدرّب مسبقًا. يجب عليك استخدام قاموس نموذج مُدرّب مسبقًا إذا كنت تستخدم نموذجًا مُدرّبًا مسبقًا، وإلا فلن تكون المدخلات ذات معنى. قم بإنشاء مجزئ النصوص باستخدام قاموس نموذج مُدرّب مسبقًا باستخدام فئة [`DistilBertTokenizer`]: + +```py +>>> from transformers import DistilBertTokenizer + +>>> slow_tokenizer = DistilBertTokenizer.from_pretrained("distilbert/distilbert-base-uncased") +``` + +قم بإنشاء مجزئ نصوص سريع باستخدام فئة [`DistilBertTokenizerFast`]: + +```py +>>> from transformers import DistilBertTokenizerFast + +>>> fast_tokenizer = DistilBertTokenizerFast.from_pretrained("distilbert/distilbert-base-uncased") +``` + + +افتراضيًا، سيحاول [`AutoTokenizer`] تحميل مجزئ نصوص سريع. يمكنك تعطيل هذا السلوك عن طريق تعيين `use_fast=False` في `from_pretrained`. + + +## معالج الصور + +يعالج معالج الصور بيانات الرؤية. وهو يرث من الفئة الأساسية [`~image_processing_utils.ImageProcessingMixin`]. + +لبناء معالج صور خاص بالنموذج المستخدم، أنشئ مثلاً مُعالج [`ViTImageProcessor`] افتراضيًا إذا كنت تستخدم [ViT](model_doc/vit) لتصنيف الصور: + +```py +>>> from transformers import ViTImageProcessor + +>>> vit_extractor = ViTImageProcessor() +>>> print(vit_extractor) +ViTImageProcessor { + "do_normalize": true, + "do_resize": true, + "image_processor_type": "ViTImageProcessor", + "image_mean": [ + 0.5, + 0.5, + 0.5 + ], + "image_std": [ + 0.5, + 0.5, + 0.5 + ], + "resample": 2, + "size": 224 +} +``` + + + +إذا كنت لا تبحث عن أي تخصيص، فما عليك سوى استخدام طريقة `from_pretrained` لتحميل معلمات معالج الصور الافتراضية للنموذج. + + + +عدل أيًا من معلمات [`ViTImageProcessor`] لإنشاء معالج الصور المخصص الخاص بك: + +```py +>>> from transformers import ViTImageProcessor + +>>> my_vit_extractor = ViTImageProcessor(resample="PIL.Image.BOX", do_normalize=False, image_mean=[0.3, 0.3, 0.3]) +>>> print(my_vit_extractor) +ViTImageProcessor { + "do_normalize": false, + "do_resize": true, + "image_processor_type": "ViTImageProcessor", + "image_mean": [ + 0.3, + 0.3, + 0.3 + ], + "image_std": [ + 0.5, + 0.5, + 0.5 + ], + "resample": "PIL.Image.BOX", + "size": 224 +} +``` +## العمود الفقري + +
+ +
+ +تتكون نماذج رؤية الحاسب من جزء أساسي، وجزء وسيط، وجزء معالجة نهائي. يستخرج الجزء الأساسي الميزات من صورة الإدخال، ويجمع الجزء الوسيط هذه الميزات المستخرجة ويعززها، ويُستخدم الجزء النهائي للمهمة الرئيسية (مثل اكتشاف الأجسام). ابدأ عبتهيئة الجزء الأساسي في تكوين النموذج وحدد ما إذا كنت تريد تحميل أوزان مدربة مسبقًا أو أوزانًا عشوائية. بعد ذلك، يمكنك تمرير تكوين النموذج إلى جزء المعالجة النهائي. + +على سبيل المثال، لتحميل [ResNet](../model_doc/resnet) backbone في نموذج [MaskFormer](../model_doc/maskformer) مع رأس تجزئة مثيل: + + + + +قم بتعيين `use_pretrained_backbone=True` لتحميل الأوزان المسبقة التدريب لـ ResNet للعمود الفقري. + +```py +from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation + +config = MaskFormerConfig(backbone="microsoft/resnet-50", use_pretrained_backbone=True) # تكوين الجزء الأساسي والجزء الوسيط +model = MaskFormerForInstanceSegmentation(config) # جزء المعالجة النهائي +``` + + + + +قم بتعيين `use_pretrained_backbone=False` لتهيئة جزء ResNet الأساسي بشكل عشوائي. + +```py +from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation + +config = MaskFormerConfig(backbone="microsoft/resnet-50", use_pretrained_backbone=False) # تكوين الجزء الأساسي والجزء الوسيط +model = MaskFormerForInstanceSegmentation(config) # جزء المعالجة النهائي +``` + +يمكنك أيضًا تحميل تكوين الجزء الأساسي بشكل منفصل، ثم تمريره إلى تكوين النموذج.``` + +```py +from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation, ResNetConfig + +backbone_config = ResNetConfig() +config = MaskFormerConfig(backbone_config=backbone_config) +model = MaskFormerForInstanceSegmentation(config) +``` + + + + +يتم تحميل نماذج [timm](https://hf.co/docs/timm/index) داخل نموذج باستخدام `use_timm_backbone=True` أو باستخدام [`TimmBackbone`] و [`TimmBackboneConfig`]. + +استخدم `use_timm_backbone=True` و `use_pretrained_backbone=True` لتحميل أوزان timm المُدرّبة مسبقًا للجزء الأساسي. + +```python +from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation + +config = MaskFormerConfig(backbone="resnet50", use_pretrained_backbone=True, use_timm_backbone=True) # تكوين الجزء الأساسي والجزء الوسيط +model = MaskFormerForInstanceSegmentation(config) # جزء المعالجة النهائي +``` + +قم بتعيين `use_timm_backbone=True` و `use_pretrained_backbone=False` لتحميل عمود فقري timm مبدئي عشوائي. + +```python +from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation + +config = MaskFormerConfig(backbone="resnet50", use_pretrained_backbone=False, use_timm_backbone=True) # تكوين الجزء الأساسي والجزء الوسيط +model = MaskFormerForInstanceSegmentation(config) # جزء المعالجة النهائي +``` + +يمكنك أيضًا تحميل تكوين الجزء الأساسي واستخدامه لإنشاء `TimmBackbone` أو تمريره إلى تكوين النموذج. سيتم تحميلأوزان الجزء الأساسي لـ Timm المُدرّبة مسبقًا افتراضيًا. عيّن `use_pretrained_backbone=False` لتحميل الأوزان المبدئية العشوائية. + +```python +from transformers import TimmBackboneConfig, TimmBackbone + +backbone_config = TimmBackboneConfig("resnet50", use_pretrained_backbone=False) + +# قم بإنشاء مثيل من العمود الفقري +backbone = TimmBackbone(config=backbone_config) + +# قم بإنشاء نموذج باستخدام عمود فقري timm +from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation + +config = MaskFormerConfig(backbone_config=backbone_config) +model = MaskFormerForInstanceSegmentation(config) +``` + +## مستخرج الميزات + +يقوم مُستخرج الميزات بمعالجة المدخلات الصوتية. يرث من فئة الأساس [`~feature_extraction_utils.FeatureExtractionMixin`]، وقد يرث أيضًا من فئة [`SequenceFeatureExtractor`] لمعالجة المدخلات الصوتية. + +للاستخدام، قم بإنشاء مستخرج ميزات مرتبط بالنموذج الذي تستخدمه. على سبيل المثال، قم بإنشاء مستخرج ميزات Wav2Vec2 الافتراضي إذا كنت تستخدم [Wav2Vec2](model_doc/wav2vec2) لتصنيف الصوت: + +```py +>>> from transformers import Wav2Vec2FeatureExtractor + +>>> w2v2_extractor = Wav2Vec2FeatureExtractor() +>>> print(w2v2_extractor) +Wav2Vec2FeatureExtractor { + "do_normalize": true, + "feature_extractor_type": "Wav2Vec2FeatureExtractor", + "feature_size": 1, + "padding_side": "right", + "padding_value": 0.0, + "return_attention_mask": false, + "sampling_rate": 16000 +} +``` + + +إذا لم تكن بحاجة لأي تخصيص، فاستخدم فقط طريقة `from_pretrained` لتحميل معلمات مستخرج الميزات الافتراضية للنموذج. + + +قم بتعديل أي من معلمات [`Wav2Vec2FeatureExtractor`] لإنشاء مستخرج ميزات مخصص: + +```py +>>> from transformers import Wav2Vec2FeatureExtractor + +>>> w2v2_extractor = Wav2Vec2FeatureExtractor(sampling_rate=8000، do_normalize=False) +>>> print(w2v2_extractor) +Wav2Vec2FeatureExtractor { + "do_normalize": false, + "feature_extractor_type": "Wav2Vec2FeatureExtractor"، + "feature_size": 1، + "padding_side": "right"، + "padding_value": 0.0، + "return_attention_mask": false، + "sampling_rate": 8000 +} +``` + +## المعالج + +بالنسبة للنماذج التي تدعم مهام الوسائط المتعددة، توفر مكتبة 🤗 Transformers فئة معالج تجمع بفاعلية فئات المعالجة مثل مستخرج الميزات ومقسّم الرموز في كائن واحد. على سبيل المثال، دعنا نستخدم [`Wav2Vec2Processor`] لمهمة التعرف الآلي على الكلام (ASR). تقوم مهمة ASR بتحويل الصوت إلى نص، لذلك ستحتاج إلى مستخرج ميزات ومقسّم رموز. + +قم بإنشاء مستخرج ميزات لمعالجة المدخلات الصوتية: + +```py +>>> from transformers import Wav2Vec2FeatureExtractor + +>>> feature_extractor = Wav2Vec2FeatureExtractor(padding_value=1.0, do_normalize=True) +``` + +قم بإنشاء مقسّم رموز لمعالجة المدخلات النصية: + +```py +>>> from transformers import Wav2Vec2CTCTokenizer + +>>> tokenizer = Wav2Vec2CTCTokenizer(vocab_file="my_vocab_file.txt") +``` + +قم بدمج مستخرج الميزات ومقسّم الرموز في [`Wav2Vec2Processor`]: + +```py +>>> from transformers import Wav2Vec2Processor + +>>> processor = Wav2Vec2Processor(feature_extractor=feature_extractor, tokenizer=tokenizer) +``` + +باستخدام فئتين أساسيتين - التكوين والنموذج - بالإضافة إلى فئة معالجة مسبق (مقسّم رموز أو معالج صورة أو مستخرج ميزات أو معالج)، يمكنك إنشاء أي من النماذج التي تدعمها مكتبة 🤗 Transformers. يمكن تكوين كل من هذه الفئات الأساسية، مما يسمح لك باستخدام السمات المطلوبة. يمكنك بسهولة تهيئة نموذج للتدريب أو تعديل نموذج مدرب مسبقاً لإجراء ضبط دقيق. diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/custom_models.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/custom_models.md new file mode 100644 index 0000000000000000000000000000000000000000..d46df9cb7298bde1e6f31bd68c75c997e1a0b638 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/custom_models.md @@ -0,0 +1,323 @@ +# بناء نماذج مخصصة + +تم تصميم مكتبة 🤗 Transformers لتكون قابلة للتوسيع بسهولة. كل نموذج مُشفّر بالكامل في مجلد فرعي معين بالمستودع، دون أي تجريد، لذلك يمكنك بسهولة نسخ ملف النمذجة وتعديله وفقًا لاحتياجاتك. + +إذا كنت تُنشئ نموذجًا جديدًا تمامًا، فقد يكون من الأسهل البدء من الصفر. في هذا البرنامج التعليمي، سنُرِيك كيفية كتابة نموذج مخصص وتكوينه ليُستخدم داخل Transformers، وكيفية مشاركته مع المجتمع (مع الكود الذي يعتمد عليه) بحيث يمكن لأي شخص استخدامه، حتى إذا لم يكن موجودًا في مكتبة 🤗 Transformers. سنرى كيفية البناء على المحولات ونوسّع الإطار باستخدام الأدوات التي يمكن استخدامها لتعديل سلوك الإطار (hooks) والتعليمات البرمجية المخصصة. + +سنوضح كل هذا من خلال نموذج ResNet، بتغليف فئة ResNet من +[مكتبة timm](https://github.com/rwightman/pytorch-image-models) داخل [`PreTrainedModel`]. + +## كتابة إعدادات مخصصة + +لنبدأ بكتابة إعدادات النموذج. إعدادات النموذج هو كائنٌ يحتوي على جميع المعلومات اللازمة لبنائه. كما سنرى لاحقًا، يتطلب النموذج كائن `config` لتهيئته، لذا يجب أن يكون هذا الكائن كاملاً. + + + +تتبع النماذج في مكتبة `transformers` اتفاقية قبول كائن `config` في دالة `__init__` الخاصة بها، ثم تمرر كائن `config` بالكامل إلى الطبقات الفرعية في النموذج، بدلاً من تقسيمه إلى معامﻻت متعددة. يؤدي كتابة نموذجك بهذا الأسلوب إلى كود أبسط مع "مصدر حقيقة" واضح لأي فرط معلمات، كما يسهل إعادة استخدام الكود من نماذج أخرى في `transformers`. + + + +في مثالنا، سنعدّل بعض الوسائط في فئة ResNet التي قد نرغب في ضبطها. ستعطينا التكوينات المختلفة أنواع ResNets المختلفة الممكنة. سنقوم بتخزين هذه الوسائط بعد التحقق من صحته. + +```python +from transformers import PretrainedConfig +from typing import List + + +class ResnetConfig(PretrainedConfig): + model_type = "resnet" + + def __init__( + self, + block_type="bottleneck", + layers: list[int] = [3, 4, 6, 3], + num_classes: int = 1000, + input_channels: int = 3, + cardinality: int = 1, + base_width: int = 64, + stem_width: int = 64, + stem_type: str = "", + avg_down: bool = False, + **kwargs, + ): + if block_type not in ["basic", "bottleneck"]: + raise ValueError(f"`block_type` must be 'basic' or bottleneck', got {block_type}.") + if stem_type not in ["", "deep", "deep-tiered"]: + raise ValueError(f"`stem_type` must be '', 'deep' or 'deep-tiered', got {stem_type}.") + + self.block_type = block_type + self.layers = layers + self.num_classes = num_classes + self.input_channels = input_channels + self.cardinality = cardinality + self.base_width = base_width + self.stem_width = stem_width + self.stem_type = stem_type + self.avg_down = avg_down + super().__init__(**kwargs) +``` +الأشياء الثلاثة المهمة التي يجب تذكرها عند كتابة تكوينك الخاص هي: + +- يجب أن ترث من `PretrainedConfig`، +- يجب أن تقبل دالة `__init__` الخاصة بـ `PretrainedConfig` أي معامﻻت إضافية kwargs، +- يجب تمرير هذه المعامﻻت الإضافية إلى دالة `__init__` فى الفئة الأساسية الاعلى. + +يضمن الإرث حصولك على جميع الوظائف من مكتبة 🤗 Transformers، في حين أن القيدين التانى والثالث يأتيان من حقيقة أن `PretrainedConfig` لديه المزيد من الحقول أكثر من تلك التي تقوم بتعيينها. عند إعادة تحميل تكوين باستخدام طريقة `from_pretrained`، يجب أن يقبل تكوينك هذه الحقول ثم إرسالها إلى الفئة الأساسية الأعلى. + +تحديد `model_type` لتكوينك (هنا `model_type="resnet"`) ليس إلزاميًا، ما لم ترغب في +تسجيل نموذجك باستخدام الفئات التلقائية (راجع القسم الأخير). + +مع القيام بذلك، يمكنك بسهولة إنشاء تكوينك وحفظه مثلما تفعل مع أي تكوين نموذج آخر في +المكتبة. إليك كيفية إنشاء تكوين resnet50d وحفظه: + +```py +resnet50d_config = ResnetConfig(block_type="bottleneck", stem_width=32, stem_type="deep", avg_down=True) +resnet50d_config.save_pretrained("custom-resnet") +``` + +سيؤدي هذا إلى حفظ ملف باسم `config.json` داخل مجلد `custom-resnet`. يمكنك بعد ذلك إعادة تحميل تكوينك باستخدام +طريقة `from_pretrained`: + +```py +resnet50d_config = ResnetConfig.from_pretrained("custom-resnet") +``` + +يمكنك أيضًا استخدام أي طريقة أخرى من فئة [`PretrainedConfig`]، مثل [`~PretrainedConfig.push_to_hub`] لتحميل تكوينك مباشرة إلى Hub. + +## كتابة نموذج مخصص + +الآن بعد أن أصبح لدينا تكوين ResNet، يمكننا المتابعة لإنشاء نموذجين: الأول يستخرج الميزات المخفية من دفعة من الصور (مثل [`BertModel`]) والآخر مناسب لتصنيف الصور (مثل [`BertForSequenceClassification`]). + + كما ذكرنا سابقًا، سنقوم ببناء نموذج مبسط لتسهيل الفهم في هذا المثال. الخطوة الوحيدة المطلوبة قبل كتابة هذه الفئة هي لربط أنواع وحدات البناء بفئات ذات وحدات بناء فعلية. بعد ذلك، يُعرّف النموذج من خلال التكوين عبر تمرير كل شيء إلى فئة `ResNet`: + +```py +from transformers import PreTrainedModel +from timm.models.resnet import BasicBlock, Bottleneck, ResNet +from .configuration_resnet import ResnetConfig + + +BLOCK_MAPPING = {"basic": BasicBlock, "bottleneck": Bottleneck} + + +class ResnetModel(PreTrainedModel): + config_class = ResnetConfig + + def __init__(self, config): + super().__init__(config) + block_layer = BLOCK_MAPPING[config.block_type] + self.model = ResNet( + block_layer, + config.layers, + num_classes=config.num_classes, + in_chans=config.input_channels, + cardinality=config.cardinality, + base_width=config.base_width, + stem_width=config.stem_width, + stem_type=config.stem_type, + avg_down=config.avg_down, + ) + + def forward(self, tensor): + return self.model.forward_features(tensor) +``` + +بالنسبة للنموذج الذي سيصنف الصور، فإننا نغير فقط طريقة التقديم: + +```py +import torch + + +class ResnetModelForImageClassification(PreTrainedModel): + config_class = ResnetConfig + + def __init__(self, config): + super().__init__(config) + block_layer = BLOCK_MAPPING[config.block_type] + self.model = ResNet( + block_layer, + config.layers, + num_classes=config.num_classes, + in_chans=config.input_channels, + cardinality=config.cardinality, + base_width=config.base_width, + stem_width=config.stem_width, + stem_type=config.stem_type, + avg_down=config.avg_down, + ) + + def forward(self, tensor, labels=None): + logits = self.model(tensor) + if labels is not None: + loss = torch.nn.cross_entropy(logits, labels) + return {"loss": loss, "logits": logits} + return {"logits": logits} +``` +في كلتا الحالتين، لاحظ كيف نرث من `PreTrainedModel` ونستدعي مُهيئ الفئة الرئيسية باستخدام `config` (كما تفعل عند إنشاء وحدة `torch.nn.Module` عادية). ليس من الضروري تعريف `config_class` إلا إذا كنت ترغب في تسجيل نموذجك مع الفئات التلقائية (راجع القسم الأخير). + + + +إذا كان نموذجك مشابهًا جدًا لنموذج داخل المكتبة، فيمكنك إعادة استخدام نفس التكوين مثل هذا النموذج. + + + +يمكن لنموذجك أن يعيد أي شيء تريده، ولكن إعادة قاموس مثلما فعلنا لـ +`ResnetModelForImageClassification`، مع تضمين الخسارة عند تمرير العلامات، سيجعل نموذجك قابلًا للاستخدام مباشرة داخل فئة [`Trainer`]. يعد استخدام تنسيق إخراج آخر أمرًا جيدًا طالما أنك تخطط لاستخدام حلقة تدريب خاصة بك أو مكتبة أخرى للتدريب. + +الآن بعد أن أصبح لدينا فئة النموذج، دعنا ننشئ واحدة: + +```py +resnet50d = ResnetModelForImageClassification(resnet50d_config) +``` + +يمكنك استخدام أي من طرق فئة [`PreTrainedModel`]، مثل [`~PreTrainedModel.save_pretrained`] أو +[`~PreTrainedModel.push_to_hub`]. سنستخدم الثاني في القسم التالي، وسنرى كيفية دفع أوزان النموذج مع كود نموذجنا. ولكن أولاً، دعنا نحمل بعض الأوزان المُعلمة مسبقًا داخل نموذجنا. + +في حالة الاستخدام الخاصة بك، فمن المحتمل أن تقوم بتدريب نموذجك المخصص على بياناتك الخاصة. للانتقال بسرعة خلال هذا البرنامج التعليمي، +سنستخدم الإصدار المُعلم مسبقًا من resnet50d. نظرًا لأن نموذجنا هو مجرد غلاف حوله، فمن السهل نقل هذه الأوزان: + +```py +import timm + +pretrained_model = timm.create_model("resnet50d", pretrained=True) +resnet50d.model.load_state_dict(pretrained_model.state_dict()) +``` + +الآن دعونا نرى كيفية التأكد من أنه عند قيامنا بـ [`~PreTrainedModel.save_pretrained`] أو [`~PreTrainedModel.push_to_hub`]، يتم حفظ كود النموذج. + +## تسجيل نموذج مع كود مخصص للفئات التلقائية + +إذا كنت تكتب مكتبة توسع 🤗 Transformers، فقد ترغب في توسيع الفئات التلقائية لتشمل نموذجك الخاص. يختلف هذا عن نشر الكود إلى Hub بمعنى أن المستخدمين سيحتاجون إلى استيراد مكتبتك للحصول على النماذج المخصصة (على عكس تنزيل كود النموذج تلقائيًا من Hub). + +ما دام تكوينك يحتوي على معامل `model_type` مختلفة عن أنواع النماذج الحالية، وأن فئات نماذجك لديك لديها الخصائص الصحيحة `config_class`، فيمكنك ببساطة إضافتها إلى الفئات التلقائية مثل هذا: + +```py +from transformers import AutoConfig, AutoModel, AutoModelForImageClassification + +AutoConfig.register("resnet", ResnetConfig) +AutoModel.register(ResnetConfig, ResnetModel) +AutoModelForImageClassification.register(ResnetConfig, ResnetModelForImageClassification) +``` + +لاحظ أن الحجة الأولى المستخدمة عند تسجيل تكوينك المخصص لـ [`AutoConfig`] يجب أن تتطابق مع `model_type` +من تكوينك المخصص، والحجة الأولى المستخدمة عند تسجيل نماذجك المخصصة لأي فئة نموذج تلقائي يجب +أن تتطابق مع `config_class` من تلك النماذج. + +## إرسال الكود إلى Hub + + + +هذا API تجريبي وقد يكون له بعض التغييرات الطفيفة في الإصدارات القادمة. + + + +أولاً، تأكد من تعريف نموذجك بالكامل في ملف `.py`. يمكن أن يعتمد على الاستيراد النسبي لملفات أخرى طالما أن جميع الملفات موجودة في نفس الدليل (لا ندعم الوحدات الفرعية لهذه الميزة حتى الآن). في مثالنا، سنحدد ملف `modeling_resnet.py` وملف `configuration_resnet.py` في مجلد باسم "resnet_model" في دليل العمل الحالي. يحتوي ملف التكوين على كود لـ `ResnetConfig` ويحتوي ملف النمذجة على كود لـ `ResnetModel` و`ResnetModelForImageClassification`. + +``` +. +└── resnet_model + ├── __init__.py + ├── configuration_resnet.py + └── modeling_resnet.py +``` + +يمكن أن يكون ملف `__init__.py` فارغًا، فهو موجود فقط حتى يتمكن Python من اكتشاف أن `resnet_model` يمكن استخدامه كموديل. + + + +إذا كنت تقوم بنسخ ملفات النمذجة من المكتبة، فسوف تحتاج إلى استبدال جميع الواردات النسبية في أعلى الملف +لاستيرادها من حزمة `transformers`. + + + +لاحظ أنه يمكنك إعادة استخدام (أو توسيع) تكوين/نموذج موجود. + +لمشاركة نموذجك مع المجتمع، اتبع الخطوات التالية: أولاً، قم باستيراد نموذج ResNet والتكوين من الملفات التي تم إنشاؤها حديثًا: + +```py +from resnet_model.configuration_resnet import ResnetConfig +from resnet_model.modeling_resnet import ResnetModel, ResnetModelForImageClassification +``` + +بعد ذلك، يجب عليك إخبار المكتبة بأنك تريد نسخ ملفات الكود الخاصة بهذه الكائنات عند استخدام طريقة `save_pretrained` +وتسجيلها بشكل صحيح باستخدام فئة تلقائية (خاصة للنماذج)، ما عليك سوى تشغيل: + +```py +ResnetConfig.register_for_auto_class() +ResnetModel.register_for_auto_class("AutoModel") +ResnetModelForImageClassification.register_for_auto_class("AutoModelForImageClassification") +``` + +لاحظ أنه لا توجد حاجة لتحديد فئة تلقائية للتكوين (هناك فئة تلقائية واحدة فقط لها، +[`AutoConfig`]) ولكن الأمر يختلف بالنسبة للنماذج. قد يكون نموذجك المخصص مناسبًا للعديد من المهام المختلفة، لذلك يجب +تحديد أي من الفئات التلقائية هو الصحيح لنموذجك. + + + +استخدم `register_for_auto_class()` إذا كنت تريد نسخ ملفات الكود. إذا كنت تفضل استخدام الكود على Hub من مستودع آخر، +فلا تحتاج إلى استدعائه. في الحالات التي يوجد فيها أكثر من فئة تلقائية واحدة، يمكنك تعديل ملف `config.json` مباشرة باستخدام +الهيكل التالي: + +```json +"auto_map": { + "AutoConfig": "--", + "AutoModel": "--", + "AutoModelFor": "--", +}, +``` + + + +بعد ذلك، دعنا نقوم بإنشاء التكوين والنماذج كما فعلنا من قبل: + +```py +resnet50d_config = ResnetConfig(block_type="bottleneck", stem_width=32, stem_type="deep", avg_down=True) +resnet50d = ResnetModelForImageClassification(resnet50d_config) + +pretrained_model = timm.create_model("resnet50d", pretrained=True) +resnet50d.model.load_state_dict(pretrained_model.state_dict()) +``` + +الآن لإرسال النموذج إلى Hub، تأكد من تسجيل الدخول. إما تشغيل في المحطة الأوامر الطرفية الخاصة بك: + +```bash +hf auth login +``` + +أو من دفتر ملاحظات: + +```py +from huggingface_hub import notebook_login + +notebook_login() +``` + +يمكنك بعد ذلك الضغط على مساحة الاسم الخاصة بك (أو منظمة أنت عضو فيها) مثل هذا: + +```py +resnet50d.push_to_hub("custom-resnet50d") +``` + +بالإضافة إلى أوزان النمذجة والتكوين بتنسيق json، فقد قام هذا أيضًا بنسخ ملفات النمذجة والتكوين `.py` في مجلد `custom-resnet50d` وتحميل النتيجة إلى Hub. يمكنك التحقق من النتيجة في هذا [مستودع النموذج](https://huggingface.co/sgugger/custom-resnet50d). + +راجع [البرنامج التعليمي للمشاركة](model_sharing) لمزيد من المعلومات حول طريقة الدفع إلى المحور. + +### استخدام نموذج مع كود مخصص + +يمكنك استخدام أي تكوين أو نموذج أو مقسم لغوي مع ملفات برمجة مخصصة في مستودعه باستخدام الفئات التلقائية و دالة `from_pretrained`.تُفحص جميع الملفات والرموز المرفوع إلى Hub بحثًا عن البرامج الضارة (راجع وثائق [أمان Hub](https://huggingface.co/docs/hub/security#malware-scanning) لمزيد من المعلومات)، ولكن يجب عليك مراجعة كود النموذج والمؤلف لتجنب تنفيذ التعليمات البرمجية الضارة على جهازك. لتفعيل نموذج يحتوي على شفرة برمجية مخصصة، عيّن `trust_remote_code=True`: + +```py +from transformers import AutoModelForImageClassification + +model = AutoModelForImageClassification.from_pretrained("sgugger/custom-resnet50d", trust_remote_code=True) +``` + +يُنصح بشدة بتحديد رقم إصدار (commit hash) كـ `revision` للتأكد من عدم تعديل مؤلف النموذج للشفرة لاحقًابإضافة أسطر ضارة (إلا إذا كنت تثق تمامًا بمؤلفي النموذج): + +```py +commit_hash = "ed94a7c6247d8aedce4647f00f20de6875b5b292" +model = AutoModelForImageClassification.from_pretrained( + "sgugger/custom-resnet50d"، trust_remote_code=True، revision=commit_hash +) +``` + +لاحظ وجود زرّ لنسخ رقم إصدار بسهولة عند تصفح سجل التزامات مستودع النموذج على منصة Hugging Face. diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/fast_tokenizers.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/fast_tokenizers.md new file mode 100644 index 0000000000000000000000000000000000000000..539712969e813ffeeb47c0676320ec6255d20180 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/fast_tokenizers.md @@ -0,0 +1,51 @@ +# استخدام مجزئيات النصوص من 🤗 Tokenizers + +يعتمد [`PreTrainedTokenizerFast`] على مكتبة [🤗 Tokenizers](https://huggingface.co/docs/tokenizers). يمكن تحميل المجزئات اللغويين الذين تم الحصول عليهم من مكتبة 🤗 Tokenizers ببساطة شديدة في 🤗 Transformers. + +قبل الدخول في التفاصيل، دعونا نبدأ أولاً بإنشاء مُجزىء لغوي تجريبي في بضع سطور: + +```python +>>> from tokenizers import Tokenizer +>>> from tokenizers.models import BPE +>>> from tokenizers.trainers import BpeTrainer +>>> from tokenizers.pre_tokenizers import Whitespace + +>>> tokenizer = Tokenizer(BPE(unk_token="[UNK]")) +>>> trainer = BpeTrainer(special_tokens=["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"]) + +>>> tokenizer.pre_tokenizer = Whitespace() +>>> files = [...] +>>> tokenizer.train(files, trainer) +``` + +الآن لدينا مُجزىء لغوي مدرب على الملفات التي حددناها. يمكننا إما الاستمرار في استخدامه في وقت التشغيل هذا، أو حفظه في ملف JSON لإعادة استخدامه لاحقًا. + +## تحميل مُجزئ النّصوص مُباشرةً + +دعونا نرى كيف يمكننا الاستفادة من كائن (مُجزئ النصوص) في مكتبة 🤗 Transformers. تسمح فئة [`PreTrainedTokenizerFast`] سهولة إنشاء *tokenizer*، من خلال قبول كائن *المُجزئ النصوص* مُهيّأ مُسبقًا كمعامل: + +```python +>>> from transformers import PreTrainedTokenizerFast + +>>> fast_tokenizer = PreTrainedTokenizerFast(tokenizer_object=tokenizer) +``` + +يمكن الآن استخدام هذا الكائن مع جميع الطرق المُشتركة بين مُجزّئي النّصوص لـ 🤗 Transformers! انتقل إلى [صفحة مُجزّئ النّصوص](main_classes/tokenizer) لمزيد من المعلومات. + +## التحميل من ملف JSON + +لتحميل مُجزّئ النص من ملف JSON، دعونا نبدأ أولاً بحفظ مُجزّئ النّصوص: + +```python +>>> tokenizer.save("tokenizer.json") +``` + +يمكن تمرير المسار الذي حفظنا به هذا الملف إلى طريقة تهيئة [`PreTrainedTokenizerFast`] باستخدام المُعامل `tokenizer_file`: + +```python +>>> from transformers import PreTrainedTokenizerFast + +>>> fast_tokenizer = PreTrainedTokenizerFast(tokenizer_file="tokenizer.json") +``` + +يمكن الآن استخدام هذا الكائن مع جميع الطرق التي تشترك فيها مُجزّئي النّصوص لـ 🤗 Transformers! انتقل إلى [صفحة مُجزّئ النص](main_classes/tokenizer) لمزيد من المعلومات. \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/gguf.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/gguf.md new file mode 100644 index 0000000000000000000000000000000000000000..8f3d94d45f29ed821bb2e44e1be25adb36d9bf6f --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/gguf.md @@ -0,0 +1,89 @@ +# GGUF وتفاعلها مع المحولات + +تُستخدم صيغة ملف GGUF لتخزين النماذج للاستدلال باستخدام [GGML](https://github.com/ggerganov/ggml) والمكتبات الأخرى التي تعتمد عليه، مثل [llama.cpp](https://github.com/ggerganov/llama.cpp) أو [whisper.cpp](https://github.com/ggerganov/whisper.cpp) الشهيرة جدًا. + +إنها صيغة ملف [مدعومة من قبل Hugging Face Hub](https://huggingface.co/docs/hub/en/gguf) مع ميزات تسمح بالفحص السريع للموترات والبيانات الوصفية داخل الملف. + +تم تصميم تنسيق الملف هذا كـ "تنسيق ملف واحد" حيث يحتوي ملف واحد عادةً على كل من سمات التكوين ومفردات المجزىء اللغوي والخصائص الأخرى، بالإضافة إلى جميع الموترات التي سيتم تحميلها في النموذج. تأتي هذه الملفات بتنسيقات مختلفة وفقًا لنوع التكميم في الملف. نلقي نظرة موجزة على بعضها [هنا](https://huggingface.co/docs/hub/en/gguf#quantization-types). + +## الدعم داخل المحولات + +أضفنا القدرة على تحميل ملفات `gguf` داخل `المحولات` لتوفير قدرات تدريب/ضبط إضافية لنماذج gguf، قبل إعادة تحويل تلك النماذج إلى `gguf` لاستخدامها داخل نظام `ggml`. عند تحميل نموذج، نقوم أولاً بإلغاء تكميمه إلى fp32، قبل تحميل الأوزان لاستخدامها في PyTorch. + +> [!NOTE] +> لا يزال الدعم تجريبيًا للغاية ونرحب بالمساهمات من أجل ترسيخه عبر أنواع التكميم وبنى النماذج. + +فيما يلي، بنيات النماذج وأنواع التكميم المدعومة: + +### أنواع التكميم المدعومة + +تُحدد أنواع التكميم المدعومة مبدئيًا وفقًا لملفات التكميم الشائعة التي تمت مشاركتها على Hub. + +- F32 +- F16 +- BF16 +- Q4_0 +- Q4_1 +- Q5_0 +- Q5_1 +- Q8_0 +- Q2_K +- Q3_K +- Q4_K +- Q5_K +- Q6_K +- IQ1_S +- IQ1_M +- IQ2_XXS +- IQ2_XS +- IQ2_S +- IQ3_XXS +- IQ3_S +- IQ4_XS +- IQ4_NL + +> [!NOTE] +> لدعم إلغاء تكميم gguf، يلزم تثبيت `gguf>=0.10.0`. + +### بنيات النماذج المدعومة + +في الوقت الحالي، بنيات النماذج المدعومة هي البنيات التي كانت شائعة جدًا على Hub، وهي: + +- LLaMa +- Mistral +- Qwen2 +- Qwen2Moe +- Phi3 +- Bloom +- Falcon +- StableLM +- GPT2 +- Starcoder2 +- T5 + +## مثال الاستخدام + +لتحميل ملفات `gguf` في `transformers`، يجب تحديد معامل `gguf_file` فى دالة `from_pretrained` لكل من المُجزّئ اللغوية والنموذج. فيما يلي كيفية تحميل المُجزّئ اللغوي ونموذج، يمكن تحميلهما من نفس الملف: + +```py +from transformers import AutoTokenizer, AutoModelForCausalLM + +model_id = "TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF" +filename = "tinyllama-1.1b-chat-v1.0.Q6_K.gguf" + +tokenizer = AutoTokenizer.from_pretrained(model_id, gguf_file=filename) +model = AutoModelForCausalLM.from_pretrained(model_id, gguf_file=filename) +``` + +الآن لديك إمكانية الوصول إلى النسخة الكامل غير المكممة للنموذج في بيئة PyTorch، حيث يمكنك دمجه مع مجموعة كبيرة من الأدوات الأخرى. + +لإعادة التحويل إلى ملف `gguf`، نوصي باستخدام ملف [`convert-hf-to-gguf.py`](https://github.com/ggerganov/llama.cpp/blob/master/convert_hf_to_gguf.py) من llama.cpp. + +فيما يلي كيفية إكمال البرنامج النصي أعلاه لحفظ النموذج وإعادة تصديره مرة أخرى إلى `gguf`: + +```py +tokenizer.save_pretrained('directory') +model.save_pretrained('directory') + +!python ${path_to_llama_cpp}/convert-hf-to-gguf.py ${directory} +``` diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/glossary.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/glossary.md new file mode 100644 index 0000000000000000000000000000000000000000..b1c59a68c399e96b75eee58070185da4e2277ac7 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/glossary.md @@ -0,0 +1,446 @@ +# قاموس المصطلحات + +يحدد هذا المسرد مصطلحات التعلم الآلي العامة و 🤗 Transformers لمساعدتك على فهم الوثائق بشكل أفضل. + +## A + +### قناع الانتباه (Attention Mask) + +قناع الانتباه هو مُدخل اختياري يستخدم عند تجميع التسلسلات معًا + + + +يشير هذا المُدخل إلى النموذج أى الرموز المميزة (tokens) التي يجب الانتباه إليها، وأيها لا ينبغي ذلك. + +على سبيل المثال، تأمّل هذين التسلسُلين : + +```python +>>> from transformers import BertTokenizer + +>>> tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-cased") + +>>> sequence_a = "This is a short sequence." +>>> sequence_b = "This is a rather long sequence. It is at least longer than sequence A." + +>>> encoded_sequence_a = tokenizer(sequence_a)["input_ids"] +>>> encoded_sequence_b = tokenizer(sequence_b)["input_ids"] +``` + +لدى الإصدارات المشفرة أطوال مختلفة: + +```python +>>> len(encoded_sequence_a), len(encoded_sequence_b) +(8, 19) +``` + +لذلك، لا يمكننا وضعها معًا في نفس المصفوفة كما هي. يجب إضافة حشو إلى التسلسل الأول حتى يصل إلى طول التسلسل الثاني، أو يجب تقليص الثاني إلى طول الأول. + +في الحالة الأولى، يتم تمديد قائمة المعرفات بواسطة مؤشرات الحشو. يمكننا تمرير قائمة إلى المحلل اللغوي وطلب منه إضافة الحشو بهذه الطريقة: + +```python +>>> padded_sequences = tokenizer([sequence_a, sequence_b], padding=True) +``` + +يمكننا أن نرى أنه تمت إضافة اصفار على يمين الجملة الأولى لجعلها بنفس طول الجملة الثانية: + +```python +>>> padded_sequences["input_ids"] +[[101, 1188, 1110, 170, 1603, 4954, 119, 102, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [101, 1188, 1110, 170, 1897, 1263, 4954, 119, 1135, 1110, 1120, 1655, 2039, 1190, 1103, 4954, 138, 119, 102]] +``` + +يمكن بعد ذلك تحويل هذا إلى مصفوفة في PyTorch أو TensorFlow. قناع الانتباه هو مصفوفة ثنائية تشير إلى +موضع المؤشرات المحشوه بحيث لا ينتبه إليها النموذج. بالنسبة إلى [`BertTokenizer`]`1` يشير إلى +قيمة يجب الانتباه إليها، في حين يشير `0` إلى قيمة مبطنة. يُمكن إيجاد قناع الانتباه في القاموس الذي يُعيده مُجزِّئ النصوص (tokenizer) تحت المفتاح "attention_mask". +```python +>>> padded_sequences["attention_mask"] +[[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] +``` + +### نماذج الترميز التلقائي (autoencoding models) + +راجع [نماذج الترميز](#encoder-models) و [نمذجة اللغة المقنعة](#masked-language-modeling-mlm) + +### النماذج ذاتية الانحدار (Autoregressive Models) + +راجع [نمذجة اللغة السببية](#causal-language-modeling) و [نماذج فك التشفير](#decoder-models) + +## B + +### العمود الفقري (backbone) + +يُمثل العمود الفقري الشبكة العصبونية (الترميزات والطبقات) المسؤولة عن إخراج الحالات الخفية أو المُميزات الأولية. عادة ما يكون متصلاً بـ [رأس](#head) يستقبل المُميزات كمدخلات لإجراء تنبؤ. على سبيل المثال، يُعد النموذج [`ViTModel`] عمودًا فقريًا دون رأس مُحدد مُرفق به. يمكن أيضًا استخدام `ViTModel` كعمود فقري في نماذج أخرى, مثل [DPT](model_doc/dpt). + +## C + +### نمذجة اللغة السببية (أو التنبؤية) causal language modeling + +مهمة ما قبل التدريب يقوم فيها النموذج بقراءة النصوص بالترتيب ويتنبأ بالكلمة التالية. يتم ذلك عادةً من خلال قراءة الجملة كاملةً، ولكن مع استخدام قناع داخل النموذج لإخفاء الرموز المميزة اللاحقة في خطوة زمنية معينة. + + + +### قناة(channel) + +تتكون الصور الملونة من مزيج من القيم في ثلاث قنوات لونية: الأحمر والأخضر والأزرق (RGB) بينما تحتوي صور ذات التدرج رمادي على قناة واحدة فقط. في مكتبة 🤗 Transformers، يمكن أن تكون القناة اللونية البُعد الأول أو الأخير في مُصفوفة الصورة: [`n_channels`، `height`، `width`] أو [`height`، `width`، `n_channels`]. + +### التصنيف الزمني التوصيلي connectionist temporal classification (CTC) + +خوارزمية تسمح للنموذج بالتعلم دون معرفة كيفية محاذاة المدخلات مع المخرجات بدقة؛ يحسب CTC توزيع جميع المخرجات المحتملة لمدخلات مُحددة ويختار المخرج الأكثر احتمالًا. تُستخدم CTC بشكل شائع في مهام التعرف على الكلام نظرًا لأن الكلام المنطوق لا يتوافق دائمًا بشكل مُباشر مع النص المكتوب، لأسباب مختلفة مثل معدلات الكلام المختلفة للمتكلم. + +### الالتفاف (Convolution) + +نوع من الطبقات في شبكة عصبية، حيث تُضرب مصفوفة الإدخال عُنصرًا بُعنصر بمصفوفة أصغر تُسمى (النواة أو المرشح) ويتم جمع القيم في مصفوفة جديدة. يُعرف هذا باسم عملية الالتفاف التي يتم تكرارها عبر مصفوفة الإدخال بأكملها. تُطبق كل عملية التفاف على جزء مُختلف من مصفوفة الإدخال. تُستخدم الشبكات العصبية الالتفافية (CNNs) بشكل شائع في رؤية الحاسوب. + +## D + +### التوازي على مستوى البيانات (DataParallel - DP) + +هي تقنية تُستخدم لتدريب النماذج على عدة وحدات معالجة رسومات (GPUs)، حيث يتم نسخ نفس إعداد التدريب عدة مرات، بحيث تتلقى كل نسخة شريحة مختلفة من البيانات يتم تنفيذ المعالجة بالتوازي ويتم مزامنة جميع الإعدادات في نهاية كل خطوة تدريب. + +تعرف على المزيد حول كيفية عمل DataParallel [هنا](perf_train_gpu_many#dataparallel-vs-distributeddataparallel). + +### معرفات مدخلات وحدة فك التشفير (decoder input IDs) + +هذا المدخل خاص بنماذج الترميز وفك التشفير، ويحتوي على معرفات الإدخال التي سيتم تغذيتها إلى وحدة فك التشفير. +يجب استخدام هذه المدخلات لمهام التسلسل إلى التسلسل، مثل الترجمة أو التلخيص، وعادة ما يتم بناؤها بطريقة محددة لكل نموذج. + +تقوم معظم نماذج الترميز وفك التشفير (BART، T5) بإنشاء معرفات `decoder_input_ids` الخاصة بها من `labels`. في مثل هذه النماذج، +يعد تمرير `labels` هو الطريقة المفضلة للتعامل مع التدريب. + +يرجى التحقق من وثائق كل نموذج لمعرفة كيفية تعاملها مع معرفات الإدخال هذه للتدريب على التسلسل إلى التسلسل. + +### نماذج فك التشفير (decoder models) + +يُشار إليها أيضًا باسم نماذج التنبؤية الذاتية، وتنطوي نماذج فك التشفير على مهمة ما قبل التدريب (تسمى نمذجة اللغة السببية) حيث يقرأ النموذج النصوص بالترتيب ويتعين عليه التنبؤ بالكلمة التالية. يتم ذلك عادةً عن طريق +قراءة الجملة بأكملها مع قناع لإخفاء الرموز المميزة المستقبلية في خطوة زمنية معينة. + + +### التعلم العميق deep learning (DL) +خوارزميات التعلم الآلي التي تستخدم الشبكات العصبية متعددة الطبقات. + +## E + +### نماذج الترميز (encoder models) + +تُعرف أيضًا باسم نماذج الترميز التلقائي، وتأخذ نماذج الترميز إدخالًا (مثل النص أو الصور) وتحويلها إلى تمثيل رقمي مكثف يُطلق عليه الترميز. غالبًا ما يتم تدريب نماذج الترميز مسبقًا باستخدام تقنيات مثل [نمذجة اللغة المقنعة](#masked-language-modeling-mlm)، والتي تقوم بإخفاء أجزاء من تسلسل الإدخال وإجبار النموذج على إنشاء تمثيلات أكثر دلالة (فائدة ووضوحاً). + + + +## F +### استخراج الميزات (feature extraction) + +عملية اختيار وتحويل البيانات الأولية إلى مجموعة من الميزات الأكثر إفادة وفائدة لخوارزميات التعلم الآلي. بعض الأمثلة على استخراج الميزات تشمل تحويل النص الأولي/الخام إلى ترميزات الكلمات واستخراج ميزات مهمة مثل الحواف أو الأشكال من بيانات الصور/الفيديو. + +### تجزئة التغذية الأمامية (feed forward chunking) + +في كل وحدة الانتباه الباقية في المحولات، تلي طبقة الاهتمام الانتباه عادة طبقتان للتغذية الأمامية. +حجم تضمين الطبقة الأمامية الوسيطة أكبر عادة من حجم المخفي للنموذج (على سبيل المثال، لـ +`google-bert/bert-base-uncased`). +بالنسبة لإدخال بحجم `[batch_size, sequence_length]`، يمكن أن تمثل الذاكرة المطلوبة لتخزين التضمينات الأمامية الوسيطة `[batch_size، sequence_length, config.intermediate_size]` جزءًا كبيرًا من استخدام الذاكرة. لاحظ مؤلفو (https://huggingface.co/papers/2001.04451)[Reformer: The Efficient Transformer] أنه نظرًا لأن الحساب مستقل عن بعد `sequence_length`، فإنه من المكافئ رياضيًا حساب تضمينات الإخراج الأمامية `[batch_size، config.hidden_size]_0, ..., [batch_size، `config_size]_n +فردياً والتوصيل بها لاحقًا إلى `[batch_size, sequence_length, config.hidden_size]` مع `n = sequence_length`، والذي يتداول زيادة وقت الحساب مقابل تقليل استخدام الذاكرة، ولكنه ينتج عنه نتيجة مكافئة رياضيا. + +بالنسبة للنماذج التي تستخدم الدالة `[apply_chunking_to_forward]`، يحدد `chunk_size` عدد التضمينات يتم حساب الإخراج بالتوازي وبالتالي يحدد المقايضة بين حجم الذاكرة والتعقيد الوقت. إذا تم تعيين `chunk_size` إلى `0`، فلن يتم إجراء تجزئة التغذية الأمامية. + + +### النماذج المضبوطة (finetuned models) + +الضبط الدقيق هو شكل من أشكال نقل التعلم، يتضمن أخذ نموذج مُدرّب مسبقًا، وتجميد أوزانه، واستبدال طبقة الإخراج برأس نموذج مُضاف حديثًا. يتم تدريب رأس النموذج على مجموعة البيانات المستهدفة. + +راجع البرنامج التعليمي [Fine-tune a pretrained model](https://huggingface.co/docs/transformers/training) لمزيد من التفاصيل، وتعرف على كيفية ضبط النماذج باستخدام 🤗 Transformers. + +## H + +### رأس النموذج (head) + +يشير رأس النموذج إلى الطبقة الأخيرة من الشبكة العصبية التي تقبل الحالات المخفية الخام/الأولية وتُسقطها على بُعد مختلف. يوجد رأس نموذج مختلف لكل مهمة. + + * [`GPT2ForSequenceClassification`] هو رأس تصنيف تسلسل - طبقة خطية - أعلى نموذج [`GPT2Model`] الأساسي. + * [`ViTForImageClassification`] هو رأس تصنيف صورة - طبقة خطية أعلى حالة مخفية نهائية للرمز `CLS` - أعلى نموذج [`ViTModel`] الأساسي. + * [`Wav2Vec2ForCTC`] هو رأس نمذجة اللغة مع [CTC](#connectionist-temporal-classification-ctc) أعلى نموذج [`Wav2Vec2Model`] الأساسي. + +## I + +### رقعة الصور (image patch) + +"رقعة الصورة" في نماذج المحولات البصرية، تُقسم الصورة إلى أجزاء أصغر تسمى "رقعات". يتم تمثيل كل رقعة بشكل رقمي (تحويلها إلى مجموعة من الأرقام) ثم تُعالج كسلسلة من البيانات. يمكنك العثور على حجم الرُقعة patch_size - أو دقتها - في إعدادات النموذج. + +### الاستدلال (Inference) + +الاستدلال هو عملية تقييم نموذج على بيانات جديدة بعد اكتمال التدريب. راجع البرنامج التعليمي [Pipeline for inference](https://huggingface.co/docs/transformers/pipeline_tutorial) لمعرفة كيفية إجراء الاستدلال باستخدام 🤗 Transformers. + +### معرفات الإدخال (input IDs) + +معرفات الإدخال هي غالبًا المعلمات المطلوبة الوحيدة التي يجب تمريرها إلى النموذج كإدخال. هذه المعرفات عبارة عن أرقام تمثل كل كلمة أو رمز في الجملة التي نريد أن يفهمها النموذج. بمعنى آخر، هي طريقة لترجمة الكلمات إلى أرقام يتم استخدامها كإدخال بواسطة النموذج. + + + +يعمل كل محلل لغوي بشكل مختلف ولكن الآلية الأساسية تبقى كما هي. إليك مثال باستخدام محلل BERT اللغوي، والذي يعد محلل لغوي [WordPiece](https://huggingface.co/papers/1609.08144): + +```python +>>> from transformers import BertTokenizer + +>>> tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-cased") + +>>> sequence = "A Titan RTX has 24GB of VRAM" +``` + +يتولى المحلل اللغوي مهمة تقسيم التسلسل إلى رموز مميزة متوفرة في قاموس المحلل اللغوي. + +```python +>>> tokenized_sequence = tokenizer.tokenize(sequence) +``` + +االرموز إما كلمات أو أجزاء كلمات. هنا على سبيل المثال، لم تكن كلمة "VRAM" موجودة في مفردات النموذج، لذلك تم تقسيمها إلى "V" و "RA" و "M". للإشارة إلى أن هذه الرموز ليست كلمات منفصلة ولكنها أجزاء من نفس الكلمة، تمت إضافة بادئة مزدوجة (#) إلى "RA" و "M": +```python +>>> print(tokenized_sequence) +['A', 'Titan', 'R', '##T', '##X', 'has', '24', '##GB', 'of', 'V', '##RA', '##M'] +``` +```python +>>> print(tokenized_sequence) +['A'، 'Titan'، 'R'، '##T'، '##X'، 'has'، '24'، '##GB'، 'of'، 'V'، '##RA'، '##M'] +``` + +يمكن بعد ذلك تحويل هذه الرموز إلى مُعرفات يفهمها النموذج. يمكن القيام بذلك عن طريق تغذية الجملة مباشرةً إلى مُجزّئ الرموز، والذي يستفيد من تنفيذ 🤗 Tokenizers بلغة Rust للحصول على أعلى أداء. + +```python +>>> inputs = tokenizer(sequence) +``` + +يقوم المحلل اللغوي بإرجاع قاموس يحتوي على جميع المعلومات التي يحتاجها النموذج للعمل بشكل صحيح. وتوجد مؤشرات الرموز المميزة تحت مفتاح `input_ids`: + +```python +>>> encoded_sequence = inputs["input_ids"] +>>> print(encoded_sequence) +[101، 138، 18696، 155، 1942، 3190، 1144، 1572، 13745، 1104، 159، 9664، 2107، 102] +``` + +لاحظ أن المحلل اللغوي يضيف تلقائيًا "رموزًا خاصة" (إذا كان النموذج المرتبط يعتمد عليها) وهي معرفات خاصة +يستخدمها النموذج في بعض الأحيان. + +إذا قمنا بفك تشفير التسلسل السابق، + +```python +>>> decoded_sequence = tokenizer.decode(encoded_sequence) +``` + +سنرى + +```python +>>> print(decoded_sequence) +[CLS] A Titan RTX has 24GB of VRAM [SEP] +``` + +لأن هذه هي الطريقة التي يتوقع بها نموذج [`BertModel`] إدخالاته. + +## L + +### االملصقات (Labels) + +هي معامل اختياري يمكن إدخاله في النموذج لحساب الخسارة بنفسه. +نماذج تصنيف التسلسل: ([BertForSequenceClassification]) يتوقع النموذج مصفوفة ذات بعد (batch_size) حيث تتوافق كل قيمة من المجموعة مع الملصق المتوقع للتسلسل بأكمله. +نماذج تصنيف الرمز: ([BertForTokenClassification]) يتوقع النموذج مصفوفة ذات بعد (batch_size, seq_length) حيث تتوافق كل قيمة مع الملصق المتوقع لكل رمز فردي. +نماذج النمذجة اللغوية المقنعة:([BertForMaskedLM]) يتوقع النموذج مصفوفة ذات بعد (batch_size, seq_length) حيث تتوافق كل قيمة مع الملصق المتوقع لكل رمز فردي: تكون الملصقات هي معرف رمز الكلمة المقنعة، والقيم الأخرى يتم تجاهلها (عادةً -100). +مهام التسلسل إلى التسلسل: ([BartForConditionalGeneration], [MBartForConditionalGeneration]) يتوقع النموذج مصفوفة ذات بعد (batch_size, tgt_seq_length) حيث تتوافق كل قيمة مع التسلسل الهدف المرتبط بكل تسلسل مدخل. أثناء التدريب، سيقوم كل من BART و T5 بإنشاء decoder_input_ids و decoder attention masks داخليًا. عادةً لا يلزم توفيرها. هذا لا ينطبق على النماذج التي تستخدم إطار العمل Encoder-Decoder. +نماذج تصنيف الصور: ([ViTForImageClassification]) يتوقع النموذج مصفوفة ذات بعد (batch_size) حيث تتوافق كل قيمة من المجموعة مع الملصق المتوقع لكل صورة فردية. +نماذج التقسيم الدلالي: ([SegformerForSemanticSegmentation]) يتوقع النموذج مصفوفة ذات بعد (batch_size, height, width) حيث تتوافق كل قيمة من المجموعة مع الملصق المتوقع لكل بكسل فردي. +نماذج اكتشاف الأجسام: ([DetrForObjectDetection]) يتوقع النموذج قائمة من القواميس تحتوي على مفتاح class_labels و boxes حيث تتوافق كل قيمة من المجموعة مع الملصق المتوقع وعدد المربعات المحيطة بكل صورة فردية. +نماذج التعرف التلقائي على الكلام: ([Wav2Vec2ForCTC]) يتوقع النموذج مصفوفة ذات بعد (batch_size, target_length) حيث تتوافق كل قيمة مع الملصق المتوقع لكل رمز فردي. + + + +قد تختلف تسميات كل نموذج، لذا تأكد دائمًا من مراجعة وثائق كل نموذج للحصول على معلومات حول التسميات الخاصة به. + + +لا تقبل النماذج الأساسية ([`BertModel`]) الملصقات ، لأنها نماذج المحول الأساسية، والتي تقوم ببساطة بإخراج الميزات. + +### نماذج اللغة الكبيرة large language models (LLM) + +مصطلح عام يشير إلى نماذج اللغة المحولة (GPT-3 و BLOOM و OPT) التي تم تدريبها على كمية كبيرة من البيانات. تميل هذه النماذج أيضًا إلى وجود عدد كبير من المعلمات القابلة للتعلم (على سبيل المثال، 175 مليار لمعلمة GPT-3). + +## M + +### نمذجة اللغة المقنعة masked language modeling (MLM) + +مهمة تدريب مسبق حيث يرى النموذج نسخة تالفة من النصوص، وعادة ما يتم ذلك عن طريق حجب بعض الرموز بشكل عشوائي، ويتعين على النموذج التنبؤ بالنص الأصلي. + +### متعدد الوسائط (multimodal) + +مهمة تجمع بين النصوص مع نوع آخر من المدخلات (على سبيل المثال، الصور). + +## N + +### توليد اللغة الطبيعية Natural language generation (NLG) + +جميع المهام المتعلقة بتوليد النص (على سبيل المثال، [اكتب باستخدام المحولات](https://transformer.huggingface.co/)، والترجمة). + +### معالجة اللغة الطبيعية Natural language processing (NLP) + +طريقة عامة للقول "التعامل مع النصوص". + +### فهم اللغة الطبيعية Natural language understanding (NLU) + +جميع المهام المتعلقة بفهم ما هو موجود في نص (على سبيل المثال تصنيف النص بأكمله، أو الكلمات الفردية). + +## P + +### خط الأنابيب (pipeline) + +في مكتبة Transformers، يُشير مصطلح "خط الأنابيب" إلى سلسلة من الخطوات التي يتم تنفيذها بترتيب محدد لمعالجة البيانات وتحويلها وإرجاع تنبؤ من نموذج. بعض المراحل الشائعة في خط الأنابيب قد تشمل معالجة البيانات الأولية، واستخراج الميزات، والتوحيد. + +للحصول على مزيد من التفاصيل، راجع [خطوط الأنابيب للاستدلال](https://huggingface.co/docs/transformers/pipeline_tutorial). + +### التوازي على مستوى خط الأنابيب (PipelineParallel) + +تقنية توازي يتم فيها تقسيم النموذج رأسياً (على مستوى الطبقة) عبر وحدات معالجة الرسومات (GPU) متعددة، بحيث توجد طبقة واحدة أو عدة طبقات من النموذج على وحدة معالجة الرسومات (GPU) واحدة فقط. تقوم كل وحدة معالجة رسومات (GPU) بمعالجة مراحل مختلفة من خط الأنابيب بالتوازي والعمل على جزء صغير من الدفعة. تعرف على المزيد حول كيفية عمل PipelineParallel [هنا](perf_train_gpu_many#from-naive-model-parallelism-to-pipeline-parallelism). + +### قيم البكسل (pixel values) + +مصفوفة من التمثيلات الرقمية لصورة يتم تمريرها إلى نموذج. تأخذ قيم البكسل شكل [`batch_size`، `num_channels`، `height`، `width`]، ويتم إنشاؤها من معالج الصور. + +### التجميع (Pooling) + +هي عملية تقوم بتقليص مصفوفة إلى مصفوفة أصغر، إما عن طريق أخذ القيمة القصوى أو المتوسط الحسابي للأبعاد التي يتم تجميعها. توجد طبقات التجميع بشكل شائع بين الطبقات التلافيفية convolutional layers لتقليل حجم تمثيل الميزات. + +### معرفات الموضع (position IDs) + +على عكس الشبكات العصبية المتكررة (RNNs) التي تتضمن موضع كل رمز (token) ضمن بنيتها، لا تدرك المحولات موضع كل رمز. لذلك، تستخدم معرفات الموضع (`position_ids`) من قبل النموذج لتحديد موضع كل رمز في قائمة الرموز. + +إنها معلمة اختيارية. إذا لم يتم تمرير أي `position_ids` إلى النموذج، يتم إنشاء المعرفات تلقائيًا كترميزات موضعية مطلقة. + +يتم اختيار الترميزات الموضعية المطلقة في النطاق `[0، config.max_position_embeddings - 1]`. تستخدم بعض النماذج أنواعًا أخرى من الترميزات الموضعية، مثل الترميزات الموضعية الجيبية أو الترميزات الموضعية النسبية. + +### ما قبل المعالجة (preprocessing) + +مهمة إعداد البيانات الخام بتنسيق يمكن أن تستهلكه نماذج التعلم الآلي بسهولة. على سبيل المثال، عادةً ما تتم معالجة النص مسبقًا عن طريق التمييز. للحصول على فكرة أفضل عن كيفية ظهور المعالجة المسبقة لأنواع الإدخال الأخرى، راجع البرنامج التعليمي [Preprocess](https://huggingface.co/docs/transformers/preprocessing). + +### النموذج المسبق التدريب (pretrained model) + +نموذج تم تدريبه مسبقًا على بعض البيانات (على سبيل المثال، كل Wikipedia). تنطوي طرق التدريب المسبق على هدف ذاتي الإشراف، والذي يمكن أن يكون قراءة النص ومحاولة التنبؤ بالكلمة التالية ( راجع (causal-language-modeling#)[نمذجة اللغة السببية] ) أو قناع بعض الكلمات ومحاولة التنبؤ بها ( راجع (masked-language#)[نمذجة اللغة المقنعة]- عرض MLM). + +لدى نماذج الكلام والرؤية أهدافها التدريبية المسبقة الخاصة. على سبيل المثال، Wav2Vec2 هو نموذج كلام تم تدريبه مسبقًا على مهمة تباينية تتطلب من النموذج تحديد تمثيل الكلام "الحقيقي" من مجموعة من تمثيلات الكلام "الخاطئة". من ناحية أخرى، BEiT هو نموذج رؤية تم تدريبه مسبقًا على مهمة نمذجة صورة مقنعة تقوم بقناع بعض رقع الصورة وتتطلب من النموذج التنبؤ بالرقع المقنعة (مشابهة لهدف نمذجة اللغة المقيدة). + +## R + +### شبكة عصبية متكررة (RNN) + +هي نوع من النماذج التي تستخدم حلقة متكررة فوق طبقة معينة لمعالجة النصوص. + +### التعلم التمثيلي (representation learning) + +هو فرع من فروع تعلم الآلة يركز على تعلم تمثيلات ذات معنى للبيانات الخام. بعض الأمثلة على تقنيات التعلم التمثيلي تشمل تضمين الكلمات، والمشفرات ذاتية، وشبكات التنافس التوليدية(GANs). + +## S + +### معدل العينات (sampling rate) + +قياس، بالهرتز، لعدد العينات (إشارة الصوت) المأخوذة في الثانية. ينتج معدل العينات عن تمييز إشارة مستمرة مثل الكلام. + +### الانتباه الذاتي (Self-Attention) + +هو آلية تتيح لكل عنصر في المدخل أن يحدد أي العناصر الأخرى في نفس المدخل يجب أن ينتبه إليها. + +### التعلم الذاتي الخاضع للإشراف (supervised learning) + +فئة من تقنيات التعلم الآلي التي يقوم فيها النموذج بإنشاء هدفه التعليمي الخاص من البيانات غير الموسومة. يختلف عن [التعلم غير الخاضع للإشراف](#unsupervised-learning) و [التعلم الخاضع للإشراف](#supervised-learning) في أن عملية التعلم خاضعة للإشراف، ولكن ليس صراحة من المستخدم. + +مثال واحد على التعلم الذاتي الخاضع للإشراف هو [نمذجة اللغة المقيدة](#masked-language- عرض MLM)، حيث يتم تمرير جمل للنموذج مع إزالة نسبة من رموزه ويتعلم التنبؤ بالرموز المفقودة. + +### التعلم شبه الخاضع للإشراف (semi-supervised learning) + +فئة واسعة من تقنيات تدريب التعلم الآلي التي تستفيد من كمية صغيرة من البيانات الموسومة مع كمية أكبر من البيانات غير الموسومة لتحسين دقة النموذج، على عكس [التعلم الخاضع للإشراف](#supervised-learning) و [التعلم غير الخاضع للإشراف](#unsupervised-learning). + +مثال على نهج التعلم شبه الخاضع للإشراف هو "التدريب الذاتي"، حيث يتم تدريب نموذج على بيانات موسومة، ثم يستخدم لتقديم تنبؤات حول البيانات غير الموسومة. يتم إضافة الجزء من البيانات غير الموسومة التي يتنبأ بها النموذج بأكبر قدر من الثقة إلى مجموعة البيانات الموسومة ويتم استخدامها لإعادة تدريب النموذج. + +### تسلسل إلى تسلسل (seq2seq) + +نماذج تولد تسلسلًا جديدًا من إدخال، مثل نماذج الترجمة، أو نماذج التلخيص (مثل [Bart](model_doc/bart) أو [T5](model_doc/t5)). + +### Sharded DDP + +اسم آخر لمفهوم [Zero Redundancy Optimizer](#zero-redundancy-optimizer-zero) الأساسي كما هو مستخدم من قبل العديد من التطبيقات الأخرى لـ Zero. + +### الخطوة (Stride) + +في العمليات التلافيفية أو التجميعية، تشير الخطوة إلى المسافة التي يتحرك بها النواة (kernel) فوق المصفوفة. خطوة تساوي 1 تعني أن النواة تتحرك بكسل واحد في كل مرة. + +### التعلم الخاضع للإشراف (supervised learning) + +هو نوع من تدريب النماذج التي تستخدم بيانات مُعلَّمة بشكل مباشر لتصحيح أداء النموذج وتوجيهه. يتم تغذية البيانات إلى النموذج قيد التدريب، ويتم مقارنة تنبؤاته بالنتائج الصحيحة المعروفة. يقوم النموذج بتعديل أوزانه بناءً على مدى خطأ تنبؤاته، وتتكرر هذه العملية لتحسين أداء النموذج. + +## T + +### توازي Tensor (TP) + +تقنية توازي لتدريب وحدات معالجة الرسومات (GPU) متعددة يتم فيها تقسيم المصفوفة إلى عدة أجزاء، لذا بدلاً من وجود المصفوفة بأكملها على وحدة معالجة الرسومات (GPU) واحدة، توجد كل شظية من المصفوفة على وحدة معالجة الرسومات (GPU) المخصصة لها. تتم معالجة الشظايا بشكل منفصل وبالتوازي على وحدات معالجة الرسومات (GPU) المختلفة ويتم مزامنة النتائج في نهاية خطوة المعالجة. هذا ما يُطلق عليه أحيانًا التوازي الأفقي، حيث يحدث الانقسام على المستوى الأفقي. + +تعرف على المزيد حول توازي Tensor [هنا](perf_train_gpu_many#tensor-parallelism). + +### الرمز اللغوي (Token) + +جزء من جملة، عادة ما يكون كلمة، ولكن يمكن أن يكون أيضًا كلمة فرعية (غالبًا ما يتم تقسيم الكلمات غير الشائعة إلى كلمات فرعية) أو علامة ترقيم. + +### معرفات نوع الرمز (token type ids) + +الغرض من بعض النماذج هو إجراء التصنيف على أزواج من الجمل أو الإجابة على الأسئلة. + + + +يتطلب ذلك تسلسلين مختلفين يتم دمجهما في إدخال "input_ids" واحد، والذي يتم عادةً باستخدام رموز خاصة، مثل رموز التصنيف (`[CLS]`) والفاصل (`[SEP]`). على سبيل المثال، يقوم نموذج BERT ببناء إدخال تسلسلين على النحو التالي: + +```python +>>> # [CLS] SEQUENCE_A [SEP] SEQUENCE_B [SEP] +``` + +يمكننا استخدام برنامجنا للتمييز لإنشاء مثل هذه الجملة تلقائيًا عن طريق تمرير التسلسلين إلى `tokenizer` كمعامليين (وليس قائمة، كما كان من قبل) مثل هذا: + +```python +>>> from transformers import BertTokenizer + +>>> tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-cased") +>>> sequence_a = "HuggingFace is based in NYC" +>>> sequence_b = "Where is HuggingFace based?" + +>>> encoded_dict = tokenizer(sequence_a، sequence_b) +>>> decoded = tokenizer.decode(encoded_dict["input_ids"]) +``` + +والذي سيعيد: + +```python +>>> print(decoded) +[CLS] HuggingFace is based in NYC [SEP] Where is HuggingFace based؟ [SEP] +``` + +هذا يكفي لبعض النماذج لفهم أين ينتهي تسلسل واحد وأين يبدأ الآخر. ومع ذلك، تستخدم نماذج أخرى، مثل BERT، أيضًا معرفات نوع الرمز (يُطلق عليها أيضًا معرفات الجزء). يتم تمثيلها كماسك ثنائي لتحديد نوعي التسلسل في النموذج. + +يعيد برنامج الترميز هذا القناع كإدخال "token_type_ids": + +```python +>>> encoded_dict["token_type_ids"] +[0، 0، 0، 0، 0، 0، 0، 0، 0، 0، 1، 1، 1، 1، 1، 1، 1، 1، 1] +``` + +يتم تمثيل التسلسل الأول، "السياق" المستخدم للسؤال، بجميع رموزه بواسطة `0`، في حين يتم تمثيل التسلسل الثاني، المقابل إلى "السؤال"، بجميع رموزه بواسطة `1`. + +تستخدم بعض النماذج، مثل [`XLNetModel`] رمزًا إضافيًا يمثله `2`. + +### التعلم الانتقالي (Transfer Learning) + +تقنية تنطوي على أخذ نموذج تم تدريبه مسبقًا وتكييفه مع مجموعة بيانات خاصة بمهمتك. بدلاً من تدريب نموذج من الصفر، يمكنك الاستفادة من المعرفة المكتسبة من نموذج موجود كنقطة بداية. يسرع هذا عملية التعلم ويقلل من كمية بيانات التدريب المطلوبة. + +### المحول (Transformer) + +هو بنية لنموذج تعلم عميق يعتمد على الانتباه الذاتي. + +## U + +### التعلم غير الخاضع للإشراف (unsupervised learning) + +شكل من أشكال تدريب النماذج حيث لا يتم وضع علامات على البيانات المقدمة إلى النموذج. تستفيد تقنيات التعلم غير الخاضعة للإشراف من المعلومات الإحصائية لتوزيع البيانات للعثور على الأنماط المفيدة للمهمة المعنية. + +## Z + +### محسن التكرار الصفري (ZeRO) + +تقنية توازي تقوم بتشظية المصفوفات بطريقة مشابهة لـ [TensorParallel](#tensor-parallelism-tp)، باستثناء إعادة بناء المصفوفة بالكامل في الوقت المناسب لحساب التقدير أو الحساب الخلفي، وبالتالي لا يلزم تعديل النموذج. تدعم هذه الطريقة أيضًا تقنيات الإخلاء المختلفة للتعويض عن ذاكرة GPU المحدودة. + +تعرف على المزيد حول Zero [هنا](perf_train_gpu_many#zero-data-parallelism). diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/how_to_hack_models.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/how_to_hack_models.md new file mode 100644 index 0000000000000000000000000000000000000000..8ce3589732f06aee0de0bde51843af967f0e26a7 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/how_to_hack_models.md @@ -0,0 +1,163 @@ +# كيفية تعديل أي نموذج من نماذج Transformers + +توفر مكتبة [🤗 Transformers](https://github.com/huggingface/transformers) مجموعة من النماذج المسبقة التدريب والأدوات لمعالجة اللغات الطبيعية، والرؤية، وما إلى ذلك. على الرغم من أن هذه النماذج تغطي مجموعة واسعة من التطبيقات، فقد تواجه حالات استخدام لا تدعمها المكتبة بشكل افتراضي. يُمكن للتخصيص أن يفتح إمكانيات جديدة، مثل إضافة طبقات جديدة، أو تعديل البنية المعمارية، أو تحسين آليات الانتباه. سيُوضح لك هذا الدليل كيفية تعديل نماذج Transformers الموجودة لتلبية احتياجاتك المحددة. الشيء الرائع هو أنك لست بحاجة إلى الخروج من إطار عمل Transformers لإجراء هذه التغييرات. ي يمكنك تعديل النماذج مباشرةً في Transformers والاستفادة من الميزات مثل [واجهة برمجة التطبيقات Trainer](https://huggingface.co/docs/transformers/main/en/main_classes/trainer)، و [PreTrainedModel](https://huggingface.co/docs/transformers/main/en/main_classes/model#transformers.PreTrainedModel)، والضبط الدقيق الفعال باستخدام أدوات مثل [PEFT](https://huggingface.co/docs/peft/index). + +سنرشدك في هذا الدليل لكيفية تخصيص نماذج Transformers الموجودة لتلبية متطلباتك، دون فقدان مزايا الإطار. ستتعلم كيفية: + +- تعديل بنية نموذج ما من خلال تغيير آلية الانتباه الخاصة به. +- تطبيق تقنيات مثل Low-Rank Adaptation (LoRA) على مكونات نموذج محددة. + +نحن نشجعك على المساهمة باختراقاتك الخاصة ومشاركتها هنا مع المجتمع1 + +## مثال: تعديل آلية الانتباه في نموذج Segment Anything (SAM) + +نموذج **Segment Anything (SAM)** هو نموذج رائد في مجال تجزئة الصور. في تنفيذه الافتراضي، يستخدم SAM إسقاطًا مجمعًا للاستعلام والمفتاح والقيمة (`qkv`) في آلية الانتباه الخاصة به. ومع ذلك، قد ترغب في ضبط مكونات محددة فقط من آلية الانتباه، مثل إسقاطات الاستعلام (`q`) والقيمة (`v`)، لتقليل عدد المعلمات القابلة للتدريب والموارد الحسابية المطلوبة. + +### الدافع + +من خلال تقسيم الإسقاط المجمع `qkv` إلى إسقاطات منفصلة `q` و `k` و `v`، يمكنك تطبيق تقنيات مثل **LoRA** (Low-Rank Adaptation) على إسقاطي `q` و `v` فقط. يسمح لك هذا بما يلي: + +- ضبط عدد أقل من المعلمات، مما يقلل من العبء الحسابي. +- تحقيق أداء أفضل من خلال التركيز على مكونات محددة. +- تجربة استراتيجيات تعديل مختلفة في آلية الانتباه. + +### التنفيذ + +#### **الخطوة 1: إنشاء فئة اهتمام مخصصة** + +بعد ذلك، قم بإنشاء فئة فرعية من فئة `SamVisionAttention` الأصلية وعدلها لتضم إسقاطات `q` و `k` و `v` منفصلة. + +```python +import torch +import torch.nn as nn +from transformers.models.sam.modeling_sam import SamVisionAttention + +class SamVisionAttentionSplit(SamVisionAttention, nn.Module): + def __init__(self, config, window_size): + super().__init__(config, window_size) + del self.qkv + # إسقاطات منفصلة q و k و v + self.q = nn.Linear(config.hidden_size, config.hidden_size, bias=config.qkv_bias) + self.k = nn.Linear(config.hidden_size, config.hidden_size, bias=config.qkv_bias) + self.v = nn.Linear(config.hidden_size, config.hidden_size, bias=config.qkv_bias) + self._register_load_state_dict_pre_hook(self.split_q_k_v_load_hook) + + def split_q_k_v_load_hook(self, state_dict, prefix, *args): + keys_to_delete = [] + for key in list(state_dict.keys()): + if "qkv." in key: + # تقسيم q و k و v من الإسقاط المجمع + q, k, v = state_dict[key].chunk(3, dim=0) + # استبدال الإسقاطات الفردية q و k و v + state_dict[key.replace("qkv.", "q.")] = q + state_dict[key.replace("qkv.", "k.")] = k + state_dict[key.replace("qkv.", "v.")] = v + # وضع علامة على مفتاح qkv القديم للحذف + keys_to_delete.append(key) + + # حذف مفاتيح qkv القديمة + for key in keys_to_delete: + del state_dict[key] + + def forward(self, hidden_states: torch.Tensor, output_attentions=False) -> torch.Tensor: + batch_size, height, width, _ = hidden_states.shape + qkv_shapes = (batch_size * self.num_attention_heads, height * width, -1) + query = self.q(hidden_states).reshape((batch_size, height * width,self.num_attention_heads, -1)).permute(0,2,1,3).reshape(qkv_shapes) + key = self.k(hidden_states).reshape((batch_size, height * width,self.num_attention_heads, -1)).permute(0,2,1,3).reshape(qkv_shapes) + value = self.v(hidden_states).reshape((batch_size, height * width,self.num_attention_heads, -1)).permute(0,2,1,3).reshape(qkv_shapes) + + attn_weights = (query * self.scale) @ key.transpose(-2, -1) + + if self.use_rel_pos: + attn_weights = self.add_decomposed_rel_pos( + attn_weights, query, self.rel_pos_h, self.rel_pos_w, (height, width), (height, width) + ) + + attn_weights = torch.nn.functional.softmax(attn_weights, dtype=torch.float32, dim=-1).to(query.dtype) + attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training) + attn_output = (attn_probs @ value).reshape(batch_size, self.num_attention_heads, height, width, -1) + attn_output = attn_output.permute(0, 2, 3, 1, 4).reshape(batch_size, height, width, -1) + attn_output = self.proj(attn_output) + + if output_attentions: + outputs = (attn_output, attn_weights) + else: + outputs = (attn_output, None) + return outputs +``` + +**الشرح:** + +- **الإسقاطات المنفصلة:** يتم إزالة الإسقاط المُجمع `qkv`، وإنشاء إسقاطات خطية منفصلة `q` و `k` و `v`. +- **دالة استدعاء تحميل الأوزان:** تقوم طريقة `_split_qkv_load_hook` بتقسيم أوزان `qkv` المسبقة التدريب إلى أوزان `q` و `k` و `v` منفصلة عند تحميل النموذج. يضمن هذا التوافق مع أي نموذج مسبق التدريب. +- **التنفيذ الأمامي:** يتم حساب الاستعلامات والمفاتيح والقيم بشكل منفصل، وتستمر آلية الانتباه كالمعتاد. + +#### **الخطوة 2: استبدال فئة الانتباه الأصلية** + +استبدل فئة `SamVisionAttention` الأصلية بفئتك المخصصة بحيث يستخدم النموذج آلية الانتباه المعدلة. + +```python +from transformers import SamModel +from transformers.models.sam import modeling_sam + +# استبدال فئة الاهتمام في وحدة نمطية modeling_sam +modeling_sam.SamVisionAttention = SamVisionAttentionSplit + +# تحميل نموذج SAM المسبق التدريب +model = SamModel.from_pretrained("facebook/sam-vit-base") +``` + +**الشرح:** + +- **استبدال الفئة:** من خلال تعيين فئتك المخصصة إلى `modeling_sam.SamVisionAttention`، فإن أي حالات من فئة `SamVisionAttention` في النموذج ستستخدم النسخة المعدلة. وبالتالي، عند استدعاء `SamModel`، سيتم استخدام `SamVisionAttentionSplit` المحددة حديثًا. +- **تحميل النموذج:** يتم تحميل النموذج باستخدام `from_pretrained`، ويتم دمج آلية الانتباه المخصصة. + +#### **الخطوة 3: تطبيق LoRA على إسقاطات محددة** + +مع وجود إسقاطات `q` و `k` و `v` منفصلة، يمكنك الآن تطبيق LoRA على مكونات محددة، مثل إسقاطات `q` و `v`. + +```python +from peft import LoraConfig, get_peft_model + +config = LoraConfig( + r=16, + lora_alpha=32, + target_modules=["q", "v"], # تطبيق LoRA على إسقاطات q و v + lora_dropout=0.1, + task_type="mask-generation" +) + +# تطبيق LoRA على النموذج +model = get_peft_model(model, config) +``` + +**الشرح:** + +- **تكوين LoRA:** تحدد `LoraConfig` المرتبة `r`، وعامل القياس `lora_alpha`، والوحدات المستهدفة (`"q"` و `"v"`)، ومعدل التخلي، ونوع المهمة. +- **تطبيق LoRA:** تقوم دالة `get_peft_model` بتطبيق LoRA على الوحدات المحددة في النموذج. +- **تقليل المعلمات:** من خلال التركيز على `q` و `v`، فإنك تقلل عدد المعلمات القابلة للتدريب، مما يؤدي إلى تسريع التدريب وتقليل استخدام الذاكرة. + +#### **الخطوة 4: التحقق من عدد المعلمات القابلة للتدريب** + +من السهل التحقق من عدد المعلمات القابلة للتدريب ومعرفة تأثير تعديلك. + +```python +model.print_trainable_parameters() +``` + +**الناتج المتوقع:** + +``` +عدد المعلمات القابلة للتدريب: 608,256 || جميع المعلمات: 94,343,728 || نسبة المعلمات القابلة للتدريب: 0.6447 +عدد المعلمات القابلة للتدريب: 912,384 || جميع المعلمات: 94,647,856 || نسبة المعلمات القابلة للتدريب: 0.9640 # مع k +``` + +## المساهمة بابداعاتك الخاصة + +يمكن لتعديل النماذج المسبقة التدريب أن يفتح آفاقًا جديدة للبحث والتطبيق. من خلال فهم وتعديل الآليات الداخلية للنماذج مثل SAM، يمكنك تخصيصها لتلبية احتياجاتك المحددة، وتحسين الأداء، وتجربة أفكار جديدة. + +إذا قمت بتطوير تعديﻻتك الخاصة لنماذج Transformers وترغب في مشاركتها، ففكر في المساهمة في هذه الوثيقة. + +- **إنشاء طلب سحب (Pull Request):** شارك تغييراتك وتحسيناتك في التعليمات البرمجية مباشرة في المستودع. +- **كتابة التوثيق:** قدم تفسيرات وأمثلة واضحة لتعديلاتك. +- **التفاعل مع المجتمع:** ناقش أفكارك واحصل على تعليقات من المطورين والباحثين الآخرين من خلال فتح مشكلة. diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/index.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/index.md new file mode 100644 index 0000000000000000000000000000000000000000..c37dbd1c6d9fc3a313b522d0a88c01606a12bac6 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/index.md @@ -0,0 +1,342 @@ +# 🤗 Transformers: لمحة عامة + +أحدث ما في مجال التعلم الآلي لـ [PyTorch](https://pytorch.org/) و [TensorFlow](https://www.tensorflow.org/) و [JAX](https://jax.readthedocs.io/en/latest/) + +توفر 🤗 Transformers واجهات برمجة التطبيقات (APIs) والأدوات اللازمة لتنزيل وتدريب أحدث النماذج المسبقة التدريب بسهولة. ويمكن أن يقلل استخدام النماذج المسبقة التدريب من تكاليف الحوسبة والحد من الأثر البيئي، وتوفّر الوقت والموارد اللازمين لتدريب نموذج من الصفر. وتدعم هذه النماذج المهام الشائعة في مجالات مختلفة، مثل: + + +📝 **معالجة اللغات الطبيعية**: تصنيف النصوص، وتعريف الكيانات المسماة، والإجابة على الأسئلة، ونمذجة اللغة، والتلخيص، والترجمة، والاختيار من متعدد، وتوليد النصوص.
+🖼️ **الرؤية الحاسوبية**: تصنيف الصور، وكشف الأشياء، وتجزئتها.
+🗣️ **الصوت**: التعرف التلقائي على الكلام، وتصنيف الصوت.
+🐙 **متعدد الوسائط**: الإجابة على الأسئلة الجدولية، والتعرف البصري على الحروف، واستخراج المعلومات من المستندات الممسوحة ضوئيًا، وتصنيف الفيديو، والإجابة على الأسئلة البصرية. + +تدعم 🤗 Transformers التوافق بين أطر العمل المختلفة مثل PyTorch و TensorFlow و JAX. ويوفر ذلك المرونة لاستخدام إطار عمل مختلف في كل مرحلة من مراحل حياة النموذج؛ قم بتدريب نموذج في ثلاث خطوط من التعليمات البرمجية في إطار واحد، وقم بتحميله للاستدلال في إطار آخر. ويمكن أيضًا تصدير النماذج إلى صيغ مثل ONNX و TorchScript للنشر في بيئات الإنتاج. + +انضم إلى المجتمع المتنامي على [Hub](https://huggingface.co/models) أو [المنتدى](https://discuss.huggingface.co/) أو [Discord](https://discord.com/invite/JfAtkvEtRb) اليوم! + +## إذا كنت تبحث عن دعم مخصص من فريق Hugging Face + + + HuggingFace Expert Acceleration Program + + +## المحتويات + +ينقسم التوثيق إلى خمسة أقسام: + +- **ابدأ** تقدم جولة سريعة في المكتبة وتعليمات التثبيت للبدء. +- **الدروس التعليمية** هي مكان رائع للبدء إذا كنت مبتدئًا. سيساعدك هذا القسم على اكتساب المهارات الأساسية التي تحتاجها للبدء في استخدام المكتبة. +- **أدلة كيفية الاستخدام** تُظهر لك كيفية تحقيق هدف محدد، مثل ضبط نموذج مسبق التدريب لنمذجة اللغة أو كيفية كتابة ومشاركة نموذج مخصص. +- **الأدلة المفاهيمية** تقدم مناقشة وتفسيرًا أكثر للأفكار والمفاهيم الأساسية وراء النماذج والمهام وفلسفة التصميم في 🤗 Transformers. +- **واجهة برمجة التطبيقات (API)** تصف جميع الفئات والوظائف: + + - **الفئات الرئيسية** تشرح الفئات الأكثر أهمية مثل التكوين والنمذجة والتحليل النصي وخط الأنابيب. + - **النماذج** تشرح الفئات والوظائف المتعلقة بكل نموذج يتم تنفيذه في المكتبة. + - **المساعدون الداخليون** يشرحون فئات ووظائف المساعدة التي يتم استخدامها داخليًا. + + +## النماذج والأطر المدعومة + +يمثل الجدول أدناه الدعم الحالي في المكتبة لكل من هذه النماذج، وما إذا كان لديها محلل نحوي Python (يُسمى "بطيء"). محلل نحوي "سريع" مدعوم بمكتبة 🤗 Tokenizers، وما إذا كان لديها دعم في Jax (عبر Flax) و/أو PyTorch و/أو TensorFlow. + + + + +| Model | PyTorch support | TensorFlow support | Flax Support | +|:------------------------------------------------------------------------:|:---------------:|:------------------:|:------------:| +| [ALBERT](model_doc/albert) | ✅ | ✅ | ✅ | +| [ALIGN](model_doc/align) | ✅ | ❌ | ❌ | +| [AltCLIP](model_doc/altclip) | ✅ | ❌ | ❌ | +| [Audio Spectrogram Transformer](model_doc/audio-spectrogram-transformer) | ✅ | ❌ | ❌ | +| [Autoformer](model_doc/autoformer) | ✅ | ❌ | ❌ | +| [Bark](model_doc/bark) | ✅ | ❌ | ❌ | +| [BART](model_doc/bart) | ✅ | ✅ | ✅ | +| [BARThez](model_doc/barthez) | ✅ | ✅ | ✅ | +| [BARTpho](model_doc/bartpho) | ✅ | ✅ | ✅ | +| [BEiT](model_doc/beit) | ✅ | ❌ | ✅ | +| [BERT](model_doc/bert) | ✅ | ✅ | ✅ | +| [Bert Generation](model_doc/bert-generation) | ✅ | ❌ | ❌ | +| [BertJapanese](model_doc/bert-japanese) | ✅ | ✅ | ✅ | +| [BERTweet](model_doc/bertweet) | ✅ | ✅ | ✅ | +| [BigBird](model_doc/big_bird) | ✅ | ❌ | ✅ | +| [BigBird-Pegasus](model_doc/bigbird_pegasus) | ✅ | ❌ | ❌ | +| [BioGpt](model_doc/biogpt) | ✅ | ❌ | ❌ | +| [BiT](model_doc/bit) | ✅ | ❌ | ❌ | +| [Blenderbot](model_doc/blenderbot) | ✅ | ✅ | ✅ | +| [BlenderbotSmall](model_doc/blenderbot-small) | ✅ | ✅ | ✅ | +| [BLIP](model_doc/blip) | ✅ | ✅ | ❌ | +| [BLIP-2](model_doc/blip-2) | ✅ | ❌ | ❌ | +| [BLOOM](model_doc/bloom) | ✅ | ❌ | ✅ | +| [BORT](model_doc/bort) | ✅ | ✅ | ✅ | +| [BridgeTower](model_doc/bridgetower) | ✅ | ❌ | ❌ | +| [BROS](model_doc/bros) | ✅ | ❌ | ❌ | +| [ByT5](model_doc/byt5) | ✅ | ✅ | ✅ | +| [CamemBERT](model_doc/camembert) | ✅ | ✅ | ❌ | +| [CANINE](model_doc/canine) | ✅ | ❌ | ❌ | +| [Chameleon](model_doc/chameleon) | ✅ | ❌ | ❌ | +| [Chinese-CLIP](model_doc/chinese_clip) | ✅ | ❌ | ❌ | +| [CLAP](model_doc/clap) | ✅ | ❌ | ❌ | +| [CLIP](model_doc/clip) | ✅ | ✅ | ✅ | +| [CLIPSeg](model_doc/clipseg) | ✅ | ❌ | ❌ | +| [CLVP](model_doc/clvp) | ✅ | ❌ | ❌ | +| [CodeGen](model_doc/codegen) | ✅ | ❌ | ❌ | +| [CodeLlama](model_doc/code_llama) | ✅ | ❌ | ✅ | +| [Cohere](model_doc/cohere) | ✅ | ❌ | ❌ | +| [Conditional DETR](model_doc/conditional_detr) | ✅ | ❌ | ❌ | +| [ConvBERT](model_doc/convbert) | ✅ | ✅ | ❌ | +| [ConvNeXT](model_doc/convnext) | ✅ | ✅ | ❌ | +| [ConvNeXTV2](model_doc/convnextv2) | ✅ | ✅ | ❌ | +| [CPM](model_doc/cpm) | ✅ | ✅ | ✅ | +| [CPM-Ant](model_doc/cpmant) | ✅ | ❌ | ❌ | +| [CTRL](model_doc/ctrl) | ✅ | ✅ | ❌ | +| [CvT](model_doc/cvt) | ✅ | ✅ | ❌ | +| [DAC](model_doc/dac) | ✅ | ❌ | ❌ | +| [Data2VecAudio](model_doc/data2vec) | ✅ | ❌ | ❌ | +| [Data2VecText](model_doc/data2vec) | ✅ | ❌ | ❌ | +| [Data2VecVision](model_doc/data2vec) | ✅ | ✅ | ❌ | +| [DBRX](model_doc/dbrx) | ✅ | ❌ | ❌ | +| [DeBERTa](model_doc/deberta) | ✅ | ✅ | ❌ | +| [DeBERTa-v2](model_doc/deberta-v2) | ✅ | ✅ | ❌ | +| [Decision Transformer](model_doc/decision_transformer) | ✅ | ❌ | ❌ | +| [Deformable DETR](model_doc/deformable_detr) | ✅ | ❌ | ❌ | +| [DeiT](model_doc/deit) | ✅ | ✅ | ❌ | +| [DePlot](model_doc/deplot) | ✅ | ❌ | ❌ | +| [Depth Anything](model_doc/depth_anything) | ✅ | ❌ | ❌ | +| [DETA](model_doc/deta) | ✅ | ❌ | ❌ | +| [DETR](model_doc/detr) | ✅ | ❌ | ❌ | +| [DialoGPT](model_doc/dialogpt) | ✅ | ✅ | ✅ | +| [DiNAT](model_doc/dinat) | ✅ | ❌ | ❌ | +| [DINOv2](model_doc/dinov2) | ✅ | ❌ | ✅ | +| [DistilBERT](model_doc/distilbert) | ✅ | ✅ | ✅ | +| [DiT](model_doc/dit) | ✅ | ❌ | ✅ | +| [DonutSwin](model_doc/donut) | ✅ | ❌ | ❌ | +| [DPR](model_doc/dpr) | ✅ | ✅ | ❌ | +| [DPT](model_doc/dpt) | ✅ | ❌ | ❌ | +| [EfficientFormer](model_doc/efficientformer) | ✅ | ✅ | ❌ | +| [EfficientNet](model_doc/efficientnet) | ✅ | ❌ | ❌ | +| [ELECTRA](model_doc/electra) | ✅ | ✅ | ✅ | +| [EnCodec](model_doc/encodec) | ✅ | ❌ | ❌ | +| [Encoder decoder](model_doc/encoder-decoder) | ✅ | ✅ | ✅ | +| [ERNIE](model_doc/ernie) | ✅ | ❌ | ❌ | +| [ErnieM](model_doc/ernie_m) | ✅ | ❌ | ❌ | +| [ESM](model_doc/esm) | ✅ | ✅ | ❌ | +| [FairSeq Machine-Translation](model_doc/fsmt) | ✅ | ❌ | ❌ | +| [Falcon](model_doc/falcon) | ✅ | ❌ | ❌ | +| [FalconMamba](model_doc/falcon_mamba) | ✅ | ❌ | ❌ | +| [FastSpeech2Conformer](model_doc/fastspeech2_conformer) | ✅ | ❌ | ❌ | +| [FLAN-T5](model_doc/flan-t5) | ✅ | ✅ | ✅ | +| [FLAN-UL2](model_doc/flan-ul2) | ✅ | ✅ | ✅ | +| [FlauBERT](model_doc/flaubert) | ✅ | ✅ | ❌ | +| [FLAVA](model_doc/flava) | ✅ | ❌ | ❌ | +| [FNet](model_doc/fnet) | ✅ | ❌ | ❌ | +| [FocalNet](model_doc/focalnet) | ✅ | ❌ | ❌ | +| [Funnel Transformer](model_doc/funnel) | ✅ | ✅ | ❌ | +| [Fuyu](model_doc/fuyu) | ✅ | ❌ | ❌ | +| [Gemma](model_doc/gemma) | ✅ | ❌ | ✅ | +| [Gemma2](model_doc/gemma2) | ✅ | ❌ | ❌ | +| [GIT](model_doc/git) | ✅ | ❌ | ❌ | +| [GLPN](model_doc/glpn) | ✅ | ❌ | ❌ | +| [GPT Neo](model_doc/gpt_neo) | ✅ | ❌ | ✅ | +| [GPT NeoX](model_doc/gpt_neox) | ✅ | ❌ | ❌ | +| [GPT NeoX Japanese](model_doc/gpt_neox_japanese) | ✅ | ❌ | ❌ | +| [GPT-J](model_doc/gptj) | ✅ | ✅ | ✅ | +| [GPT-Sw3](model_doc/gpt-sw3) | ✅ | ✅ | ✅ | +| [GPTBigCode](model_doc/gpt_bigcode) | ✅ | ❌ | ❌ | +| [GPTSAN-japanese](model_doc/gptsan-japanese) | ✅ | ❌ | ❌ | +| [Granite](model_doc/granite) | ✅ | ❌ | ❌ | +| [Graphormer](model_doc/graphormer) | ✅ | ❌ | ❌ | +| [Grounding DINO](model_doc/grounding-dino) | ✅ | ❌ | ❌ | +| [GroupViT](model_doc/groupvit) | ✅ | ✅ | ❌ | +| [HerBERT](model_doc/herbert) | ✅ | ✅ | ✅ | +| [Hiera](model_doc/hiera) | ✅ | ❌ | ❌ | +| [Hubert](model_doc/hubert) | ✅ | ✅ | ❌ | +| [I-BERT](model_doc/ibert) | ✅ | ❌ | ❌ | +| [IDEFICS](model_doc/idefics) | ✅ | ✅ | ❌ | +| [Idefics2](model_doc/idefics2) | ✅ | ❌ | ❌ | +| [ImageGPT](model_doc/imagegpt) | ✅ | ❌ | ❌ | +| [Informer](model_doc/informer) | ✅ | ❌ | ❌ | +| [InstructBLIP](model_doc/instructblip) | ✅ | ❌ | ❌ | +| [InstructBlipVideo](model_doc/instructblipvideo) | ✅ | ❌ | ❌ | +| [Jamba](model_doc/jamba) | ✅ | ❌ | ❌ | +| [JetMoe](model_doc/jetmoe) | ✅ | ❌ | ❌ | +| [Jukebox](model_doc/jukebox) | ✅ | ❌ | ❌ | +| [KOSMOS-2](model_doc/kosmos-2) | ✅ | ❌ | ❌ | +| [LayoutLM](model_doc/layoutlm) | ✅ | ✅ | ❌ | +| [LayoutLMv2](model_doc/layoutlmv2) | ✅ | ❌ | ❌ | +| [LayoutLMv3](model_doc/layoutlmv3) | ✅ | ✅ | ❌ | +| [LayoutXLM](model_doc/layoutxlm) | ✅ | ❌ | ❌ | +| [LED](model_doc/led) | ✅ | ✅ | ❌ | +| [LeViT](model_doc/levit) | ✅ | ❌ | ❌ | +| [LiLT](model_doc/lilt) | ✅ | ❌ | ❌ | +| [LLaMA](model_doc/llama) | ✅ | ❌ | ✅ | +| [Llama2](model_doc/llama2) | ✅ | ❌ | ✅ | +| [Llama3](model_doc/llama3) | ✅ | ❌ | ✅ | +| [LLaVa](model_doc/llava) | ✅ | ❌ | ❌ | +| [LLaVA-NeXT](model_doc/llava_next) | ✅ | ❌ | ❌ | +| [LLaVa-NeXT-Video](model_doc/llava_next_video) | ✅ | ❌ | ❌ | +| [Longformer](model_doc/longformer) | ✅ | ✅ | ❌ | +| [LongT5](model_doc/longt5) | ✅ | ❌ | ✅ | +| [LUKE](model_doc/luke) | ✅ | ❌ | ❌ | +| [LXMERT](model_doc/lxmert) | ✅ | ✅ | ❌ | +| [M-CTC-T](model_doc/mctct) | ✅ | ❌ | ❌ | +| [M2M100](model_doc/m2m_100) | ✅ | ❌ | ❌ | +| [MADLAD-400](model_doc/madlad-400) | ✅ | ✅ | ✅ | +| [Mamba](model_doc/mamba) | ✅ | ❌ | ❌ | +| [mamba2](model_doc/mamba2) | ✅ | ❌ | ❌ | +| [Marian](model_doc/marian) | ✅ | ✅ | ✅ | +| [MarkupLM](model_doc/markuplm) | ✅ | ❌ | ❌ | +| [Mask2Former](model_doc/mask2former) | ✅ | ❌ | ❌ | +| [MaskFormer](model_doc/maskformer) | ✅ | ❌ | ❌ | +| [MatCha](model_doc/matcha) | ✅ | ❌ | ❌ | +| [mBART](model_doc/mbart) | ✅ | ✅ | ✅ | +| [mBART-50](model_doc/mbart50) | ✅ | ✅ | ✅ | +| [MEGA](model_doc/mega) | ✅ | ❌ | ❌ | +| [Megatron-BERT](model_doc/megatron-bert) | ✅ | ❌ | ❌ | +| [Megatron-GPT2](model_doc/megatron_gpt2) | ✅ | ✅ | ✅ | +| [MGP-STR](model_doc/mgp-str) | ✅ | ❌ | ❌ | +| [Mistral](model_doc/mistral) | ✅ | ✅ | ✅ | +| [Mixtral](model_doc/mixtral) | ✅ | ❌ | ❌ | +| [mLUKE](model_doc/mluke) | ✅ | ❌ | ❌ | +| [MMS](model_doc/mms) | ✅ | ✅ | ✅ | +| [MobileBERT](model_doc/mobilebert) | ✅ | ✅ | ❌ | +| [MobileNetV1](model_doc/mobilenet_v1) | ✅ | ❌ | ❌ | +| [MobileNetV2](model_doc/mobilenet_v2) | ✅ | ❌ | ❌ | +| [MobileViT](model_doc/mobilevit) | ✅ | ✅ | ❌ | +| [MobileViTV2](model_doc/mobilevitv2) | ✅ | ❌ | ❌ | +| [MPNet](model_doc/mpnet) | ✅ | ✅ | ❌ | +| [MPT](model_doc/mpt) | ✅ | ❌ | ❌ | +| [MRA](model_doc/mra) | ✅ | ❌ | ❌ | +| [MT5](model_doc/mt5) | ✅ | ✅ | ✅ | +| [MusicGen](model_doc/musicgen) | ✅ | ❌ | ❌ | +| [MusicGen Melody](model_doc/musicgen_melody) | ✅ | ❌ | ❌ | +| [MVP](model_doc/mvp) | ✅ | ❌ | ❌ | +| [NAT](model_doc/nat) | ✅ | ❌ | ❌ | +| [Nemotron](model_doc/nemotron) | ✅ | ❌ | ❌ | +| [Nezha](model_doc/nezha) | ✅ | ❌ | ❌ | +| [NLLB](model_doc/nllb) | ✅ | ❌ | ❌ | +| [NLLB-MOE](model_doc/nllb-moe) | ✅ | ❌ | ❌ | +| [Nougat](model_doc/nougat) | ✅ | ✅ | ✅ | +| [Nyströmformer](model_doc/nystromformer) | ✅ | ❌ | ❌ | +| [OLMo](model_doc/olmo) | ✅ | ❌ | ❌ | +| [OneFormer](model_doc/oneformer) | ✅ | ❌ | ❌ | +| [OpenAI GPT](model_doc/openai-gpt) | ✅ | ✅ | ❌ | +| [OpenAI GPT-2](model_doc/gpt2) | ✅ | ✅ | ✅ | +| [OpenLlama](model_doc/open-llama) | ✅ | ❌ | ❌ | +| [OPT](model_doc/opt) | ✅ | ✅ | ✅ | +| [OWL-ViT](model_doc/owlvit) | ✅ | ❌ | ❌ | +| [OWLv2](model_doc/owlv2) | ✅ | ❌ | ❌ | +| [PaliGemma](model_doc/paligemma) | ✅ | ❌ | ❌ | +| [PatchTSMixer](model_doc/patchtsmixer) | ✅ | ❌ | ❌ | +| [PatchTST](model_doc/patchtst) | ✅ | ❌ | ❌ | +| [Pegasus](model_doc/pegasus) | ✅ | ✅ | ✅ | +| [PEGASUS-X](model_doc/pegasus_x) | ✅ | ❌ | ❌ | +| [Perceiver](model_doc/perceiver) | ✅ | ❌ | ❌ | +| [Persimmon](model_doc/persimmon) | ✅ | ❌ | ❌ | +| [Phi](model_doc/phi) | ✅ | ❌ | ❌ | +| [Phi3](model_doc/phi3) | ✅ | ❌ | ❌ | +| [PhoBERT](model_doc/phobert) | ✅ | ✅ | ✅ | +| [Pix2Struct](model_doc/pix2struct) | ✅ | ❌ | ❌ | +| [PLBart](model_doc/plbart) | ✅ | ❌ | ❌ | +| [PoolFormer](model_doc/poolformer) | ✅ | ❌ | ❌ | +| [Pop2Piano](model_doc/pop2piano) | ✅ | ❌ | ❌ | +| [ProphetNet](model_doc/prophetnet) | ✅ | ❌ | ❌ | +| [PVT](model_doc/pvt) | ✅ | ❌ | ❌ | +| [PVTv2](model_doc/pvt_v2) | ✅ | ❌ | ❌ | +| [QDQBert](model_doc/qdqbert) | ✅ | ❌ | ❌ | +| [Qwen2](model_doc/qwen2) | ✅ | ❌ | ❌ | +| [Qwen2Audio](model_doc/qwen2_audio) | ✅ | ❌ | ❌ | +| [Qwen2MoE](model_doc/qwen2_moe) | ✅ | ❌ | ❌ | +| [Qwen2VL](model_doc/qwen2_vl) | ✅ | ❌ | ❌ | +| [RAG](model_doc/rag) | ✅ | ✅ | ❌ | +| [REALM](model_doc/realm) | ✅ | ❌ | ❌ | +| [RecurrentGemma](model_doc/recurrent_gemma) | ✅ | ❌ | ❌ | +| [Reformer](model_doc/reformer) | ✅ | ❌ | ❌ | +| [RegNet](model_doc/regnet) | ✅ | ✅ | ✅ | +| [RemBERT](model_doc/rembert) | ✅ | ✅ | ❌ | +| [ResNet](model_doc/resnet) | ✅ | ✅ | ✅ | +| [RetriBERT](model_doc/retribert) | ✅ | ❌ | ❌ | +| [RoBERTa](model_doc/roberta) | ✅ | ✅ | ✅ | +| [RoBERTa-PreLayerNorm](model_doc/roberta-prelayernorm) | ✅ | ✅ | ✅ | +| [RoCBert](model_doc/roc_bert) | ✅ | ❌ | ❌ | +| [RoFormer](model_doc/roformer) | ✅ | ✅ | ✅ | +| [RT-DETR](model_doc/rt_detr) | ✅ | ❌ | ❌ | +| [RT-DETR-ResNet](model_doc/rt_detr_resnet) | ✅ | ❌ | ❌ | +| [RWKV](model_doc/rwkv) | ✅ | ❌ | ❌ | +| [SAM](model_doc/sam) | ✅ | ✅ | ❌ | +| [SeamlessM4T](model_doc/seamless_m4t) | ✅ | ❌ | ❌ | +| [SeamlessM4Tv2](model_doc/seamless_m4t_v2) | ✅ | ❌ | ❌ | +| [SegFormer](model_doc/segformer) | ✅ | ✅ | ❌ | +| [SegGPT](model_doc/seggpt) | ✅ | ❌ | ❌ | +| [SEW](model_doc/sew) | ✅ | ❌ | ❌ | +| [SEW-D](model_doc/sew-d) | ✅ | ❌ | ❌ | +| [SigLIP](model_doc/siglip) | ✅ | ❌ | ❌ | +| [Speech Encoder decoder](model_doc/speech-encoder-decoder) | ✅ | ❌ | ✅ | +| [Speech2Text](model_doc/speech_to_text) | ✅ | ✅ | ❌ | +| [SpeechT5](model_doc/speecht5) | ✅ | ❌ | ❌ | +| [Splinter](model_doc/splinter) | ✅ | ❌ | ❌ | +| [SqueezeBERT](model_doc/squeezebert) | ✅ | ❌ | ❌ | +| [StableLm](model_doc/stablelm) | ✅ | ❌ | ❌ | +| [Starcoder2](model_doc/starcoder2) | ✅ | ❌ | ❌ | +| [SuperPoint](model_doc/superpoint) | ✅ | ❌ | ❌ | +| [SwiftFormer](model_doc/swiftformer) | ✅ | ✅ | ❌ | +| [Swin Transformer](model_doc/swin) | ✅ | ✅ | ❌ | +| [Swin Transformer V2](model_doc/swinv2) | ✅ | ❌ | ❌ | +| [Swin2SR](model_doc/swin2sr) | ✅ | ❌ | ❌ | +| [SwitchTransformers](model_doc/switch_transformers) | ✅ | ❌ | ❌ | +| [T5](model_doc/t5) | ✅ | ✅ | ✅ | +| [T5v1.1](model_doc/t5v1.1) | ✅ | ✅ | ✅ | +| [Table Transformer](model_doc/table-transformer) | ✅ | ❌ | ❌ | +| [TAPAS](model_doc/tapas) | ✅ | ✅ | ❌ | +| [TAPEX](model_doc/tapex) | ✅ | ✅ | ✅ | +| [Time Series Transformer](model_doc/time_series_transformer) | ✅ | ❌ | ❌ | +| [TimeSformer](model_doc/timesformer) | ✅ | ❌ | ❌ | +| [Trajectory Transformer](model_doc/trajectory_transformer) | ✅ | ❌ | ❌ | +| [Transformer-XL](model_doc/transfo-xl) | ✅ | ✅ | ❌ | +| [TrOCR](model_doc/trocr) | ✅ | ❌ | ❌ | +| [TVLT](model_doc/tvlt) | ✅ | ❌ | ❌ | +| [TVP](model_doc/tvp) | ✅ | ❌ | ❌ | +| [UDOP](model_doc/udop) | ✅ | ❌ | ❌ | +| [UL2](model_doc/ul2) | ✅ | ✅ | ✅ | +| [UMT5](model_doc/umt5) | ✅ | ❌ | ❌ | +| [UniSpeech](model_doc/unispeech) | ✅ | ❌ | ❌ | +| [UniSpeechSat](model_doc/unispeech-sat) | ✅ | ❌ | ❌ | +| [UnivNet](model_doc/univnet) | ✅ | ❌ | ❌ | +| [UPerNet](model_doc/upernet) | ✅ | ❌ | ❌ | +| [VAN](model_doc/van) | ✅ | ❌ | ❌ | +| [VideoLlava](model_doc/video_llava) | ✅ | ❌ | ❌ | +| [VideoMAE](model_doc/videomae) | ✅ | ❌ | ❌ | +| [ViLT](model_doc/vilt) | ✅ | ❌ | ❌ | +| [VipLlava](model_doc/vipllava) | ✅ | ❌ | ❌ | +| [Vision Encoder decoder](model_doc/vision-encoder-decoder) | ✅ | ✅ | ✅ | +| [VisionTextDualEncoder](model_doc/vision-text-dual-encoder) | ✅ | ✅ | ✅ | +| [VisualBERT](model_doc/visual_bert) | ✅ | ❌ | ❌ | +| [ViT](model_doc/vit) | ✅ | ✅ | ✅ | +| [ViT Hybrid](model_doc/vit_hybrid) | ✅ | ❌ | ❌ | +| [VitDet](model_doc/vitdet) | ✅ | ❌ | ❌ | +| [ViTMAE](model_doc/vit_mae) | ✅ | ✅ | ❌ | +| [ViTMatte](model_doc/vitmatte) | ✅ | ❌ | ❌ | +| [ViTMSN](model_doc/vit_msn) | ✅ | ❌ | ❌ | +| [VITS](model_doc/vits) | ✅ | ❌ | ❌ | +| [ViViT](model_doc/vivit) | ✅ | ❌ | ❌ | +| [Wav2Vec2](model_doc/wav2vec2) | ✅ | ✅ | ✅ | +| [Wav2Vec2-BERT](model_doc/wav2vec2-bert) | ✅ | ❌ | ❌ | +| [Wav2Vec2-Conformer](model_doc/wav2vec2-conformer) | ✅ | ❌ | ❌ | +| [Wav2Vec2Phoneme](model_doc/wav2vec2_phoneme) | ✅ | ✅ | ✅ | +| [WavLM](model_doc/wavlm) | ✅ | ❌ | ❌ | +| [Whisper](model_doc/whisper) | ✅ | ✅ | ✅ | +| [X-CLIP](model_doc/xclip) | ✅ | ❌ | ❌ | +| [X-MOD](model_doc/xmod) | ✅ | ❌ | ❌ | +| [XGLM](model_doc/xglm) | ✅ | ✅ | ✅ | +| [XLM](model_doc/xlm) | ✅ | ✅ | ❌ | +| [XLM-ProphetNet](model_doc/xlm-prophetnet) | ✅ | ❌ | ❌ | +| [XLM-RoBERTa](model_doc/xlm-roberta) | ✅ | ✅ | ✅ | +| [XLM-RoBERTa-XL](model_doc/xlm-roberta-xl) | ✅ | ❌ | ❌ | +| [XLM-V](model_doc/xlm-v) | ✅ | ✅ | ✅ | +| [XLNet](model_doc/xlnet) | ✅ | ✅ | ❌ | +| [XLS-R](model_doc/xls_r) | ✅ | ✅ | ✅ | +| [XLSR-Wav2Vec2](model_doc/xlsr_wav2vec2) | ✅ | ✅ | ✅ | +| [YOLOS](model_doc/yolos) | ✅ | ❌ | ❌ | +| [YOSO](model_doc/yoso) | ✅ | ❌ | ❌ | +| [ZoeDepth](model_doc/zoedepth) | ✅ | ❌ | ❌ | + + diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/installation.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/installation.md new file mode 100644 index 0000000000000000000000000000000000000000..d3bd4c655b6038238ec7bacf3a2723685a7c3a21 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/installation.md @@ -0,0 +1,246 @@ +# التثبيت (Installation) + +قم بتثبيت مكتبة 🤗 Transformers المناسبة لمكتبة التعلم العميق التي تستخدمها، وقم بإعداد ذاكرة التخزين المؤقت الخاصة بك، وقم بإعداد 🤗 Transformers للعمل دون اتصال بالإنترنت (اختياري). + +تم اختبار 🤗 Transformers على Python 3.6 والإصدارات الأحدث، وPyTorch 1.1.0 والإصدارات الأحدث، وTensorFlow 2.0 والإصدارات الأحدث، وFlax. اتبع تعليمات التثبيت أدناه لمكتبة التعلم العميق التي تستخدمها: + +* تعليمات تثبيت [PyTorch](https://pytorch.org/get-started/locally/). +* تعليمات تثبيت [TensorFlow 2.0](https://www.tensorflow.org/install/pip). +* تعليمات تثبيت [Flax](https://flax.readthedocs.io/en/latest/). + +## التثبيت باستخدام pip + +يجب عليك تثبيت 🤗 Transformers داخل [بيئة افتراضية](https://docs.python.org/3/library/venv.html). إذا لم تكن غير ملم ببيئات Python الافتراضية، فراجع هذا [الدليل](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/). البيئة الافتراضية تسهل إدارة المشاريع المختلف، وتجنب مشكلات التوافق بين المكتبات المطلوبة (اعتماديات المشروع). + +ابدأ بإنشاء بيئة افتراضية في دليل مشروعك: + +```bash +python -m venv .env +``` + +قم بتفعيل البيئة الافتراضية. على Linux وMacOs: + +```bash +source .env/bin/activate +``` + +قم بتفعيل البيئة الافتراضية على Windows: + +```bash +.env/Scripts/activate +``` + +الآن أنت مستعد لتثبيت 🤗 Transformers باستخدام الأمر التالي: + +```bash +pip install transformers +``` + +للحصول على الدعم الخاص بـ CPU فقط، يمكنك تثبيت 🤗 Transformers ومكتبة التعلم العميق في خطوة واحدة. على سبيل المثال، قم بتثبيت 🤗 Transformers وPyTorch باستخدام: + +```bash +pip install 'transformers[torch]' +``` + +🤗 Transformers وTensorFlow 2.0: + +```bash +pip install 'transformers[tf-cpu]' +``` + + + +لمستخدمي M1 / ARM + +ستحتاج إلى تثبيت ما يلي قبل تثبيت TensorFLow 2.0 +```bash +brew install cmake +brew install pkg-config +``` + + + +🤗 Transformers وFlax: + +```bash +pip install 'transformers[flax]' +``` + +أخيرًا، تحقق مما إذا كان 🤗 Transformers قد تم تثبيته بشكل صحيح عن طريق تشغيل الأمر التالي. سيقوم بتنزيل نموذج مدرب مسبقًا: + +```bash +python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('we love you'))" +``` + +ثم قم بطباعة التسمية والنتيجة: + +```bash +[{'label': 'POSITIVE', 'score': 0.9998704791069031}] +``` + +## التثبيت من المصدر + +قم بتثبيت 🤗 Transformers من المصدر باستخدام الأمر التالي: + +```bash +pip install git+https://github.com/huggingface/transformers +``` + +يقوم هذا الأمر بتثبيت أحدث إصدار تجريبي `main` بدلاً من الإصدار المستقر `stable`. يعد إصدار `main` مفيدًا للمواكبة مع أحدث التطورات. على سبيل المثال، إذا تم إصلاح خطأ منذ الإصدار الرسمي الأخير ولكن لم يتم طرح إصدار جديد بعد. ومع ذلك، فإن هذا يعني أن إصدار التجريبي `main` قد لا يكون مستقرًا دائمًا. نسعى جاهدين للحفاظ على تشغيل إصدار `main`، ويتم حل معظم المشكلات عادةً في غضون بضع ساعات أو يوم. إذا واجهتك مشكلة، يرجى فتح [تقرير عن خلل](https://github.com/huggingface/transformers/issues) حتى نتمكن من إصلاحها في أقرب وقت ممكن! + +تحقق مما إذا كان 🤗 Transformers قد تم تثبيته بشكل صحيح عن طريق تشغيل الأمر التالي: + +```bash +python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('I love you'))" +``` + +تحقق مما إذا كان 🤗 Transformers قد تم تثبيته بشكل صحيح عن طريق تشغيل الأمر التالي: + +```bash +python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('I love you'))" +``` + +## التثبيت القابل للتعديل + +ستحتاج إلى تثبيت قابل للتعديل إذا كنت ترغب في: + +* استخدام إصدار `main` من كود المصدر. +* المساهمة في 🤗 Transformers وتحتاج إلى اختبار التغييرات في الكود. + +قم باستنساخ المستودع وقم بتثبيت 🤗 Transformers باستخدام الأوامر التالية: + +```bash +git clone https://github.com/huggingface/transformers.git +cd transformers +pip install -e . +``` + + ستقوم هذه الأوامر بربط المجلد الذي قمت باستنساخ المستودع فيه بمسارات مكتبة Python. بمعنى آخر، سيبحث Python داخل المجلد الذي قمت باستنساخه بالإضافة إلى المسارات المعتادة للمكتبات. على سبيل المثال، إذا تم تثبيت حزم Python الخاصة بك عادةً في `~/anaconda3/envs/main/lib/python3.7/site-packages/`, فسيقوم Python أيضًا بالبحث في المجلد الذي قمت باستنساخه: `~/transformers/`. + + + +يجب عليك الاحتفاظ بمجلد `transformers` إذا كنت تريد الاستمرار في استخدام المكتبة. + + + +الآن يمكنك تحديث المستنسخ الخاص بك بسهولة إلى أحدث إصدار من 🤗 Transformers باستخدام الأمر التالي: + +```bash +cd ~/transformers/ +git pull +``` + +ستجد بيئة Python الإصدار `main` من 🤗 Transformers في المرة التالية التي تقوم فيها بتشغيله. + +## التثبيت باستخدام conda + +قم بالتثبيت من قناة conda `conda-forge`: + +```bash +conda install conda-forge::transformers +``` + +## إعداد ذاكرة التخزين المؤقت + +تُحمّل النماذج المُسبقة التدريب وتُخزّن مؤقتًا في: `~/.cache/huggingface/hub`. هذا هو المجلد الافتراضي الذي يُحدده متغير البيئة `TRANSFORMERS_CACHE`. على Windows، يكون دليل ذاكرة التخزين المؤقت الافتراضي هو `C:\Users\username\.cache\huggingface\hub`. يمكنك تغيير متغيرات البيئة shell الموضحة أدناه - حسب الأولوية - لتحديد دليل ذاكرة تخزين مؤقت مختلف: + +1. متغير البيئة (افتراضي): `HF_HUB_CACHE` أو `TRANSFORMERS_CACHE`. +2. متغير البيئة: `HF_HOME`. +3. متغير البيئة: `XDG_CACHE_HOME` + `/huggingface`. + + + +سيستخدم 🤗 Transformers متغيرات البيئة `PYTORCH_TRANSFORMERS_CACHE` أو `PYTORCH_PRETRAINED_BERT_CACHE` إذا كنت قادمًا من إصدار سابق من هذه المكتبة وقمت بتعيين متغيرات البيئة هذه، ما لم تحدد متغير البيئة `TRANSFORMERS_CACHE`. + + + +## الوضع دون اتصال بالإنترنت + +قم بتشغيل 🤗 Transformers في بيئة محمية بجدار حماية أو غير متصلة باستخدام الملفات المخزنة مؤقتًا محليًا عن طريق تعيين متغير البيئة `HF_HUB_OFFLINE=1`. + + + +أضف [🤗 Datasets](https://huggingface.co/docs/datasets/) إلى سير عمل التدريب غير المتصل باستخدام متغير البيئة `HF_DATASETS_OFFLINE=1`. + + + +```bash +HF_DATASETS_OFFLINE=1 HF_HUB_OFFLINE=1 \ +python examples/pytorch/translation/run_translation.py --model_name_or_path google-t5/t5-small --dataset_name wmt16 --dataset_config ro-en ... +``` + +يجب أن يعمل هذا البرنامج النصي دون توقف أو انتظار انتهاء المهلة الزمنية لأنه لن يحاول تنزيل النموذج من Hub. + +يمكنك أيضًا تجاوز تحميل نموذج من Hub من كل استدعاء [`~PreTrainedModel.from_pretrained`] باستخدام معلمة [`local_files_only`]. عندما يتم تعيينها على `True`، يتم تحميل الملفات المحلية فقط: + +```py +from transformers import T5Model + +model = T5Model.from_pretrained("./path/to/local/directory", local_files_only=True) +``` + +### جلب النماذج والمُجزّئات لاستخدامها دون اتصال بالإنترنت + +خيار آخر لاستخدام 🤗 Transformers دون اتصال هو تنزيل الملفات مسبقًا، ثم الإشارة إلى مسارها المحلي عند الحاجة إلى استخدامها دون اتصال. هناك ثلاث طرق للقيام بذلك: + +* قم بتنزيل ملف عبر واجهة المستخدم على [Model Hub](https://huggingface.co/models) بالنقر فوق أيقونة ↓. + + ![download-icon](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/download-icon.png) + +* استخدم سير عمل [`PreTrainedModel.from_pretrained`] و [`PreTrainedModel.save_pretrained`]: + + 1. قم بتنزيل ملفاتك مسبقًا باستخدام [`PreTrainedModel.from_pretrained`]: +* استخدم سير عمل [`PreTrainedModel.from_pretrained`] و [`PreTrainedModel.save_pretrained`]: + + 1. قم بتنزيل ملفاتك مسبقًا باستخدام [`PreTrainedModel.from_pretrained`]: + + ```py + >>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM + + >>> tokenizer = AutoTokenizer.from_pretrained("bigscience/T0_3B") + >>> model = AutoModelForSeq2SeqLM.from_pretrained("bigscience/T0_3B") + ``` + + 2. احفظ ملفاتك إلى دليل محدد باستخدام [`PreTrainedModel.save_pretrained`]: + + ```py + >>> tokenizer.save_pretrained("./your/path/bigscience_t0") + >>> model.save_pretrained("./your/path/bigscience_t0") + ``` + + 3. الآن عندما تكون غير متصل بالإنترنت، أعد تحميل ملفاتك باستخدام [`PreTrainedModel.from_pretrained`] من الدليل المحدد: + + ```py + >>> tokenizer = AutoTokenizer.from_pretrained("./your/path/bigscience_t0") + >>> model = AutoModel.from_pretrained("./your/path/bigscience_t0") + ``` + +* قم بتنزيل الملفات برمجيًا باستخدام مكتبة [huggingface_hub](https://github.com/huggingface/huggingface_hub/tree/main/src/huggingface_hub): + + 1. قم بتثبيت مكتبة `huggingface_hub` في بيئتك الافتراضية: + + ```bash + python -m pip install huggingface_hub + ``` + + 2. استخدم وظيفة [`hf_hub_download`](https://huggingface.co/docs/hub/adding-a-library#download-files-from-the-hub) لتنزيل ملف إلى مسار محدد. على سبيل المثال، يقوم الأمر التالي بتنزيل ملف `config.json` من نموذج [T0](https://huggingface.co/bigscience/T0_3B) إلى المسار المطلوب: + + ```py + >>> from huggingface_hub import hf_hub_download + + >>> hf_hub_download(repo_id="bigscience/T0_3B", filename="config.json", cache_dir="./your/path/bigscience_t0") + ``` + +بمجرد تنزيل ملفك وتخزينه مؤقتًا محليًا، حدد مساره المحلي الخاص به لتحميله واستخدامه: + +```py +>>> from transformers import AutoConfig + +>>> config = AutoConfig.from_pretrained("./your/path/bigscience_t0/config.json") +``` + + + +راجع قسم [كيفية تنزيل الملفات من Hub](https://huggingface.co/docs/hub/how-to-downstream) لمزيد من التفاصيل حول تنزيل الملفات المخزنة على Hub. + + diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/llm_tutorial.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/llm_tutorial.md new file mode 100644 index 0000000000000000000000000000000000000000..264797a982b9ade0c70c29d7acf3c10ff498dc0b --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/llm_tutorial.md @@ -0,0 +1,248 @@ +# التوليد باستخدام نماذج اللغات الكبيرة (LLMs) + +[[open-in-colab]] + +تعد LLMs، أو نماذج اللغة الكبيرة، المكون الرئيسي وراء توليد النصوص. وباختصار، تتكون من نماذج محول كبيرة مسبقة التدريب تم تدريبها للتنبؤ بالكلمة التالية (أو، بشكل أكثر دقة، الرمز اللغوي) بالنظر إلى نص معين. نظرًا لأنها تتنبأ برمز واحد في كل مرة، يجب عليك القيام بشيء أكثر تعقيدًا لتوليد جمل جديدة بخلاف مجرد استدعاء النموذج - يجب عليك إجراء التوليد التلقائي. + +التوليد التلقائي هو إجراء وقت الاستدلال الذي يتضمن استدعاء النموذج بشكل متكرر باستخدام مخرجاته الخاصة، بالنظر إلى بعض المدخلات الأولية. في 🤗 Transformers، يتم التعامل مع هذا بواسطة دالة [`~generation.GenerationMixin.generate`]، والتي تتوفر لجميع النماذج ذات القدرات التوليدية. + +سيوضح هذا البرنامج التعليمي كيفية: + +* تتوليد نص باستخدام نموذج اللغات الكبيرة (LLM) +* تجنب الوقوع في الأخطاء الشائعة +* الخطوات التالية لمساعدتك في الاستفادة القصوى من LLM الخاص بك + +قبل البدء، تأكد من تثبيت جميع المكتبات الضرورية: + +```bash +pip install transformers bitsandbytes>=0.39.0 -q +``` + +## توليد النص + +يأخذ نموذج اللغة المدرب لـ [نمذجة اللغة السببية](tasks/language_modeling) يأخذ تسلسلًا من رموز نصية كمدخل ويعيد توزيع الاحتمالية للرمز التالي. + + +
+ +
"التنبؤ بالكلمة التالية لنموذج اللغة (LLM)"
+
+ +هناك جانب بالغ الأهمية في التوليد التلقائي باستخدام LLMs وهو كيفية اختيار الرمز التالي من توزيع الاحتمالية هذا. كل شيء مسموح به في هذه الخطوة طالما أنك تنتهي برمز للتكرار التالي. وهذا يعني أنه يمكن أن يكون بسيطًا مثل اختيار الرمز الأكثر احتمالًا من توزيع الاحتمالية أو معقدًا مثل تطبيق عشرات التحولات قبل أخذ العينات من التوزيع الناتج. + + +
+ +
"التوليد التلقائي المتسلسل"
+
+ +تتكرر العملية الموضحة أعلاه بشكل تكراري حتى يتم الوصول إلى شرط التوقف. في الوضع المثالي، يحدد النموذج شرط التوقف، والذي يجب أن يتعلم عند إخراج رمز نهاية التسلسل (`EOS`). إذا لم يكن الأمر كذلك، يتوقف التوليد عند الوصول إلى طول أقصى محدد مسبقًا. + +من الضروري إعداد خطوة اختيار الرمز وشرط التوقف بشكل صحيح لجعل نموذجك يتصرف كما تتوقع في مهمتك. ولهذا السبب لدينا [`~generation.GenerationConfig`] ملف مرتبط بكل نموذج، والذي يحتوي على معلمة توليدية افتراضية جيدة ويتم تحميله جنبًا إلى جنب مع نموذجك. + +دعنا نتحدث عن الكود! + + + + +إذا كنت مهتمًا بالاستخدام الأساسي لـ LLM، فإن واجهة [`Pipeline`](pipeline_tutorial) عالية المستوى هي نقطة انطلاق رائعة. ومع ذلك، غالبًا ما تتطلب LLMs ميزات متقدمة مثل التكميم والتحكم الدقيق في خطوة اختيار الرمز، والتي يتم تنفيذها بشكل أفضل من خلال [`~generation.GenerationMixin.generate`]. التوليد التلقائي باستخدام LLMs يستهلك الكثير من المواردد ويجب تنفيذه على وحدة معالجة الرسومات للحصول على أداء كافٍ. + + + +أولاً، تحتاج إلى تحميل النموذج. + +```py +>>> from transformers import AutoModelForCausalLM + +>>> model = AutoModelForCausalLM.from_pretrained( +... "mistralai/Mistral-7B-v0.1", device_map="auto", load_in_4bit=True +... ) +``` + +ستلاحظ وجود معاملين في الاستدعاء `from_pretrained`: + + - `device_map` يضمن انتقال النموذج إلى وحدة معالجة الرسومات (GPU) الخاصة بك + - `load_in_4bit` يطبق [4-bit dynamic quantization](main_classes/quantization) لخفض متطلبات الموارد بشكل كبير + +هناك طرق أخرى لتهيئة نموذج، ولكن هذا خط أساس جيد للبدء باستخدام LLM. + +بعد ذلك، تحتاج إلى معالجة إدخال النص الخاص بك باستخدام [مُجزّئ اللغوي](tokenizer_summary). + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1", padding_side="left") +>>> model_inputs = tokenizer(["A list of colors: red, blue"], return_tensors="pt").to("cuda") +``` + +يحتوي متغير `model_inputs` على النص المدخل بعد تقسيمه إلى وحدات لغوية (tokens)، بالإضافة إلى قناع الانتباه. في حين أن [`~generation.GenerationMixin.generate`] تبذل قصارى جهدها لاستنتاج قناع الانتباه عندما لا يتم تمريره، نوصي بتمريره كلما أمكن ذلك للحصول على نتائج مثالية. + +بعد تقسيم المدخلات إلى وحدات لغوية، يمكنك استدعاء الدالة [`~generation.GenerationMixin.generate`] لإرجاع الوحدات اللغوية الناتجة. يجب بعد ذلك تحويل الوحدات المولدة إلى نص قبل طباعته. + +```py +>>> generated_ids = model.generate(**model_inputs) +>>> tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'A list of colors: red, blue, green, yellow, orange, purple, pink,' +``` + +أخيرًا، ليس عليك معالجة المتتاليات الواحدة تلو الأخرى! يمكنك معالجة مجموعة من المدخلات دفعة واحدة، والتي ستعمل على تحسين الإنتاجية بشكل كبير بتكلفة صغيرة في زمن الاستجابة واستهلاك الذاكر. كل ما عليك التأكد منه هو تعبئة المدخلات بشكل صحيح (المزيد حول ذلك أدناه). + +```py +>>> tokenizer.pad_token = tokenizer.eos_token # Most LLMs don't have a pad token by default +>>> model_inputs = tokenizer( +... ["A list of colors: red, blue", "Portugal is"], return_tensors="pt", padding=True +... ).to("cuda") +>>> generated_ids = model.generate(**model_inputs) +>>> tokenizer.batch_decode(generated_ids, skip_special_tokens=True) +['A list of colors: red, blue, green, yellow, orange, purple, pink,', +'Portugal is a country in southwestern Europe, on the Iber'] +``` + +وهذا كل شيء! في بضع سطور من التعليمات البرمجية، يمكنك تسخير قوة LLM. + +## الأخطاء الشائعة + +هناك العديد من [استراتيجيات التوليد](generation_strategies)، وفي بعض الأحيان قد لا تكون القيم الافتراضية مناسبة لحالتك الاستخدام. إذا لم تكن الإخراج الخاصة بك متوافقة مع ما تتوقعه، فقد قمنا بإنشاء قائمة بأكثر الأخطاء الشائعة وكيفية تجنبها. + +```py +>>> from transformers import AutoModelForCausalLM, AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1") +>>> tokenizer.pad_token = tokenizer.eos_token # Most LLMs don't have a pad token by default +>>> model = AutoModelForCausalLM.from_pretrained( +... "mistralai/Mistral-7B-v0.1", device_map="auto", load_in_4bit=True +... ) +``` + +### الإخراج المولد قصير جدًا/طويل جدًا + +إذا لم يتم تحديد العدد الأقصى للرموز في [`~generation.GenerationConfig`] الملف، `generate` يعيد ما يصل إلى 20 رمزًا بشكل افتراضي. نوصي بشدة بتعيين `max_new_tokens` يدويًا في مكالمة `generate` للتحكم في العدد الأقصى من الرموز الجديدة التي يمكن أن يعيدها. ضع في اعتبارك أن LLMs (بشكل أكثر دقة، [نماذج فك التشفير فقط](https://huggingface.co/learn/nlp-course/chapter1/6؟fw=pt)) تعيد أيضًا المدخلات الأصلية كجزء من الناتج. +```py +>>> model_inputs = tokenizer(["A sequence of numbers: 1, 2"], return_tensors="pt").to("cuda") + +>>> # By default, the output will contain up to 20 tokens +>>> generated_ids = model.generate(**model_inputs) +>>> tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'A sequence of numbers: 1, 2, 3, 4, 5' + +>>> # Setting `max_new_tokens` allows you to control the maximum length +>>> generated_ids = model.generate(**model_inputs, max_new_tokens=50) +>>> tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'A sequence of numbers: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,' +``` + +### وضع التوليد الافتراضي + +بشكل افتراضي، وما لم يتم تحديده في [`~generation.GenerationConfig`] الملف، `generate` يحدد الكلمة الأكثر احتمالًا فى كل خطوة من خطوات عملية التوليد (وهذا يُعرف بالتشفير الجشع). اعتمادًا على مهمتك، قد يكون هذا غير مرغوب فيه؛ تستفيد المهام الإبداعية مثل برامج الدردشة أو كتابة مقال ستفيد من أسلوب العينة العشوائية في اختيار الكلمات، تمن ناحية أخرى، فإن المهام التي تعتمد على مدخلات محددة مثل تحويل الصوت إلى نص أو الترجم من فك التشفير الجشع. قم بتفعيل أسلوب العينات العشوائية باستخدام `do_sample=True`، ويمكنك معرفة المزيد حول هذا الموضوع في [تدوينة المدونة](https://huggingface.co/blog/how-to-generate). + +```py +>>> # Set seed or reproducibility -- you don't need this unless you want full reproducibility +>>> from transformers import set_seed +>>> set_seed(42) + +>>> model_inputs = tokenizer(["I am a cat."], return_tensors="pt").to("cuda") + +>>> # LLM + greedy decoding = repetitive, boring output +>>> generated_ids = model.generate(**model_inputs) +>>> tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'I am a cat. I am a cat. I am a cat. I am a cat' + +>>> # With sampling, the output becomes more creative! +>>> generated_ids = model.generate(**model_inputs, do_sample=True) +>>> tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'I am a cat. Specifically, I am an indoor-only cat. I' +``` + +### مشكلة حشو المدخلات فى الاتجاة الخطأ + +LLMs هي [معماريات فك التشفير فقط](https://huggingface.co/learn/nlp-course/chapter1/6؟fw=pt)، مما يعني أنها تستمر في التكرار على موجه الإدخال الخاص بك. فإن جميع المدخلات يجب أن تكون بنفس الطول. لحل هذه المسألة، يتم إضافة رموز حشو إلى المدخلات الأقصر. نظرًا لأن LLMs لا تولي اهتمامًا لرموز الحشو هذه، ذلك، يجب تحديد الجزء المهم من المدخل الذي يجب أن يركز عليه النموذج، وهذا يتم عن طريق ما يسمى بـ "قناع الانتباه". يجب أن يكون الحشو في بداية المدخل (الحشو من اليسار)، وليس في نهايته. + +```py +>>> # The tokenizer initialized above has right-padding active by default: the 1st sequence, +>>> # which is shorter, has padding on the right side. Generation fails to capture the logic. +>>> model_inputs = tokenizer( +... ["1, 2, 3", "A, B, C, D, E"], padding=True, return_tensors="pt" +... ).to("cuda") +>>> generated_ids = model.generate(**model_inputs) +>>> tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'1, 2, 33333333333' + +>>> # With left-padding, it works as expected! +>>> tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1", padding_side="left") +>>> tokenizer.pad_token = tokenizer.eos_token # Most LLMs don't have a pad token by default +>>> model_inputs = tokenizer( +... ["1, 2, 3", "A, B, C, D, E"], padding=True, return_tensors="pt" +... ).to("cuda") +>>> generated_ids = model.generate(**model_inputs) +>>> tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'1, 2, 3, 4, 5, 6,' +``` + +### موجه غير صحيح + +تتوقع بعض نماذج اللغات الكبيرة على صيغة محددة للمدخلات للعمل بشكل صحيح. إذا لم يتم اتباع هذه الصيغة، فإن أداء النموذج يتأثر سلبًا: لكن هذا التدهور قد لا يكون واضحًا للعيان. تتوفر معلومات إضافية حول التوجيه، بما في ذلك النماذج والمهام التي تحتاج إلى توخي الحذر، في [الدليل](tasks/prompting). دعنا نرى مثالاً باستخدام LLM للدردشة، والذي يستخدم [قالب الدردشة](chat_templating): +```python +>>> tokenizer = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-alpha") +>>> model = AutoModelForCausalLM.from_pretrained( +... "HuggingFaceH4/zephyr-7b-alpha", device_map="auto", load_in_4bit=True +... ) +>>> set_seed(0) +>>> prompt = """How many helicopters can a human eat in one sitting? Reply as a thug.""" +>>> model_inputs = tokenizer([prompt], return_tensors="pt").to("cuda") +>>> input_length = model_inputs.input_ids.shape[1] +>>> generated_ids = model.generate(**model_inputs, max_new_tokens=20) +>>> print(tokenizer.batch_decode(generated_ids[:, input_length:], skip_special_tokens=True)[0]) +"I'm not a thug, but i can tell you that a human cannot eat" +>>> # Oh no, it did not follow our instruction to reply as a thug! Let's see what happens when we write +>>> # a better prompt and use the right template for this model (through `tokenizer.apply_chat_template`) + +>>> set_seed(0) +>>> messages = [ +... { +... "role": "system", +... "content": "You are a friendly chatbot who always responds in the style of a thug", +... }, +... {"role": "user", "content": "How many helicopters can a human eat in one sitting?"}, +... ] +>>> model_inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt").to("cuda") +>>> input_length = model_inputs.shape[1] +>>> generated_ids = model.generate(model_inputs, do_sample=True, max_new_tokens=20) +>>> print(tokenizer.batch_decode(generated_ids[:, input_length:], skip_special_tokens=True)[0]) +'None, you thug. How bout you try to focus on more useful questions?' +>>> # As we can see, it followed a proper thug style 😎 +``` + +## موارد إضافية + +في حين أن عملية التوليد التلقائي بسيطة نسبيًا، فإن الاستفادة القصوى من LLM الخاص بك يمكن أن تكون مهمة صعبة لأن هناك العديد من الأجزاء المتحركة. للخطوات التالية لمساعدتك في الغوص بشكل أعمق في استخدام LLM وفهمه: + +### استخدامات متقدمة للتوليد في نماذج اللغات الكبيرة + +1. دليل حول كيفية [التحكم في طرق التوليد المختلفة](generation_strategies)، وكيفية إعداد ملف تكوين التوليد، وكيفية بث الناتج؛ +2. [تسريع توليد النص](llm_optims)؛ +3.[قوالب موجهات للدردشة LLMs](chat_ +4. [دليل تصميم الموجه](tasks/prompting); +5. مرجع واجهة برمجة التطبيقات (API) [`~generation.GenerationConfig`], [`~generation.GenerationMixin.generate`], و [generate-related classes](internal/generation_utils). والعديد من الفئات الأخرى المرتبطة بعملية التوليد.! + +### لوحات صدارة نماذج اللغات الكبيرة +1. لوحة صدارة نماذج اللغات الكبيرة المفتوحة المصدر (Open LLM Leaderboard): تركز على جودة النماذج مفتوحة المصدر [رابط لوحة الصدارة](https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard). +2. لوحة صدارة أداء نماذج اللغات الكبيرة المفتوحة المصدر (Open LLM-Perf Leaderboard): تركز على إنتاجية نماذج اللغات الكبيرة [رابط لوحة الصدارة](https://huggingface.co/spaces/optimum/llm-perf-leaderboard). + +### زمن الاستجابة والإنتاجية واستهلاك الذاكرة +1. دليل تحسين نماذج اللغات الكبيرة من حيث السرعة والذاكرة: دليل تحسين نماذج اللغات الكبيرة. +2. التكميم (Quantization): دليل حول تقنية التكميم التكميم مثل تقنيتي bitsandbytes و autogptq، والتي توضح كيفية تقليل متطلبات الذاكرة بشكل كبير. + +### مكتبات مرتبطة +1. [`optimum`](https://github.com/huggingface/optimum), امتداد لمكتبة Transformers يعمل على تحسين الأداء لأجهزة معينة. +2. [`outlines`](https://github.com/outlines-dev/outlines), مكتبة للتحكم في توليد النصوص (على سبيل المثال، لتوليد ملفات JSON). +3. [`SynCode`](https://github.com/uiuc-focal-lab/syncode), مكتبة للتوليد الموجه بقواعد اللغة الخالية من السياق (على سبيل المثال، JSON، SQL، Python). +4. [`text-generation-inference`](https://github.com/huggingface/text-generation-inference), خادم جاهز للإنتاج لنماذج اللغات الكبيرة. +5. [`text-generation-webui`](https://github.com/oobabooga/text-generation-webui), واجهة مستخدم لتوليد النصوص.   diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/llm_tutorial_optimization.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/llm_tutorial_optimization.md new file mode 100644 index 0000000000000000000000000000000000000000..9ddf0b59c900b3e56b7c0122d1c8867c4fbbc33e --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/llm_tutorial_optimization.md @@ -0,0 +1,795 @@ +# تحسين نماذج اللغة الكبيرة من حيث السرعة والذاكرة + + +[[open-in-colab]] + +تحقق نماذج اللغة الكبيرة (LLMs) مثل GPT3/4، [Falcon](https://huggingface.co/tiiuae/falcon-40b)، و [Llama](https://huggingface.co/meta-llama/Llama-2-70b-hf) تقدمًا سريعًا في قدرتها على معالجة المهام التي تركز على الإنسان، مما يجعلها أدوات أساسية في الصناعات القائمة على المعرفة الحديثة. +لا يزال نشر هذه النماذج في المهام الواقعية يمثل تحديًا، ومع ذلك: + +- لكي تظهر نماذج اللغة الكبيرة قدرات فهم وتوليد النصوص قريبة من قدرات الإنسان، فإنها تتطلب حاليًا إلى تكوينها من مليارات المعلمات (انظر [كابلان وآخرون](https://huggingface.co/papers/2001.08361)، [وي وآخرون](https://huggingface.co/papers/2206.07682)). وهذا بدوره يزيد من متطلبات الذاكرة للاستدلال. +- في العديد من المهام الواقعية، تحتاج نماذج اللغة الكبيرة إلى معلومات سياقية شاملة. يتطلب ذلك قدرة النموذج على إدارة تسلسلات إدخال طويلة للغاية أثناء الاستدلال. + +يكمن جوهر صعوبة هذه التحديات في تعزيز القدرات الحسابية والذاكرة لنماذج اللغة الكبيرة، خاصة عند التعامل مع تسلسلات الإدخال الضخمة. + +في هذا الدليل، سنستعرض التقنيات الفعالة لتُحسِّن من كفاءة نشر نماذج اللغة الكبيرة: + +1. سنتناول تقنية "دقة أقل" التي أثبتت الأبحاث فعاليتها في تحقيق مزايا حسابية دون التأثير بشكل ملحوظ على أداء النموذج عن طريق العمل بدقة رقمية أقل [8 بت و4 بت](/main_classes/quantization). + +2. **اFlash Attention:** إن Flash Attention وهي نسخة مُعدَّلة من خوارزمية الانتباه التي لا توفر فقط نهجًا أكثر كفاءة في استخدام الذاكرة، ولكنها تحقق أيضًا كفاءة متزايدة بسبب الاستخدام الأمثل لذاكرة GPU. + +3. **الابتكارات المعمارية:** حيث تم اقتراح هياكل متخصصة تسمح باستدلال أكثر فعالية نظرًا لأن نماذج اللغة الكبيرة يتم نشرها دائمًا بنفس الطريقة أثناء عملية الاستدلال، أي توليد النص التنبؤي التلقائي مع سياق الإدخال الطويل، فقد تم اقتراح بنيات نموذج متخصصة تسمح بالاستدلال الأكثر كفاءة. أهم تقدم في بنيات النماذج هنا هو [عذر](https://huggingface.co/papers/2108.12409)، [الترميز الدوار](https://huggingface.co/papers/2104.09864)، [الاهتمام متعدد الاستعلامات (MQA)](https://huggingface.co/papers/1911.02150) و [مجموعة الانتباه بالاستعلام (GQA)](https://huggingface.co/papers/2305.13245). + +على مدار هذا الدليل، سنقدم تحليلًا للتوليد التنبؤي التلقائي من منظور المُوتِّرات. نتعمق في مزايا وعيوب استخدام دقة أقل، ونقدم استكشافًا شاملاً لخوارزميات الانتباه الأحدث، ونناقش بنيات نماذج نماذج اللغة الكبيرة المحسنة. سندعم الشرح بأمثلة عملية تُبرِز كل تحسين على حدة. + +## 1. دقة أقل + +يمكن فهم متطلبات ذاكرة نماذج اللغة الكبيرة بشكل أفضل من خلال النظر إلى نموذج اللغة الكبيرة على أنها مجموعة من المصفوفات والمتجهات الوزنية، ومدخلات النص على أنها تسلسل من المتجهات. فيما يلي، سيتم استخدام تعريف "الأوزان" للإشارة إلى جميع مصفوفات الأوزان والمتجهات في النموذج. +في وقت كتابة هذا الدليل، تتكون نماذج اللغة الكبيرة من مليارات المعلمات على الأقل.كل معلمة يتم تمثيلها برقم عشري مثل 4.5689 `` والذي يتم تخزينه عادةً بتنسيق [float32](https://en.wikipedia.org/wiki/Single-precision_floating-point_format)، [bfloat16](https://en.wikipedia.org/wiki/Bfloat16_floating-point_format)، أو [float16](https://en.wikipedia.org/wiki/Half-precision_floating-point_format) . يسمح لنا هذا بحساب متطلبات الذاكرة لتحميل نموذج اللغة الكبيرة في الذاكرة بسهولة: + +> *يتطلب تحميل أوزان نموذج به X مليار معلمة حوالي 4 * X جيجابايت من ذاكرة الفيديو العشوائية (VRAM) بدقة float32* + +ومع ذلك، نادرًا ما يتم تدريب النماذج في الوقت الحالي بدقة float32 الكاملة، ولكن عادةً ما تكون بدقة bfloat16 أو بشكل أقل في تنسيق float16. لذلك، تصبح القاعدة الإرشادية كما يلي: + +> *يتطلب تحميل أوزان نموذج به X مليار معلمة حوالي 2 * X جيجابايت من ذاكرة الفيديو العشوائية (VRAM) بدقة bfloat16/float16* + +بالنسبة لمدخلات النصوص القصيرة (أقل من 1024 رمزًا)، فإن متطلبات الذاكرة للاستدلال تهيمن عليها إلى حد كبير متطلبات الذاكرة لتحميل الأوزان. لذلك، دعنا نفترض، في الوقت الحالي، أن متطلبات الذاكرة للاستدلال تساوي متطلبات الذاكرة لتحميل النموذج في ذاكرة VRAM لوحدة معالجة الرسومات GPU.. + +ولإعطاء بعض الأمثلة على مقدار ذاكرة الفيديو العشوائية (VRAM) التي يتطلبها تحميل نموذج بتنسيق bfloat16 تقريبًا: + +- **GPT3** يتطلب 2 \* 175 جيجا بايت = **350 جيجا بايت** VRAM +- [**بلوم**](https://huggingface.co/bigscience/bloom) يتطلب 2 \* 176 جيجا بايت = **352 جيجا بايت** VRAM +- [**Llama-2-70b**](https://huggingface.co/meta-llama/Llama-2-70b-hf) يتطلب 2 \* 70 جيجا بايت = **140 جيجا بايت** VRAM +- [**Falcon-40b**](https://huggingface.co/tiiuae/falcon-40b) يتطلب 2 \* 40 جيجا بايت = **80 جيجا بايت** VRAM +- [**MPT-30b**](https://huggingface.co/mosaicml/mpt-30b) يتطلب 2 \* 30 جيجا بايت = **60 جيجا بايت** VRAM +- [**bigcode/starcoder**](https://huggingface.co/bigcode/starcoder) يتطلب 2 \* 15.5 = **31 جيجا بايت** VRAM + +عند كتابة هذا الدليل، أكبر شريحة لوحدة معالجة الرسومات المتوفّرة هي A100 و H100 التي توفر 80 جيجابايت من ذاكرة الفيديو العشوائية (VRAM). تتطلب معظم النماذج المدرجة أعلاه أكثر من 80 جيجابايت فقط لتحميلها، وبالتالي فهي تتطلب بالضرورة [التوازي للموتّرات](https://huggingface.co/docs/transformers/perf_train_gpu_many#tensor-parallelism) و/أو [لتوازي الخطي](https://huggingface.co/docs/transformers/perf_train_gpu_many#naive-model-parallelism-vertical-and-pipeline-parallelism). + +🤗 لا يدعم Transformers موازاة التنسور خارج الصندوق لأنه يتطلب كتابة هيكلة النموذج بطريقة محددة. إذا كنت مهتمًا بكتابة نماذج بطريقة صديقة لموازاة التنسور، فلا تتردد في إلقاء نظرة على [مكتبة الاستدلال بتوليد النص](https://github.com/huggingface/text-generation-inference/tree/main/server/text_generation_server/models/custom_modeling). + +بدعم موازاة قنوات المعالجة البسيطة خارج الصندوق. للقيام بذلك، قم بتحميل النموذج باستخدام `device="auto"` والذي سيقوم تلقائيًا بوضع الطبقات المختلفة على وحدات معالجة الرسومات (GPU) المتاحة كما هو موضح [هنا](https://huggingface.co/docs/accelerate/v0.22.0/en/concept_guides/big_model_inference). +لاحظ، مع ذلك، أنه في حين أن موازاة قنوات المعالجة البسيطة فعالة للغاية، إلا أنها لا تعالج مشكلات عدم نشاط وحدة معالجة الرسومات (GPU). لهذا، تكون موازاة قنوات المعالجة المتقدمة مطلوبة كما هو موضح [هنا](https://huggingface.co/docs/transformers/en/perf_train_gpu_many#naive-model-parallelism-vertical-and-pipeline-parallelism). + +إذا كان لديك حق الوصول إلى عقدة 8 x 80 جيجابايت A100، فيمكنك تحميل BLOOM كما يلي + +```bash +!pip install transformers accelerate bitsandbytes optimum +``` +```python +from transformers import AutoModelForCausalLM + +model = AutoModelForCausalLM.from_pretrained("bigscience/bloom", device_map="auto", pad_token_id=0) +``` + +من خلال استخدام `device_map="auto"` سيتم توزيع طبقات الاهتمام بالتساوي عبر جميع وحدات معالجة الرسومات (GPU) المتاحة. + +في هذا الدليل، سنستخدم [bigcode/octocoder](https://huggingface.co/bigcode/octocoder) لأنه يمكن تشغيله على شريحة جهاز GPU A100 ذات 40 جيجا بايت. لاحظ أن جميع تحسينات الذاكرة والسرعة التي سنطبقها من الآن فصاعدًا تنطبق بالتساوي على النماذج التي تتطلب موازاة النماذج أو المصفوفات. + +نظرًا لأن النموذج مُحمَّل بدقة bfloat16، فباستخدام قاعدتنا الإرشادية أعلاه، نتوقع أن تكون متطلبات الذاكرة لتشغيل الاستدلال باستخدام `bigcode/octocoder` حوالي 31 جيجا بايت من ذاكرة الفيديو العشوائية (VRAM). دعنا نجرب. + +نقوم أولاً بتحميل النموذج والمجزىء اللغوي ثم نقوم بتمرير كلاهما إلى كائن [قنوات المعالجة](https://huggingface.co/docs/transformers/main_classes/pipelines) في Transformers. + +```python +from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline +import torch + +model = AutoModelForCausalLM.from_pretrained("bigcode/octocoder", torch_dtype=torch.bfloat16, device_map="auto", pad_token_id=0) +tokenizer = AutoTokenizer.from_pretrained("bigcode/octocoder") + +pipe = pipeline("text-generation", model=model, tokenizer=tokenizer) +``` + +```python +prompt = "Question: Please write a function in Python that transforms bytes to Giga bytes.\n\nAnswer:" + +result = pipe(prompt, max_new_tokens=60)[0]["generated_text"][len(prompt):] +result +``` + +**الإخراج**: +``` +Here is a Python function that transforms bytes to Giga bytes:\n\n```python\ndef bytes_to_giga_bytes(bytes):\n return bytes / 1024 / 1024 / 1024\n```\n\nThis function takes a single +``` + +رائع، يمكننا الآن استخدام النتيجة مباشرة لتحويل البايت إلى جيجا بايت. + +```python +def bytes_to_giga_bytes(bytes): + return bytes / 1024 / 1024 / 1024 +``` + +دعونا نستدعي [`torch.cuda.max_memory_allocated`](https://pytorch.org/docs/stable/generated/torch.cuda.max_memory_allocated.html) لقياس ذروة تخصيص ذاكرة وحدة معالجة الرسومات (GPU). + +```python +bytes_to_giga_bytes(torch.cuda.max_memory_allocated()) +``` + +**الإخراج**: +```bash +29.0260648727417 +``` + +قريب بما يكفي من حسابنا التقريبي! يمكننا أن نرى أن الرقم غير صحيح تمامًا لأن الانتقال من البايت إلى الكيلوبايت يتطلب الضرب في 1024 بدلاً من 1000. لذلك يمكن أيضًا فهم صيغة التقريب على أنها حساب "بحد أقصى X جيجا بايت". +لاحظ أنه إذا حاولنا تشغيل النموذج بدقة float32 الكاملة، فستكون هناك حاجة إلى 64 جيجا بايت من ذاكرة الفيديو العشوائية (VRAM). + +> يتم تدريب جميع النماذج تقريبًا بتنسيق bfloat16 في الوقت الحالي، ولا يوجد سبب لتشغيل النموذج بدقة float32 الكاملة إذا [كانت وحدة معالجة الرسومات (GPU) الخاصة بك تدعم bfloat16](https://discuss.pytorch.org/t/bfloat16-native-support/117155/5). لن توفر دقة float32 نتائج استدلال أفضل من الدقة التي تم استخدامها لتدريب النموذج. + +إذا لم تكن متأكدًا من تنسيق تخزين أوزان النموذج على Hub، فيمكنك دائمًا الاطلاع على تهيئة نقطة التفتيش في `"torch_dtype"`، على سبيل المثال [هنا](https://huggingface.co/meta-llama/Llama-2-7b-hf/blob/6fdf2e60f86ff2481f2241aaee459f85b5b0bbb9/config.json#L21). يوصى بتعيين النموذج إلى نفس نوع الدقة كما هو مكتوب في التهيئة عند التحميل باستخدام `from_pretrained(..., torch_dtype=...)` إلا إذا كان النوع الأصلي هو float32، وفي هذه الحالة يمكن استخدام `float16` أو `bfloat16` للاستدلال. + + +دعونا نحدد وظيفة `flush(...)` لتحرير جميع الذاكرة المخصصة بحيث يمكننا قياس ذروة ذاكرة وحدة معالجة الرسومات (GPU) المخصصة بدقة. + +```python +del pipe +del model + +import gc +import torch + +def flush(): + gc.collect() + torch.cuda.empty_cache() + torch.cuda.reset_peak_memory_stats() +``` + +دعونا نستدعيه الآن للتجربة التالية. + +```python +flush() +``` +في الإصدار الأخير من مكتبة Accelerate، يمكنك أيضًا استخدام طريقة مساعدة تسمى `release_memory()` + +```python +from accelerate.utils import release_memory +# ... + +release_memory(model) +``` +```python +from accelerate.utils import release_memory +# ... + +release_memory(model) +``` + +والآن ماذا لو لم يكن لدى وحدة معالجة الرسومات (GPU) لديك 32 جيجا بايت من ذاكرة الفيديو العشوائية (VRAM)؟ لقد وجد أن أوزان النماذج يمكن تحويلها إلى 8 بتات أو 4 بتات دون خسارة كبيرة في الأداء (انظر [Dettmers et al.](https://huggingface.co/papers/2208.07339)). +يمكن تحويل النموذج إلى 3 بتات أو 2 بتات مع فقدان مقبول في الأداء كما هو موضح في ورقة [GPTQ](https://huggingface.co/papers/2210.17323) 🤯. + +دون الدخول في الكثير من التفاصيل، تهدف مخططات التكميم إلى تخفيض دقة الأوزان مع محاولة الحفاظ على دقة نتائج النموذج كما هي (*أي* أقرب ما يمكن إلى bfloat16). +لاحظ أن التكميم يعمل بشكل خاص جيدًا لتوليد النص حيث كل ما نهتم به هو اختيار *مجموعة الرموز الأكثر احتمالًا التالية* ولا نهتم حقًا بالقيم الدقيقة لتوزيع الرمز التالي *logit*. +كل ما يهم هو أن توزيع الرمز التالي *logit* يظل كما هو تقريبًا بحيث تعطي عملية `argmax` أو `topk` نفس النتائج. + +هناك عدة تقنيات للتكميم، والتي لن نناقشها بالتفصيل هنا، ولكن بشكل عام، تعمل جميع تقنيات التكميم كما يلي: + +- 1. تكميم جميع الأوزان إلى الدقة المستهدفة +- 2. تحميل الأوزان المحولة، ومرر تسلسل المدخلات من المتجهات بتنسيق bfloat16 +- 3. قم بتحويل الأوزان ديناميكيًا إلى bfloat1 لإجراء الحسابات مع متجهات المدخلات بدقة `bfloat16` + +باختصار، هذا يعني أن مضروبات *مصفوفة المدخلات-الوزن*، حيث \\( X \\) هي المدخلات، \\( W \\) هي مصفوفة وزن و \\( Y \\) هي الناتج: + +$$ Y = X * W $$ + +تتغير إلى + +$$ Y = X * \text{dequantize}(W) $$ + +لكل عملية ضرب المصفوفات. يتم تنفيذ إلغاء التكميم وإعادة التكميم بشكل متسلسل لجميع مصفوفات الأوزان أثناء مرور المدخلات عبر رسم الشبكة. + +لذلك، غالبًا ما لا يتم تقليل وقت الاستدلال عند استخدام الأوزان المكممة، ولكن بدلاً من ذلك يزيد. + +كفى نظرية، دعنا نجرب! لتكميم الأوزان باستخدام المحولات، تحتاج إلى التأكد من تثبيت مكتبة [`bitsandbytes`](https://github.com/TimDettmers/bitsandbytes). + +```bash +!pip install bitsandbytes +``` + +يمكننا بعد ذلك تحميل النماذج في تكميم 8 بت ببساطة عن طريق إضافة علامة `load_in_8bit=True` إلى `from_pretrained`. + +```python +model = AutoModelForCausalLM.from_pretrained("bigcode/octocoder", load_in_8bit=True, pad_token_id=0) +``` + +الآن، دعنا نعيد تشغيل مثالنا ونقيس استخدام الذاكرة. + +```python +pipe = pipeline("text-generation", model=model, tokenizer=tokenizer) + +result = pipe(prompt, max_new_tokens=60)[0]["generated_text"][len(prompt):] +result +``` + +**الإخراج**: +``` +Here is a Python function that transforms bytes to Giga bytes:\n\n```python\ndef bytes_to_giga_bytes(bytes):\n return bytes / 1024 / 1024 / 1024\n```\n\nThis function takes a single +``` + +جميل، نحصل على نفس النتيجة كما في السابق، لذلك لا يوجد فقدان في الدقة! دعنا نلقي نظرة على مقدار الذاكرة المستخدمة هذه المرة. + +```python +bytes_to_giga_bytes(torch.cuda.max_memory_allocated()) +``` + +**الإخراج**: +``` +15.219234466552734 +``` + +أقل بكثير! لقد انخفضنا إلى ما يزيد قليلاً عن 15 جيجابايت، وبالتالي يمكننا تشغيل هذا النموذج على وحدات معالجة الرسومات للمستهلك مثل 4090. + +نرى مكسبًا لطيفًا جدًا في كفاءة الذاكرة ولا يوجد تقريبًا أي تدهور في ناتج النموذج. ومع ذلك، يمكننا أيضًا ملاحظة تباطؤ طفيف أثناء الاستدلال. + +نحذف النماذج ونفرغ الذاكرة مرة أخرى. +```python +del model +del pipe +``` + +```python +flush() +``` + +دعنا نرى ما هو استهلاك ذاكرة GPU الذروة الذي يوفره تكميم 4 بت. يمكن تكميم النموذج إلى 4 بت باستخدام نفس واجهة برمجة التطبيقات كما في السابق - هذه المرة عن طريق تمرير `load_in_4bit=True` بدلاً من `load_in_8bit=True`. + +```python +model = AutoModelForCausalLM.from_pretrained("bigcode/octocoder", load_in_4bit=True, pad_token_id=0) + +pipe = pipeline("text-generation", model=model, tokenizer=tokenizer) + +result = pipe(prompt, max_new_tokens=60)[0]["generated_text"][len(prompt):] +result +``` + +**الإخراج**: +``` +Here is a Python function that transforms bytes to Giga bytes:\n\n```\ndef bytes_to_gigabytes(bytes):\n return bytes / 1024 / 1024 / 1024\n```\n\nThis function takes a single argument +``` + +نحن نرى تقريبًا نفس نص الإخراج كما في السابق - فقط `python` مفقود قبل مقطع الكود. دعنا نرى مقدار الذاكرة المطلوبة. + +```python +bytes_to_giga_bytes(torch.cuda.max_memory_allocated()) +``` + +**الإخراج**: +``` +9.543574333190918 +``` + +فقط 9.5 جيجابايت! هذا ليس كثيرًا بالفعل لنموذج يزيد عدد معاملاته عن 15 مليار. + +على الرغم من أننا نرى تدهورًا بسيطًا جدًا في الدقة لنموذجنا هنا، إلا أن تكميم 4 بت يمكن أن يؤدي في الممارسة العملية غالبًا إلى نتائج مختلفة مقارنة بتكميم 8 بت أو الاستدلال الكامل `bfloat16`. الأمر متروك للمستخدم لتجربته. + +لاحظ أيضًا أن الاستدلال هنا كان أبطأ قليلاً مقارنة بتكميم 8 بت والذي يرجع إلى طريقة التكميم الأكثر عدوانية المستخدمة لتكميم 4 بت مما يؤدي إلى \\( \text{quantize} \\) و \\( \text{dequantize} \\) يستغرق وقتًا أطول أثناء الاستدلال. + +```python +del model +del pipe +``` +```python +flush() +``` + +بشكل عام، رأينا أن تشغيل OctoCoder بدقة 8 بت قلل من ذاكرة GPU VRAM المطلوبة من 32G GPU VRAM إلى 15 جيجابايت فقط، وتشغيل النموذج بدقة 4 بت يقلل من ذاكرة GPU VRAM المطلوبة إلى ما يزيد قليلاً عن 9 جيجابايت. + +يسمح تكميم 4 بت بتشغيل النموذج على وحدات معالجة الرسومات مثل RTX3090 و V100 و T4 والتي يمكن الوصول إليها بسهولة لمعظم الأشخاص. + +لمزيد من المعلومات حول التكميم ولمعرفة كيف يمكن تكميم النماذج لطلب ذاكرة GPU VRAM أقل حتى من 4 بت، نوصي بالاطلاع على تنفيذ [`AutoGPTQ`](https://huggingface.co/docs/transformers/main/en/main_classes/quantization#autogptq-integration%60). + +> كاستنتاج، من المهم تذكر أن تكميم النموذج يتداول كفاءة الذاكرة المحسنة مقابل الدقة وفي بعض الحالات وقت الاستدلال. + +إذا لم تكن ذاكرة GPU قيدًا لحالتك الاستخدام، فغالبًا لا توجد حاجة للنظر في التكميم. ومع ذلك، لا يمكن للعديد من وحدات معالجة الرسومات ببساطة تشغيل نماذج اللغة الكبيرة بدون طرق التكميم وفي هذه الحالة، تعد مخططات التكميم 4 بت و 8 بت أدوات مفيدة للغاية. + +لمزيد من المعلومات حول الاستخدام التفصيلي، نوصي بشدة بإلقاء نظرة على [وثائق تكميم المحولات](https://huggingface.co/docs/transformers/main_classes/quantization#general-usage). + +بعد ذلك، دعنا نلقي نظرة على كيفية تحسين الكفاءة الحسابية وكفاءة الذاكرة باستخدام خوارزميات أفضل وبنية نموذج محسنة. + +## 2. الانتباه السريع + +تتشارك نماذج اللغة الكبيرة (LLMs) الأعلى أداءً اليوم تقريبًا نفس البنية الأساسية التي تتكون من طبقات التغذية الأمامية، وطبقات التنشيط، وطبقات التطبيع الطبقي، والأهم من ذلك، طبقات الانتباه الذاتي. + +تعد طبقات الانتباه الذاتي مركزية لنماذج اللغة الكبيرة (LLMs) حيث تمكن النموذج من فهم العلاقات السياقية بين رموز المدخلات. +ومع ذلك، فإن استهلاك ذاكرة GPU الذروة لطبقات الانتباه الذاتي ينمو بشكل *رباعي* في كل من التعقيد الحسابي وتعقيد الذاكرة مع عدد رموز المدخلات (والذي يُطلق عليه أيضًا *طول التسلسل*) الذي نسميه في ما يلي بـ \\( N \\) . +على الرغم من أن هذا غير ملحوظ حقًا للتسلسلات الأقصر (حتى 1000 رمز إدخال)، إلا أنه يصبح مشكلة خطيرة للتسلسلات الأطول (حوالي 16000 رمز إدخال). + +دعنا نلقي نظرة أقرب. الصيغة لحساب الناتج \\( \mathbf{O} \\) لطبقة الانتباه الذاتي لإدخال \\( \mathbf{X} \\) بطول \\( N \\) هي: + +$$ \textbf{O} = \text{Attn}(\mathbf{X}) = \mathbf{V} \times \text{Softmax}(\mathbf{QK}^T) \text{ with } \mathbf{Q} = \mathbf{W}_q \mathbf{X}, \mathbf{V} = \mathbf{W}_v \mathbf{X}, \mathbf{K} = \mathbf{W}_k \mathbf{X} $$ + +يعد \\( \mathbf{X} = (\mathbf{x}_1, ... \mathbf{x}_{N}) \\) بالتالي تسلسل الإدخال إلى طبقة الاهتمام. وستتكون كل من الإسقاطات \\( \mathbf{Q} \\) و \\( \mathbf{K} \\) من \\( N \\) من المتجهات مما يؤدي إلى أن يكون حجم \\( \mathbf{QK}^T \\) هو \\( N^2 \\). + +عادة ما يكون لدى LLMs العديد من رؤوس الاهتمام، وبالتالي يتم إجراء العديد من حسابات الاهتمام الذاتي بالتوازي. +وبافتراض أن LLM لديها 40 رأس اهتمام وتعمل بدقة bfloat16، يمكننا حساب متطلبات الذاكرة لتخزين مصفوفات \\( \mathbf{QK^T} \\) لتكون \\( 40 * 2 * N^2 \\) بايت. بالنسبة لـ \\( N=1000 \\)، لا يلزم سوى حوالي 50 ميجابايت من VRAM، ولكن بالنسبة لـ \\( N=16000 \\) سنحتاج إلى 19 جيجابايت من VRAM، وبالنسبة لـ \\( N=100,000 \\) سنحتاج إلى ما يقرب من 1 تيرابايت فقط لتخزين مصفوفات \\( \mathbf{QK}^T \\). + +باختصار، سرعان ما يصبح خوارزمية الانتباه الذاتي الافتراضية مكلفة للغاية من حيث الذاكرة بالنسبة لسياقات الإدخال الكبيرة. + +مع تحسن LLMs في فهم النص وتوليد النص، يتم تطبيقها على مهام متزايدة التعقيد. في حين أن النماذج كانت تتعامل سابقًا مع ترجمة أو تلخيص بضع جمل، فإنها الآن تدير صفحات كاملة، مما يتطلب القدرة على معالجة أطوال إدخال واسعة. + +كيف يمكننا التخلص من متطلبات الذاكرة الباهظة للتطويلات المدخلة الكبيرة؟ نحن بحاجة إلى طريقة جديدة لحساب آلية الاهتمام الذاتي التي تتخلص من مصفوفة \\( QK^T \\). [طريقه داو وآخرون.](https://huggingface.co/papers/2205.14135) طوروا بالضبط مثل هذا الخوارزمية الجديدة وأطلقوا عليها اسم **Flash Attention**. + +باختصار، يكسر الاهتمام الفلاشي حساب \\( \mathbf{V} \times \operatorname{Softmax}(\mathbf{QK}^T\\)) ويحسب بدلاً من ذلك قطعًا أصغر من الإخراج عن طريق التكرار عبر العديد من خطوات حساب Softmax: + +$$ \textbf{O}_i \leftarrow s^a_{ij} * \textbf{O}_i + s^b_{ij} * \mathbf{V}_{j} \times \operatorname{Softmax}(\mathbf{QK}^T_{i,j}) \text{ for multiple } i, j \text{ iterations } $$ + +مع \\( s^a_{ij} \\) و \\( s^b_{ij} \\) كونها بعض إحصائيات التطبيع softmax التي يجب إعادة حسابها لكل \\( i \\) و \\( j \\). + +يرجى ملاحظة أن Flash Attention بالكامل أكثر تعقيدًا إلى حد ما ويتم تبسيطه بشكل كبير هنا حيث أن التعمق كثيرًا يخرج عن نطاق هذا الدليل. القارئ مدعو لإلقاء نظرة على ورقة Flash Attention المكتوبة جيدًا [1] لمزيد من التفاصيل. + +الفكرة الرئيسية هنا هي: + +> من خلال تتبع إحصائيات التطبيع softmax واستخدام بعض الرياضيات الذكية، يعطي Flash Attention **مخرجات متطابقة رقميًا** مقارنة بطبقة الاهتمام الذاتي الافتراضية بتكلفة ذاكرة لا تزيد خطيًا مع \\( N \\). + +عند النظر إلى الصيغة، قد يقول المرء بديهيًا أن الاهتمام الفلاشي يجب أن يكون أبطأ بكثير مقارنة بصيغة الاهتمام الافتراضية حيث يلزم إجراء المزيد من الحسابات. في الواقع، يتطلب Flash Attention المزيد من عمليات الفاصلة العائمة مقارنة بالاهتمام العادي حيث يجب إعادة حساب إحصائيات التطبيع softmax باستمرار (راجع [الورقة](https://huggingface.co/papers/2205.14135) لمزيد من التفاصيل إذا كنت مهتمًا) + +> ومع ذلك، فإن الاهتمام الفلاشي أسرع بكثير في الاستدلال مقارنة بالاهتمام الافتراضي الذي يأتي من قدرته على تقليل الطلبات على ذاكرة GPU الأبطأ ذات النطاق الترددي العالي (VRAM)، والتركيز بدلاً من ذلك على ذاكرة SRAM الأسرع الموجودة على الشريحة. + +من الناحية الأساسية، يتأكد Flash Attention من إمكانية إجراء جميع عمليات الكتابة والقراءة الوسيطة باستخدام ذاكرة SRAM السريعة الموجودة على الشريحة بدلاً من الاضطرار إلى الوصول إلى ذاكرة VRAM الأبطأ لحساب متجه الإخراج \\( \mathbf{O} \\). + +من الناحية العملية، لا يوجد حاليًا أي سبب **عدم** استخدام الاهتمام الفلاشي إذا كان متاحًا. الخوارزمية تعطي نفس المخرجات رياضيا، وأسرع وأكثر كفاءة في استخدام الذاكرة. + +لنلقِ نظرة على مثال عملي. + + +يحصل نموذج OctoCoder الخاص بنا الآن على موجه إدخال أطول بشكل كبير يتضمن ما يسمى *موجه النظام*. تُستخدم موجهات النظام لتوجيه LLM إلى مساعد أفضل مصمم لمهام المستخدمين. +فيما يلي، نستخدم موجه النظام الذي سيجعل OctoCoder مساعد ترميز أفضل. + +```python +system_prompt = """Below are a series of dialogues between various people and an AI technical assistant. +The assistant tries to be helpful, polite, honest, sophisticated, emotionally aware, and humble but knowledgeable. +The assistant is happy to help with code questions and will do their best to understand exactly what is needed. +It also tries to avoid giving false or misleading information, and it caveats when it isn't entirely sure about the right answer. +That said, the assistant is practical really does its best, and doesn't let caution get too much in the way of being useful. + +The Starcoder models are a series of 15.5B parameter models trained on 80+ programming languages from The Stack (v1.2) (excluding opt-out requests). +The model uses Multi Query Attention, was trained using the Fill-in-the-Middle objective, and with 8,192 tokens context window for a trillion tokens of heavily deduplicated data. +----- + +Question: Write a function that takes two lists and returns a list that has alternating elements from each input list. + +Answer: Sure. Here is a function that does that. + +def alternating(list1, list2): + results = [] + for i in range(len(list1)): + results.append(list1[i]) + results.append(list2[i]) + return results + +Question: Can you write some test cases for this function? + +Answer: Sure, here are some tests. + +assert alternating([10, 20, 30], [1, 2, 3]) == [10, 1, 20, 2, 30, 3] +assert alternating([True, False], [4, 5]) == [True, 4, False, 5] +assert alternating([], []) == [] + +Question: Modify the function so that it returns all input elements when the lists have uneven length. The elements from the longer list should be at the end. + +Answer: Here is the modified function. + +def alternating(list1, list2): + results = [] + for i in range(min(len(list1), len(list2))): + results.append(list1[i]) + results.append(list2[i]) + if len(list1) > len(list2): + results.extend(list1[i+1:]) + else: + results.extend(list2[i+1:]) + return results +----- +""" +``` +لأغراض التوضيح، سنكرر موجه النظام عشر مرات بحيث يكون طول الإدخال طويلاً بما يكفي لملاحظة وفورات ذاكرة Flash Attention. +نضيف موجه النص الأصلي "سؤال: يرجى كتابة وظيفة في Python تقوم بتحويل البايتات إلى جيجا بايت. + +```python +long_prompt = 10 * system_prompt + prompt +``` + +نقوم بتنفيذ نموذجنا مرة أخرى بدقة bfloat16. + +```python +model = AutoModelForCausalLM.from_pretrained("bigcode/octocoder", torch_dtype=torch.bfloat16, device_map="auto") +tokenizer = AutoTokenizer.from_pretrained("bigcode/octocoder") + +pipe = pipeline("text-generation", model=model, tokenizer=tokenizer) +``` + +دعنا الآن نقوم بتشغيل النموذج تمامًا مثلما كان من قبل *بدون اهتمام فلاشي* وقياس متطلبات ذاكرة GPU وقت الذروة ووقت الاستدلال. + +```python +import time + +start_time = time.time() +result = pipe(long_prompt, max_new_tokens=60)[0]["generated_text"][len(long_prompt):] + +print(f"Generated in {time.time() - start_time} seconds.") +result +``` + +**الإخراج**: +``` +تم التوليد في 10.96854019165039 ثانية. +بالتأكيد. إليك وظيفة للقيام بذلك. + +def bytes_to_giga(bytes): +return bytes / 1024 / 1024 / 1024 + +الإجابة: بالتأكيد. إليك وظيفة للقيام بذلك. + +ديف +``` + +نحصل على نفس الإخراج كما كان من قبل، ولكن هذه المرة، يقوم النموذج بتكرار الإجابة عدة مرات حتى يتم قطعها عند 60 رمزًا. ليس من المستغرب أننا كررنا موجه النظام عشر مرات لأغراض التوضيح وبالتالي قمنا بتشغيل النموذج لتكرار نفسه. + +**ملاحظة** لا ينبغي تكرار موجه النظام عشر مرات في التطبيقات الواقعية - مرة واحدة كافية! + +دعنا نقيس متطلبات ذاكرة GPU وقت الذروة. + +```python +bytes_to_giga_bytes(torch.cuda.max_memory_allocated()) +``` + +**الإخراج**: +``` +37.668193340301514 +``` + +كما نرى، فإن متطلبات ذاكرة GPU وقت الذروة أعلى بكثير مما كانت عليه في البداية، وهو ما يرجع إلى حد كبير إلى تسلسل الإدخال الأطول. أيضًا، يستغرق التوليد أكثر من دقيقة بقليل الآن. + +نستدعي `flush()` لتحرير ذاكرة GPU لتجربتنا التالية. + +```python +flush() +``` + +لمقارنة، دعونا نقوم بتشغيل نفس الدالة، ولكن تمكين الاهتمام فلاش بدلا من ذلك. +للقيام بذلك، نقوم بتحويل النموذج إلى [BetterTransformer](Https://huggingface.co/docs/optimum/bettertransformer/overview) ومن خلال القيام بذلك تمكين PyTorch's [SDPA self-attention](Https://pytorch.org/docs/master/generated/torch.nn.functional.scaled_dot_product_attention) والتي بدورها قادرة على استخدام الاهتمام فلاش. + +```python +model.to_bettertransformer() +``` + +الآن نقوم بتشغيل نفس مقتطف التعليمات البرمجية بالضبط كما كان من قبل وتحت الغطاء سوف تستخدم المحولات الاهتمام فلاش. + +```py +start_time = time.time() +with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=False, enable_mem_efficient=False): + result = pipe(long_prompt, max_new_tokens=60)[0]["generated_text"][len(long_prompt):] + +print(f"Generated in {time.time() - start_time} seconds.") +result +``` + +**الإخراج**: +``` +تم التوليد في 3.0211617946624756 ثانية. +بالتأكيد. إليك وظيفة للقيام بذلك. + +def bytes_to_giga(bytes): +return bytes / 1024 / 1024 / 1024 + +الإجابة: بالتأكيد. إليك وظيفة للقيام بذلك. + +ديف +``` + +نحصل على نفس النتيجة بالضبط كما كان من قبل، ولكن يمكننا ملاحظة تسريع كبير بفضل الاهتمام فلاش. + +دعنا نقيس استهلاك الذاكرة لآخر مرة. + +```python +bytes_to_giga_bytes(torch.cuda.max_memory_allocated()) +``` + +**الإخراج**: +``` +32.617331981658936 +``` + +ونحن تقريبا مرة أخرى إلى ذاكرة GPU الذروة الأصلية لدينا 29GB. + +يمكننا أن نلاحظ أننا نستخدم فقط حوالي 100 ميجابايت إضافية من ذاكرة GPU عند تمرير تسلسل إدخال طويل جدًا مع الاهتمام فلاش مقارنة بتمرير تسلسل إدخال قصير كما فعلنا في البداية. + +```py +flush() +``` + +لمزيد من المعلومات حول كيفية استخدام Flash Attention، يرجى الاطلاع على [صفحة doc هذه](Https://huggingface.co/docs/transformers/en/perf_infer_gpu_one#flashattention-2). + +## 3. الابتكارات المعمارية + +حتى الآن، نظرنا في تحسين الكفاءة الحسابية والذاكرة من خلال: + +- صب الأوزان في تنسيق دقة أقل +- استبدال خوارزمية الاهتمام الذاتي بإصدار أكثر كفاءة من حيث الذاكرة والحساب + +دعونا الآن نلقي نظرة على كيفية تغيير بنية LLM بحيث تكون أكثر فعالية وكفاءة للمهام التي تتطلب مدخلات نصية طويلة، على سبيل المثال: +- استرجاع الأسئلة المعززة، +- تلخيص، +- الدردشة + +لاحظ أن "الدردشة" لا تتطلب من LLM التعامل مع مدخلات نصية طويلة فحسب، بل تتطلب أيضًا أن يكون LLM قادرًا على التعامل بكفاءة مع الحوار ذهابًا وإيابًا بين المستخدم والمساعد (مثل ChatGPT). + +بمجرد تدريبها، يصبح من الصعب تغيير بنية LLM الأساسية، لذلك من المهم مراعاة مهام LLM مسبقًا وتحسين بنية النموذج وفقًا لذلك. +هناك مكونان مهمان لبنية النموذج يصبحان بسرعة عنق زجاجة للذاكرة و/أو الأداء لتسلسلات الإدخال الكبيرة. + +- الترميزات الموضعية +- ذاكرة التخزين المؤقت للقيمة الرئيسية + +دعنا نلقي نظرة على كل مكون بمزيد من التفاصيل + +### 3.1 تحسين الترميزات الموضعية لـ LLMs + +يضع الاهتمام الذاتي كل رمز في علاقة مع رموز أخرى. +كمثال، يمكن أن تبدو مصفوفة \\( \operatorname{Softmax}(\mathbf{QK}^T) \\) لتسلسل الإدخال النصي *"مرحبًا"، "أنا"، "أحب"، "أنت"* كما يلي: + +![](/blog/assets/163_optimize_llm/self_attn_tokens.png) + +يتم منح كل رمز كلمة كتلة احتمال يتم من خلالها الاهتمام بجميع رموز الكلمات الأخرى، وبالتالي يتم وضعها في علاقة مع جميع رموز الكلمات الأخرى. على سبيل المثال، تحضر كلمة *"الحب"* كلمة *"مرحبًا"* بنسبة 5%، و *"أنا"* بنسبة 30%، ونفسها بنسبة 65%. + +سيواجه LLM القائم على الاهتمام الذاتي، ولكن بدون الترميزات الموضعية، صعوبات كبيرة في فهم مواضع نصوص الإدخال بالنسبة لبعضها البعض. +ويرجع ذلك إلى أن درجة الاحتمال التي يحسبها \\( \mathbf{QK}^T \\) تربط كل رمز كلمة بكل رمز كلمة أخرى في حسابات \\( O (1) \\) بغض النظر عن مسافة الموضع النسبي بينهما. +لذلك، بالنسبة إلى LLM بدون ترميزات موضعية، يبدو أن كل رمز له نفس المسافة إلى جميع الرموز الأخرى، على سبيل المثال، سيكون من الصعب التمييز بين *"مرحبًا أنا أحبك"* و *"أنت تحبني مرحبًا"*. + +لكي يفهم LLM ترتيب الجملة، يلزم وجود *إشارة* إضافية ويتم تطبيقها عادةً في شكل *الترميزات الموضعية* (أو ما يُطلق عليه أيضًا *الترميزات الموضعية*). +لم يتم ترجمة النص الخاص والروابط وأكواد HTML وCSS بناءً على طلبك. + +قدم مؤلفو الورقة البحثية [*Attention Is All You Need*](https://huggingface.co/papers/1706.03762) تضمينات موضعية جيبية مثلثية \\( \mathbf{P} = \mathbf{p}_1, \ldots, \mathbf{p}_N \\) حيث يتم حساب كل متجه \\( \mathbf{p}_i \\) كدالة جيبية لموضعه \\( i \\) . +بعد ذلك يتم ببساطة إضافة التضمينات الموضعية إلى متجهات تسلسل الإدخال \\( \mathbf{\hat{X}} = \mathbf{\hat{x}}_1, \ldots, \mathbf{\hat{x}}_N \\) = \\( \mathbf{x}_1 + \mathbf{p}_1, \ldots, \mathbf{x}_N + \mathbf{p}_N \\) وبالتالي توجيه النموذج لتعلم ترتيب الجملة بشكل أفضل. + +بدلاً من استخدام التضمينات الموضعية الثابتة، استخدم آخرون (مثل [Devlin et al.](https://huggingface.co/papers/1810.04805)) تضمينات موضعية مكتسبة يتم من خلالها تعلم التضمينات الموضعية \\( \mathbf{P} \\) أثناء التدريب. + +كانت التضمينات الموضعية الجيبية والمكتسبة هي الطرق السائدة لترميز ترتيب الجملة في نماذج اللغة الكبيرة، ولكن تم العثور على بعض المشكلات المتعلقة بهذه التضمينات الموضعية: + +1. التضمينات الموضعية الجيبية والمكتسبة هي تضمينات موضعية مطلقة، أي ترميز تضمين فريد لكل معرف موضعي: \\( 0, \ldots, N \\) . كما أظهر [Huang et al.](https://huggingface.co/papers/2009.13658) و [Su et al.](https://huggingface.co/papers/2104.09864)، تؤدي التضمينات الموضعية المطلقة إلى أداء ضعيف لنماذج اللغة الكبيرة للمدخلات النصية الطويلة. بالنسبة للمدخلات النصية الطويلة، يكون من المفيد إذا تعلم النموذج المسافة الموضعية النسبية التي تمتلكها رموز المدخلات إلى بعضها البعض بدلاً من موضعها المطلق. +2. عند استخدام التضمينات الموضعية المكتسبة، يجب تدريب نموذج اللغة الكبيرة على طول إدخال ثابت \\( N \\)، مما يجعل من الصعب الاستقراء إلى طول إدخال أطول مما تم تدريبه عليه. + +في الآونة الأخيرة، أصبحت التضمينات الموضعية النسبية التي يمكنها معالجة المشكلات المذكورة أعلاه أكثر شعبية، وأبرزها: + +- [تضمين الموضع الدوراني (RoPE)](https://huggingface.co/papers/2104.09864) +- [ALiBi](https://huggingface.co/papers/2108.12409) + +يؤكد كل من *RoPE* و *ALiBi* أنه من الأفضل توجيه نموذج اللغة الكبيرة حول ترتيب الجملة مباشرة في خوارزمية الانتباه الذاتي حيث يتم وضع رموز الكلمات في علاقة مع بعضها البعض. على وجه التحديد، يجب توجيه ترتيب الجملة عن طريق تعديل عملية \\( \mathbf{QK}^T \\) . + +دون الدخول في الكثير من التفاصيل، يشير *RoPE* إلى أنه يمكن ترميز المعلومات الموضعية في أزواج الاستعلام-المفتاح، على سبيل المثال \\( \mathbf{q}_i \\) و \\( \mathbf{x}_j \\) عن طريق تدوير كل متجه بزاوية \\( \theta * i \\) و \\( \theta * j \\) على التوالي مع \\( i, j \\) تصف موضع الجملة لكل متجه: + +$$ \mathbf{\hat{q}}_i^T \mathbf{\hat{x}}_j = \mathbf{{q}}_i^T \mathbf{R}_{\theta, i -j} \mathbf{{x}}_j. $$ + +يمثل \\( \mathbf{R}_{\theta, i - j} \\) مصفوفة دورانية. \\( \theta \\) *لا* يتم تعلمه أثناء التدريب، ولكن بدلاً من ذلك يتم تعيينه إلى قيمة محددة مسبقًا تعتمد على طول تسلسل الإدخال الأقصى أثناء التدريب. + +> من خلال القيام بذلك، يتم التأثير على درجة الاحتمال بين \\( \mathbf{q}_i \\) و \\( \mathbf{q}_j \\) فقط إذا \\( i \ne j \\) ويعتمد فقط على المسافة النسبية \\( i - j \\) بغض النظر عن المواضع المحددة لكل متجه \\( i \\) و \\( j \\) . + +يستخدم *RoPE* في العديد من نماذج اللغة الكبيرة الأكثر أهمية اليوم، مثل: + +- [**Falcon**](https://huggingface.co/tiiuae/falcon-40b) +- [**Llama**](https://huggingface.co/papers/2302.13971) +- [**PaLM**](https://huggingface.co/papers/2204.02311) + +كبديل، يقترح *ALiBi* مخطط ترميز موضعي نسبي أبسط بكثير. يتم إضافة المسافة النسبية التي تمتلكها رموز المدخلات إلى بعضها البعض كعدد صحيح سلبي مقياس بقيمة محددة مسبقًا `m` إلى كل إدخال استعلام-مفتاح لمصفوفة \\( \mathbf{QK}^T \\) مباشرة قبل حساب softmax. + +![](/blog/assets/163_optimize_llm/alibi.png) + +كما هو موضح في ورقة [ALiBi](https://huggingface.co/papers/2108.12409)، يسمح هذا الترميز الموضعي النسبي البسيط للنموذج بالحفاظ على أداء عالٍ حتى في تسلسلات المدخلات النصية الطويلة جدًا. + +يُستخدم *ALiBi* في العديد من أهم نماذج اللغة الكبيرة المستخدمة اليوم، مثل: + +- [**MPT**](https://huggingface.co/mosaicml/mpt-30b) +- [**BLOOM**](https://huggingface.co/bigscience/bloom) + +يمكن لكل من ترميزات الموضع *RoPE* و *ALiBi* الاستقراء إلى أطوال إدخال لم يتم ملاحظتها أثناء التدريب، في حين ثبت أن الاستقراء يعمل بشكل أفضل بكثير خارج الصندوق لـ *ALiBi* مقارنة بـ *RoPE*. +بالنسبة لـ ALiBi، ما عليك سوى زيادة قيم مصفوفة الموضع المثلث السفلي لمطابقة طول تسلسل الإدخال. +بالنسبة لـ *RoPE*، يؤدي الحفاظ على نفس \\( \theta \\) الذي تم استخدامه أثناء التدريب إلى نتائج سيئة عند تمرير إدخالات نصية أطول بكثير من تلك التي شوهدت أثناء التدريب، راجع [Press et al.](https://huggingface.co/papers/2108.12409). ومع ذلك، وجد المجتمع بعض الحيل الفعالة التي تقوم بتعديل \\( \theta \\)، مما يسمح لترميزات الموضع *RoPE* بالعمل بشكل جيد لتسلسلات إدخال النص المستقرئة (راجع [هنا](https://github.com/huggingface/transformers/pull/24653)). + +> كل من RoPE و ALiBi عبارة عن ترميزات موضع نسبي *لا* يتم تعلمها أثناء التدريب، ولكن بدلاً من ذلك تستند إلى الحدس التالي: + - يجب إعطاء الإشارات الموضعية حول إدخالات النص مباشرة إلى مصفوفة \\( QK^T \\) لطبقة الاهتمام الذاتي + - يجب تحفيز LLM لتعلم ترميزات موضعية ثابتة *نسبية* المسافة لبعضها البعض + - كلما ابتعدت رموز إدخال النص عن بعضها البعض، انخفض احتمال الاستعلام والقيمة. كل من RoPE و ALiBi يقللان من احتمال الاستعلام والمفتاح للرموز البعيدة عن بعضها البعض. يقوم RoPE بذلك عن طريق تقليل منتج المتجه من خلال زيادة الزاوية بين متجهات الاستعلام والمفتاح. تضيف ALiBi أرقامًا كبيرة سالبة إلى المنتج الاتجاهي + +في الختام، من الأفضل تدريب نماذج اللغة الكبيرة المراد نشرها في مهام تتطلب التعامل مع إدخالات نصية كبيرة باستخدام ترميزات موضعية نسبية، مثل RoPE و ALiBi. لاحظ أيضًا أنه حتى إذا تم تدريب نموذج لغة كبيرة باستخدام RoPE و ALiBi على طول ثابت يبلغ، على سبيل المثال، \\( N_1 = 2048 \\)، فيمكن استخدامه عمليًا بإدخالات نصية أكبر بكثير من \\( N_1 \\)، مثل \\( N_2 = 8192> N_1 \\) عن طريق استقراء الترميزات الموضعية. + +### 3.2 ذاكرة التخزين المؤقت للمفتاح والقيمة + +تعمل عملية توليد النص ذاتي التراجع باستخدام نماذج اللغة الكبيرة عن طريق إدخال تسلسل إدخال بشكل تكراري، وأخذ عينات من الرمز التالي، وإلحاق الرمز التالي بتسلسل الإدخال، والاستمرار في ذلك حتى ينتج نموذج اللغة الكبيرة رمزًا يشير إلى انتهاء التوليد. + +يرجى الاطلاع على [دليل إنشاء النص الخاص بـ Transformer](https://huggingface.co/docs/transformers/llm_tutorial#generate-text) للحصول على شرح مرئي أفضل لكيفية عمل التوليد ذاتي التراجع. + +دعنا ننفذ مقتطفًا قصيرًا من التعليمات البرمجية لإظهار كيفية عمل التوليد ذاتي التراجع في الممارسة. ببساطة، سنأخذ الرمز الأكثر احتمالًا عبر `torch.argmax`. + +```python +input_ids = tokenizer(prompt, return_tensors="pt")["input_ids"].to("cuda") + +for _ in range(5): + next_logits = model(input_ids)["logits"][:, -1:] + next_token_id = torch.argmax(next_logits,dim=-1) + + input_ids = torch.cat([input_ids, next_token_id], dim=-1) + print("shape of input_ids", input_ids.shape) + +generated_text = tokenizer.batch_decode(input_ids[:, -5:]) +generated_text +``` + +**الإخراج**: +``` +shape of input_ids torch.Size([1, 21]) +shape of input_ids torch.Size([1, 22]) +shape of input_ids torch.Size([1, 23]) +shape of input_ids torch.Size([1, 24]) +shape of input_ids torch.Size([1, 25]) +[' Here is a Python function'] +``` + +كما نرى، في كل مرة نزيد من رموز إدخال النص بالرمز الذي تم أخذ عينات منه للتو. + +باستثناءات قليلة جدًا، يتم تدريب نماذج اللغة الكبيرة باستخدام [هدف نمذجة اللغة السببية](https://huggingface.co/docs/transformers/tasks/language_modeling#causal-language-modeling) وبالتالي يتم قناع المثلث العلوي لمصفوفة نتيجة الاهتمام - وهذا هو السبب في ترك نتائج الاهتمام فارغة (*أي لها احتمال 0*) في المخططين أعلاه. للحصول على ملخص سريع حول نمذجة اللغة السببية، يمكنك الرجوع إلى مدونة [*Illustrated Self Attention*](https://jalammar.github.io/illustrated-gpt2/#part-2-illustrated-self-attention). + +ونتيجة لذلك، *لا* تعتمد الرموز *أبدًا* على الرموز السابقة، وبشكل أكثر تحديدًا، لا يتم أبدًا وضع المتجه \\( \mathbf{q}_i \\) في علاقة مع أي متجهات المفاتيح والقيم \\( \mathbf{k}_j، \mathbf{v}_j \\) إذا \\( j> i \\). بدلاً من ذلك، يحضر \\( \mathbf{q}_i \\) فقط إلى متجهات المفاتيح والقيم السابقة \\( \mathbf{k}_{m < i}، \mathbf{v}_{m < i} \text{ , for } m \in \{0، \ ldots i - 1\} \\). لتقليل الحسابات غير الضرورية، يمكن تخزين ذاكرة التخزين المؤقت لكل طبقة للمفاتيح ومتجهات القيم لجميع الخطوات الزمنية السابقة. + +فيما يلي، سنطلب من نموذج اللغة الكبيرة استخدام ذاكرة التخزين المؤقت للمفاتيح والقيم عن طريق استردادها وإرسالها لكل عملية توجيه. +في Transformers، يمكننا استرداد ذاكرة التخزين المؤقت للمفاتيح والقيم عن طريق تمرير علم `use_cache` إلى مكالمة `forward` ويمكننا بعد ذلك تمريره مع الرمز الحالي. + +```python +past_key_values = None # past_key_values is the key-value cache +generated_tokens = [] +next_token_id = tokenizer(prompt, return_tensors="pt")["input_ids"].to("cuda") + +for _ in range(5): + next_logits, past_key_values = model(next_token_id, past_key_values=past_key_values, use_cache=True).to_tuple() + next_logits = next_logits[:, -1:] + next_token_id = torch.argmax(next_logits, dim=-1) + + print("shape of input_ids", next_token_id.shape) + print("length of key-value cache", len(past_key_values[0][0])) # past_key_values are of shape [num_layers, 0 for k, 1 for v, batch_size, length, hidden_dim] + generated_tokens.append(next_token_id.item()) + +generated_text = tokenizer.batch_decode(generated_tokens) +generated_text +``` + +**الإخراج**: +``` +shape of input_ids torch.Size([1, 1]) +length of key-value cache 20 +shape of input_ids torch.Size([1, 1]) +length of key-value cache 21 +shape of input_ids torch.Size([1, 1]) +length of key-value cache 22 +shape of input_ids torch.Size([1, 1]) +length of key-value cache 23 +shape of input_ids torch.Size([1, 1]) +length of key-value cache 24 +[' Here', ' is', ' a', ' Python', ' function'] +``` + +كما هو موضح، عند استخدام ذاكرة التخزين المؤقت للمفاتيح والقيم، لا يتم زيادة رموز إدخال النص في الطول، ولكنها تظل متجه إدخال واحدًا. من ناحية أخرى، يتم زيادة طول ذاكرة التخزين المؤقت للمفاتيح والقيم بواحد في كل خطوة فك التشفير. + +> يعني استخدام ذاكرة التخزين المؤقت للمفاتيح والقيم أن \\( \mathbf{QK}^T \\) يتم تقليله بشكل أساسي إلى \\( \mathbf{q}_c\mathbf{K}^T \\) مع \\( \mathbf{q}_c \\) كونها إسقاط الاستعلام للرمز المدخل الحالي الذي يكون *دائمًا* مجرد متجه واحد. + +لاستخدام ذاكرة التخزين المؤقت للمفاتيح والقيم ميزتان: +- زيادة كبيرة في الكفاءة الحسابية حيث يتم إجراء حسابات أقل مقارنة بحساب مصفوفة \\( \mathbf{QK}^T \\) الكاملة. يؤدي ذلك إلى زيادة سرعة الاستدلال +- لا تزداد الذاكرة القصوى المطلوبة بشكل تربيعي مع عدد الرموز المولدة، ولكنها تزداد بشكل خطي فقط. + +> يجب *دائمًا* استخدام ذاكرة التخزين المؤقت للمفاتيح والقيم حيث يؤدي ذلك إلى نتائج متطابقة وزيادة كبيرة في السرعة لتسلسلات الإدخال الأطول. ذاكرة التخزين المؤقت للمفاتيح والقيم ممكّنة بشكل افتراضي في Transformers عند استخدام خط أنابيب النص أو طريقة [`generate`](https://huggingface.co/docs/transformers/main_classes/text_generation). + + + + +لاحظ أنه على الرغم من نصيحتنا باستخدام ذاكرة التخزين المؤقت للمفاتيح والقيم، فقد يكون إخراج نموذج اللغة الكبيرة مختلفًا قليلاً عند استخدامها. هذه خاصية نوى ضرب المصفوفة نفسها - يمكنك قراءة المزيد عنها [هنا](https://github.com/huggingface/transformers/issues/25420#issuecomment-1775317535). + + + +#### 3.2.1 محادثة متعددة الجولات + +ذاكرة التخزين المؤقت للمفاتيح والقيم مفيدة بشكل خاص للتطبيقات مثل الدردشة حيث تكون هناك حاجة إلى عدة تمريرات من فك التشفير ذاتي التراجع. دعنا نلقي نظرة على مثال. + +``` +المستخدم: كم عدد الأشخاص الذين يعيشون في فرنسا؟ +المساعد: يعيش حوالي 75 مليون شخص في فرنسا +المستخدم: وكم عدد الأشخاص في ألمانيا؟ +المساعد: يوجد في ألمانيا حوالي 81 مليون نسمة + +User: How many people live in France? +Assistant: Roughly 75 million people live in France +User: And how many are in Germany? +Assistant: Germany has ca. 81 million inhabitants +``` + +In this chat، يقوم LLM بتشغيل فك التشفير التلقائي مرتين: + 1. المرة الأولى، تكون ذاكرة التخزين المؤقت key-value فارغة، ويكون موجه الإدخال هو "User: How many people live in France؟" ويقوم النموذج بإنشاء النص "Roughly 75 million people live in France" بشكل تلقائي أثناء زيادة ذاكرة التخزين المؤقت key-value في كل خطوة فك تشفير. + 2. في المرة الثانية، يكون موجه الإدخال هو "User: How many people live in France؟ \n Assistant: Roughly 75 million people live in France \n User: And how many in Germany؟". بفضل ذاكرة التخزين المؤقت، يتم بالفعل حساب جميع متجهات القيمة الرئيسية لجاريتين الأولى. لذلك يتكون موجه الإدخال فقط من "User: And how many in Germany؟". أثناء معالجة موجه الإدخال المختصر، يتم ربط متجهات القيمة المحسوبة بذاكرة التخزين المؤقت key-value الخاصة بفك التشفير الأول. يتم بعد ذلك إنشاء إجابة المساعد الثانية "Germany has ca. 81 million inhabitants" بشكل تلقائي باستخدام ذاكرة التخزين المؤقت key-value المكونة من متجهات القيمة المشفرة لـ "User: How many people live in France؟ \n Assistant: Roughly 75 million people live in France \n User: And how many are in Germany؟". + +يجب ملاحظة أمرين هنا: + 1. الحفاظ على كل السياق أمر بالغ الأهمية للنماذج اللغوية الكبيرة (LLMs) التي يتم نشرها في الدردشة بحيث يفهم LLM كل سياق المحادثة السابق. على سبيل المثال، بالنسبة للمثال أعلاه، يحتاج LLM إلى فهم أن المستخدم يشير إلى السكان عند السؤال "And how many are in Germany؟". + 2. ذاكرة التخزين المؤقت key-value مفيدة للغاية للدردشة حيث تتيح لنا النمو المستمر لتاريخ الدردشة المشفرة بدلاً من الاضطرار إلى إعادة تشفير تاريخ الدردشة من البداية (كما هو الحال، على سبيل المثال، عند استخدام بنية ترميز فك التشفير). + +في `transformers`، ستعيد مكالمة `generate` `past_key_values` عندما يتم تمرير `return_dict_in_generate=True`، بالإضافة إلى `use_cache=True` الافتراضي. لاحظ أنه غير متوفر بعد من خلال واجهة `pipeline`. + +```python +# Generation as usual +prompt = system_prompt + "Question: Please write a function in Python that transforms bytes to Giga bytes.\n\nAnswer: Here" +model_inputs = tokenizer(prompt، return_tensors='pt') +generation_output = model.generate(**model_inputs، max_new_tokens=60، return_dict_in_generate=True) +decoded_output = tokenizer.batch_decode(generation_output.sequences)[0] + +# Piping the returned `past_key_values` to speed up the next conversation round +prompt = decoded_output + "\nQuestion: How can I modify the function above to return Mega bytes instead?\n\nAnswer: Here" +model_inputs = tokenizer(prompt، return_tensors='pt') +generation_output = model.generate( + **model_inputs، + past_key_values=generation_output.past_key_values، + max_new_tokens=60، + return_dict_in_generate=True +) +tokenizer.batch_decode(generation_output.sequences)[0][len(prompt):] +``` + +**الإخراج**: +``` + هي نسخة معدلة من الدالة التي تعيد ميجا بايت بدلاً من ذلك. + +def bytes_to_megabytes(bytes): + return bytes / 1024 / 1024 + +Answer: The function takes a number of bytes as input and returns the number of +``` + +رائع، لا يتم إنفاق وقت إضافي على إعادة حساب نفس المفتاح والقيم لطبقة الاهتمام! ومع ذلك، هناك شيء واحد يجب ملاحظته. في حين أن ذروة الذاكرة المطلوبة لمصفوفة \\( \mathbf{QK}^T \\) يتم تقليلها بشكل كبير، فإن الاحتفاظ بذاكرة التخزين المؤقت key-value في الذاكرة يمكن أن يصبح مكلفًا جدًا من حيث الذاكرة لسلاسل الإدخال الطويلة أو الدردشة متعددة الجولات. تذكر أن ذاكرة التخزين المؤقت key-value بحاجة إلى تخزين متجهات القيمة الرئيسية لجميع متجهات الإدخال السابقة \\( \mathbf{x}_i \text{، لـ } i \in \{1، \ ldots، c - 1\} \\) لجميع طبقات الاهتمام الذاتي وكل رؤوس الاهتمام. + +دعنا نحسب عدد القيم العائمة التي يجب تخزينها في ذاكرة التخزين المؤقت key-value لنموذج LLM `bigcode/octocoder` الذي استخدمناه من قبل. +يبلغ عدد القيم العائمة ضعف طول التسلسل مضروبًا في عدد رؤوس الاهتمام مضروبًا في بعد رأس الاهتمام ومضروبًا في عدد الطبقات. +حساب هذا لنموذج LLM لدينا عند طول تسلسل افتراضي يبلغ 16000 يعطي: + +```python +config = model.config +2 * 16_000 * config.n_layer * config.n_head * config.n_embd // config.n_head +``` + +**الإخراج**: +``` +7864320000 +``` + +Roughly 8 مليار قيمة عائمة! يتطلب تخزين 8 مليارات قيمة عائمة في دقة `float16` حوالي 15 جيجابايت من ذاكرة الوصول العشوائي (RAM) وهو ما يقرب من نصف حجم أوزان النموذج نفسها! +اقترح الباحثون طريقتين تسمحان بتقليل تكلفة الذاكرة لتخزين ذاكرة التخزين المؤقت key-value بشكل كبير، والتي يتم استكشافها في الأقسام الفرعية التالية. + +#### 3.2.2 Multi-Query-Attention (MQA) + +[Multi-Query-Attention](https://huggingface.co/papers/1911.02150) اقترحها Noam Shazeer في ورقته *Fast Transformer Decoding: One Write-Head is All You Need*. كما يقول العنوان، اكتشف Noam أنه بدلاً من استخدام `n_head` من أوزان إسقاط القيمة الرئيسية، يمكن استخدام زوج واحد من أوزان إسقاط رأس القيمة التي يتم مشاركتها عبر جميع رؤوس الاهتمام دون أن يتدهور أداء النموذج بشكل كبير. + +> باستخدام زوج واحد من أوزان إسقاط رأس القيمة، يجب أن تكون متجهات القيمة الرئيسية \\( \mathbf{k}_i، \mathbf{v}_i \\) متطابقة عبر جميع رؤوس الاهتمام والتي بدورها تعني أننا بحاجة فقط إلى تخزين زوج إسقاط قيمة رئيسي واحد في ذاكرة التخزين المؤقت بدلاً من `n_head` منها. + +نظرًا لأن معظم LLMs تستخدم ما بين 20 و100 رأس اهتمام، فإن MQA يقلل بشكل كبير من استهلاك الذاكرة لذاكرة التخزين المؤقت key-value. بالنسبة إلى LLM المستخدم في هذا الدفتر، يمكننا تقليل استهلاك الذاكرة المطلوبة من 15 جيجابايت إلى أقل من 400 ميجابايت عند طول تسلسل الإدخال 16000. + +بالإضافة إلى توفير الذاكرة، يؤدي MQA أيضًا إلى تحسين الكفاءة الحسابية كما هو موضح في ما يلي. +في فك التشفير التلقائي، يجب إعادة تحميل متجهات القيمة الرئيسية الكبيرة، ودمجها مع زوج متجه القيمة الحالي، ثم إدخالها في \\( \mathbf{q}_c\mathbf{K}^T \\) الحساب في كل خطوة. بالنسبة لفك التشفير التلقائي، يمكن أن تصبح عرض النطاق الترددي للذاكرة المطلوبة لإعادة التحميل المستمر عنق زجاجة زمنيًا خطيرًا. من خلال تقليل حجم متجهات القيمة الرئيسية، يجب الوصول إلى ذاكرة أقل، وبالتالي تقليل عنق الزجاجة في عرض النطاق الترددي للذاكرة. لمزيد من التفاصيل، يرجى إلقاء نظرة على [ورقة Noam](https://huggingface.co/papers/1911.02150). + +الجزء المهم الذي يجب فهمه هنا هو أن تقليل عدد رؤوس الاهتمام بالقيمة الرئيسية إلى 1 لا معنى له إلا إذا تم استخدام ذاكرة التخزين المؤقت للقيمة الرئيسية. يظل الاستهلاك الذروي لذاكرة النموذج لمرور واحد للأمام بدون ذاكرة التخزين المؤقت للقيمة الرئيسية دون تغيير لأن كل رأس اهتمام لا يزال لديه متجه استعلام فريد بحيث يكون لكل رأس اهتمام مصفوفة \\( \mathbf{QK}^T \\) مختلفة. + +شهدت MQA اعتمادًا واسع النطاق من قبل المجتمع ويتم استخدامها الآن بواسطة العديد من LLMs الأكثر شهرة: + +- [**Falcon**](https://huggingface.co/tiiuae/falcon-40b) +- [**PaLM**](https://huggingface.co/papers/2204.02311) +- [**MPT**](https://huggingface.co/mosaicml/mpt-30b) +- [**BLOOM**](https://huggingface.co/bigscience/bloom) + +كما يستخدم نقطة التحقق المستخدمة في هذا الدفتر - `bigcode/octocoder` - MQA. + +#### 3.2.3 مجموعة الاستعلام الاهتمام (GQA) + +[مجموعة الاستعلام الاهتمام](https://huggingface.co/papers/2305.13245)، كما اقترح Ainslie et al. من Google، وجد أن استخدام MQA يمكن أن يؤدي غالبًا إلى تدهور الجودة مقارنة باستخدام إسقاطات رأس القيمة الرئيسية المتعددة. تجادل الورقة بأنه يمكن الحفاظ على أداء النموذج بشكل أكبر عن طريق تقليل عدد أوزان إسقاط رأس الاستعلام بشكل أقل حدة. بدلاً من استخدام وزن إسقاط قيمة رئيسية واحدة فقط، يجب استخدام `n كخاتمة، من المستحسن بشدة استخدام GQA أو MQA إذا تم نشر LLM باستخدام فك التشفير التلقائي ويتطلب التعامل مع تسلسلات الإدخال الكبيرة كما هو الحال على سبيل المثال للدردشة. + + +## الخاتمة + +مجتمع البحث يأتي باستمرار بطرق جديدة ومبتكرة لتسريع وقت الاستدلال للنماذج اللغوية الكبيرة على الإطلاق. كمثال، أحد اتجاهات البحث الواعدة هو [فك التشفير التخميني](https://huggingface.co/papers/2211.17192) حيث تقوم "الرموز السهلة" بإنشائها نماذج اللغة الأصغر والأسرع ويتم إنشاء "الرموز الصعبة" فقط بواسطة LLM نفسه. إن التعمق في التفاصيل يتجاوز نطاق هذا الدفتر، ولكن يمكن قراءته في هذه [تدوينة المدونة اللطيفة](https://huggingface.co/blog/assisted-generation). + +السبب في أن LLMs الضخمة مثل GPT3/4، وLlama-2-70b، وClaude، وPaLM يمكن أن تعمل بسرعة كبيرة في واجهات الدردشة مثل [Hugging Face Chat](https://huggingface.co/chat/) أو ChatGPT يرجع إلى حد كبير إلى التحسينات المذكورة أعلاه في الدقة والخوارزميات والهندسة المعمارية. +في المستقبل، ستكون أجهزة التسريع مثل وحدات معالجة الرسومات (GPUs) ووحدات معالجة الرسومات (TPUs)، وما إلى ذلك... ستكون أسرع فقط وستسمح بمزيد من الذاكرة، ولكن يجب دائمًا التأكد من استخدام أفضل الخوارزميات والهندسة المعمارية المتاحة للحصول على أكبر قدر من المال diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/model_memory_anatomy.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/model_memory_anatomy.md new file mode 100644 index 0000000000000000000000000000000000000000..db3473e5e02ac8bea6abf19a5db07cc54d390969 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/model_memory_anatomy.md @@ -0,0 +1,226 @@ +# تشريح عملية تدريب النموذج + +لفهم تقنيات تحسين الأداء التي يمكن تطبيقها لتحسين كفاءة استخدام الذاكرة وسرعة تدريب النموذج، من المفيد التعرف على كيفية استخدام وحدة معالجة الرسوميات (GPU) أثناء التدريب، وكيف تختلف كثافة العمليات الحسابية باختلاف العملية التي يتم تنفيذها. + +لنبدأ باستكشاف مثال توضيحي على استخدام وحدة GPU وتشغيل تدريب نموذج. وللتوضيح، سنحتاج إلى تثبيت بعض المكتبات: + +```bash +pip install transformers datasets accelerate nvidia-ml-py3 +``` + +تتيح مكتبة `nvidia-ml-py3` إمكانية مراقبة استخدام الذاكرة في النماذج من داخل بايثون. قد تكون على دراية بأمر `nvidia-smi` في الجهاز - تسمح هذه المكتبة بالوصول إلى نفس المعلومات مباشرة في بايثون. + +ثم، نقوم بإنشاء بعض البيانات الوهمية:معرّفات رموز عشوائية بين 100 و30000 وتصنيفات ثنائية للمصنف. + +في المجموع، نحصل على 512 تسلسلًا، لكل منها طول 512، ونخزنها في [`~datasets.Dataset`] بتنسيق PyTorch. + +```py +>>> import numpy as np +>>> from datasets import Dataset + +>>> seq_len, dataset_size = 512, 512 +>>> dummy_data = { +... "input_ids": np.random.randint(100, 30000, (dataset_size, seq_len)), +... "labels": np.random.randint(0, 1, (dataset_size)), +... } +>>> ds = Dataset.from_dict(dummy_data) +>>> ds.set_format("pt") +``` + +لطباعة إحصائيات موجزة لاستخدام وحدة GPU وتشغيل التدريب مع [`Trainer`]، نقوم بتعريف دالتين مساعدتين: + +```py +>>> from pynvml import * + +>>> def print_gpu_utilization(): +... nvmlInit() +... handle = nvmlDeviceGetHandleByIndex(0) +... info = nvmlDeviceGetMemoryInfo(handle) +... print(f"GPU memory occupied: {info.used//1024**2} MB.") + +>>> def print_summary(result): +... print(f"Time: {result.metrics['train_runtime']:.2f}") +... print(f"Samples/second: {result.metrics['train_samples_per_second']:.2f}") +... print_gpu_utilization() +``` + +دعنا نتأكد من أننا نبدأ بذاكرة وحدة GPU خالية: + +```py +>>> print_gpu_utilization() +GPU memory occupied: 0 MB. +``` + +يبدو ذلك جيدًا: لم يتم شغل ذاكرة وحدة معالجة الرسومات كما نتوقع قبل تحميل أي نماذج. إذا لم يكن الأمر كذلك على جهازك، فتأكد من إيقاف جميع العمليات التي تستخدم ذاكرة وحدة GPU. ومع ذلك، لا يمكن للمستخدم استخدام كل ذاكرة وحدة GPU الفارغة. عندما يتم تحميل نموذج إلى وحدة GPU، يتم أيضًا تحميل النواة، والتي يمكن أن تستهلك 1-2 جيجابايت من الذاكرة. ولرؤية مقدار ذلك، نقوم بتحميل مصفوفة صغيرة إلى وحدة GPU والتي تؤدي إلى تحميل النواة أيضًا. + +```py +>>> import torch + +>>> torch.ones((1, 1)).to("cuda") +>>> print_gpu_utilization() +GPU memory occupied: 1343 MB. +``` + +نلاحظ أن النواة وحدها تستهلك 1.3 جيجابايت من ذاكرة وحدة GPU. الآن دعنا نرى مقدار المساحة التي يستخدمها النموذج. + +## تحميل النموذج + +أولاً، نقوم بتحميل نموذج `google-bert/bert-large-uncased`. نقوم بتحميل أوزان النموذج مباشرة إلى وحدة GPU حتى نتمكن من التحقق من مقدار المساحة التي تستخدمها الأوزان فقط. + +```py +>>> from transformers import AutoModelForSequenceClassification + +>>> model = AutoModelForSequenceClassification.from_pretrained("google-bert/bert-large-uncased").to("cuda") +>>> print_gpu_utilization() +GPU memory occupied: 2631 MB. +``` + +يمكننا أن نرى أن أوزان النموذج وحدها تستهلك 1.3 جيجابايت من ذاكرة وحدة GPU. يعتمد الرقم الدقيق على وحدة GPU المحددة التي تستخدمها. لاحظ أنه في وحدات GPU الأحدث، قد يستغرق النموذج في بعض الأحيان مساحة أكبر نظرًا لأن الأوزان يتم تحميلها بطريقة مُحسّنة تُسرّع من استخدام النموذج. الآن يمكننا أيضًا التحقق بسرعة مما إذا كنا نحصل على نفس النتيجة كما هو الحال مع `nvidia-smi` CLI: + +```bash +nvidia-smi +``` + +```bash +Tue Jan 11 08:58:05 2022 ++-----------------------------------------------------------------------------+ +| NVIDIA-SMI 460.91.03 Driver Version: 460.91.03 CUDA Version: 11.2 | +|-------------------------------+----------------------+----------------------+ +| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC | +| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. | +| | | MIG M. | +|===============================+======================+======================| +| 0 Tesla V100-SXM2... On | 00000000:00:04.0 Off | 0 | +| N/A 37C P0 39W / 300W | 2631MiB / 16160MiB | 0% Default | +| | | N/A | ++-------------------------------+----------------------+----------------------+ + ++-----------------------------------------------------------------------------+ +| Processes: | +| GPU GI CI PID Type Process name GPU Memory | +| ID ID Usage | +|=============================================================================| +| 0 N/A N/A 3721 C ...nvs/codeparrot/bin/python 2629MiB | ++-----------------------------------------------------------------------------+ +``` + +نحصل على نفس الرقم كما كان من قبل، ويمكنك أيضًا أن ترى أننا نستخدم GPU من طراز V100 مع 16 جيجابايت من الذاكرة. لذا الآن يمكننا بدء تدريب النموذج ورؤية كيف يتغير استخدام ذاكرة GPU. أولاً، نقوم بإعداد بعض معاملات التدريب القياسية: + +```py +default_args = { + "output_dir": "tmp"، + "eval_strategy": "steps"، + "num_train_epochs": 1، + "log_level": "error"، + "report_to": "none"، +} +``` + + + + إذا كنت تخطط لتشغيل عدة تجارب، من أجل مسح الذاكرة بشكل صحيح بين التجارب، قم بإعادة تشغيل نواة Python بين التجارب. + + + +## استخدام الذاكرة في التدريب الأساسي + +دعونا نستخدم [`Trainer`] وقم بتدريب النموذج دون استخدام أي تقنيات تحسين أداء GPU وحجم دفعة يبلغ 4: + +```py +>>> from transformers import TrainingArguments، Trainer، logging + +>>> logging.set_verbosity_error() + + +>>> training_args = TrainingArguments(per_device_train_batch_size=4، **default_args) +>>> trainer = Trainer(model=model، args=training_args، train_dataset=ds) +>>> result = trainer.train() +>>> print_summary(result) +``` + +``` +الوقت: 57.82 +العينات / الثانية: 8.86 +ذاكرة GPU المشغولة: 14949 ميجابايت. +``` + +يمكننا أن نرى أن حجم دفعة صغير نسبيًا يملأ تقريبًا ذاكرة GPU بالكامل. ومع ذلك، غالبًا ما يؤدي حجم دفعة أكبر في تقارب نموذج أسرع أو أداء أفضل في النهاية. لذلك نريد أن نضبط حجم الدفعة وفقًا لاحتياجات النموذج لدينا وليس مع قيود وحدة GPU. ما يثير الاهتمام هو أننا نستخدم ذاكرة أكثر بكثير من حجم النموذج. +لفهم سبب ذلك بشكل أفضل، دعنا نلقي نظرة على عمليات النموذج واحتياجاته من الذاكرة. + +## تشريح عمليات النموذج + +تتضمن بنية المحولات 3 مجموعات رئيسية من العمليات مُجمعة أدناه حسب كثافة العمليات الحسابية. + +1. **عمليات ضرب المصفوفات** + + تقوم الطبقات الخطية ومكونات الانتباه متعدد الرؤوس جميعها بعمليات ضرب ** المصفوفة بالمصفوفة** على دفعات. هذه العمليات هي أكثر أجزاء تدريب المحولات كثافة من الناحية الحسابية. + +2. **عمليات التسوية الإحصائية** + +تُعد عمليات Softmax والتسوية الطبقية أقل كثافة من ناحية الحسابية من عمليات ضرب المصفوفات، وتنطوي على عملية أو أكثر من عمليات **الاختزال**، والتي يتم تطبيق نتيجتها بعد ذلك عبر خريطة. + +3. **العمليات على مستوى العناصر** + + هذه هي العمليات المتبقية: **الانحيازات، والتسرب، ووظائف التنشيط، والوصلات المتبقية**. هذه هي عمليات أقل كثافة من الناحية الحسابية. + +يمكن أن تكون هذه المعرفة مفيدة لمعرفة عند تحليل اختناقات الأداء. + +هذا الملخص مُشتق من [نقل البيانات هو كل ما تحتاجه: دراسة حالة حول تحسين المحولات 2020](https://huggingface.co/papers/2007.00072) + + +## تشريح ذاكرة النموذج + +لقد رأينا أن تدريب النموذج يستخدم ذاكرة أكثر بكثير من مجرد وضع النموذج على GPU. ويرجع ذلك إلى +هناك العديد من المكونات أثناء التدريب التي تستخدم ذاكرة GPU. المكونات الموجودة في ذاكرة GPU هي التالية: + +1. أوزان النموذج +2. الدول المُحسّن +3. المُتدرجات +4. تنشيطات المسار الأمامي المحفوظة لحساب المُتدرجات +5. المخازن المؤقتة +6. ذاكرة محددة الوظائف + +يتطلب نموذج نموذجي مدرب بدقة مختلطة 18 بايت للمُحسّن AdamW كل معلمة نموذج بالإضافة إلى ذاكرة التنشيط. للاستدلال لا توجد حالات مُحسّن و مُتدرجات، لذلك يمكننا طرح تلك. وهكذا ننتهي مع 6 بايت لكل +معلمة نموذج للدقة المختلطة الاستدلال، بالإضافة إلى ذاكرة التنشيط. + +دعنا نلقي نظرة على التفاصيل. + +**أوزان النموذج:** + +- 4 بايت * عدد المعلمات للتدريب على دقة fp32 +- 6 بايت * عدد المعلمات لتدريب الدقة المختلطة (يحافظ على نموذج في fp32 وآخر بدقة fp16 في الذاكرة) + +**حالات المُحسّن:** + +- 8 بايت * عدد المعلمات للمُحسّن AdamW العادي (يحافظ على حالتين) +- 2 بايت * عدد المعلمات لمُحسّنات 8 بت AdamW مثل [bitsandbytes](https://github.com/TimDettmers/bitsandbytes) +- 4 بايت * عدد المعلمات لمُحسّنات مثل SGD مع الزخم momentum (يحافظ على حالة واحدة فقط) + +**المُتدرجات** + +- 4 بايت * عدد المعلمات للتدريب بدقة fp32 أو بدقة مختلطة (المُتدرجات تكون دائمًا بدقة fp32) + +**تنشيطات المسار الأمامي** + +- يعتمد الحجم على العديد من العوامل، وأهمها طول التسلسل وحجم المخفية وحجم الدُفعة. + +هناك المدخلات والمخرجات لذي يتم تمريرها وإرجاعها بواسطة وظائف المسار الأمامي والمسار الخلفي وتنشيطات المسار الأمامي المحفوظة لحساب المُتدرجات. + +**الذاكرة المؤقتة** + +بالإضافة إلى ذلك، هناك جميع أنواع المتغيرات المؤقتة التي يتم تحريرها بمجرد الانتهاء من الحساب، ولكن في +لحظة يمكن أن تتطلب هذه المتغيرات المؤقتة ذاكرة إضافية ويقد تؤدي إلى نفاد الذاكرة المُخصصة (OOM). لذلك، عند البرمجة، من المهم التفكير بشكل استراتيجي حول هذه المتغيرات المؤقتة وأحيانًا تحريرها بشكل صريح بمجرد عدم الحاجة إليها. + +**ذاكرة محددة الوظائف** + +ثم، قد يكون لبرنامجك احتياجات خاصة بالذاكرة. على سبيل المثال، عند إنشاء نص باستخدام البحث الشعاعي، يحتاج البرنامج +إلى الاحتفاظ بنسخ متعددة من المدخلات والمخرجات. + +**سرعة تنفيذ `forward` مقابل `backward`** + +بالنسبة للالتفافات والطبقات الخطية، هناك ضِعف عدد العمليات 2x flops في المسار الخلفى مقارنة بالمسار الأمامي، والتي يُترجم عمومًا إلى ~2x أبطأ (أحيانًا أكثر، لأن الأحجام في المسار الخلفى تميل إلى أن تكون أكثر صعوبة). عادةً ما تكون عمليات التنشيط محدودة بعرض النطاق الترددي، ومن المعتاد أن يتعين على التنشيط قراءة المزيد من البيانات في المسار الخلفى أكثر من المسار الأمامى. +(على سبيل المثال، قراءة التنشيط المسار الأمامى مرة واحدة، وتكتب مرة واحدة، وبينما تقرأ عملية التنشيط الخلفي مرتين، gradOutput وإخراج الأمام، وتكتب مرة واحدة، gradInput). + +كما ترى، هناك بضعة أماكن يمكننا فيها توفير ذاكرة GPU أو تسريع العمليات. +الآن بعد أن فهمت ما يؤثر على استخدام GPU وسرعة الحساب، راجع +صفحة وثائق [أساليب وأدوات التدريب الفعال على GPU واحد](perf_train_gpu_one) لمعرفة المزيد حول تقنيات تحسين الأداء. \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/model_sharing.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/model_sharing.md new file mode 100644 index 0000000000000000000000000000000000000000..b4b1bb821b9bce1beb3b1fb4d507567106ad5a1f --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/model_sharing.md @@ -0,0 +1,223 @@ +# شارك نموذجك مع العالم + +أظهرت آخر درسين تعليميين كيفية ضبط نموذج بدقة باستخدام PyTorch و Keras و 🤗 Accelerate لعمليات التهيئة الموزعة. والخطوة التالية هي مشاركة نموذجك مع المجتمع! في Hugging Face، نؤمن بالمشاركة المفتوحة للمعرفة والموارد لتمكين الجميع من الاستفادة من الذكاء الاصطناعي. ونشجعك على مشاركة نموذجك مع المجتمع لمساعدة الآخرين على توفير الوقت والموارد. + +في هذا الدرس، ستتعلم طريقتين لمشاركة نموذجك المدرب أو مضبوط على منصة [Model Hub](https://huggingface.co/models): + +- رفع ملفاتك إلى منصة Hub مباشرة باستخدام الكود البرمجي. + +- قم بسحب وإفلات ملفاتك إلى Hub باستخدام الواجهة web. + + + + + +لمشاركة نموذج مع المجتمع، تحتاج إلى حساب على [huggingface.co](https://huggingface.co/join). يمكنك أيضًا الانضمام إلى منظمة موجودة أو إنشاء منظمة جديدة. + + + +## ميزات المستودع + +يعمل كل مستودع على Model Hub مثل مستودع GitHub النتقليدي. تقدم مستودعاتنا التحكم في الإصدارات وسجل التغييرات، وقدرة على رؤية الاختلافات بين الإصدارات. + +تعتمد آلية التحكم في الإصدارات على منصة Model Hub على نظامي git و [git-lfs](https://git-lfs.github.com/). وبعبارة أخرى، يمكنك التعامل مع كل نموذج كأنه مستودع مستقل، مما يمكّن من زيادة التحكم في الوصول والقابلية للتطوير. يسمح التحكم في الإصدار بإجراء تعديلات وتثبيت إصدار محدد من النموذج باستخدام رمز التغيير (commit hash) أو وسم (tag) أو فرع (branch). + +بفضل هذه الميزة، يمكنك تحميل إصدار محدد من النموذج باستخدام معلمة الإصدار "revision": + +```py +>>> model = AutoModel.from_pretrained( +... "julien-c/EsperBERTo-small", revision="4c77982" # اسم العلامة، أو اسم الفرع، أو تجزئة الالتزام +... ) +``` + +من السهل أيضًا تعديل الملفات الموجودة داخل مستودع، ويمكنك عرض سجل التغييرات التي طرأت على هذه الملفات ومعاينة الاختلافات بين الإصدارات المختلفة: + +![vis_diff](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/vis_diff.png) + +## الإعداد + +قبل مشاركة نموذج على Hub، ستحتاج إلى بيانات اعتماد حساب Hugging Face الخاصة بك. إذا كنت تستخدم منصة الأوامر، فقم بتشغيل الأمر التالي في بيئة افتراضية حيث تم تثبيت 🤗 Transformers. سيقوم هذا الأمر بتخزين رمز الدخول الخاص بك في مجلد تخزين المؤقت لـ Hugging Face (`~/.cache/` بشكل افتراضي): + +```bash +hf auth login +``` + +إذا كنت تستخدم دفتر ملاحظات مثل Jupyter أو Colaboratory، فتأكد من تثبيت مكتبة [`huggingface_hub`](https://huggingface.co/docs/hub/adding-a-library). تسمح لك هذه المكتبة بالتفاعل برمجيًا مع Hub. + +```bash +pip install huggingface_hub +``` + +ثم استخدم `notebook_login` لتسجيل الدخول إلى Hub، واتبع الرابط [هنا](https://huggingface.co/settings/token) لإنشاء رمز للتسجيل: + +```py +>>> from huggingface_hub import notebook_login + +>>> notebook_login() +``` + + +## تحويل النموذج ليتوافق مع جميع الأطر العمل + +لضمان إمكانية استخدام نموذجك من قبل شخص يعمل بإطار عمل مختلف، نوصي بتحويل نموذجك ورفعه مع نقاط التحقق من PyTorch و TensorFlow. في حين أن المستخدمين لا يزال بإمكانهم تحميل نموذجك من إطار عمل مختلف إذا تخطيت هذه الخطوة، إلا أنه سيكون أبطأ لأن 🤗 Transformers ستحتاج إلى تحويل نقطة التحقق أثناء التشغيل. + +تحويل نقطة التحقق لإطار عمل آخر أمر سهل. تأكد من تثبيت PyTorch و TensorFlow (راجع [هنا](installation) لتعليمات التثبيت)، ثم ابحث عن النموذج الملائم لمهمتك في الإطار الآخر. + + + +حدد `from_tf=True` لتحويل نقطة تحقق من TensorFlow إلى PyTorch: + +```py +>>> pt_model = DistilBertForSequenceClassification.from_pretrained("path/to/awesome-name-you-picked", from_tf=True) +>>> pt_model.save_pretrained("path/to/awesome-name-you-picked") +``` + + +حدد `from_pt=True` لتحويل نقطة تحقق من PyTorch إلى TensorFlow: + +```py +>>> tf_model = TFDistilBertForSequenceClassification.from_pretrained("path/to/awesome-name-you-picked", from_pt=True) +``` + +بعد ذلك، يمكنك حفظ نموذج TensorFlow الجديد بنقطة التحقق الجديدة: + +```py +>>> tf_model.save_pretrained("path/to/awesome-name-you-picked") +``` + + +إذا كان النموذج متاحًا في Flax، فيمكنك أيضًا تحويل نقطة تحقق من PyTorch إلى Flax: + +```py +>>> flax_model = FlaxDistilBertForSequenceClassification.from_pretrained( +... "path/to/awesome-name-you-picked", from_pt=True +... ) +``` + + + +## دفع نموذج أثناء التدريب + + + + + +مشاركة نموذجك على Hub مر بسيط للغاية كل ما عليك هو إضافة معلمة أو استدعاء رد إضافي. كما تذكر من درس [التدريب الدقيق](training)، فإن فئة [`TrainingArguments`] هي المكان الذي تحدد فيه المعلمات الفائقة وخيارات التدريب الإضافية. تشمل إحدى خيارات التدريب هذه القدرة على دفع النموذج مباشرة إلى المنصة Hub. قم بتعيين `push_to_hub=True` في [`TrainingArguments`]: + +```py +>>> training_args = TrainingArguments(output_dir="my-awesome-model", push_to_hub=True) +``` + +مرر معامﻻت التدريب كالمعتاد إلى [`Trainer`]: + +```py +>>> trainer = Trainer( +... model=model, +... args=training_args, +... train_dataset=small_train_dataset, +... eval_dataset=small_eval_dataset, +... compute_metrics=compute_metrics, +... ) +``` + +بعد ضبط نموذجك بدقة، يمكنك استخدام دالة [`~transformers.Trainer.push_to_hub`] المتاحة في [`Trainer`] لدفع النموذج المدرب إلى المنصة Hub. سوف تضيف 🤗 Transformers تلقائيًا المعلمات الفائقة المستخدمة في التدريب ونتائج التدريب وإصدارات الإطار إلى بطاقة معلومات النموذج الخاصة بك! + +```py +>>> trainer.push_to_hub() +``` + + +شارك نموذجًا على Hub باستخدام [`PushToHubCallback`]. في دالة [`PushToHubCallback`], أضف: + +- دليل إخراج لنموذجك. +- مُجزّئ اللغوي. +- `hub_model_id`، والذي هو اسم مستخدم Hub واسم النموذج الخاص بك. + +```py +>>> from transformers import PushToHubCallback + +>>> push_to_hub_callback = PushToHubCallback( +... output_dir="./your_model_save_path", tokenizer=tokenizer, hub_model_id="your-username/my-awesome-model" +... ) +``` + +أضف الاستدعاء إلى [`fit`](https://keras.io/api/models/model_training_apis/)، وسيقوم 🤗 Transformers بدفع النموذج المدرب إلى Hub: + +```py +>>> model.fit(tf_train_dataset, validation_data=tf_validation_dataset, epochs=3, callbacks=push_to_hub_callback) +``` + + + +## استخدام دالة `push_to_hub` + +يمكنك أيضًا استدعاء `push_to_hub` مباشرة على نموذجك لتحميله إلى Hub. + +حدد اسم نموذجك في `push_to_hub`: + +```py +>>> pt_model.push_to_hub("my-awesome-model") +``` + +ينشئ هذا مستودعًا تحت اسم المستخدم الخاص بك باسم نموذج `my-awesome-model`. يمكن للمستخدمين الآن تحميل نموذجك باستخدام دالة `from_pretrained`: + +```py +>>> from transformers import AutoModel + +>>> model = AutoModel.from_pretrained("your_username/my-awesome-model") +``` +```py +>>> from transformers import AutoModel + +>>> model = AutoModel.from_pretrained("your_username/my-awesome-model") +``` + +إذا كنت تنتمي إلى منظمة وتريد دفع نموذجك تحت اسم المنظمة بدلاً من ذلك، فما عليك سوى إضافته إلى `repo_id`: + +```py +>>> pt_model.push_to_hub("my-awesome-org/my-awesome-model") +``` + +يمكن أيضًا استخدام دالة `push_to_hub` لإضافة ملفات أخرى إلى مستودع النماذج. على سبيل المثال، أضف رموزًا إلى مستودع نموذج: + +```py +>>> tokenizer.push_to_hub("my-awesome-model") +``` + +أو ربما تريد إضافة إصدار TensorFlow من نموذج PyTorch المضبوط: + +```py +>>> tf_model.push_to_hub("my-awesome-model") +``` + +الآن عند الانتقال إلى ملفك الشخصي على Hugging Face، يجب أن ترى مستودع النماذج الذي أنشأته حديثًا. سيؤدي النقر فوق علامة التبويب **Files** إلى عرض جميع الملفات التي قمت بتحميلها في المستودع. + +للحصول على مزيد من التفاصيل حول كيفية إنشاء الملفات وتحميلها إلى مستودع، راجع وثائق Hub [هنا](https://huggingface.co/docs/hub/how-to-upstream). + +## التحميل باستخدام الواجهة web + +يمكن للمستخدمين الذين يفضلون نهج عدم الترميز تحميل نموذج من خلال واجهة Hub web. قم بزيارة [huggingface.co/new](https://huggingface.co/new) لإنشاء مستودع جديد: + +![new_model_repo](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/new_model_repo.png) + +من هنا، أضف بعض المعلومات حول نموذجك: + +- حدد **مالك** المستودع. يمكن أن يكون هذا أنت أو أي من المنظمات التي تنتمي إليها. +- اختر اسمًا لنموذجك، والذي سيكون أيضًا اسم المستودع. +- اختر ما إذا كان نموذجك عامًا أم خاصًا. +- حدد ترخيص الاستخدام لنموذجك. + +الآن انقر فوق علامة التبويب **Files** ثم انقر فوق الزر **Add file** لإضافة ملف جديد إلى مستودعك. ثم اسحب وأسقط ملفًا لتحميله وأضف رسالة الالتزام. + +![upload_file](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/upload_file.png) + +## إضافة بطاقة نموذج + +للتأكد من فهم المستخدمين لقدرات نموذجك وقيوده وتحيزاته المحتملة واعتباراته الأخلاقية، يرجى إضافة بطاقة نموذج إلى مستودعك. يتم تعريف بطاقة النموذج في ملف `README.md`. يمكنك إضافة بطاقة نموذج عن طريق: + +* قم بإنشاء ملف `README.md` وتحميله يدويًا. +* انقر فوق الزر **Edit model card** في مستودع نموذجك. + +الق نظرة على بطاقة [DistilBert](https://huggingface.co/distilbert/distilbert-base-uncased) للحصول على مثال جيد على نوع المعلومات التي يجب أن تتضمنها بطاقة النموذج. للحصول على مزيد من التفاصيل حول الخيارات الأخرى التي يمكنك التحكم فيها في ملف `README.md` مثل البصمة الكربونية للنموذج أو أمثلة الأداة، راجع الوثائق [هنا](https://huggingface.co/docs/hub/models-cards). \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/model_summary.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/model_summary.md new file mode 100644 index 0000000000000000000000000000000000000000..97a75dd4b608bafabdc6631635d6dd008aa6225d --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/model_summary.md @@ -0,0 +1,89 @@ +# عائلة نماذج المحول + +منذ إطلاقه في عام 2017، ألهم نموذج [المحول الأصلي](https://huggingface.co/papers/1706.03762) (راجع مدونة [المحول المشروح](http://nlp.seas.harvard.edu/2018/04/03/attention.html) لمقدمة تقنية مبسطة)، ألهم العديد من النماذج الجديدة والمبتكرة التي تتجاوز مهام معالجة اللغات الطبيعية (NLP). هناك نماذج للتنبؤ [بالبنية البروتينات المطوية](https://huggingface.co/blog/deep-learning-with-proteins)، و[تدريب على اتخاذ القرار](https://huggingface.co/blog/train-decision-transformers)، و[التنبؤ بالسلاسل الزمنية](https://huggingface.co/blog/time-series-transformers). مع وجود العديد من متغيرات المحول المتاحة، قد يكون من السهل أن تفوتك الصورة الأكبر. ما تشترك فيه جميع هذه النماذج هو أنها تستند إلى بنية المحول الأصلية. تستخدم بعض النماذج فقط الترميز أو فك الترميز، بينما تستخدم نماذج أخرى كليهما. يوفر هذا تصنيفًا مفيدًا لتصنيف واستعراض الفروقات الرئيسية بين نماذج عائلة المحولات، وسيساعدك على فهم النماذج التي لم تصادفها من قبل. + +إذا لم تكن على دراية بنموذج المحول الأصلي أو تحتاج إلى تذكير، فراجع الفصل الخاص بـ [كيف تعمل المحولات](https://huggingface.co/course/chapter1/4؟fw=pt) من دورة Hugging Face. + +
+ +
+ +## رؤية الحاسب (Computer vision) + + + +### الشبكة التلافيفية (Convolutional network) + +لطالما كانت الشبكات التلافيفية (CNNs) الطريقة السائدة لمهام رؤية الحاسب حتى برز [محول الرؤية](https://huggingface.co/papers/2010.11929) قابليته للتطوير وكفاءته العالية. وحتى بعد ذلك، لا تزال بعض أفضل صفات CNN، مثل ثبات الإزاحة، قوية جدًا (خاصة بالنسبة لمهام معينة) لدرجة أن بعض المحولات تدمج التلافيف في بنيتها. قلب [ConvNeXt](model_doc/convnext) هذا التبادل رأسًا على عقب وأدرج خيارات التصميم من المحولات لتحديث CNN. على سبيل المثال، يستخدم ConvNeXt نوافذ منزلقة غير متداخلة لتقسيم الصورة إلى رقع وزيادة حقل مجال العام الخاص بها. كما يقوم ConvNeXt بعدة خيارات مثل تصميم الطبقة لتكون أكثر كفاءة في الذاكرة وتحسين الأداء، مما يجعله منافسًا قويًا للمحولات! + +### الترميز[[cv-encoder]] (Encoder) + +فتح [محول الرؤية (ViT)](model_doc/vit) الباب أمام مهام رؤية الحاسب دون الاعتماد على التلافيف. يستخدم ViT ترميز محول قياسي، لكن إنجازه الرئيسي كان طريقة معالجته للصورة. فهو تقسّم الصورة إلى رقّعات ذات حجم ثابت ويستخدمها لإنشاء تضمين، تمامًا مثل تقسيم الجملة إلى رموز. استفاد ViT من بنية المُحوِّلات الفعالة لإظهار نتائج تنافسية مع CNNs في ذلك الوقت مع الحاجة إلى موارد أقل للتدريب. وسرعان ما تبع ViT نماذج رؤية أخرى يمكنها أيضًا التعامل مع مهام الرؤية الكثيفة مثل التجزئة والتعرف. + +من بين هذه النماذج [Swin](model_doc/swin) Transformer. فهو يبني خرائط سمات هرمية (مثل CNN 👀 على عكس ViT) من رقّعات أصغر حجمًا ودمجها مع الرقع المجاورة في طبقات أعمق. يتم حساب الانتباه فقط ضمن نافذة محلية، ويتم تحويل النافذة بين طبقات الانتباه لإنشاء اتصالات تساعد النموذج على التعلم بشكل أفضل. نظرًا لأن محول Swin يمكنه إنتاج خرائط خصائص هرمية، فهو مرشح جيد لمهام التنبؤ الكثيفة مثل التجزئة والتعرف. كما يستخدم [SegFormer](model_doc/segformer) ترميز محول لبناء خرائط خصائص هرمية، ولكنه يضيف فك تشفير بسيط متعدد الطبقات (MLP) في الأعلى لدمج جميع خرائط الخصائص وإجراء تنبؤ. + +استلهمت نماذج الرؤية الأخرى، مثل BeIT وViTMAE، الإلهام من هدف التدريب المسبق لـ BERT. يتم تدريب [BeIT](model_doc/beit) مسبقًا من خلال *نمذجة الصور المقنعة (MIM)*؛ يتم إخفاء رقّعات الصور بشكل عشوائي، كما يتم تحويل الصورة إلى رموز بصرية. يتم تدريب BeIT للتنبؤ بالرموز البصرية المُناظرة للرقع المخفية. لدى [ViTMAE](model_doc/vitmae) هدف تدريب مسبق مُماثل، باستثناء أنه يجب عليه التنبؤ بالبكسلات بدلاً من الرموز البصرية. ما هو غير عادي هو أن إخفاء 75% من رقع الصور! يقوم فك التشفير بإعادة بناء البكسلات من الرموز المخفية والرقّعات المشفرة. بعد التدريب المسبق، يتم التخلص من فك التشفير، ويصبح الترميز جاهزًا للاستخدام في مهام التالية. + +### فك التشفير[[cv-decoder]] (Decoder) + +نادرًا ما تستخدم نماذج الرؤية التي تعتمد على فك التشفير فقط لأن معظم نماذج الرؤية تعتمد على الترميز لتعلم تمثيل الصورة. ولكن بالنسبة للاستخدامات مثل توليد الصور، يعد فك التشفير مناسبًا بشكل طبيعي، كما رأينا من نماذج توليد النصوص مثل GPT-2. يستخدم نموذج [ImageGPT](model_doc/imagegpt) نفس بنية GPT-2، ولكنه بدلاً من التنبؤ بالرمز التالي في تسلسل، فإنه يتنبأ بالبكسل التالي في صورة. بالإضافة إلى توليد الصور، يمكن أيضًا ضبط ImageGPT بدقة لتصنيف الصور. + +### الترميز وفك التشفير[[cv-encoder-decoder]] (Encoder-decoder) + +تستخدم نماذج الرؤية بشكل شائع ترميزًا (يُعرف أيضًا باسم العمود الفقري) لاستخراج ميزات الصورة المهمة قبل تمريرها إلى فك التشفير لنموذج المُحوّل. يستخدم [DETR](model_doc/detr) عمودًا فقريًا مُدربًا مسبقًا، ولكنه يستخدم أيضًا الببنية الكاملة للترميز وفك تشفير لنموذج المحول للكشف عن الأشياء. يتعلم الترميز تمثيلات الصور ويجمعها مع استعلامات الكائنات (كل استعلام كائن هو تضمين مُتعلم يركز على منطقة أو كائن في صورة) في فك التشفير. يتنبأ DETR بإحداثيات مربع الحدود وتسمية الفئة لكل استعلام كائن. + +## معالجة اللغات الطبيعية (Natural language processing - NLP) + + + +### الترميز اللغوي[[nlp-encoder]] + +نموذج [BERT](model_doc/bert) هو محوّل (Transformer) يعتمد على الترميز فقط يقوم بشكل عشوائي بإخفاء رموز معينة في المدخلات لتجنب رؤية باقى الرموز الأخرى، مما يسمح له "بالغش". يتمثل هدف التدريب المسبق في التنبؤ بالرمز المخفي بناءً على السياق. يسمح هذا لـ BERT باستخدام السياقات اليمنى واليسرى بالكامل لمساعدته في تعلم تمثيل أعمق وأغنى للبيانات المدخلة. ومع ذلك، كان هناك مجال للتحسين في استراتيجية التدريب المسبق لـ BERT. نموذج [RoBERTa](model_doc/roberta) اضاف تحسين من خلال تقديم وصفة تدريب مسبق جديدة تشمل التدريب لفترة أطول وعلى دفعات أكبر، وإخفاء الرموز عشوائيًا في كل حقبة بدلاً من مرة واحدة فقط أثناء المعالجة المسبقة، وإزالة هدف التنبؤ بالجملة التالية. + +تتمثل الاستراتيجية السائدة لتحسين الأداء في زيادة حجم النموذج. ولكن تدريب النماذج الكبيرة مكلف من الناحية الحسابية. إحدى طرق تقليل التكاليف الحسابية هي استخدام نموذج أصغر مثل [DistilBERT](model_doc/distilbert). يستخدم DistilBERT [ تقنية تقطير المعرفة](https://huggingface.co/papers/1503.02531) - وهي تقنية ضغط - لإنشاء نموذج أصغر من BERT مع الحفاظ على معظم قدراته على فهم اللغةا. + +مرت معظم نماذج المحول في الاتجاه نحو المزيد من المعلمات، مما أدى إلى ظهور نماذج جديدة تركز على تحسين كفاءة التدريب. يقلّل [ALBERT](model_doc/albert) من استهلاك الذاكرة عن طريق تقليل عدد المعلمات بطريقتين: فصل تضمين المفردات الأكبر إلى مصفوفتين أصغر والسماح للمستويات بمشاركة المعلمات. أضاف [DeBERTa](model_doc/deberta) آلية انتباه منفصلة حيث يتم ترميز الكلمة وموضعها بشكل منفصل في متجهين. يتم حساب الانتباه من هذه المتجهات المنفصلة بدلاً من متجه واحد يحتوي على تضمين الكلمة والموقع. ركز [Longformer](model_doc/longformer) أيضًا على جعل الانتباه أكثر كفاءة، خاصة لمعالجة المستندات ذات تسلسلات أطولل. فهو يستخدم مزيجًا من انتباه النوافذ المحلية (يتم حساب الانتباه فقط ن نافذة ذات حجم ثابت حول كل رمز) والانتباه العام (فقط لرموز مهمة محددة مثل `[CLS]` للتصنيف) لإنشاء مصفوفة انتباه متفرقة بدلاً من مصفوفة انتباه كاملة. + +### فك التشفير[[nlp-decoder]] + + نموذج [GPT-2](model_doc/gpt2) هو محول فك تشفير فقط يتنبأ بالكلمة التالية في التسلسل. إنه يخفي الرموز التالية الموجودة على اليمين حتى لا يتمكن النموذج من "الغش" بالنظر إليها. من خلال التدريب المسبق على كميات هائلة من النصوص، أصبح [GPT-2](model_doc/gpt2) بارعًا في توليد النصوص، حتى لو لم تكن النص دقيقًا أو صحيحًا في بعض الأحيان فقط. ولكن كان يفتقر إلى سياق لترابط المتبادل (bidirectional context) الموجود من التدريب المسبق لـ [BERT](model_doc/bert) ، مما جعله غير مناسب لمهام معينة. يجمع [XLNET](model_doc/xlnet) بين أفضل ما في أهداف التدريب المسبق لـ [BERT](model_doc/bert) و [GPT-2](model_doc/gpt2) من خلال اعتماد نهج النمذجة اللغوية باستخدام التباديل (Permutation Language Modeling - PLM) الذي يسمح له بتعلم الترابط ثنائي الاتجاه. + +بعد ظهور [GPT-2](model_doc/gpt2)، تطورت النماذج اللغوية بشكل أكبر حجمًا وأكثر تعقيدًا وأصبحت تُعرف الآن باسم *نماذج اللغة الكبيرة (LLMs)*. توضح LLMs مهارات تعلم قليلة الكمية أو حتى معدومة إذا تم تدريبها على مجموعة بيانات كبيرة بما يكفي. [GPT-J](model_doc/gptj) هو LLM به 6 مليارات معلمة مدربة على 400 مليار رمز. تبعه نموذج [OPT](model_doc/opt)، وهي عائلة من نماذج فك التشفير فقط، أكبرها 175 مليار معلمة ودُرب على 180 مليار رمز. تم إصدار [BLOOM](model_doc/bloom) في نفس الوقت تقريبًا، ويحتوي أكبر نموذج في العائلة على 176 مليار معلمة ودُرب على 366 مليار رمز في 46 لغة و13 لغة برمجة. + +### الترميز وفك التشفير[[nlp-encoder-decoder]] + +يحتفظ [BART](model_doc/bart) ببنية المحول الأصلية، ولكنه يعدّل هدف التدريب المسبق باستخدام إفساد *إدخال النصوص*، حيث يتم استبدال بعض نطاقات النص برمز `mask` واحد. يتنبأ فك التشفير بالرموز غير الفاسدة (يتم إخفاء الرموز المستقبلية) ويستخدم حالات الترميز المخفية للمساعدة. [Pegasus](model_doc/pegasus) مشابه لـ BART، ولكن Pegasus يقوم بإخفاء جمل كاملة بدلاً من مقاطع النص. بالإضافة إلى نمذجة اللغة المقنعة، يتم تدريب Pegasus مسبقًا بواسطة توليد الجمل الفارغة (GSG). يقوم هدف GSG بإخفاء الجمل الكاملة المهمة للمستند، واستبدالها برمز `mask`. يجب على فك التشفير توليد المخرجات من الجمل المتبقية. [T5](model_doc/t5) هو نموذج فريد من نوعه يحوّل جميع مهام معالجة اللغة الطبيعية إلى مشكلة نص إلى نص باستخدام بادئات محددة. على سبيل المثال، يشير البادئة `Summarize:` إلى مهمة تلخيص. يتم تدريب T5 مسبقًا بواسطة التدريب الخاضع للإشراف (GLUE وSuperGLUE) والتدريب ذاتي الإشراف (اختيار عينة عشوائية وحذف 15% من الرموز). + +## الصوت (Audio) + + + +### الترميز[[audio-encoder]] + +يستخدم [Wav2Vec2](model_doc/wav2vec2) ترميز من نوع المحوّل لتعلم تمثيلات الكلام بشكلٍ مباشر من موجات الصوت الخام. يتم تدريبه مسبقًا باستخدام مهمة تباينية لتحديد تمثيل الكلام الصحيح من مجموعة من التمثيلات الخاطئة. [HuBERT](model_doc/hubert) مشابه لـ Wav2Vec2 ولكنه له عملية تدريب مختلفة. يتم إنشاء تسميات الهدف عن طريق خطوة تجميع يتم فيها ت تخصيص مقاطع الصوت المتشابهة إلى مجموعات، تُصبح كل واحدة منها وحدةً خفية. ويتم تعيين الوحدة الخفية إلى تمثيل لإجراء تنبؤ. + +### الترميز وفك التشفير[[audio-encoder-decoder]] + +[Speech2Text](model_doc/speech_to_text) هو نموذج كلام مصمم للتعرف التلقائي على الكلام (ASR) وترجمة الكلام. يقبل النموذج ميزات بنك المرشح اللغوي التي تم استخراجها من شكل موجة الصوت وتم تدريبه مسبقًا بطريقة ذاتية التعلم لتوليد نسخة أو ترجمة. [Whisper](model_doc/whisper) هو أيضًا نموذج ASR، ولكنه على عكس العديد من نماذج الكلام الأخرى، يتم تدريبه مسبقًا على كمية كبيرة من بيانات نسخ النص الصوتي ✨ المسماة ✨ لتحقيق الأداء الصفري. يحتوي جزء كبير من مجموعة البيانات أيضًا على لغات غير اللغة الإنجليزية، مما يعني أنه يمكن استخدام Whisper أيضًا للغات منخفضة الموارد. من الناحية الهيكلية، يشبه Whisper نموذج Speech2Text. يتم تحويل إشارة الصوت إلى طيف لوجاريتم مل-ميل يتم تشفيره بواسطة الترميز. يقوم فك التشفير بتوليد النسخة بطريقة ذاتية التعلم من حالات الترميز المخفية والرموز السابقة. + +## متعدد الوسائط (Multimodal) + + + +### Encoder[[mm-encoder]] + +نموذج [VisualBERT](model_doc/visual_bert) هو نموذج متعدد الوسائط لمهام الرؤية اللغوية تم إصداره بعد فترة وجيزة من BERT. فهو يجمع بين BERT ونظام اكتشاف كائن مسبق التدريب لاستخراج ميزات الصورة في تضمينات بصرية، يتم تمريرها جنبًا إلى جنب مع التضمينات النصية إلى BERT. يتنبأ VisualBERT بالنص المقنع بناءً على النص غير المقنع والتضمينات المرئية، ويجب عليه أيضًا التنبؤ بما إذا كان النص متوافقًا مع الصورة. عندما تم إصدار ViT، اعتمد [ViLT](model_doc/vilt) ViT في بنيتها لأنه كان من الأسهل الحصول على تضمينات الصورة بهذه الطريقة. يتم معالجة تضمينات الصورة بشكل مشترك مع التضمينات النصية. ومن هناك، يتم التدريب المسبق لـ ViLT بواسطة مطابقة الصورة النصية، ونمذجة اللغة المقنعة، وإخفاء كلمة كاملة. + +يتّبع [CLIP](model_doc/clip) نهجًا مختلفًا ويقوم بتنبؤ ثنائي من ("الصورة"، "النص"). يتم تدريب مشفر صورة (ViT) ومشفر نص (Transformer) بشكل مشترك على مجموعة بيانات مكونة من 400 مليون ثنائي من ("صورة"، "نص") لتعظيم التشابه بين متجهات ترميز الصورة ومتجهات النص ثنائي ("الصورة"، "النص"). بعد التدريب المسبق، يمكنك استخدام اللغة الطبيعية لتوجيه CLIP للتنبؤ بالنص المُعطى بناءً على صورة أو العكس بالعكس. [OWL-ViT](model_doc/owlvit) يبني على CLIP باستخدامه كعمود فقري للكشف عن الكائنات بدون إشراف. بعد التدريب المسبق، يتم إضافة رأس كشف الأجسام لإجراء تنبؤ بمجموعة مُحدّد عبر ثنائيات ("class"، "bounding box"). + +### Encoder-decoder[[mm-encoder-decoder]] + +التعرّف البصري على الحروف (OCR) مهمة قديمة لتعرّف النصوص، التي تنطوي عادةً على عدة مكونات لفهم الصورة وتوليد النص. [TrOCR](model_doc/trocr) بتبسيط العملية باستخدام محول متكامل من النهاية إلى النهاية. المشفر هو نموذج على غرار ViT لفهم الصورة ويعالج الصورة كقطع ثابتة الحجم. يقبل فك التشفير حالات الإخفاء للمشفر وينشئ النص بشكل تلقائي. [Donut](model_doc/donut) هو نموذج أكثر عمومية لفهم المستندات المرئية لا يعتمد على نهج OCR. يستخدم محول Swin كمشفر وBART متعدد اللغات كمُفكّك تشفير. يتم تدريب Donut على قراءة النص عن طريق التنبؤ بالكلمة التالية بناءً على ملاحظات الصورة والنص. يقوم فك التشفير بتوليد تتسلسلًا رمزيًا بناءً على موجه (Prompt). يتم تمثيل الموجه بواسطة رمز خاص لكل مهمة. على سبيل المثال، يحتوي تحليل المستند على رمز خاص "parsing" يتم دمجه مع حالات الإخفاء للـمُشفّر لتحليل المستند بتنسيق إخراج منظم (JSON). + +## التعلم التعزيزي (Reinforcement learning - RL) + + + +### فك التشفير[[rl-decoder]] + +يقوم نموذج "محوّل القرارات والمسارات" (Decision and Trajectory Transformer) بتحويل الحالة (State) والإجراء (Action) والمكافأة (Reward) كمشكلة نمذجة تسلسلية. [محوّل القرارات](model_doc/decision_transformer) يقوم بتوليد سلسلة من الإجراءات التي تؤدي إلى عائد مرغوب في المستقبل بناءً على العوائد المتوقعة، والحالات والإجراءات السابقة. في الخطوات الزمنية *K* الأخيرة، يتم تحويل كل وسائط البيانات الثلاث vإلى متجهات تضمين رمزيّة ومعالجتها بواسطة نموذج مشابه لـ GPT للتنبؤ برمز الإجراء المستقبلي.يقوم [محول المسار](model_doc/trajectory_transformer) أيضًا بتحويل الحالات والإجراءات والمكافآت إلى رموز ومعالجتها باستخدام هيكلية GPT. على عكس "محوّل القرارات"، الذي يركز على تكييف المكافأة، يقوم "محوّل المسارات" بتوليد إجراءات مستقبلية باستخدام البحث الشعاعي (Beam Search). diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/modular_transformers.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/modular_transformers.md new file mode 100644 index 0000000000000000000000000000000000000000..b500fec1c92d25efc0de93890c69cd9cafeefd67 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/modular_transformers.md @@ -0,0 +1,184 @@ +# المحولات النمطية + +مكتبة `transformers` هي إطار عمل ذو فلسفة محدد؛ يتم تعريف فلسفتنا في [الدليل المفاهيمي](./philosophy). + +جوهر هذه الفلسفة يتمثل في مبدأ [نموذج واحد، ملف واحد](https://huggingface.co/blog/transformers-design-philosophy) +في المكتبة. الجانب السلبي لهذا المكون هو تقييده لوراثة واستيراد مكونات الملفات. + +نتيجة لذلك، تتكرر مكونات النموذج عبر العديد من الملفات. يحتوي `transformers` على عدد كبير من طبقات الانتباه، يقارب عدد النماذج، والكثير منها متطابق. يتسبب هذا في تباعد عمليات التنفيذ المستقلة مع تطبيق الإصلاحات والتغييرات. +على أجزاء محددة من التعليمات البرمجية. + +ولمعالجة ذلك، اعتمدنا مفهوم "النسخ" في المكتبة. فبإضافة تعليق يُشير إلى أن التعليمات البرمجية هي نسخة من أخرى، نضمن من خلال أنظمة CI والأوامر المحلية عدم تباعد النسخ. لكن هذه العملية، رغم بساطتها، تُسبب إرهاقاً. كما أنها تزيد العبء على المساهمين، وهو ما نهدف إلى تجاوزه. + +غالباً ما تتطلب مساهمات النماذج إضافة تعليمات برمجية (حوالي 1000 سطر)، ومعالج (حوالي 500 سطر)، واختبارات، ووثائق، إلخ. ونادراً ما تقل مساهمات النماذج عن 3000-5000 سطر من التعليمات البرمجية، معظمها أكواد نمطية. هذا يرفع مستوى المساهمات، + +ونهدف مع المحولات النمطية إلى خفض هذا المستوى إلى حدّ مقبول. + +## ما هو؟ + +تقدم المحولات النمطية مفهوم ملف "نمطي" لمجلد نموذج. يقبل هذا الملف النمطي تعليمات برمجية +غير مقبولة عادة في ملفات النمذجة/المعالجة، حيث يسمح بالاستيراد من نماذج مجاورة وكذلك +الوراثة من الفئات إلى فئات أخرى. + +يعرّف هذا الملف النمطي النماذج والمعالجات وفئة التكوين التي سيتم تعريفها في وحداتهم +المتعلقة. + +وأخيرًا، يقدم هذا الميزة أداة `linter` جديدة والتي ستعمل على "تفكيك" الملف النمطي إلى بنية "نموذج واحد، ملف واحد" +هيكل الدليل. سيتم إنشاء هذه الملفات تلقائيًا في كل مرة يتم فيها تشغيل البرنامج النصي؛ مما يقلل من المساهمات المطلوبة +إلى الملف النمطي، وبالتالي فقط إلى التغييرات بين النموذج المساهم والنماذج الأخرى. + +سيقوم مستخدمو النموذج في النهاية باستيراد واستخدام واجهة الملف الواحد، لذا لا يتوقع حدوث أي تغيير هنا. من خلال القيام بذلك، +نأمل في الجمع بين أفضل ما في العالمين: تمكين المساهمات البسيطة مع الالتزام بفلسفتنا. + +لذلك، هذا بديل لعلامات `# Copied from`، ويمكن توقع انتقال النماذج المساهمة سابقًا إلى +تنسيق المحولات النمطية الجديد في الأشهر المقبلة. + +### التفاصيل + +تُبسط أداة "linter" الوراثة، مُنشئةً جميع الملفات المفردة من الملف النمطي، مع الحفاظ على شفافيتها أمام مستخدمي Python. حاليًا، تُبسط الأداة مستوىً واحدًا من الوراثة + +على سبيل المثال: +- إذا ورثت فئة التكوين من فئة أخرى وأضافت/حذفت معامل، فسيتم إما الإشارة إلى الملف المولد مباشرةً + (في حالة الإضافة) أو إزالته تمامًا (في حالة الحذف). +- إذا ورثت فئة من فئة أخرى، على سبيل المثال: `class GemmaModel(LlamaModel):`، تُستنتج التبعيات تلقائيًا + سيتم استنتاج جميع الوحدات الفرعية تلقائيًا من الفئة الأصلية. +- إذا قمت بتعريف وظائف جديدة في الملف `modular` واستخدمتها داخل الفئات، فستستنتج أداة linter ذلك تلقائيًا + +يجب أن تكون قادرًا على كتابة كل شيء (المجزىء اللغوي، ومُعالِج الصور، والنموذج، والتكوين) في الملف `modular`، وسيتم إنشاء الملفات المُقابلة تلقائيًا. + +### التطبيق + +[TODO] نقدم اختبارًا جديدًا، للتأكد من أن المحتوى المولد يتطابق مع ما هو موجود في `modular_xxxx.py` + +### الأمثلة + +هنا مثال سريع باستخدام BERT و RoBERTa. النموذجان مرتبطان ارتباطًا وثيقًا: يختلف تنفيذهما النموذجي في طبقة تضمين. + +بدلاً من إعادة تعريف النموذج بالكامل، إليك كيف يبدو ملف `modular_roberta.py` لفئات النمذجة والتكوين (لأغراض المثال، يتم تجاهل المجزىء اللغوي في هذا الوقت حيث أنه مختلف جدًا). + +```python +from torch import nn +from ..bert.configuration_bert import BertConfig +from ..bert.modeling_bert import ( + BertModel, + BertEmbeddings, + BertForMaskedLM +) + +# تكوين RoBERTa مطابق لتكوين BERT +class RobertaConfig(BertConfig): + model_type = 'roberta' + +# نعيد تعريف الإضافات هنا لتسليط الضوء على اختلاف معرف الحشو، ونعيد تعريف الإضافات الموضعية +class RobertaEmbeddings(BertEmbeddings): + def __init__(self, config): + super().__init__(config()) + + self.padding_idx = config.pad_token_id + self.position_embeddings = nn.Embedding( + config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx + ) + +# نموذج RoBERTa مطابق لنموذج BERT، باستثناء طبقة الإضافات. +# نعيد تعريف الإضافات أعلاه، لذا هنا لا توجد حاجة لعمل إضافي +class RobertaModel(BertModel): + def __init__(self, config): + super().__init__(config) + self.embeddings = RobertaEmbeddings(config) + + +# الرؤوس الآن تحتاج فقط إلى إعادة تعريف النموذج داخل `RobertaModel` الصحيح +class RobertaForMaskedLM(BertForMaskedLM): + def __init__(self, config): + super().__init__(config) + self.model = RobertaModel(config) +``` + +لاحظ أنه إذا لم تستخدم الاعتماد الذي حددته، فستحصل على الخطأ التالي: + +```bash +ValueError: You defined `RobertaEmbeddings` in the modular_roberta.py, it should be used + when you define `BertModel`, as it is one of it's direct dependencies. Make sure + you use it in the `__init__` function. +``` + +بالإضافة إلى ذلك، قد تجد قائمة بالأمثلة هنا: + +## ما هو ليس كذلك + +ليس بديلاً لتعليمات برمجة النمذجة (بعد؟)، وإذا لم يكن نموذجك يعتمد على أي شيء آخر موجود من قبل، فيمكنك إضافة ملف `نمذجة` كالعادة. + + +## الاستخدام المتقدم + +### إزالة السمات والوظائف +لإزالة السمات التي لا تستخدم في نموذجك النمطي، والتي لا تريد رؤيتها في النمذجة المفككة: + +```python +class GemmaModel(LlamaModel): | class GemmaModel(PreTrainedModel): + def __init__(self, config): | def __init__(self, config): + super().__init__(self, eos_token) | super().__init__(config) + del self.embed_tokens | self.padding_idx = config.pad_token_id + | self.vocab_size = config.vocab_size + | + | self.layers = nn.ModuleList( + | [LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] + | ) + | self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + | self.rotary_emb = LlamaRotaryEmbedding(config=config) + | self.gradient_checkpointing = False + | + | # Initialize weights and apply final processing + | self.post_init() +``` +إذا قمت بالتحقق من `LlamaModel` الأصلي، فستجد `embed_tokens` الذي تمت إزالته هنا (كما هو متوقع!) + +إزالة وظيفة مشابهة، تحتاج فقط إلى كتابتها مع `raise ValueError("")` لمحاكاة السلوك الذي تريده فعليًا عند إزالة وظيفة أصلية في بايثون. + +```python +class GemmaTokenizer(LlamaTokenizer): + ... + + def get_spm_processor(self): + raise AttributeError("Not needed for Gemma") + + def unk_token_length(self): + raise AttributeError("Not needed for Gemma") +``` + +### تعريف وظائف جديدة + +إذا قمت بتعريف وظيفة جديدة في الملف `modular` لاستخدامها داخل فئة، على سبيل المثال + +```python +def my_new_function(*args, **kwargs): + # Do something here + pass + +class GemmaModel(LlamaModel): + def forward(*args, **kwargs): + # Call the function + example = my_new_function(*args, **kwargs) + # continue here +``` + +سيتم نسخ وظيفة `my_new_function` (وبشكل متكرر، أي وظائف أخرى جديدة يتم استدعاؤها في جسمها) تلقائيًا +في الملف الذي يتم استخدامه. + +### استدعاء `super()` +قمنا مؤخرًا بشحن بعض الميزات التي تسمح لك بالانتقال من: +```python +class GemmaTokenizer(LlamaTokenizer, PretrainedTokenizerFast): | class GemmaModel(nn.Module): + def __init__(self, eos_token=""): | def __init__(self): + eos_token = AddedToken(eos_token) | eos_token = AddedToken(eos_token) + PretrainedTokenizerFast.__init__(self, eos_token) | super().__init__(eos_token) +``` +هذا مفيد عندما لا تريد تفكيك استدعاء `super()`، وتريد التمييز بين أي استدعاء super init تقوم به! + +### التسمية الخاصة +ندعم الآن أيضًا حالات خاصة مثل +```python +class GemmaVisionModel(CLIPModel): + pass +``` +حيث اسم فئة `GemmaVision` الخاصة بك ليس هو نفسه `Gemma` النمطي. هذا مفيد للغاية للنماذج المركبة. diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/multilingual.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/multilingual.md new file mode 100644 index 0000000000000000000000000000000000000000..b4b2a94fd40a33cfb683f88cd8f662df73cb4f0f --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/multilingual.md @@ -0,0 +1,160 @@ +# النماذج متعددة اللغات للاستدلال + +هناك العديد من النماذج متعددة اللغات في مكتبة 🤗 Transformers، وتختلف طريقة استخدامها للاستدلال عن النماذج أحادية اللغة. ولكن ليس كل استخدام النماذج متعددة اللغات مختلف. فبعض النماذج، مثل [google-bert/bert-base-multilingual-uncased](https://huggingface.co/google-bert/bert-base-multilingual-uncased)، يمكن استخدامها تمامًا مثل النموذج أحادي اللغة. سيوضح لك هذا الدليل كيفية استخدام النماذج متعددة اللغات التي تختلف طريقة استخدامها للاستدلال. + +## XLM + +يحتوي XLM على عشر نسخ مختلفة، واحدة منها فقط أحادية اللغة. ويمكن تقسيم نسخ النماذج التسع المتبقية إلى فئتين: نسخ التي تستخدم تضمينات اللغة (language embeddings) وتلك التي لا تستخدمها. + +### XLM مع تضمينات اللغة + +تستخدم النماذج التالية من XLM تضمينات اللغة لتحديد اللغة المستخدمة أثناء الاستدلال: + +- `FacebookAI/xlm-mlm-ende-1024` (نمذجة اللغة المقنعة، الإنجليزية-الألمانية) +- `FacebookAI/xlm-mlm-enfr-1024` (نمذجة اللغة المقنعة، الإنجليزية-الفرنسية) +- `FacebookAI/xlm-mlm-enro-1024` (نمذجة اللغة المقنعة، الإنجليزية-الرومانية) +- `FacebookAI/xlm-mlm-xnli15-1024` (نمذجة اللغة المقنعة، لغات XNLI) +- `FacebookAI/xlm-mlm-tlm-xnli15-1024` (نمذجة اللغة المقنعة + الترجمة، لغات XNLI) +- `FacebookAI/xlm-clm-enfr-1024` (نمذجة اللغة السببية، الإنجليزية-الفرنسية) +- `FacebookAI/xlm-clm-ende-1024` (نمذجة اللغة السببية، الإنجليزية-الألمانية) + +تُمثل تضمينات اللغة على شكل مصفوفة بنفس شكل `input_ids` التي يتم تمريره إلى النموذج. وتعتمد القيم في هذه المصفوفات على اللغة المستخدمة ويتم تحديدها بواسطة معاملى المجزىء `lang2id` و `id2lang`. + +في هذا المثال، قم بتحميل نسخة `FacebookAI/xlm-clm-enfr-1024` ( نمذجة اللغة السببية، الإنجليزية-الفرنسية): + +```py +>>> import torch +>>> from transformers import XLMTokenizer, XLMWithLMHeadModel + +>>> tokenizer = XLMTokenizer.from_pretrained("FacebookAI/xlm-clm-enfr-1024") +>>> model = XLMWithLMHeadModel.from_pretrained("FacebookAI/xlm-clm-enfr-1024") +``` + +تُظهر خاصية `lang2id` في المجزىء اللغات وأرقام تعريفها في هذا النموذج: + +```py +>>> print(tokenizer.lang2id) +{'en': 0, 'fr': 1} +``` + +بعد ذلك، قم بإنشاء مثال على المدخلات: + +```py +>>> input_ids = torch.tensor([tokenizer.encode("Wikipedia was used to")]) # batch size of 1 +``` + +قم بتعيين معرف اللغة إلى `"en"` واستخدمه لتحديد تضمين اللغة. وتضمين اللغة عبارة عن مصفوفة مملوءة بـ `0` لأن هذا هو معرف اللغة الإنجليزية. يجب أن تكون هذه المصفوفة بنفس حجم `input_ids`. + +```py +>>> language_id = tokenizer.lang2id["en"] # 0 +>>> langs = torch.tensor([language_id] * input_ids.shape[1]) # torch.tensor([0, 0, 0, ..., 0]) + +>>> # نقوم بإعادة تشكيلها لتكون بالحجم (batch_size، sequence_length) +>>> langs = langs.view(1, -1) # الآن بالحجم [1، sequence_length] (لدينا batch size تساوي 1) +``` + +الآن يمكنك تمرير `input_ids` وتضمين اللغة إلى النموذج: + +```py +>>> outputs = model(input_ids, langs=langs) +``` + +يمكن لنص البرنامج النصي [run_generation.py](https://github.com/huggingface/transformers/tree/main/examples/pytorch/text-generation/run_generation.py) توليد النص باستخدام تضمينات اللغة مع نقاط تفتيش `xlm-clm`. + +### XLM بدون تضمينات اللغة + +النماذج التالية من XLM لا تتطلب تضمينات اللغة أثناء الاستنتاج: + +- `FacebookAI/xlm-mlm-17-1280` (نمذجة اللغة المقنعة، 17 لغة) +- `FacebookAI/xlm-mlm-100-1280` (نمذجة اللغة المقنعة، 100 لغة) + +تُستخدم هذه النماذج لتمثيل الجمل العامة، على عكس نسح XLM السابقة. + +## BERT + +يمكن استخدام النماذج التالية من BERT للمهام متعددة اللغات: + +- `google-bert/bert-base-multilingual-uncased` (نمذجة اللغة المقنعة + التنبؤ بالجملة التالية، 102 لغة) +- `google-bert/bert-base-multilingual-cased` (نمذجة اللغة المقنعة + التنبؤ بالجملة التالية، 104 لغات) + +لا تتطلب هذه النماذج تضمينات اللغة أثناء الاستدلال. يجب أن تُحدّد اللغة من السياق وتستنتج وفقاً لذلك. + +## XLM-RoBERTa + +يمكن استخدام النماذج التالية من XLM-RoBERTa للمهام متعددة اللغات: + +- `FacebookAI/xlm-roberta-base` (نمذجة اللغة المقنعة، 100 لغة) +- `FacebookAI/xlm-roberta-large` (نمذجة اللغة المقنعة، 100 لغة) + +تم تدريب XLM-RoBERTa على 2.5 تيرابايت من بيانات CommonCrawl الجديدة والمحسنة في 100 لغة. ويوفر مكاسب قوية على النماذج متعددة اللغات التي تم إصدارها سابقاً مثل mBERT أو XLM في مهام المصب مثل التصنيف، ووضع العلامات التسلسلية، والأسئلة والأجوبة. + +## M2M100 + +يمكن استخدام النماذج التالية من M2M100 للترجمة متعددة اللغات: + +- `facebook/m2m100_418M` (الترجمة) +- `facebook/m2m100_1.2B` (الترجمة) + +في هذا المثال، قم بتحميل نسحة `facebook/m2m100_418M` لترجمة النص من الصينية إلى الإنجليزية. يمكنك تعيين اللغة المصدر في المجزىء اللغوى: + +```py +>>> from transformers import M2M100ForConditionalGeneration, M2M100Tokenizer + +>>> en_text = "Do not meddle in the affairs of wizards, for they are subtle and quick to anger." +>>> chinese_text = "不要插手巫師的事務, 因為他們是微妙的, 很快就會發怒." + +>>> tokenizer = M2M100Tokenizer.from_pretrained("facebook/m2m100_418M", src_lang="zh") +>>> model = M2M100ForConditionalGeneration.from_pretrained("facebook/m2m100_418M") +``` + +تقسيم النّص إلى رموز: + +```py +>>> encoded_zh = tokenizer(chinese_text, return_tensors="pt") +``` + +يجبر M2M100 معرف اللغة الهدف كأول رمز مولد للترجمة إلى اللغة الهدف. قم بتعيين `forced_bos_token_id` إلى `en` في طريقة `generate` للترجمة إلى الإنجليزية: + +```py +>>> generated_tokens = model.generate(**encoded_zh, forced_bos_token_id=tokenizer.get_lang_id("en")) +>>> tokenizer.batch_decode(generated_tokens, skip_special_tokens=True) +'Do not interfere with the matters of the witches, because they are delicate and will soon be angry.' +``` + +## MBart + +يمكن استخدام النماذج التالية من MBart للترجمة متعددة اللغات: + +- `facebook/mbart-large-50-one-to-many-mmt` (الترجمة الآلية متعددة اللغات من واحد إلى كثير، 50 لغة) +- `facebook/mbart-large-50-many-to-many-mmt` (الترجمة الآلية متعددة اللغات من كثير إلى كثير، 50 لغة) +- `facebook/mbart-large-50-many-to-one-mmt` (الترجمة الآلية متعددة اللغات من كثير إلى واحد، 50 لغة) +- `facebook/mbart-large-50` (الترجمة متعددة اللغات، 50 لغة) +- `facebook/mbart-large-cc25` + +في هذا المثال، قم بتحميل نسخة `facebook/mbart-large-50-many-to-many-mmt` لترجمة النص من الفنلندية إلى الإنجليزية. يمكنك تعيين اللغة المصدر في المجزىء: + +```py +>>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM + +>>> en_text = "Do not meddle in the affairs of wizards, for they are subtle and quick to anger." +>>> fi_text = "Älä sekaannu velhojen asioihin, sillä ne ovat hienovaraisia ja nopeasti vihaisia." + +>>> tokenizer = AutoTokenizer.from_pretrained("facebook/mbart-large-50-many-to-many-mmt", src_lang="fi_FI") +>>> model = AutoModelForSeq2SeqLM.from_pretrained("facebook/mbart-large-50-many-to-many-mmt") +``` + +تقسيم النّص إلى رموز: + +```py +>>> encoded_en = tokenizer(en_text, return_tensors="pt") +``` + +يجبر MBart معرف لغة الهدف كأول رمز مولد للترجمة إلى اللغة الهدف. قم بتعيين `forced_bos_token_id` إلى `en` في طريقة `generate` للترجمة إلى الإنجليزية: + +```py +>>> generated_tokens = model.generate(**encoded_en, forced_bos_token_id=tokenizer.lang_code_to_id["en_XX"]) +>>> tokenizer.batch_decode(generated_tokens, skip_special_tokens=True) +"Don't interfere with the wizard's affairs, because they are subtle, will soon get angry." +``` + +إذا كنت تستخدم نسخة `facebook/mbart-large-50-many-to-one-mmt`، فلا تحتاج إلى إجبار معرف لغة الهدف كأول رمز مولد، وإلا فإن الاستخدام هو نفسه. \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/notebooks.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/notebooks.md new file mode 100644 index 0000000000000000000000000000000000000000..d9b481a6c315980d7b6c9003abadd5500d511de2 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/notebooks.md @@ -0,0 +1,140 @@ +# دفاتر ملاحظات 🤗 Transformers + +يمكنك أن تجد هنا قائمة بدفاتر الملاحظات الرسمية التي تقدمها Hugging Face. + +كما نود أن ندرج هنا محتوى مثيرًا للاهتمام تم إنشاؤه بواسطة المجتمع. +إذا كتبت دفتر ملاحظات يستفيد من 🤗 Transformers وتود إدراجه هنا، فيُرجى فتح طلب سحب حتى يمكن تضمينه ضمن دفاتر ملاحظات المجتمع. + + +## دفاتر ملاحظات Hugging Face 🤗 + +### دفاتر ملاحظات التوثيق + +يمكنك فتح أي صفحة من صفحات التوثيق كدفتر ملاحظات في Colab (يوجد زر مباشرة على تلك الصفحات) ولكنها مدرجة هنا أيضًا إذا كنت بحاجة إليها: + +| دفتر الملاحظات | الوصف | | | +|:----------|:-------------|:-------------|------:| +| [جولة سريعة في المكتبة](https://github.com/huggingface/notebooks/blob/main/transformers_doc/en/quicktour.ipynb) | عرض لمختلف واجهات برمجة التطبيقات في Transformers |[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/quicktour.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/en/transformers_doc/quicktour.ipynb)| +| [ملخص المهام](https://github.com/huggingface/notebooks/blob/main/transformers_doc/en/task_summary.ipynb) | كيفية تشغيل نماذج مكتبة Transformers مهمة تلو الأخرى |[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/task_summary.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/en/task_summary.ipynb)| +| [معالجة البيانات مسبقًا](https://github.com/huggingface/notebooks/blob/main/transformers_doc/en/preprocessing.ipynb) | كيفية استخدام محلل لغوي لمعالجة بياناتك مسبقًا |[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/preprocessing.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/en/preprocessing.ipynb)| +| [الضبط الدقيق لنموذج مُدرَّب مسبقًا](https://github.com/huggingface/notebooks/blob/main/transformers_doc/en/training.ipynb) | كيفية استخدام المدرب لضبط نموذج مُدرَّب مسبقًا بدقة |[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/training.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/en/training.ipynb)| +| [ملخص للمحللات اللغوية](https://github.com/huggingface/notebooks/blob/main/transformers_doc/en/tokenizer_summary.ipynb) | الاختلافات بين خوارزمية المحلل اللغوي |[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/tokenizer_summary.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/en/tokenizer_summary.ipynb)| +| [النماذج متعددة اللغات](https://github.com/huggingface/notebooks/blob/main/transformers_doc/en/multilingual.ipynb) | كيفية استخدام النماذج متعددة اللغات للمكتبة |[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/multilingual.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/en/multilingual.ipynb)| + + +### أمثلة PyTorch + +#### معالجة اللغة الطبيعية[[pytorch-nlp]] + +| دفتر الملاحظات | الوصف | | | +|:----------|:-------------|:-------------|------:| +| [تدريب محللك اللغوي](https://github.com/huggingface/notebooks/blob/main/examples/tokenizer_training.ipynb) | كيفية تدريب واستخدام محللك اللغوي الخاص بك |[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/tokenizer_training.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/tokenizer_training.ipynb)| +| [تدريب نموذج لغتك](https://github.com/huggingface/notebooks/blob/main/examples/language_modeling_from_scratch.ipynb) | كيفية البدء بسهولة في استخدام المحولات |[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling_from_scratch.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/language_modeling_from_scratch.ipynb)| +| [كيفية ضبط نموذج بدقة على تصنيف النص](https://github.com/huggingface/notebooks/blob/main/examples/text_classification.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج مُدرَّب مسبقًا بدقة على أي مهمة GLUE. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/text_classification.ipynb)| +| [كيفية ضبط نموذج بدقة على النمذجة اللغوية](https://github.com/huggingface/notebooks/blob/main/examples/language_modeling.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج مُدرَّب مسبقًا بدقة على مهمة LM سببية أو مقنعة. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/language_modeling.ipynb)| +| [كيفية ضبط نموذج بدقة على تصنيف الرموز المميزة](https://github.com/huggingface/notebooks/blob/main/examples/token_classification.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج مُدرَّب مسبقًا بدقة على مهمة تصنيف الرموز المميزة (NER، PoS). | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/token_classification.ipynb)| +| [كيفية ضبط نموذج بدقة على الإجابة على الأسئلة](https://github.com/huggingface/notebooks/blob/main/examples/question_answering.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج مُدرَّب مسبقًا بدقة على SQUAD. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/question_answering.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/question_answering.ipynb)| +| [كيفية ضبط نموذج بدقة على الاختيار من متعدد](https://github.com/huggingface/notebooks/blob/main/examples/multiple_choice.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج مُدرَّب مسبقًا بدقة على SWAG. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/multiple_choice.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/multiple_choice.ipynb)| +| [كيفية ضبط نموذج بدقة على الترجمة](https://github.com/huggingface/notebooks/blob/main/examples/translation.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج مُدرَّب مسبقًا بدقة على WMT. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/translation.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/translation.ipynb)| +| [كيفية ضبط نموذج بدقة على التلخيص](https://github.com/huggingface/notebooks/blob/main/examples/summarization.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج مُدرَّب مسبقًا بدقة على XSUM. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/summarization.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/summarization.ipynb)| +| [كيفية تدريب نموذج لغة من البداية](https://github.com/huggingface/blog/blob/main/notebooks/01_how_to_train.ipynb)| تسليط الضوء على جميع الخطوات لتدريب نموذج Transformer بشكل فعال على بيانات مخصصة | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/blog/blob/main/notebooks/01_how_to_train.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/blog/blob/main/notebooks/01_how_to_train.ipynb)| +| [كيفية إنشاء نص](https://github.com/huggingface/blog/blob/main/notebooks/02_how_to_generate.ipynb)| كيفية استخدام أساليب فك التشفير المختلفة لإنشاء اللغة باستخدام المحولات | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/blog/blob/main/notebooks/02_how_to_generate.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/blog/blob/main/notebooks/02_how_to_generate.ipynb)| +| [كيفية إنشاء نص (مع قيود)](https://github.com/huggingface/blog/blob/main/notebooks/53_constrained_beam_search.ipynb)| كيفية توجيه إنشاء اللغة باستخدام القيود التي يوفرها المستخدم | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/blog/blob/main/notebooks/53_constrained_beam_search.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/blog/blob/main/notebooks/53_constrained_beam_search.ipynb)| +| [Reformer](https://github.com/huggingface/blog/blob/main/notebooks/03_reformer.ipynb)| كيف يدفع Reformer حدود النمذجة اللغوية | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patrickvonplaten/blog/blob/main/notebooks/03_reformer.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/patrickvonplaten/blog/blob/main/notebooks/03_reformer.ipynb)| + +#### رؤية الكمبيوتر[[pytorch-cv]] + +| دفتر الملاحظات | الوصف | | | +|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:-----------------------------------------------------------------------------------------------------------------------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------:| +| [كيفية ضبط نموذج بدقة على تصنيف الصور (Torchvision)](https://github.com/huggingface/notebooks/blob/main/examples/image_classification.ipynb) | يوضح كيفية معالجة البيانات مسبقًا باستخدام Torchvision وضبط أي نموذج رؤية مُدرَّب مسبقًا بدقة على تصنيف الصور | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb) | [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb)| +| [كيفية ضبط نموذج بدقة على تصنيف الصور (Albumentations)](https://github.com/huggingface/notebooks/blob/main/examples/image_classification_albumentations.ipynb) | يوضح كيفية معالجة البيانات مسبقًا باستخدام Albumentations وضبط أي نموذج رؤية مُدرَّب مسبقًا بدقة على تصنيف الصور | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification_albumentations.ipynb) | [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/image_classification_albumentations.ipynb)| +| [كيفية ضبط نموذج بدقة على تصنيف الصور (Kornia)](https://github.com/huggingface/notebooks/blob/main/examples/image_classification_kornia.ipynb) | يوضح كيفية معالجة البيانات مسبقًا باستخدام Kornia وضبط أي نموذج رؤية مُدرَّب مسبقًا بدقة على تصنيف الصور | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification_kornia.ipynb) | [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/image_classification_kornia.ipynb)| +| [كيفية إجراء الكشف عن الأشياء بدون لقطات مع OWL-ViT](https://github.com/huggingface/notebooks/blob/main/examples/zeroshot_object_detection_with_owlvit.ipynb) | يوضح كيفية إجراء الكشف عن الأشياء بدون لقطات على الصور باستخدام استعلامات نصية | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/zeroshot_object_detection_with_owlvit.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/zeroshot_object_detection_with_owlvit.ipynb)| +| [كيفية ضبط نموذج وصف الصور بدقة](https://github.com/huggingface/notebooks/blob/main/examples/image_captioning_blip.ipynb) | يوضح كيفية ضبط BLIP بدقة لوصف الصور على مجموعة بيانات مخصصة | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_captioning_blip.ipynb) | [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/image_captioning_blip.ipynb)| +| [كيفية بناء نظام تشابه الصور مع Transformers](https://github.com/huggingface/notebooks/blob/main/examples/image_similarity.ipynb) | يوضح كيفية بناء نظام تشابه الصور | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_similarity.ipynb) | [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/image_similarity.ipynb)| +| [كيفية ضبط نموذج SegFormer بدقة على التجزئة الدلالية](https://github.com/huggingface/notebooks/blob/main/examples/semantic_segmentation.ipynb) | يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج SegFormer مُدرَّب مسبقًا بدقة على التجزئة الدلالية | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/semantic_segmentation.ipynb) | [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/semantic_segmentation.ipynb)| +| [كيفية ضبط نموذج VideoMAE بدقة على تصنيف الفيديو](https://github.com/huggingface/notebooks/blob/main/examples/video_classification.ipynb) | يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج VideoMAE مُدرَّب مسبقًا بدقة على تصنيف الفيديو | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/video_classification.ipynb) | [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/video_classification.ipynb)| + + +#### الصوت[[pytorch-audio]] + +| دفتر الملاحظات | الوصف | | | +|:----------|:-------------|:-------------|------:| +| [كيفية ضبط نموذج التعرف على الكلام باللغة الإنجليزية بدقة](https://github.com/huggingface/notebooks/blob/main/examples/speech_recognition.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج كلام مُدرَّب مسبقًا بدقة على TIMIT | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/speech_recognition.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/speech_recognition.ipynb)| +| [كيفية ضبط نموذج التعرف على الكلام بأي لغة بدقة](https://github.com/huggingface/notebooks/blob/main/examples/multi_lingual_speech_recognition.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج كلام مُدرَّب مسبقًا متعدد اللغات بدقة على Common Voice | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/multi_lingual_speech_recognition.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/multi_lingual_speech_recognition.ipynb)| +| [كيفية ضبط نموذج بدقة على تصنيف الصوت](https://github.com/huggingface/notebooks/blob/main/examples/audio_classification.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج كلام مُدرَّب مسبقًا بدقة على Keyword Spotting | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/audio_classification.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/audio_classification.ipynb)| + + +#### التسلسلات البيولوجية[[pytorch-bio]] + +| دفتر الملاحظات | الوصف | | | +|:----------|:----------------------------------------------------------------------------------------|:-------------|------:| +| [كيفية ضبط نموذج بروتين مُدرَّب مسبقًا بدقة](https://github.com/huggingface/notebooks/blob/main/examples/protein_language_modeling.ipynb) | شاهد كيفية ترميز البروتينات وضبط نموذج "لغة" بروتين مُدرَّب مسبقًا كبير بدقة | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/protein_language_modeling.ipynb) | [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/protein_language_modeling.ipynb) | +| [كيفية إنشاء طيات بروتينية](https://github.com/huggingface/notebooks/blob/main/examples/protein_folding.ipynb) | شاهد كيفية الانتقال من تسلسل البروتين إلى نموذج بروتين كامل وملف PDB | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/protein_folding.ipynb) | [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/protein_folding.ipynb) | +| [كيفية ضبط نموذج محول النيوكليوتيدات بدقة](https://github.com/huggingface/notebooks/blob/main/examples/nucleotide_transformer_dna_sequence_modelling.ipynb) | شاهد كيفية ترميز الحمض النووي وضبط نموذج "لغة" الحمض النووي مُدرَّب مسبقًا كبير بدقة | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/nucleotide_transformer_dna_sequence_modelling.ipynb) | [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/nucleotide_transformer_dna_sequence_modelling.ipynb) | +| [ضبط نموذج محول النيوكليوتيدات بدقة باستخدام LoRA](https://github.com/huggingface/notebooks/blob/main/examples/nucleotide_transformer_dna_sequence_modelling_with_peft.ipynb) | تدريب نماذج DNA أكبر بكثير بطريقة فعالة من حيث الذاكرة | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/nucleotide_transformer_dna_sequence_modelling_with_peft.ipynb) | [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/nucleotide_transformer_dna_sequence_modelling_with_peft.ipynb) | + + +#### طرائق أخرى[[pytorch-other]] + +| دفتر الملاحظات | الوصف | | | +|:----------|:----------------------------------------------------------------------------------------|:-------------|------:| +| [التنبؤ الاحتمالي بالسلاسل الزمنية](https://github.com/huggingface/notebooks/blob/main/examples/time-series-transformers.ipynb) | شاهد كيفية تدريب Time Series Transformer على مجموعة بيانات مخصصة | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/time-series-transformers.ipynb) | [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/time-series-transformers.ipynb) | + +#### دفاتر ملاحظات الأدوات المساعدة [[pytorch-utility]] + +| دفتر الملاحظات | الوصف | | | +|:----------|:-------------|:-------------|------:| +| [كيفية تصدير النموذج إلى ONNX](https://github.com/huggingface/notebooks/blob/main/examples/onnx-export.ipynb)| تسليط الضوء على كيفية التصدير وتشغيل أعباء عمل الاستدلال من خلال ONNX | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/onnx-export.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/onnx-export.ipynb)| +| [كيفية استخدام المعايير](https://github.com/huggingface/notebooks/blob/main/examples/benchmark.ipynb)| كيفية قياس أداء النماذج باستخدام المحولات | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/benchmark.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/benchmark.ipynb)| + +### أمثلة TensorFlow + +#### معالجة اللغة الطبيعية[[tensorflow-nlp]] + +| دفتر الملاحظات | الوصف | | | +|:----------|:-------------|:-------------|------:| +| [تدريب محللك اللغوي](https://github.com/huggingface/notebooks/blob/main/examples/tokenizer_training.ipynb) | كيفية تدريب واستخدام محللك اللغوي الخاص بك |[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/tokenizer_training.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/tokenizer_training.ipynb)| +| [تدريب نموذج لغتك](https://github.com/huggingface/notebooks/blob/main/examples/language_modeling_from_scratch-tf.ipynb) | كيفية البدء بسهولة في استخدام المحولات |[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling_from_scratch-tf.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/language_modeling_from_scratch-tf.ipynb)| +| [كيفية ضبط نموذج بدقة على تصنيف النص](https://github.com/huggingface/notebooks/blob/main/examples/text_classification-tf.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج مُدرَّب مسبقًا بدقة على أي مهمة GLUE. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification-tf.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/text_classification-tf.ipynb)| +| [كيفية ضبط نموذج بدقة على النمذجة اللغوية](https://github.com/huggingface/notebooks/blob/main/examples/language_modeling-tf.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج مُدرَّب مسبقًا بدقة على مهمة LM سببية أو مقنعة. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling-tf.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/language_modeling-tf.ipynb)| +| [كيفية ضبط نموذج بدقة على تصنيف الرموز المميزة](https://github.com/huggingface/notebooks/blob/main/examples/token_classification-tf.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج مُدرَّب مسبقًا بدقة على مهمة تصنيف الرموز المميزة (NER، PoS). | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification-tf.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/token_classification-tf.ipynb)| +| [كيفية ضبط نموذج بدقة على الإجابة على الأسئلة](https://github.com/huggingface/notebooks/blob/main/examples/question_answering-tf.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج مُدرَّب مسبقًا بدقة على SQUAD. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/question_answering-tf.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/question_answering-tf.ipynb)| +| [كيفية ضبط نموذج بدقة على الاختيار من متعدد](https://github.com/huggingface/notebooks/blob/main/examples/multiple_choice-tf.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج مُدرَّب مسبقًا بدقة على SWAG. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/multiple_choice-tf.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/multiple_choice-tf.ipynb)| +| [كيفية ضبط نموذج بدقة على الترجمة](https://github.com/huggingface/notebooks/blob/main/examples/translation-tf.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج مُدرَّب مسبقًا بدقة على WMT. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/translation-tf.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/translation-tf.ipynb)| +| [كيفية ضبط نموذج بدقة على التلخيص](https://github.com/huggingface/notebooks/blob/main/examples/summarization-tf.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج مُدرَّب مسبقًا بدقة على XSUM. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/summarization-tf.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/summarization-tf.ipynb)| + +#### رؤية الكمبيوتر[[tensorflow-cv]] + +| دفتر الملاحظات | الوصف | | | +|:---------------------------------------------------------------------------------------------------------------------------------------------------------|:----------------------------------------------------------------------------------------------------|:-------------|------:| +| [كيفية ضبط نموذج بدقة على تصنيف الصور](https://github.com/huggingface/notebooks/blob/main/examples/image_classification-tf.ipynb) | يوضح كيفية معالجة البيانات مسبقًا وضبط أي نموذج رؤية مُدرَّب مسبقًا بدقة على تصنيف الصور | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification-tf.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/image_classification-tf.ipynb)| +| [كيفية ضبط نموذج SegFormer بدقة على التجزئة الدلالية](https://github.com/huggingface/notebooks/blob/main/examples/semantic_segmentation-tf.ipynb) | يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج SegFormer مُدرَّب مسبقًا بدقة على التجزئة الدلالية | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/semantic_segmentation-tf.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/semantic_segmentation-tf.ipynb)| + +#### التسلسلات البيولوجية[[tensorflow-bio]] + +| دفتر الملاحظات | الوصف | | | +|:----------|:-------------|:-------------|------:| +| [كيفية ضبط نموذج بروتين مُدرَّب مسبقًا بدقة](https://github.com/huggingface/notebooks/blob/main/examples/protein_language_modeling-tf.ipynb) | شاهد كيفية ترميز البروتينات وضبط نموذج "لغة" بروتين مُدرَّب مسبقًا كبير بدقة | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/protein_language_modeling-tf.ipynb) | [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/protein_language_modeling-tf.ipynb) | + +#### دفاتر ملاحظات الأدوات المساعدة [[tensorflow-utility]] + +| دفتر الملاحظات | الوصف | | | +|:----------|:-------------|:-------------|------:| +| [كيفية تدريب نماذج TF/Keras على TPU](https://github.com/huggingface/notebooks/blob/main/examples/tpu_training-tf.ipynb) | شاهد كيفية التدريب بسرعة عالية على أجهزة TPU من Google | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/tpu_training-tf.ipynb) | [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/tpu_training-tf.ipynb) | + +### دفاتر ملاحظات Optimum + +🤗 [Optimum](https://github.com/huggingface/optimum) هو امتداد لـ 🤗 Transformers، يوفر مجموعة من أدوات تحسين الأداء التي تمكن من تحقيق أقصى قدر من الكفاءة لتدريب وتشغيل النماذج على الأجهزة المستهدفة. + +| دفتر الملاحظات | الوصف | | | +|:----------|:-------------|:-------------|------:| +| [كيفية تكميم نموذج باستخدام ONNX Runtime لتصنيف النص](https://github.com/huggingface/notebooks/blob/main/examples/text_classification_quantization_ort.ipynb)| يوضح كيفية تطبيق التكميم الثابت والديناميكي على نموذج باستخدام [ONNX Runtime](https://github.com/microsoft/onnxruntime) لأي مهمة GLUE. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification_quantization_ort.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/text_classification_quantization_ort.ipynb)| +| [كيفية ضبط نموذج بدقة على تصنيف النص باستخدام ONNX Runtime](https://github.com/huggingface/notebooks/blob/main/examples/text_classification_ort.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج بدقة على أي مهمة GLUE باستخدام [ONNX Runtime](https://github.com/microsoft/onnxruntime). | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification_ort.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/text_classification_ort.ipynb)| +| [كيفية ضبط نموذج بدقة على التلخيص باستخدام ONNX Runtime](https://github.com/huggingface/notebooks/blob/main/examples/summarization_ort.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج بدقة على XSUM باستخدام [ONNX Runtime](https://github.com/microsoft/onnxruntime). | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/summarization_ort.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/summarization_ort.ipynb)| + + +## دفاتر ملاحظات المجتمع: + +تتوفر المزيد من دفاتر الملاحظات التي طورها المجتمع [هنا](https://hf.co/docs/transformers/community#community-notebooks). + diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/pad_truncation.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/pad_truncation.md new file mode 100644 index 0000000000000000000000000000000000000000..d41d4f9c6b453b577b0b1309df87aaba9683f50e --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/pad_truncation.md @@ -0,0 +1,52 @@ +# الحشو والتقليم + +غالبًا ما تختلف مدخلات الدُفعات في الطول، لذا لا يمكن تحويلها إلى مصفوفات ذات حجم ثابت .يُعدّ الحشو والتقليم هما استراتيجيتان للتعامل مع هذه المشكلة، لإنشاء مصفوفات مستطيلة من مجموعات ذات أطوال مختلفة. ويضيف الحشو رمز **حشو** خاص لضمان أن يكون للتسلسلات الأقصر نفس طول أطول تسلسل في الدفعة أو الطول الأقصى الذي يقبله النموذج. ويعمل التقليم عكس ذلك بتقليم التسلسلات الطويلة. + +في معظم الحالات، ييُعدّ حشو دُفعتك إلى طول أطول تسلسل فيها وتقليمها إلى الطول الأقصى المقبول من النموذج حلًا فعالًا. ومع ذلك، تدعم واجهة برمجة التطبيقات المزيد من الاستراتيجيات إذا كنت بحاجة إليها. هناك ثلاثة معامﻻت تحتاجها لفهم آلية العمل: `padding`، و`truncation`، و`max_length`. + +يحكم معامل `padding` عملية الحشو. يمكن أن يكون قيمة منطقية أو نصية: + + - `True` أو `'longest'`: الحشو إلى أطول تسلسل في الدفعة (لا يتم تطبيق الحشو عند تقديم تسلسل واحد فقط). + - `'max_length'`: الحشو إلى طول محدد بواسطة معامل `max_length` أو الطول الأقصى الذي يقبله + النموذج إذا لم يتم توفير `max_length` (`max_length=None`). سيظل الحشو مطبقًا إذا قدمت تسلسلًا واحدًا فقط. + - `False` أو `'do_not_pad'`: لا يتم تطبيق أي حشو. هذا هو السلوك الافتراضي. + +تحكم معامل `truncation` عملية التقليم. يمكن أن يكون قيمة منطقية أو نصية: + + -قيمة `True` أو `'longest_first'` : تقليم التسلسلات إلى طول أقصى مُحدد بواسطة معامل `max_length`، أو أقصى طول يقبله النموذج في حال عدم تحديد طول مُحدد من قبل المستخدم (`max_length=None`). ستتم عملية التقليم إزالة رمز تلو الآخر، بدءًا من أطول تسلسل في الزوج، إلى أن يصل الطول إلى القيمة المُحددة. + -قيمة `'only_second'`: اقطع إلى طول أقصى محدد بواسطة معامل `max_length` أو أقصى طول يقبله النموذج إذا لم يتم توفير `max_length` (`max_length=None`). هذا سيقلم فقط الجملة الثانية من الزوج إذا تم توفير زوج من التسلسلات (أو دُفعة من أزواج التسلسلات). + -قيمة `'only_first'`: تقليم الجملة الأولى فقط من الزوج عند تقديم زوج من التسلسلات (أو دُفعة من أزواج التسلسلات) إلى طول أقصى مُحدد بواسطة حجة `max_length`، أو أقصى طول يقبله النموذج في حال عدم تحديد طول مُحدد من قبل المستخدم (`max_length=None`). + -قيمة `False` أو `'do_not_truncate'`: لا يتم تطبيق أي تقليم. هذا هو السلوك الافتراضي. +`` + +يحكم معامل `max_length` طول الحشو والتقليم. يمكن أن يكون عدد صحيح أو `None`، وعندها يُحدد افتراضيًا إلى الطول الأقصى الذي يمكن أن يقبله النموذج. إذا لم يكن للنموذج طول إدخال أقصى محدد، يتم إلغاء تنشيط التقليم أو الحشو إلى `max_length`. + +يلخّص الجدول التالي الطريقة المُوصى بها لإعداد الحشو والتقليم. إذا كنت تستخدم أزواج تسلسلات الإدخال في أي من الأمثلة التالية، فيمكنك استبدال `truncation=True` بـ `STRATEGY` المحدد في `['only_first'، 'only_second'، 'longest_first']`، أي `truncation='only_second'` أو `truncation='longest_first'` للتحكم في كيفية تقليم كلا التسلسلين في الزوج كما هو موضّح سابقًا. + + +# حيل الترميز + +هناك العديد من الاستراتيجيات لترميز دفعات الجمل. فيما يلي بعض الأمثلة على ذلك. + +| الترميز | الحشو | التعليمات | +|--------------------------------------|-----------------------------------|---------------------------------------------------------------------------------------------| +| لا ترميز | لا حشو | `tokenizer(batch_sentences)` | +| | الحشو إلى الحد الأقصى للتسلسل في الدفعة | `tokenizer(batch_sentences, padding=True)` أو | +| | | `tokenizer(batch_sentences, padding='longest')` | +| | الحشو إلى الحد الأقصى لطول إدخال النموذج | `tokenizer(batch_sentences, padding='max_length')` | +| | الحشو إلى طول محدد | `tokenizer(batch_sentences, padding='max_length', max_length=42)` | +| | الحشو إلى مضاعف لقيمة معينة | `tokenizer(batch_sentences, padding=True, pad_to_multiple_of=8)` | +| الترميز إلى الحد الأقصى لطول إدخال النموذج | لا حشو | `tokenizer(batch_sentences, truncation=True)` أو | +| | | `tokenizer(batch_sentences, truncation=STRATEGY)` | +| | الحشو إلى الحد الأقصى للتسلسل في الدفعة | `tokenizer(batch_sentences, padding=True, truncation=True)` أو | +| | | `tokenizer(batch_sentences, padding=True, truncation=STRATEGY)` | +| | الحشو إلى الحد الأقصى لطول إدخال النموذج | `tokenizer(batch_sentences, padding='max_length', truncation=True)` أو | +| | | `tokenizer(batch_sentences, padding='max_length', truncation=STRATEGY)` | +| | الحشو إلى طول محدد | غير ممكن | +| الترميز إلى طول محدد | لا حشو | `tokenizer(batch_sentences, truncation=True, max_length=42)` أو | +| | | `tokenizer(batch_sentences, truncation=STRATEGY, max_length=42)` | +| | الحشو إلى الحد الأقصى للتسلسل في الدفعة | `tokenizer(batch_sentences, padding=True, truncation=True, max_length=42)` أو | +| | | `tokenizer(batch_sentences, padding=True, truncation=STRATEGY, max_length=42)` | +| | الحشو إلى الحد الأقصى لطول إدخال النموذج | غير ممكن | +| | الحشو إلى طول محدد | `tokenizer(batch_sentences, padding='max_length', truncation=True, max_length=42)` أو | +| | | `tokenizer(batch_sentences, padding='max_length', truncation=STRATEGY, max_length=42)` | \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/peft.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/peft.md new file mode 100644 index 0000000000000000000000000000000000000000..892d70eb5f6d1657a107ff5c5d7e065aa897c2b1 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/peft.md @@ -0,0 +1,250 @@ +# تحميل المحوّلات باستخدام 🤗 PEFT + +[[open-in-colab]] + +تقنية "التدريب الدقيق ذو الكفاءة البارامتيرية" (PEFT)](https://huggingface.co/blog/peft) تقوم بتجميد معلمات النموذج المُدرب مسبقًا أثناء الضبط الدقيق وتضيف عدد صغير من المعلمات القابلة للتدريب (المحولات) فوقه. يتم تدريب المحوّلات لتعلم معلومات خاصة بالمهام. وقد ثبت أن هذا النهج فعال للغاية من حيث استخدام الذاكرة مع انخفاض استخدام الكمبيوتر أثناء إنتاج نتائج قمماثلة للنموذج مضبوط دقيقًا بالكامل. + +عادة ما تكون المحولات المدربة باستخدام PEFT أصغر بمقدار كبير من حيث الحجم من النموذج الكامل، مما يجعل من السهل مشاركتها وتخزينها وتحميلها. + +
+ +
تبلغ أوزان المحول لطراز OPTForCausalLM المخزن على Hub حوالي 6 ميجابايت مقارنة بالحجم الكامل لأوزان النموذج، والتي يمكن أن تكون حوالي 700 ميجابايت.
+
+ +إذا كنت مهتمًا بمعرفة المزيد عن مكتبة 🤗 PEFT، فراجع [الوثائق](https://huggingface.co/docs/peft/index). + +## الإعداد + +ابدأ بتثبيت 🤗 PEFT: + +```bash +pip install peft +``` + +إذا كنت تريد تجربة الميزات الجديدة تمامًا، فقد تكون مهتمًا بتثبيت المكتبة من المصدر: + +```bash +pip install git+https://github.com/huggingface/peft.git +``` + +## نماذج PEFT المدعومة + +يدعم 🤗 Transformers بشكلٍ أصلي بعض طرق PEFT، مما يعني أنه يمكنك تحميل أوزان المحول المخزنة محليًا أو على Hub وتشغيلها أو تدريبها ببضع سطور من التعليمات البرمجية. الطرق المدعومة هي: + +- [محولات الرتبة المنخفضة](https://huggingface.co/docs/peft/conceptual_guides/lora) +- [IA3](https://huggingface.co/docs/peft/conceptual_guides/ia3) +- [AdaLoRA](https://huggingface.co/papers/2303.10512) + +إذا كنت تريد استخدام طرق PEFT الأخرى، مثل تعلم المحث أو ضبط المحث، أو حول مكتبة 🤗 PEFT بشكل عام، يرجى الرجوع إلى [الوثائق](https://huggingface.co/docs/peft/index). + +## تحميل محول PEFT + +لتحميل نموذج محول PEFT واستخدامه من 🤗 Transformers، تأكد من أن مستودع Hub أو الدليل المحلي يحتوي على ملف `adapter_config.json` وأوزان المحوّل، كما هو موضح في صورة المثال أعلاه. بعد ذلك، يمكنك تحميل نموذج محوّل PEFT باستخدام فئة `AutoModelFor`. على سبيل المثال، لتحميل نموذج محول PEFT للنمذجة اللغوية السببية: + +1. حدد معرف النموذج لPEFT +2. مرره إلى فئة [`AutoModelForCausalLM`] + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer + +peft_model_id = "ybelkada/opt-350m-lora" +model = AutoModelForCausalLM.from_pretrained(peft_model_id) +``` + + + +يمكنك تحميل محول PEFT باستخدام فئة `AutoModelFor` أو فئة النموذج الأساسي مثل `OPTForCausalLM` أو `LlamaForCausalLM`. + + + +يمكنك أيضًا تحميل محول PEFT عن طريق استدعاء طريقة `load_adapter`: + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer + +model_id = "facebook/opt-350m" +peft_model_id = "ybelkada/opt-350m-lora" + +model = AutoModelForCausalLM.from_pretrained(model_id) +model.load_adapter(peft_model_id) +``` + +راجع قسم [وثائق API](#transformers.integrations.PeftAdapterMixin) أدناه لمزيد من التفاصيل. + +## التحميل في 8 بت أو 4 بت + +راجع قسم [وثائق API](#transformers.integrations.PeftAdapterMixin) أدناه لمزيد من التفاصيل. + +## التحميل في 8 بت أو 4 بت + +يدعم تكامل `bitsandbytes` أنواع بيانات الدقة 8 بت و4 بت، والتي تكون مفيدة لتحميل النماذج الكبيرة لأنها توفر مساحة في الذاكرة (راجع دليل تكامل `bitsandbytes` [guide](./quantization#bitsandbytes-integration) لمعرفة المزيد). أضف المعلمات`load_in_8bit` أو `load_in_4bit` إلى [`~PreTrainedModel.from_pretrained`] وقم بتعيين `device_map="auto"` لتوزيع النموذج بشكل فعال على الأجهزة لديك: + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig + +peft_model_id = "ybelkada/opt-350m-lora" +model = AutoModelForCausalLM.from_pretrained(peft_model_id, quantization_config=BitsAndBytesConfig(load_in_8bit=True)) +``` + +## إضافة محول جديد + +يمكنك استخدام الدالة [`~peft.PeftModel.add_adapter`] لإضافة محوّل جديد إلى نموذج يحتوي بالفعل على محوّل آخر طالما أن المحول الجديد مطابقًا للنوع الحالي. على سبيل المثال، إذا كان لديك محول LoRA موجود مرتبط بنموذج: + +```py +from transformers import AutoModelForCausalLM, OPTForCausalLM, AutoTokenizer +from peft import LoraConfig + +model_id = "facebook/opt-350m" +model = AutoModelForCausalLM.from_pretrained(model_id) + +lora_config = LoraConfig( + target_modules=["q_proj", "k_proj"], + init_lora_weights=False +) + +model.add_adapter(lora_config, adapter_name="adapter_1") +``` + +لإضافة محول جديد: + +```py +# قم بتعليق محول جديد بنفس التكوين +model.add_adapter(lora_config, adapter_name="adapter_2") +``` + +الآن يمكنك استخدام [`~peft.PeftModel.set_adapter`] لتعيين المحول الذي سيتم استخدامه: + +```py +# استخدم adapter_1 +model.set_adapter("adapter_1") +output = model.generate(**inputs) +print(tokenizer.decode(output_disabled[0], skip_special_tokens=True)) + +# استخدم adapter_2 +model.set_adapter("adapter_2") +output_enabled = model.generate(**inputs) +print(tokenizer.decode(output_enabled[0], skip_special_tokens=True)) +``` + +## تمكين وتعطيل المحولات + +بمجرد إضافة محول إلى نموذج، يمكنك تمكين أو تعطيل وحدة المحول. لتمكين وحدة المحول: + +```py +from transformers import AutoModelForCausalLM, OPTForCausalLM, AutoTokenizer +from peft import PeftConfig + +model_id = "facebook/opt-350m" +adapter_model_id = "ybelkada/opt-350m-lora" +tokenizer = AutoTokenizer.from_pretrained(model_id) +text = "Hello" +inputs = tokenizer(text, return_tensors="pt") + +model = AutoModelForCausalLM.from_pretrained(model_id) +peft_config = PeftConfig.from_pretrained(adapter_model_id) + +# لبدء تشغيله بأوزان عشوائية +peft_config.init_lora_weights = False + +model.add_adapter(peft_config) +model.enable_adapters() +output = model.generate(**inputs) +``` + +لإيقاف تشغيل وحدة المحول: + +```py +model.disable_adapters() +output = model.generate(**inputs) +``` + +## تدريب محول PEFT + +يدعم محول PEFT فئة [`Trainer`] بحيث يمكنك تدريب محول لحالتك الاستخدام المحددة. فهو يتطلب فقط إضافة بضع سطور أخرى من التعليمات البرمجية. على سبيل المثال، لتدريب محول LoRA: + + + +إذا لم تكن معتادًا على ضبط نموذج دقيق باستخدام [`Trainer`، فراجع البرنامج التعليمي](training) لضبط نموذج مُدرب مسبقًا. + + + +1. حدد تكوين المحول باستخدام نوع المهمة والمعاملات الزائدة (راجع [`~peft.LoraConfig`] لمزيد من التفاصيل حول وظيفة هذه المعلمات). + +```py +from peft import LoraConfig + +peft_config = LoraConfig( + lora_alpha=16, + lora_dropout=0.1, + r=64, + bias="none", + task_type="CAUSAL_LM"، +) +``` + +2. أضف المحول إلى النموذج. + +```py +model.add_adapter(peft_config) +``` + +3. الآن يمكنك تمرير النموذج إلى [`Trainer`]! + +```py +trainer = Trainer(model=model, ...) +trainer.train() +``` + +لحفظ محول المدرب وتحميله مرة أخرى: + +```py +model.save_pretrained(save_dir) +model = AutoModelForCausalLM.from_pretrained(save_dir) +``` + +## إضافة طبقات قابلة للتدريب إضافية إلى محول PEFT + +```py +model.save_pretrained(save_dir) +model = AutoModelForCausalLM.from_pretrained(save_dir) +``` + +## إضافة طبقات قابلة للتدريب إضافية إلى محول PEFT + +يمكنك أيضًا إجراء تدريب دقيق لمحوّلات قابلة للتدريب إضافية فوق نموذج يحتوي بالفعل على محوّلات عن طريق تمرير معلم `modules_to_save` في تكوين PEFT الخاص بك. على سبيل المثال، إذا كنت تريد أيضًا ضبط دقيق لرأس النموذج اللغوي`lm_head` فوق نموذج بمحوّل LoRA: + +```py +from transformers import AutoModelForCausalLM, OPTForCausalLM, AutoTokenizer +from peft import LoraConfig + +model_id = "facebook/opt-350m" +model = AutoModelForCausalLM.from_pretrained(model_id) + +lora_config = LoraConfig( + target_modules=["q_proj", "k_proj"], + modules_to_save=["lm_head"]، +) + +model.add_adapter(lora_config) +``` + +## وثائق API + +[[autodoc]] integrations.PeftAdapterMixin + - load_adapter + - add_adapter + - set_adapter + - disable_adapters + - enable_adapters + - active_adapters + - get_adapter_state_dict + + + + + \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/perplexity.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/perplexity.md new file mode 100644 index 0000000000000000000000000000000000000000..e7d2a19d2c837fb4ae2f161b78e125f39db40721 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/perplexity.md @@ -0,0 +1,94 @@ +# التعقيد اللغوي للنماذج ذات الطول الثابت + +[[open-in-colab]] + + التعقيد اللغوي (PPL) هي واحدة من أكثر المقاييس شيوعًا لتقييم نماذج اللغة. قبل الخوض في التفاصيل، يجب أن نلاحظ أن المقياس ينطبق تحديدًا على نماذج اللغة الكلاسيكية (يُطلق عليها أحيانًا نماذج اللغة التلقائية المرجعية أو السببية) وهي غير محددة جيدًا لنماذج اللغة المقنعة مثل BERT (راجع [ملخص النماذج](model_summary)). + +تُعرَّف التعقيد اللغوي على أنها الأس المُرفوع لقيمة متوسط اللوغاريتم الاحتمالي لمتتالية. إذا كان لدينا تسلسل رمزي \\(X = (x_0, x_1, \dots, x_t)\\)، فإن حيرة \\(X\\) هي، + +$$\text{PPL}(X) = \exp \left\{ {-\frac{1}{t}\sum_i^t \log p_\theta (x_i|x_{ + +لكن عند التعامل مع النماذج التقريبية، نواجه عادةً قيدًا على عدد الرموز التي يمكن للنموذج معالجتها. على سبيل المثال، تحتوي أكبر نسخة من [GPT-2](model_doc/gpt2) على طول ثابت يبلغ 1024 رمزًا، لذا لا يمكننا حساب \\(p_\theta(x_t|x_{ + +تتميز هذه الطريقة بسرعة حسابها نظرًا لإمكانية حساب درجة التعقيد اللغوي لكل جزء بمسح واحد للأمام، إلا أنها تُعدّ تقريبًا ضعيفًا لدرجة التعقيد اللغوي المُحلّلة بشكل كامل، وعادةً ما تؤدي إلى درجة تعقيد لغوي أعلى (أسوأ) لأن النموذج سيكون لديه سياق أقل في معظم خطوات التنبؤ. + +بدلاً من ذلك، يجب تقييم درجة التعقيد اللغوي للنماذج ذات الطول الثابت باستخدام إستراتيجية النافذة المنزلقة. وينطوي هذا على تحريك نافذة السياق بشكل متكرر بحيث يكون للنموذج سياق أكبر عند إجراء كل تنبؤ. + +Sliding window PPL taking advantage of all available context + +هذا تقريب أقرب للتفكيك الحقيقي لاحتمالية التسلسل وسيؤدي عادةً إلى نتيجة أفضل.لكن الجانب السلبي هو أنه يتطلب تمريرًا للأمام لكل رمز في مجموعة البيانات. حل وسط عملي مناسب هو استخدام نافذة منزلقة بخطوة، بحيث يتم تحريك السياق بخطوات أكبر بدلاً من الانزلاق بمقدار 1 رمز في كل مرة. مما يسمح بإجراء الحساب بشكل أسرع مع إعطاء النموذج سياقًا كبيرًا للتنبؤات في كل خطوة. + +## مثال: حساب التعقيد اللغوي مع GPT-2 في 🤗 Transformers + +دعونا نوضح هذه العملية مع GPT-2. + +```python +from transformers import GPT2LMHeadModel, GPT2TokenizerFast + +device = "cuda" +model_id = "openai-community/gpt2-large" +model = GPT2LMHeadModel.from_pretrained(model_id).to(device) +tokenizer = GPT2TokenizerFast.from_pretrained(model_id) +``` + +سنقوم بتحميل مجموعة بيانات WikiText-2 وتقييم التعقيد اللغوي باستخدام بعض إستراتيجيات مختلفة النافذة المنزلقة. نظرًا لأن هذه المجموعة البيانات الصغيرة ونقوم فقط بمسح واحد فقط للمجموعة، فيمكننا ببساطة تحميل مجموعة البيانات وترميزها بالكامل في الذاكرة. + +```python +from datasets import load_dataset + +test = load_dataset("wikitext", "wikitext-2-raw-v1", split="test") +encodings = tokenizer("\n\n".join(test["text"]), return_tensors="pt") +``` + +مع 🤗 Transformers، يمكننا ببساطة تمرير `input_ids` كـ `labels` إلى نموذجنا، وسيتم إرجاع متوسط احتمالية السجل السالب لكل رمز كخسارة. ومع ذلك، مع نهج النافذة المنزلقة، هناك تداخل في الرموز التي نمررها إلى النموذج في كل تكرار. لا نريد تضمين احتمالية السجل للرموز التي نتعامل معها كسياق فقط في خسارتنا، لذا يمكننا تعيين هذه الأهداف إلى `-100` بحيث يتم تجاهلها. فيما يلي هو مثال على كيفية القيام بذلك بخطوة تبلغ `512`. وهذا يعني أن النموذج سيكون لديه 512 رمزًا على الأقل للسياق عند حساب الاحتمالية الشرطية لأي رمز واحد (بشرط توفر 512 رمزًا سابقًا متاحًا للاشتقاق). + +```python +import torch +from tqdm import tqdm + +max_length = model.config.n_positions +stride = 512 +seq_len = encodings.input_ids.size(1) + +nlls = [] +prev_end_loc = 0 +for begin_loc in tqdm(range(0, seq_len, stride)): + end_loc = min(begin_loc + max_length, seq_len) + trg_len = end_loc - prev_end_loc # قد تكون مختلفة عن الخطوة في الحلقة الأخيرة + input_ids = encodings.input_ids[:, begin_loc:end_loc].to(device) + target_ids = input_ids.clone() + target_ids[:, :-trg_len] = -100 + + with torch.no_grad(): + outputs = model(input_ids, labels=target_ids) + + # يتم حساب الخسارة باستخدام CrossEntropyLoss الذي يقوم بالمتوسط على التصنيفات الصحيحة + # لاحظ أن النموذج يحسب الخسارة على trg_len - 1 من التصنيفات فقط، لأنه يتحول داخليًا إلى اليسار بواسطة 1. + neg_log_likelihood = outputs.loss + + nlls.append(neg_log_likelihood) + + prev_end_loc = end_loc + if end_loc == seq_len: + break + +ppl = torch.exp(torch.stack(nlls).mean()) +``` + +يعد تشغيل هذا مع طول الخطوة مساويًا لطول الإدخال الأقصى يعادل لاستراتيجية النافذة غير المنزلقة وغير المثلى التي ناقشناها أعلاه. وكلما صغرت الخطوة، زاد السياق الذي سيحصل عليه النموذج في عمل كل تنبؤ، وكلما كانت التعقيد اللغوي المُبلغ عنها أفضل عادةً. + +عندما نقوم بتشغيل ما سبق باستخدام `stride = 1024`، أي بدون تداخل، تكون درجة التعقيد اللغوي الناتجة هي `19.44`، وهو ما يماثل `19.93` المبلغ عنها في ورقة GPT-2. من خلال استخدام `stride = 512` وبالتالي استخدام إستراتيجية النافذة المنزلقة، ينخفض هذا إلى `16.45`. هذه النتيجة ليست فقط أفضل، ولكنها محسوبة بطريقة أقرب إلى التحليل التلقائي الحقيقي لاحتمالية التسلسل. \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/philosophy.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/philosophy.md new file mode 100644 index 0000000000000000000000000000000000000000..09de2991fba28d3e650aafc30bed104396c50894 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/philosophy.md @@ -0,0 +1,49 @@ +# الفلسفة + +تُعد 🤗 Transformers مكتبة برمجية ذات رؤية واضحة صُممت من أجل: + +- الباحثون والمُتعلّمون في مجال التعلم الآلي ممن يسعون لاستخدام أو دراسة أو تطوير نماذج Transformers واسعة النطاق. +- مُطبّقي تعلم الآلة الذين يرغبون في ضبط تلك النماذج أو تشغيلها في بيئة إنتاجية، أو كليهما. +- المهندسون الذين يريدون فقط تنزيل نموذج مُدرب مسبقًا واستخدامه لحل مهمة تعلم آلي معينة. + +تم تصميم المكتبة مع الأخذ في الاعتبار هدفين رئيسيين: + +1. سهولة وسرعة الاستخدام: + + - تمّ تقليل عدد المفاهيم المُجردة التي يتعامل معها المستخدم إلى أدنى حد والتي يجب تعلمها، وفي الواقع، لا توجد مفاهيم مُجردة تقريبًا، فقط ثلاث فئات أساسية مطلوبة لاستخدام كل نموذج: [الإعدادات](main_classes/configuration)، [نماذج](main_classes/model)، وفئة ما قبل المعالجة ([مُجزّئ لغوي](main_classes/tokenizer) لـ NLP، [معالج الصور](main_classes/image_processor) للرؤية، [مستخرج الميزات](main_classes/feature_extractor) للصوت، و [معالج](main_classes/processors) للمدخﻻت متعددة الوسائط). + - يمكن تهيئة جميع هذه الفئات بطريقة بسيطة وموحدة من خلال نماذج مُدربة مسبقًا باستخدام الدالة الموحدة `from_pretrained()` والتي تقوم بتنزيل (إذا لزم الأمر)، وتخزين وتحميل كل من: فئة النموذج المُراد استخدامه والبيانات المرتبطة ( مُعاملات الإعدادات، ومعجم للمُجزّئ اللغوي،وأوزان النماذج) من نقطة تدقيق مُحددة مُخزّنة على [Hugging Face Hub](https://huggingface.co/models) أو ن من نقطة تخزين خاصة بالمستخدم. + - بالإضافة إلى هذه الفئات الأساسية الثلاث، توفر المكتبة واجهتي برمجة تطبيقات: [`pipeline`] للاستخدام السريع لأحد النماذج لأداء استنتاجات على مهمة مُحددة، و [`Trainer`] للتدريب السريع أو الضبط الدقيق لنماذج PyTorch (جميع نماذج TensorFlow متوافقة مع `Keras.fit`). + - نتيجة لذلك، هذه المكتبة ليست صندوق أدوات متعدد الاستخدامات من الكتل الإنشائية للشبكات العصبية. إذا كنت تريد توسيع أو البناء على المكتبة، فما عليك سوى استخدام Python و PyTorch و TensorFlow و Keras العادية والوراثة من الفئات الأساسية للمكتبة لإعادة استخدام الوظائف مثل تحميل النموذج وحفظه. إذا كنت ترغب في معرفة المزيد عن فلسفة الترميز لدينا للنماذج، فراجع منشور المدونة الخاص بنا [Repeat Yourself](https://huggingface.co/blog/transformers-design-philosophy). + +2. تقديم نماذج رائدة في مجالها مع أداء قريب قدر الإمكان من النماذج الأصلية: + + - نقدم مثالًا واحدًا على الأقل لكل بنية تقوم بإعادة إنتاج نتيجة مقدمة من المؤلفين الرسميين لتلك البنية. + - عادةً ما تكون الشفرة قريبة قدر الإمكان من قاعدة الشفرة الأصلية، مما يعني أن بعض شفرة PyTorch قد لا تكون "بأسلوب PyTorch" كما يمكن أن تكون نتيجة لكونها شفرة TensorFlow محولة والعكس صحيح. + +بعض الأهداف الأخرى: + +- كشف تفاصيل النماذج الداخلية بشكل متسق قدر الإمكان: + + -نتيح الوصول، باستخدام واجهة برمجة واحدة، إلى جميع الحالات المخفية (Hidden-States) وأوزان الانتباه (Attention Weights). + - تم توحيد واجهات برمجة التطبيقات الخاصة بفئات المعالجة المسبقة والنماذج الأساسية لتسهيل التبديل بين النماذج. + +- دمج مجموعة مختارة من الأدوات الواعدة لضبط النماذج بدقة (Fine-tuning) ودراستها: + + - طريقة بسيطة ومتسقة لإضافة رموز جديدة إلى مفردات التضمينات (Embeddings) لضبط النماذج بدقة. + - طرق سهلة لإخفاء (Masking) وتقليم (Pruning) رؤوس المحولات (Transformer Heads). + +- التبديل بسهولة بين PyTorch و TensorFlow 2.0 و Flax، مما يسمح بالتدريب باستخدام إطار واحد والاستدلال باستخدام إطار آخر. + +## المفاهيم الرئيسية + +تعتمد المكتبة على ثلاثة أنواع من الفئات لكل نموذج: + +- **فئات النماذج** يمكن أن تكون نماذج PyTorch ([torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module))، أو نماذج Keras ([tf.keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model))، أو نماذج JAX/Flax ([flax.linen.Module](https://flax.readthedocs.io/en/latest/api_reference/flax.linen/module.html)) التي تعمل مع الأوزان المُدربة مسبقًا المقدمة في المكتبة. +- **فئات الإعداد** تخزن معلمات التهيئة المطلوبة لبناء نموذج (مثل عدد الطبقات وحجم الطبقة المخفية). أنت لست مضطرًا دائمًا إلى إنشاء مثيل لهذه الفئات بنفسك. على وجه الخصوص، إذا كنت تستخدم نموذجًا مُدربًا مسبقًا دون أي تعديل، فإن إنشاء النموذج سيهتم تلقائيًا تهيئة الإعدادات (والذي يعد جزءًا من النموذج). +- **فئات ما قبل المعالجة** تحويل البيانات الخام إلى تنسيق مقبول من قبل النموذج. يقوم [المعالج](main_classes/tokenizer) بتخزين المعجم لكل نموذج ويقدم طرقًا لتشفير وفك تشفير السلاسل في قائمة من مؤشرات تضمين الرموز ليتم إطعامها للنموذج. تقوم [معالجات الصور](main_classes/image_processor) بمعالجة إدخالات الرؤية، وتقوم [مستخلصات الميزات](main_classes/feature_extractor) بمعالجة إدخالات الصوت، ويقوم [المعالج](main_classes/processors) بمعالجة الإدخالات متعددة الوسائط. + +يمكن تهيئة جميع هذه الفئات من نسخ مُدربة مسبقًا، وحفظها محليًا، ومشاركتها على منصة Hub عبر ثلاث طرق: + +- تسمح لك الدالة `from_pretrained()` بتهيئة النموذج وتكويناته وفئة المعالجة المسبقة من إصدار مُدرب مسبقًا إما يتم توفيره بواسطة المكتبة نفسها (يمكن العثور على النماذج المدعومة على [Model Hub](https://huggingface.co/models)) أو مخزنة محليًا (أو على خادم) بواسطة المستخدم. +- تسمح لك الدالة `save_pretrained()` بحفظ النموذج، وتكويناته وفئة المعالجة المسبقة محليًا، بحيث يمكن إعادة تحميله باستخدام الدالة `from_pretrained()`. +- تسمح لك `push_to_hub()` بمشاركة نموذج وتكويناتهوفئة المعالجة المسبقة على Hub، بحيث يمكن الوصول إليها بسهولة من قبل الجميع. diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/pipeline_tutorial.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/pipeline_tutorial.md new file mode 100644 index 0000000000000000000000000000000000000000..2dd713a6533f6e3831bdde6116f16bbdcf573f57 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/pipeline_tutorial.md @@ -0,0 +1,315 @@ +# خطوط الأنابيب الاستدلال + +يجعل [`pipeline`] من السهل استخدام أي نموذج من [Hub](https://huggingface.co/models) للاستدلال لأي مهام خاصة باللغة أو الرؤية الحاسوبية أو الكلام أو المهام متعددة الوسائط. حتى إذا لم يكن لديك خبرة في طريقة معينة أو لم تكن على دراية بالرمز الأساسي وراء النماذج، يمكنك مع ذلك استخدامها للاستدلال باستخدام [`pipeline`]! سوف يُعلمك هذا البرنامج التعليمي ما يلي: + +* استخدام [`pipeline`] للاستدلال. +* استخدم مُجزّئ أو نموذجًا محددًا. +* استخدم [`pipeline`] للمهام الصوتية والبصرية والمتعددة الوسائط. + + + +اطلع على وثائق [`pipeline`] للحصول على القائمة كاملة بالمهام المدعومة والمعلمات المتاحة. + + + +## استخدام الأنابيب + +على الرغم من أن لكل مهمة أنبوب [`pipeline`] خاص بها، إلا أنه من الأبسط استخدام تجريد خط الأنابيب العام [`pipeline`] الذي يحتوي على جميع خطوط الأنابيب الخاصة بالمهمة. يقوم [`pipeline`] تلقائيًا بتحميل نموذج افتراضي وفئة معالجة مسبقة قادرة على الاستدلال لمهمتك. دعنا نأخذ مثال استخدام [`pipeline`] للتعرف التلقائي على الكلام (ASR)، أو تحويل الكلام إلى نص. + +1. ابدأ بإنشاء [`pipeline`] وحدد مهمة الاستدلال: + +```py +>>> from transformers import pipeline + +>>> transcriber = pipeline(task="automatic-speech-recognition") +``` + +2. مرر إدخالك إلى [`pipeline`]. في حالة التعرف على الكلام، يكون هذا ملف إدخال صوتي: + +```py +>>> transcriber("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac") +{'text': 'I HAVE A DREAM BUT ONE DAY THIS NATION WILL RISE UP LIVE UP THE TRUE MEANING OF ITS TREES'} +``` + +لم تحصل على النتيجة التي تريدها؟ تحقق من بعض [نماذج التعرف على الكلام الأكثر تنزيلًا](https://huggingface.co/models?pipeline_tag=automatic-speech-recognition&sort=trending) +على Hub لمعرفة ما إذا كان بإمكانك الحصول على نسخة منقحة أفضل. + +لنَجرب نموذج [Whisper large-v2](https://huggingface.co/openai/whisper-large) من OpenAI. تم إصدار Whisper بعد عامين من إصدار Wav2Vec2، وتم تدريبه على ما يقرب من 10 أضعاف كمية البيانات. وبهذه الصفة، فإنه يتفوق على Wav2Vec2 في معظم معظم المقاييس. كما أنه يمتلك ميزة إضافية وهي في التنبؤ بعلامات الترقيم وحالة الأحرف، والتي لا يمكن تحقيقها مع Wav2Vec2. + +دعونا نجربها هنا لنرى كيف تؤدي: + +```py +>>> transcriber = pipeline(model="openai/whisper-large-v2") +>>> transcriber("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac") +{'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.'} +``` + +الآن تبدو هذه النتيجة أكثر دقة! لمقارنة عميقة حول Wav2Vec2 مقابل Whisper، راجع [دورة Audio Transformers](https://huggingface.co/learn/audio-course/chapter5/asr_models). +نشجعك بشدة على التحقق من Hub للحصول على نماذج بلغات مختلفة، ونماذج متخصصة في مجالك، وأكثر من ذلك. +يمكنك التحقق من نتائج النموذج ومقارنتها مباشرة من متصفحك على Hub لمعرفة ما إذا كان يناسبها +أو التعامل مع الحالات الخاصة بشكل أفضل من غيرها. +وإذا لم تجد نموذجًا لحالتك الاستخدام، فيمكنك دائمًا البدء في [التدريب](training) الخاص بك! + +إذا كان لديك عدة مدخلات، فيمكنك تمرير إدخالك كقائمة: + +```py +transcriber( + [ + "https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac", + "https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/1.flac", + ] +) +``` + +تعد خطوط الأنابيب مثالية للتجريب نظرًا لأن التبديل من نموذج إلى آخر أمر بسيط للغاية؛ ومع ذلك، هناك بعض الطرق لتحسينها لأحمال عمل أكبر من التجريب. راجع الأدلة التالية التي تتعمق فى التكرار عبر مجموعات البيانات الكاملة أو استخدام خطوط الأنابيب في خادم ويب: +من الوثائق: +* [استخدام خطوط الأنابيب على مجموعة بيانات](#using-pipelines-on-a-dataset) +* [استخدام خطوط الأنابيب لخادم ويب](./pipeline_webserver) + +## المعلمات + +يدعم [`pipeline`] العديد من المعلمات؛ بعضها خاص بالمهمة، والبعض الآخر عام لجميع خطوط الأنابيب. +بشكل عام، يمكنك تحديد المعلمات في أي مكان تريده: + +```py +transcriber = pipeline(model="openai/whisper-large-v2", my_parameter=1) + +out = transcriber(...) # سيتم استخدام هذا `my_parameter=1`. +out = transcriber(..., my_parameter=2) # سيتم تجاوز هذا واستخدام `my_parameter=2`. +out = transcriber(...) # سيتم الرجوع إلى استخدام `my_parameter=1`. +``` + +دعونا نلقي نظرة على 3 مهمة: + +### الجهاز + +إذا كنت تستخدم `device=n`، فإن خط الأنابيب يضع النموذج تلقائيًا على الجهاز المحدد. +سيعمل هذا بغض النظر عما إذا كنت تستخدم PyTorch أو Tensorflow. + +```py +transcriber = pipeline(model="openai/whisper-large-v2", device=0) +``` + +إذا كان النموذج كبيرًا جدًا بالنسبة لوحدة معالجة الرسومات (GPU) واحدة، وأنت تستخدم PyTorch، فيمكنك تعيين `torch_dtype='float16'` لتمكين الاستدلال بدقة FP16. عادةً ما لا يتسبب ذلك في حدوث انخفاضات كبيرة في الأداء، ولكن تأكد من تقييمه على نماذجك! + +بدلاً من ذلك، يمكنك تعيين `device_map="auto"` لتحديد كيفية تحميل مخزنات النموذج وتخزينها تلقائيًا. يتطلب استخدام معامل `device_map` مكتبه 🤗 [Accelerate](https://huggingface.co/docs/accelerate): + +```bash +pip install --upgrade accelerate +``` + +تقوم الشفرة التالية بتحميل مخزنات النموذج وتخزينها تلقائيًا عبر الأجهزة: + +```py +transcriber = pipeline(model="openai/whisper-large-v2", device_map="auto") +``` + +لاحظ أنه إذا تم تمرير `device_map="auto"`، فلا توجد حاجة لإضافة حجة `device=device` عند إنشاء خط الأنابيب الخاص بك، فقد تواجه بعض السلوكيات غير المتوقعة! + +### حجم الدفعة + +بشكل افتراضي، لن تقوم خطوط الأنابيب بتجميع الاستدلال لأسباب مفصلة [هنا](https://huggingface.co/docs/transformers/main_classes/pipelines#pipeline-batching). والسبب هو أن التجميع ليست أسرع بالضرورة، ويمكن أن تكون أبطأ في الواقع في بعض الحالات. + +ولكن إذا نجحت في حالتك الاستخدام، فيمكنك استخدام ما يلي: + +```py +transcriber = pipeline(model="openai/whisper-large-v2", device=0, batch_size=2) +audio_filenames = [f"https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/{i}.flac" for i in range(1, 5)] +texts = transcriber(audio_filenames) +``` + +هذا يشغل خط الأنابيب على ملفات الصوت الأربعة المتاحة، ولكنه سيمررها على دفعتين +إلى النموذج (الذي يوجد على وحدة معالجة الرسومات (GPU)، حيث من المرجح أن تساعد التجميع) دون الحاجة إلى أي رمز إضافي منك. +يجب أن تتطابق الإخراج دائمًا مع ما كنت ستحصل عليه دون التجميع. المقصود منه فقط كطريقة لمساعدتك في الحصول على سرعة أكبر من خط الأنابيب. + +يمكن لخطوط الأنابيب أيضًا تخفيف بعض تعقيدات التجميع لأنه، بالنسبة لبعض خطوط الأنابيب، يجب تقسيم عنصر واحد (مثل ملف صوتي طويل) إلى أجزاء متعددة لمعالجته بواسطة نموذج. يقوم خط الأنابيب بأداء هذه العملية التي تسمى تجميع الأجزاء [*batch batching*](./main_classes/pipelines#pipeline-chunk-batching) نيابة عنك. + +### معلمات خاصة بالمهمة + +توفر جميع المهام معلمات خاصة بالمهمة تتيح المرونة والخيارات الإضافية لمساعدتك في أداء عملك. +على سبيل المثال، تحتوي طريقة [`transformers.AutomaticSpeechRecognitionPipeline.__call__`] على معلمة `return_timestamps` التي تبدو واعدة لترجمة مقاطع الفيديو: +```py +>>> transcriber = pipeline(model="openai/whisper-large-v2", return_timestamps=True) +>>> transcriber("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac") +{'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.', 'chunks': [{'timestamp': (0.0, 11.88), 'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its'}, {'timestamp': (11.88, 12.38), 'text': ' creed.'}]} +``` + +كما ترون، استنتج النموذج النص.وكذلك حدد **وقت** نطق الجمل المختلفة. + +تتوفر العديد من المعلمات لكل مهمة، لذا تحقق من مرجع API لكل مهمة لمعرفة ما يمكنك تعديله! +على سبيل المثال، تحتوي [`~transformers.AutomaticSpeechRecognitionPipeline`] على معلمة `chunk_length_s` مفيدة +للعمل على ملفات الصوت الطويلة جدًا (على سبيل المثال، ترجمة الأفلام أو مقاطع الفيديو التي تستغرق ساعة) والتي لا يمكن للنموذج التعامل معها بمفرده: + +```python +>>> transcriber = pipeline(model="openai/whisper-large-v2", chunk_length_s=30) +>>> transcriber("https://huggingface.co/datasets/reach-vb/random-audios/resolve/main/ted_60.wav") +{'text': " So in college, I was a government major, which means I had to write a lot of papers. Now, when a normal student writes a paper, they might spread the work out a little like this. So, you know. You get started maybe a little slowly, but you get enough done in the first week that with some heavier days later on, everything gets done and things stay civil. And I would want to do that like that. That would be the plan. I would have it all ready to go, but then actually the paper would come along, and then I would kind of do this. And that would happen every single paper. But then came my 90-page senior thesis, a paper you're supposed to spend a year on. I knew for a paper like that, my normal workflow was not an option, it was way too big a project. So I planned things out and I decided I kind of had to go something like this. This is how the year would go. So I'd start off light and I'd bump it up"} +``` + +إذا لم تتمكن من العثور على معلمة قد تساعدك حقًا، فلا تتردد في [طلبها](https://github.com/huggingface/transformers/issues/new?assignees=&labels=feature&template=feature-request.yml)! + + +## استخدام خطوط الأنابيب على مجموعة بيانات + +يمكن أيضًا تشغيل خط الأنابيب للاستدلال على مجموعة بيانات كبيرة. أسهل طريقة نوصي بها للقيام بذلك هي باستخدام المتكرر (iterator).: + +```py +def data(): + for i in range(1000): + yield f"My example {i}" + + +pipe = pipeline(model="openai-community/gpt2", device=0) +generated_characters = 0 +for out in pipe(data()): + generated_characters += len(out[0]["generated_text"]) +``` + +يقوم المؤشر `data()` بإرجاع كل نتيجة، ويتعرف خط الأنابيب تلقائيًا +المدخل قابل للتحديد ويبدأ في جلب البيانات أثناء +يستمر في معالجتها على وحدة معالجة الرسومات (GPU) (يستخدم هذا [DataLoader](https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader) تحت الغطاء). +هذا أمر مهم لأنك لا تحتاج إلى تخصيص ذاكرة لمجموعة البيانات بأكملها +ويمكنك تغذية وحدة معالجة الرسومات (GPU) بأسرع ما يمكن. + +نظرًا لأن التجميع قد تسرع الأمور، فقد يكون من المفيد ضبط معلمة `batch_size` هنا. + +أبسط طريقة للتنقل خلال مجموعة بيانات هي فقط تحميل واحدة من 🤗 [Datasets](https://github.com/huggingface/datasets/): + +```py +# KeyDataset هي أداة مساعدة ستقوم فقط بإخراج العنصر الذي نهتم به. +from transformers.pipelines.pt_utils import KeyDataset +from datasets import load_dataset + +pipe = pipeline(model="hf-internal-testing/tiny-random-wav2vec2", device=0) +dataset = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation[:10]") + +for out in pipe(KeyDataset(dataset, "audio")): + print(out) +``` + +## استخدام خطوط الأنابيب لخادم ويب + + +إن إنشاء محرك استدلال هو موضوع معقد يستحق صفحته الخاصة. + + +[Link](./pipeline_webserver) + +## خط أنابيب الرؤية + +إن استخدام [`pipeline`] لمهام الرؤية مماثل تمامًا. + +حدد مهمتك ومرر صورتك إلى المصنف. يمكن أن تكون الصورة رابطًا أو مسارًا محليًا أو صورة مشفرة بتنسيق base64. على سبيل المثال، ما نوع القطط الموضح أدناه؟ + +![pipeline-cat-chonk](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg) + +```py +>>> from transformers import pipeline + +>>> vision_classifier = pipeline(model="google/vit-base-patch16-224") +>>> preds = vision_classifier( +... images="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg" +... ) +>>> preds = [{"score": round(pred["score"], 4), "label": pred["label"]} for pred in preds] +>>> preds +[{'score': 0.4335, 'label': 'lynx, catamount'}, {'score': 0.0348, 'label': 'cougar, puma, catamount, mountain lion, painter, panther, Felis concolor'}, {'score': 0.0324, 'label': 'snow leopard, ounce, Panthera uncia'}, {'score': 0.0239, 'label': 'Egyptian cat'}, {'score': 0.0229, 'label': 'tiger cat'}] +``` + +## خط أنابيب النص + +إن استخدام [`pipeline`] لمهام NLP مماثل تمامًا. + +```py +>>> from transformers import pipeline + +>>> # هذا النموذج هو نموذج "zero-shot-classification". +>>> # سيصنف النص، ولكن يمكنك اختيار أي تسمية قد تتخيلها +>>> classifier = pipeline(model="facebook/bart-large-mnli") +>>> classifier( +... "I have a problem with my iphone that needs to be resolved asap!!", +... candidate_labels=["urgent", "not urgent", "phone", "tablet", "computer"], +... ) +{'sequence': 'I have a problem with my iphone that needs to be resolved asap!!', 'labels': ['urgent', 'phone', 'computer', 'not urgent', 'tablet'], 'scores': [0.504, 0.479, 0.013, 0.003, 0.002]} +``` + +## خط أنابيب متعدد الوسائط + +تدعم [`pipeline`] أكثر من طريقة واحدة. على سبيل المثال، تجمع مهمة الإجابة على الأسئلة المرئية (VQA) بين النص والصورة. لا تتردد في استخدام أي رابط صورة تريده وسؤال تريد طرحه حول الصورة. يمكن أن تكون الصورة عنوان URL أو مسارًا محليًا للصورة. + +على سبيل المثال، إذا كنت تستخدم هذه [صورة الفاتورة](https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png): + +```py +>>> from transformers import pipeline + +>>> vqa = pipeline(model="impira/layoutlm-document-qa") +>>> output = vqa( +... image="https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png", +... question="What is the invoice number?", +... ) +>>> output[0]["score"] = round(output[0]["score"], 3) +>>> output +[{'score': 0.425, 'answer': 'us-001', 'start': 16, 'end': 16}] +``` + + + +لتشغيل المثال أعلاه، تحتاج إلى تثبيت [`pytesseract`](https://pypi.org/project/pytesseract/) بالإضافة إلى 🤗 Transformers: + +```bash +sudo apt install -y tesseract-ocr +pip install pytesseract +``` + + + +## استخدام `pipeline` على نماذج كبيرة مع 🤗 `accelerate`: + +يمكنك بسهولة تشغيل `pipeline` على نماذج كبيرة باستخدام 🤗 `accelerate`! أولاً، تأكد من تثبيت `accelerate` باستخدام `pip install accelerate`. + +قم أولاً بتحميل نموذجك باستخدام `device_map="auto"`! سنستخدم `facebook/opt-1.3b` كمثال لنا. + +```py +# pip install accelerate +import torch +from transformers import pipeline + +pipe = pipeline(model="facebook/opt-1.3b", torch_dtype=torch.bfloat16, device_map="auto") +output = pipe("This is a cool example!", do_sample=True, top_p=0.95) +``` + +يمكنك أيضًا تمرير نماذج محملة بـ 8 بت إذا قمت بتثبيت `bitsandbytes` وإضافة الحجة `load_in_8bit=True` + +```py +# pip install accelerate bitsandbytes +import torch +from transformers import pipeline + +pipe = pipeline(model="facebook/opt-1.3b", device_map="auto", model_kwargs={"load_in_8bit": True}) +output = pipe("This is a cool example!", do_sample=True, top_p=0.95) +``` + +لاحظ أنه يمكنك استبدال نقطة التفتيش بأي نموذج من Hugging Face يدعم تحميل النماذج الكبيرة، مثل BLOOM. + +## إنشاء عروض توضيحية ويب من خطوط الأنابيب باستخدام `gradio` + +يتم دعم خطوط الأنابيب تلقائيًا في [Gradio](https://github.com/gradio-app/gradio/)، وهي مكتبة تجعل إنشاء تطبيقات تعليم الآلة الجميلة والسهلة الاستخدام على الويب أمرًا سهلاً. أولاً، تأكد من تثبيت Gradio: + +``` +pip install gradio +``` + +بعد ذلك، يمكنك إنشاء عرض توضيحي ويب حول خط أنابيب تصنيف الصور (أو أي خط أنابيب آخر) في سطر واحد من التعليمات البرمجية عن طريق استدعاء وظيفة [`Interface.from_pipeline`](https://www.gradio.app/docs/interface#interface-from-pipeline) في Gradio لإطلاق خط الأنابيب. يقوم هذا بإنشاء واجهة بديهية للسحب والإفلات في مستعرضك: + +```py +from transformers import pipeline +import gradio as gr + +pipe = pipeline("image-classification", model="google/vit-base-patch16-224") + +gr.Interface.from_pipeline(pipe).launch() +``` + + +![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/panda-classification.png) + +بشكل افتراضي، يعمل العرض التوضيحي على خادم محلي. إذا كنت تريد مشاركتها مع الآخرين، فيمكنك إنشاء رابط عام مؤقت عن طريق تعيين `share=True` في `launch()`. يمكنك أيضًا استضافة عرضك التوضيحي على [Hugging Face Spaces](https://huggingface.co/spaces) للحصول على رابط دائم. \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/pipeline_webserver.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/pipeline_webserver.md new file mode 100644 index 0000000000000000000000000000000000000000..2a19e84d1632413557790626fd116de0ca5048f3 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/pipeline_webserver.md @@ -0,0 +1,126 @@ +# استخدام قنوات المعالجة لخادم ويب + + + +يُعدّ إنشاء محرك استدلال أمرًا معقدًا، ويعتمد الحل "الأفضل" على مساحة مشكلتك. هل تستخدم وحدة المعالجة المركزية أم وحدة معالجة الرسومات؟ هل تريد أقل زمن وصول، أم أعلى معدل نقل، أم دعمًا للعديد من النماذج، أم مجرد تحقيق أقصى تحسين نموذج محدد؟ +توجد طرق عديدة لمعالجة هذا الموضوع، لذلك ما سنقدمه هو إعداد افتراضي جيد للبدء به قد لا يكون بالضرورة هو الحل الأمثل لك.``` + + + +الشيء الرئيسي الذي يجب فهمه هو أننا يمكن أن نستخدم مؤشرًا، تمامًا كما تفعل [على مجموعة بيانات](pipeline_tutorial#using-pipelines-on-a-dataset)، نظرًا لأن خادم الويب هو أساسًا نظام ينتظر الطلبات ويعالجها عند استلامها. + +عادةً ما تكون خوادم الويب متعددة الإرسال (متعددة مؤشرات الترابط، وغير متزامنة، إلخ) للتعامل مع الطلبات المختلفة بشكل متزامن. من ناحية أخرى، فإن قنوات المعالجة (وبشكل رئيسي النماذج الأساسية) ليست رائعة للتوازي؛ حيث تستهلك الكثير من ذاكرة الوصول العشوائي، لذا من الأفضل منحها جميع الموارد المتاحة عند تشغيلها أو إذا كانت مهمة تطلب حسابات مكثفة. + +سنحل ذلك من خلال جعل خادم الويب يتعامل مع الحمل الخفيف لاستقبال الطلبات وإرسالها،وجعل مؤشر ترابط واحد يتعامل مع العمل الفعلي. سيستخدم هذا المثال `starlette`. ولكن قد تضطر إلى ضبط الكود أو تغييره إذا كنت تستخدم كودًا آخر لتحقيق التأثير نفسه. + +أنشئ `server.py`: + +```py +from starlette.applications import Starlette +from starlette.responses import JSONResponse +from starlette.routing import Route +from transformers import pipeline +import asyncio + + +async def homepage(request): + payload = await request.body() + string = payload.decode("utf-8") + response_q = asyncio.Queue() + await request.app.model_queue.put((string, response_q)) + output = await response_q.get() + return JSONResponse(output) + + +async def server_loop(q): + pipe = pipeline(model="google-bert/bert-base-uncased") + while True: + (string, response_q) = await q.get() + out = pipe(string) + await response_q.put(out) + + +app = Starlette( + routes=[ + Route("/", homepage, methods=["POST"]), + ], +) + + +@app.on_event("startup") +async def startup_event(): + q = asyncio.Queue() + app.model_queue = q + asyncio.create_task(server_loop(q)) +``` + +الآن يمكنك تشغيله باستخدام: + +```bash +uvicorn server:app +``` + +ويمكنك الاستعلام عنه: + +```bash +curl -X POST -d "test [MASK]" http://localhost:8000/ +#[{"score":0.7742936015129089,"token":1012,"token_str":".","sequence":"test."},...] +``` + +وهكذا، لديك الآن فكرة جيدة عن كيفية إنشاء خادم ويب! + +المهم حقًا هو أننا نقوم بتحميل النموذج **مرة واحدة** فقط، لذلك لا توجد نسخ من النموذج على خادم الويب. بهذه الطريقة، لا يتم استخدام ذاكرة الوصول العشوائي غير الضرورية. تسمح آلية وضع قائمة الانتظار بالقيام بأشياء متقدمة مثل تجميع بعض العناصر قبل الاستدلال لاستخدام معالجة الدفعات الديناميكية: + + + +تم كتابة نموذج الكود البرمجى أدناه بشكل مقصود مثل كود وهمي للقراءة. لا تقم بتشغيله دون التحقق مما إذا كان منطقيًا لموارد النظام الخاص بك! + + + +```py +(string, rq) = await q.get() +strings = [] +queues = [] +while True: + try: + (string, rq) = await asyncio.wait_for(q.get(), timeout=0.001) # 1ms + except asyncio.exceptions.TimeoutError: + break + strings.append(string) + queues.append(rq) +strings +outs = pipe(strings, batch_size=len(strings)) +for rq, out in zip(queues, outs): + await rq.put(out) +``` + +مرة أخرى، تم تحسين الرمز المقترح لسهولة القراءة، وليس ليكون أفضل كود. بادئ ذي بدء، لا يوجد حد لحجم الدفعة، والذي عادةً ما لا يكون فكرة عظيمة. بعد ذلك، يتم إعادة ضبط الفترة في كل عملية جلب لقائمة الانتظار، مما يعني أنه قد يتعين عليك الانتظار لفترة أطول بكثير من 1 مللي ثانية قبل تشغيل الاستدلال (تأخير الطلب الأول بهذا القدر). + +سيكون من الأفضل تحديد مهلة واحدة مدتها 1 مللي ثانية. + +سيظل هذا ينتظر دائمًا لمدة 1 مللي ثانية حتى إذا كانت قائمة الانتظار فارغًا، والذي قد لا يكون الأفضل نظرًا لأنك تريد على الأرجح البدء في إجراء الاستدلال إذا لم يكن هناك شيء في قائمة الانتظا. ولكن ربما يكون منطقيًا إذا كانت المعالجة الديناميكية للدفعات مهمة حقًا لحالة الاستخدام لديك. مرة أخرى، لا يوجد حل واحد هو الأفضل. + +## بعض الأشياء التي قد ترغب في مراعاتها + +### التحقق من الأخطاء + +هناك الكثير مما قد يحدث بشكل خاطئ في عند اتاحة النموذج للجمهور: نفاد الذاكرة، أو نفاد المساحة، أو فشل تحميل النموذج، أو قد يكون الاستعلام خاطئًا، أو قد يكون الاستعلام صحيحًا ولكن لا يزال يفشل في التشغيل بسبب خطأ في إعداد النموذج، وما إلى ذلك. + +بشكل عام، من الجيد أن يُخرِج الخادم الأخطاء للمستخدم، لذلك يُعدّ إضافة الكثير من عبارات `try..except` لعرض هذه الأخطاء فكرة +جيدة. لكن ضع في اعتبارك أنه قد يمثل أيضًا مخاطرة أمنية الكشف عن جميع تلك الأخطاء اعتمادًا على سياق الأمان لديك. + +### قطع الدائرة (Circuit breaking) + +عادةً ما تبدو خوادم الويب أفضل عندما تقوم بقطع الدائرة. وهذا يعني أنها ترجع أخطاء صحيحة عندما تكون مثقلة بشكل زائد بدلاً من الانتظار إلى أجل غير مسمى. قم بإرجاع خطأ 503 بدلاً من الانتظار لفترة طويلة جدًا أو 504 بعد فترة طويلة. + +من السهل نسبيًا تنفيذ ذلك في الكود المقترح نظرًا لوجود قائمة انتظار واحد. إن النظر في حجم قائمة الانتظار هو طريقة أساسية لبدء إرجاع الأخطاء قبل فشل خادم الويب بسبب الحمل الزائد. + +### حجب عمل خيط التنفيذ الرئيسي (Main thread) + +حاليًا، لا تدعم PyTorch العمليات غير المتزامنة، وسيؤدي الحساب إلى حجب عمل الخيط الرئيسي أثناء تشغيله. وهذا يعني أنه سيكون من الأفضل إذا تم إجبار PyTorch على أن تعمل على الخيط/العملية الخاصة به. لم يتم ذلك هنا لأن الكود أكثر تعقيدًا (في الغالب لأن خيوط التنفيذ والعمليات غير المتزامنة وقوائم الانتظار لا تتوافق معًا). ولكن في النهاية، فإنه سيؤدي نفس الوظيفة. + +سيكون هذا مهمًا إذا كان الاستدلال للعناصر الفردية طويلاً (> 1 ثانية) لأنه في هذه الحالة، فهذا يعني أنه سيتعين أثناء الاستدلال على كل استعلام الانتظار لمدة ثانية واحدة قبل حتى يلقي خطأ. + +### المعالجة الديناميكية + +بشكل عام، لا تُعدّ المعالجة بالضرورة تحسينًا مقارنةً بتمرير عنصر واحد في كل مرة (راجع [تفاصيل المعالجة بالدفعات](./main_classes/pipelines#pipeline-batching) لمزيد من المعلومات). ولكن يمكن أن تكون فعالة للغاية عند استخدامها بالإعداد الصحيح. في واجهة برمجة التطبيقات، لا توجد معالجة ديناميكية بشكل افتراضي (فرصة كبيرة جدًا للتباطؤ). ولكن بالنسبة لاستدلال BLOOM - وهو نموذج كبير جدًا - تُعدّ المعالجة الديناميكية **ضرورية** لتوفير تجربة جيدة للجميع. \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/preprocessing.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/preprocessing.md new file mode 100644 index 0000000000000000000000000000000000000000..8c1f68934d2052a5baf6d30488be968725a5be9b --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/preprocessing.md @@ -0,0 +1,521 @@ +# المعالجة المسبقة Preprocessing + +[[open-in-colab]] + +قبل تدريب نموذج على مجموعة بيانات، يجب معالجتها مسبقًا وفقًا تنسيق المتوقع لمدخلات النموذج. سواء كانت بياناتك نصية أو صورًا أو صوتًا، فيجب تحويلها وتجميعها في دفعات من الموترات. يوفر 🤗 Transformers مجموعة من فئات المعالجة المسبقة للمساعدة في إعداد بياناتك للنموذج. في هذا البرنامج التعليمي، ستتعلم أنه بالنسبة لـ: + +* للنص، استخدم [مُجزّئ الرموز](./main_classes/tokenizer) لتحويل النص إلى تسلسل من الرموز، وإنشاء تمثيل رقمي للرموز، وتجميعها في موترات(tensors). +* للكلام والصوت، استخدم [مستخرج الميزات](./main_classes/feature_extractor) لاستخراج ميزات متسلسلة من أشكال موجات الصوت وتحويلها إلى موترات. +* تستخدم مدخلات الصورة [ImageProcessor](./main_classes/image_processor) لتحويل الصور إلى موترات. +* تستخدم مدخلات متعددة الوسائط [معالجًا](./main_classes/processors) لدمج مُجزّئ الرموز ومستخرج الميزات أو معالج الصور. + + + +`AutoProcessor` **يعمل دائمًا** ويختار تلقائيًا الفئة الصحيحة للنموذج الذي تستخدمه، سواء كنت تستخدم مُجزّئ رموز أو معالج صور أو مستخرج ميزات أو معالجًا. + + + +قبل البدء، قم بتثبيت 🤗 Datasets حتى تتمكن من تحميل بعض مجموعات البيانات لتجربتها: + +```bash +pip install datasets +``` + +## معالجة اللغة الطبيعية (Natural Language Processing (NLP + + + +أداة المعالجة المسبقة الرئيسية للبيانات النصية هي [مُجزّئ اللغوي](main_classes/tokenizer). يقوم مُجزّئ اللغوي بتقسيم النص إلى "أجزاء لغوية" (tokens) وفقًا لمجموعة من القواعد. يتم تحويل الأجزاء اللغوية إلى أرقام ثم إلى منسوجات، والتي تصبح مدخلات للنموذج. يقوم المجزئ اللغوي بإضافة أي مدخلات إضافية يحتاجها النموذج. + + + +إذا كنت تخطط لاستخدام نموذج مُدرب مسبقًا، فمن المهم استخدامالمجزئ اللغوي المقترن بنفس ذلك النموذج. يضمن ذلك تقسيم النص بنفس الطريقة التي تم بها تقسيم النصوص ما قبل التدريب، واستخدام نفس القاموس الذي يربط بين الأجزاء اللغوية وأرقامها ( يُشار إليها عادةً باسم المفردات *vocab*) أثناء التدريب المسبق. + + + +ابدأ بتحميل المُجزّئ اللغوي مُدرب مسبقًا باستخدام طريقة [`AutoTokenizer.from_pretrained`]. يقوم هذا بتنزيل المفردات *vocab* الذي تم تدريب النموذج عليه: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased") +``` + +ثم مرر نصك إلى المُجزّئ اللغوي: + +```py +>>> encoded_input = tokenizer("Do not meddle in the affairs of wizards, for they are subtle and quick to anger.") +>>> print(encoded_input) +{'input_ids': [101, 2079, 2025, 19960, 10362, 1999, 1996, 3821, 1997, 16657, 1010, 2005, 2027, 2024, 11259, 1998, 4248, 2000, 4963, 1012, 102], + 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]} +``` + +يعيد المُجزّئ اللغوي قاموسًا يحتوي على ثلاثة عناصر مهمة: + +* [input_ids](glossary#input-ids) هي الفهارس المقابلة لكل رمز في الجملة. +* [attention_mask](glossary#attention-mask) يشير إلى ما إذا كان يجب الانتباه بالرمز أم لا. +* [token_type_ids](glossary#token-type-ids) يحدد التسلسل الذي ينتمي إليه الرمز عندما يكون هناك أكثر من تسلسل واحد. + +أعد إدخالك الأصلي عن طريق فك ترميز `input_ids`: + +```py +>>> tokenizer.decode(encoded_input["input_ids"]) +'[CLS] Do not meddle in the affairs of wizards, for they are subtle and quick to anger. [SEP]' +``` + +كما ترى، أضاف المُجزّئ اللغوي رمزين خاصين - `CLS` و`SEP` (مصنف وفاصل) - إلى الجملة. لا تحتاج جميع النماذج إلى +رموز خاصة، ولكن إذا فعلوا ذلك، فإن المُجزّئ اللغوي يضيفها تلقائيًا لك. + +إذا كان هناك عدة جمل تريد معالجتها مسبقًا، فقم بتمريرها كقائمة إلى مُجزّئ اللغوي: + +```py +>>> batch_sentences = [ +... "But what about second breakfast?", +... "Don't think he knows about second breakfast, Pip.", +... "What about elevensies?", +... ] +>>> encoded_inputs = tokenizer(batch_sentences) +>>> print(encoded_inputs) +{'input_ids': [[101, 1252, 1184, 1164, 1248, 6462, 136, 102], + [101, 1790, 112, 189, 1341, 1119, 3520, 1164, 1248, 6462, 117, 21902, 1643, 119, 102], + [101, 1327, 1164, 5450, 23434, 136, 102]], + 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], + 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1]]} +``` + +### الحشو Padding + +لا تكون الجمل دائمًا بنفس الطول، وهذا يمكن أن يمثل مشكلة لأن الموترات،وهي مدخلات النموذج، تحتاج إلى شكل موحد. الحشو هو استراتيجية لضمان أن تكون الموترات مستطيلة عن طريق إضافة رمز حشو *padding* خاص إلى الجمل الأقصر. + +قم بتعيين معلمة الحشو `padding` إلى `True` لحشو التسلسلات الأقصر في الدفعة لتطابق أطول تسلسل: + +```py +>>> batch_sentences = [ +... "But what about second breakfast?", +... "Don't think he knows about second breakfast, Pip.", +... "What about elevensies?", +... ] +>>> encoded_input = tokenizer(batch_sentences, padding=True) +>>> print(encoded_input) +{'input_ids': [[101, 1252, 1184, 1164, 1248, 6462, 136, 102, 0, 0, 0, 0, 0, 0, 0], + [101, 1790, 112, 189, 1341, 1119, 3520, 1164, 1248, 6462, 117, 21902, 1643, 119, 102], + [101, 1327, 1164, 5450, 23434, 136, 102, 0, 0, 0, 0, 0, 0, 0, 0]], + 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], + 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 0، 0، 0، 0، 0، 0، 0، 0]]} +``` + +تم الآن حشو الجملتين الأولى والثالثة بـ `0` لأنهما أقصر. + +### البتر Truncation + +وعلى صعيد أخر، قد يكون التسلسل طويلًا جدًا بالنسبة للنموذج للتعامل معه. في هذه الحالة، ستحتاج إلى بتر التسلسل إلى طول أقصر. + +قم بتعيين معلمة `truncation` إلى `True` لتقليم تسلسل إلى الطول الأقصى الذي يقبله النموذج: + +```py +>>> batch_sentences = [ +... "But what about second breakfast?", +... "Don't think he knows about second breakfast, Pip.", +... "What about elevensies?", +... ] +>>> encoded_input = tokenizer(batch_sentences, padding=True, truncation=True) +>>> print(encoded_input) +{'input_ids': [[101, 1252, 1184, 1164, 1248, 6462, 136, 102, 0, 0, 0, 0, 0, 0, 0], + [101, 1790, 112, 189, 1341, 1119, 3520, 1164, 1248, 6462, 117, 21902, 1643, 119, 102], + [101, 1327, 1164, 5450, 23434, 136, 102, 0, 0, 0, 0, 0, 0, 0, 0]], + 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0، 0، 0، 0، 0]]، + 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0، 0، 0، 0], + [1, 1, 1, 1, 1, 1, 1، 1، 1، 1، 1، 1، 1، 1، 1، 1], + [1، 1، 1، 1، 1، 1، 1، 0، 0، 0، 0، 0، 0، 0، 0، 0]]} +``` + + + +تحقق من دليل المفاهيم [Padding and truncation](./pad_truncation) لمعرفة المزيد حول معامﻻت الحشو و البتر المختلفة. + + + +### بناء الموترات Build tensors + +أخيرًا، تريد أن يقوم المجزئ اللغوي بإرجاع موترات (tensors) الفعلية التي ستُغذي النموذج. + +قم بتعيين معلمة `return_tensors` إلى إما `pt` لـ PyTorch، أو `tf` لـ TensorFlow: + + + + +```py +>>> batch_sentences = [ +... "But what about second breakfast?", +... "Don't think he knows about second breakfast, Pip.", +... "What about elevensies?", +... ] +>>> encoded_input = tokenizer(batch_sentences, padding=True, truncation=True, return_tensors="pt") +>>> print(encoded_input) +{'input_ids': tensor([[101, 1252, 1184, 1164, 1248, 6462, 136, 102, 0, 0, 0, 0, 0, 0, 0], + [101, 1790, 112, 189, 1341, 1119, 3520, 1164, 1248, 6462, 117, 21902, 1643, 119, 102], + [101, 1327, 1164, 5450, 23434, 136, 102, 0, 0, 0, 0, 0, 0, 0, 0]]), + 'token_type_ids': tensor([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]), + 'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]])} +``` + + + +```py +>>> batch_sentences = [ +... "But what about second breakfast?", +... "Don't think he knows about second breakfast, Pip.", +... "What about elevensies?", +... ] +>>> encoded_input = tokenizer(batch_sentences, padding=True, truncation=True, return_tensors="tf") +>>> print(encoded_input) +{'input_ids': , + 'token_type_ids': , + 'attention_mask': } +``` + + + + + +تدعم خطوط الأنابيب المختلفة معامل مُجزِّئ الرموز(tokenizer) بشكل مختلف في طريقة `()__call__` الخاصة بها. +و خطوط الأنابيب `text-2-text-generation` تدعم فقط `truncation`. +و خطوط الأنابيب `text-generation` تدعم `max_length` و`truncation` و`padding` و`add_special_tokens`. +أما في خطوط الأنابيب `fill-mask`، يمكن تمرير معامل مُجزِّئ الرموز (tokenizer) في المتغير `tokenizer_kwargs` (قاموس). + + + +## الصوت Audio + +بالنسبة للمهام الصوتية، ستحتاج إلى [مستخرج الميزات](main_classes/feature_extractor) لإعداد مجموعة البيانات الخاصة بك للنماذج. تم تصميم مستخرج الميزات لاستخراج الميزات من بيانات الصوت الخام، وتحويلها إلى موتورات. + +قم بتحميل مجموعة بيانات [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) (راجع البرنامج التعليمي لـ 🤗 [Datasets](https://huggingface.co/docs/datasets/load_hub) لمزيد من التفاصيل حول كيفية تحميل مجموعة بيانات) لمعرفة كيفية استخدام مستخرج الميزات مع مجموعات البيانات الصوتية: + +```py +>>> from datasets import load_dataset, Audio + +>>> dataset = load_dataset("PolyAI/minds14", name="en-US", split="train") +``` + +الوصول إلى العنصر الأول من عمود `audio` لمعرفة المدخلات. يؤدي استدعاء عمود `audio` إلى تحميل ملف الصوت وإعادة أخذ العينات تلقائيًا: + +```py +>>> dataset[0]["audio"] +{'array': array([ 0. , 0.00024414, -0.00024414, ..., -0.00024414, + 0. , 0. ], dtype=float32), + 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav', + 'sampling_rate': 8000} +``` + +يعيد هذا ثلاثة عناصر: + +* `array` هو إشارة الكلام المحملة - وإعادة أخذ العينات المحتملة - كصفيف 1D. +* `path` يشير إلى موقع ملف الصوت. +* `sampling_rate` يشير إلى عدد نقاط البيانات في إشارة الكلام المقاسة في الثانية. + +بالنسبة لهذا البرنامج التعليمي، ستستخدم نموذج [Wav2Vec2](https://huggingface.co/facebook/wav2vec2-base). الق نظرة على بطاقة النموذج، وستتعلم أن Wav2Vec2 مُدرب مسبقًا على صوت الكلام الذي تم أخذ عينات منه بمعدل 16 كيلو هرتز. من المهم أن يتطابق معدل أخذ العينات لبيانات الصوت مع معدل أخذ العينات لمجموعة البيانات المستخدمة لتدريب النموذج مسبقًا. إذا لم يكن معدل أخذ العينات لبياناتك هو نفسه، فيجب إعادة أخذ العينات من بياناتك. + +1. استخدم طريقة [`~datasets.Dataset.cast_column`] في 🤗 Datasets لإعادة أخذ العينات بمعدل أخذ العينات 16 كيلو هرتز: + +```py +>>> dataset = dataset.cast_column("audio", Audio(sampling_rate=16_000)) +``` + +2. استدعاء عمود `audio` مرة أخرى لأخذ عينات من ملف الصوت: + +```py +>>> dataset[0]["audio"] +{'array': array([ 2.3443763e-05, 2.1729663e-04, 2.2145823e-04, ..., + 3.8356509e-05, -7.3497440e-06, -2.1754686e-05], dtype=float32), + 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav', + 'sampling_rate': 16000} +``` + +بعد ذلك، قم بتحميل مستخرج الميزات لتطبيع وحشو المدخلات. عند إضافة حشو للبيانات النصية، تتم إضافة "0" للتسلسلات الأقصر. تنطبق نفس الفكرة على بيانات الصوت. يضيف مستخرج الميزات "0" - الذي يتم تفسيره على أنه صمت - إلى "array". + +قم بتحميل مستخرج الميزات باستخدام [`AutoFeatureExtractor.from_pretrained`]: + +```py +>>> from transformers import AutoFeatureExtractor + +>>> feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base") +``` + +مرر صفيف الصوت إلى مستخرج الميزات. كما نوصي بإضافة معامل `sampling_rate` في مستخرج الميزات من أجل تصحيح الأخطاء الصامتة التي قد تحدث بشكل أفضل. + +```py +>>> audio_input = [dataset[0]["audio"]["array"]] +>>> feature_extractor(audio_input, sampling_rate=16000) +{'input_values': [array([ 3.8106556e-04, 2.7506407e-03, 2.8015103e-03, ..., + 5.6335266e-04, 4.6588284e-06, -1.7142107e-04], dtype=float32)]} +``` + +تمامًا مثل مُجزِّئ الرموز، يمكنك تطبيق الحشو أو البتر للتعامل مع التسلسلات المتغيرة في دفعة. الق نظرة على طول التسلسل لهاتين العينتين الصوتيتين: + +```py +>>> dataset[0]["audio"]["array"].shape +(173398,) + +>>> dataset[1]["audio"]["array"].shape +(106496,) +``` + +قم بإنشاء دالة لمعالجة مجموعة البيانات بحيث يكون للنماذج الصوتية نفس الأطوال. حدد أقصى طول للعينة ، وسيقوم مستخرج الميزات إما بإضافة حشو أو بتر التسلسلات لمطابقتها: + +```py +>>> def preprocess_function(examples): +... audio_arrays = [x["array"] for x in examples["audio"]] +... inputs = feature_extractor( +... audio_arrays, +... sampling_rate=16000, +... padding=True, +... max_length=100000, +... truncation=True, +... ) +... return inputs +``` + +قم بتطبيق `preprocess_function` على أول بضع أمثلة في مجموعة البيانات: + +```py +>>> processed_dataset = preprocess_function(dataset[:5]) +``` + +أطوال العينات الآن متساوية وتطابق الطول الأقصى المحدد. يمكنك الآن تمرير مجموعة البيانات المعالجة إلى النموذج! + +```py +>>> processed_dataset["input_values"][0].shape +(100000,) + +>>> processed_dataset["input_values"][1].shape +(100000,) +``` + +## رؤية الكمبيوتر Computer vision + +بالنسبة لمهام رؤية الحاسوبية، ستحتاج إلى معالج صور [image processor](main_classes/image_processor) لإعداد مجموعة البيانات الخاصة بك لتناسب النموذج. تتكون معالجة الصور المسبقة من عدة خطوات لتحويل الصور إلى الشكل الذي يتوقعه النموذج. وتشمل هذه الخطوات، على سبيل المثال لا الحصر، تغيير الحجم والتطبيع وتصحيح قناة الألوان وتحويل الصور إلى موترات(tensors). + + + +عادة ما تتبع معالجة الصور المسبقة شكلاً من أشكال زيادة البيانات (التضخيم). كلا العمليتين، معالجة الصور المسبقة وزيادة الصور تغيران بيانات الصورة، ولكنها تخدم أغراضًا مختلفة: + +*زيادة البيانات: تغيير الصور عن طريق زيادة الصور بطريقة يمكن أن تساعد في منع الإفراط في التعميم وزيادة متانة النموذج. يمكنك أن تكون مبدعًا في كيفية زيادة بياناتك - ضبط السطوع والألوان، واالقص، والدوران، تغيير الحجم، التكبير، إلخ. ومع ذلك، كن حذرًا من عدم تغيير معنى الصور بزياداتك. +*معالجة الصور المسبقة: تضمن معالجة الصور اتتطابق الصور مع تنسيق الإدخال المتوقع للنموذج. عند ضبط نموذج رؤية حاسوبية بدقة، يجب معالجة الصور بالضبط كما كانت عند تدريب النموذج في البداية. + +يمكنك استخدام أي مكتبة تريدها لزيادة بيانات الصور. لمعالجة الصور المسبقة، استخدم `ImageProcessor` المرتبط بالنموذج. + + + +قم بتحميل مجموعة بيانات [food101](https://huggingface.co/datasets/food101) (راجع دليل 🤗 [Datasets tutorial](https://huggingface.co/docs/datasets/load_hub) لمزيد من التفاصيل حول كيفية تحميل مجموعة بيانات) لمعرفة كيف يمكنك استخدام معالج الصور مع مجموعات بيانات رؤية الحاسب: + + + +استخدم معامل `split` من 🤗 Datasets لتحميل عينة صغيرة فقط من مجموعة التدريب نظرًا لحجم البيانات كبيرة جدًا! + + + +```py +>>> from datasets import load_dataset + +>>> dataset = load_dataset("food101", split="train[:100]") +``` + +بعد ذلك، الق نظرة على الصورة مع ميزة 🤗 Datasets [`Image`](https://huggingface.co/docs/datasets/package_reference/main_classes?highlight=image#datasets.Image): + +```py +>>> dataset[0]["image"] +``` + +
+ +
+ +قم بتحميل معالج الصور باستخدام [`AutoImageProcessor.from_pretrained`]: + +```py +>>> from transformers import AutoImageProcessor + +>>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224") +``` + +أولاً، دعنا نضيف بعض الزيادات إلى الصور. يمكنك استخدام أي مكتبة تفضلها، ولكن في هذا الدليل، سنستخدم وحدة [`transforms`](https://pytorch.org/vision/stable/transforms.html) من torchvision. إذا كنت مهتمًا باستخدام مكتبة زيادة بيانات أخرى، فتعرف على كيفية القيام بذلك في [دفاتر Albumentations](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification_albumentations.ipynb) أو [دفاتر Kornia](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification_kornia.ipynb). + +1. هنا نستخدم [`Compose`](https://pytorch.org/vision/master/generated/torchvision.transforms.Compose.html) لربط بعض التحولات معًا - [`RandomResizedCrop`](https://pytorch.org/vision/main/generated/torchvision.transforms.RandomResizedCrop.html) و [`ColorJitter`](https://pytorch.org/vision/main/generated/torchvision.transforms.ColorJitter.html). +لاحظ بالنسبة لتغيير الحجم، يمكننا الحصول على متطلبات حجم الصورة من `image_processor`. بالنسبة لبعض النماذج، يُتوقع ارتفاع وعرض دقيقين، بينما بالنسبة للنماذج الأخرى، يتم تحديد الحافة الأقصر`shortest_edge` فقط. + +```py +>>> from torchvision.transforms import RandomResizedCrop, ColorJitter, Compose + +>>> size = ( +... image_processor.size["shortest_edge"] +... if "shortest_edge" in image_processor.size +... else (image_processor.size["height"], image_processor.size["width"]) +... ) + +>>> _transforms = Compose([RandomResizedCrop(size), ColorJitter(brightness=0.5, hue=0.5)]) +``` + +2. يقبل النموذج [`pixel_values`](model_doc/vision-encoder-decoder#transformers.VisionEncoderDecoderModel.forward.pixel_values) +كإدخال له. يمكن لـ `ImageProcessor` التعامل مع تطبيع الصور، وتوليد موترات(tensors) مناسبة. +قم بإنشاء دالة تجمع بين تضخيم بيانات الصور ومعالجة الصور المسبقة لمجموعة من الصور وتوليد `pixel_values`: + +```py +>>> def transforms(examples): +... images = [_transforms(img.convert("RGB")) for img in examples["image"]] +... examples["pixel_values"] = image_processor(images, do_resize=False, return_tensors="pt")["pixel_values"] +... return examples +``` + + + +في المثال أعلاه، قمنا بتعيين `do_resize=False` لأننا قمنا بالفعل بتغيير حجم الصور في تحويل زيادة الصور، +واستفدنا من خاصية `size` من `image_processor` المناسب. إذا لم تقم بتغيير حجم الصور أثناء زيادة الصور، +فاترك هذا المعلمة. بشكل افتراضي، ستتعامل `ImageProcessor` مع تغيير الحجم. + +إذا كنت ترغب في تطبيع الصور كجزء من تحويل زيادة الصور، فاستخدم قيم `image_processor.image_mean`، +و `image_processor.image_std`. + + +3. ثم استخدم 🤗 Datasets[`~datasets.Dataset.set_transform`] لتطبيق التحولات أثناء التنقل: +```py +>>> dataset.set_transform(transforms) +``` + +4. الآن عند الوصول إلى الصورة، ستلاحظ أن معالج الصور قد أضاف `pixel_values`. يمكنك تمرير مجموعة البيانات المعالجة إلى النموذج الآن! + +```py +>>> dataset[0].keys() +``` + +هكذا تبدو الصورة بعد تطبيق التحولات. تم اقتصاص الصورة بشكل عشوائي وتختلف خصائص الألوان بها. + +```py +>>> import numpy as np +>>> import matplotlib.pyplot as plt + +>>> img = dataset[0]["pixel_values"] +>>> plt.imshow(img.permute(1, 2, 0)) +``` + +
+ +
+ + + +بالنسبة للمهام مثل الكشف عن الأشياء، والتجزئة الدلالية، والتجزئة المثالية، والتجزئة الشاملة، يوفر `ImageProcessor` +تقوم هذه الطرق بتحويل النواتج الأولية للنموذج إلى تنبؤات ذات معنى مثل مربعات الحدود، +أو خرائط التجزئة. + + + +### الحشو Pad + +في بعض الحالات، على سبيل المثال، عند ضبط نموذج [DETR](./model_doc/detr) بدقة، يقوم النموذج بتطبيق زيادة المقياس أثناء التدريب. قد يتسبب ذلك في اختلاف أحجام الصور في دفعة واحدة. يمكنك استخدام [`DetrImageProcessor.pad`] +من [`DetrImageProcessor`] وتحديد دالة `collate_fn` مخصصة لتجميع الصور معًا. + +```py +>>> def collate_fn(batch): +... pixel_values = [item["pixel_values"] for item in batch] +... encoding = image_processor.pad(pixel_values, return_tensors="pt") +... labels = [item["labels"] for item in batch] +... batch = {} +... batch["pixel_values"] = encoding["pixel_values"] +... batch["pixel_mask"] = encoding["pixel_mask"] +... batch["labels"] = labels +... return batch +``` + +## متعدد الوسائط Mulimodal + +بالنسبة للمهام التي تتطلب مدخلات متعددة الوسائط، ستحتاج إلى معالج [processor](main_classes/processors) لإعداد مجموعة البيانات الخاصة بك لتناسب النموذج. يقترن المعالج بين بمعالجين آخرين مثل محول النص إلى رمز ومستخرج الميزات. + +قم بتحميل مجموعة بيانات [LJ Speech](https://huggingface.co/datasets/lj_speech) (راجع دليل 🤗 [Datasets tutorial](https://huggingface.co/docs/datasets/load_hub) لمزيد من التفاصيل حول كيفية تحميل مجموعة بيانات) لمعرفة كيف يمكنك استخدام معالج للتعرف التلقائي على الكلام (ASR): + +```py +>>> from datasets import load_dataset + +>>> lj_speech = load_dataset("lj_speech", split="train") +``` + +بالنسبة لـ ASR، فأنت تركز بشكل أساسي على `audio` و `text` لذا يمكنك إزالة الأعمدة الأخرى: + +```py +>>> lj_speech = lj_speech.map(remove_columns=["file", "id", "normalized_text"]) +``` + +الآن الق نظرة على أعمدة `audio` و `text`: +```py +>>> lj_speech = lj_speech.map(remove_columns=["file", "id", "normalized_text"]) +``` + +الآن الق نظرة على أعمدة `audio` و `text`: + +```py +>>> lj_speech[0]["audio"] +{'array': array([-7.3242188e-04, -7.6293945e-04, -6.4086914e-04, ..., + 7.3242188e-04, 2.1362305e-04, 6.1035156e-05], dtype=float32), + 'path': '/root/.cache/huggingface/datasets/downloads/extracted/917ece08c95cf0c4115e45294e3cd0dee724a1165b7fc11798369308a465bd26/LJSpeech-1.1/wavs/LJ001-0001.wav', + 'sampling_rate': 22050} + +>>> lj_speech[0]["text"] +'Printing, in the only sense with which we are at present concerned, differs from most if not from all the arts and crafts represented in the Exhibition' +``` + +تذكر أنه يجب عليك دائمًا [إعادة أخذ العينات](preprocessing#audio) لمعدل أخذ العينات في مجموعة البيانات الصوتية الخاصة بك لمطابقة معدل أخذ العينات في مجموعة البيانات المستخدمة لتدريب النموذج مسبقًا! + +```py +>>> lj_speech = lj_speech.cast_column("audio", Audio(sampling_rate=16_000)) +``` + +قم بتحميل معالج باستخدام [`AutoProcessor.from_pretrained`]: + +```py +>>> from transformers import AutoProcessor + +>>> processor = AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h") +``` + +1. قم بإنشاء دالة لمعالجة بيانات الصوت الموجودة في `array` إلى `input_values`، ورموز `text` إلى `labels`. هذه هي المدخلات للنموذج: + +```py +>>> def prepare_dataset(example): +... audio = example["audio"] + +... example.update(processor(audio=audio["array"], text=example["text"], sampling_rate=16000)) + +... return example +``` + +2. قم بتطبيق دالة `prepare_dataset` على عينة: + +```py +>>> prepare_dataset(lj_speech[0]) +``` + +لقد أضاف المعالج الآن `input_values` و `labels`، وتم أيضًا إعادة أخذ العينات لمعدل أخذ العينات بشكل صحيح إلى 16 كيلو هرتز. يمكنك تمرير مجموعة البيانات المعالجة إلى النموذج الآن! diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/quicktour.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/quicktour.md new file mode 100644 index 0000000000000000000000000000000000000000..1795c3a5d74fcc36ce97b05fcf46b004ebc1202f --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/quicktour.md @@ -0,0 +1,543 @@ +# جولة سريعة + +[[open-in-colab]] + +ابدأ رحلتك مع مكتبة 🤗 Transformers! سواء كنت مطورًا أو مستخدمًا عاديًا، ستساعدك هذه الجولة السريعة على البدء وستُظهر لك كيفية استخدام [`pipeline`] للاستنتاج، وتحميل نموذج مُدرب مسبقًا ومعالج مُسبق مع [AutoClass](./model_doc/auto)، وتدريب نموذج بسرعة باستخدام PyTorch أو TensorFlow. إذا كنت مبتدئًا، نوصي بالاطلاع على دروسنا أو [الدورة](https://huggingface.co/course/chapter1/1) للحصول على شرح أكثر تعمقًا للمفاهيم المقدمة هنا. + +قبل البدء، تأكد من تثبيت جميع المكتبات الضرورية: + +```bash +!pip install transformers datasets evaluate accelerate +``` + +ستحتاج أيضًا إلى تثبيت إطار عمل التعلم الآلي المفضل لديك: + + + + +```bash +pip install torch +``` + + + +```bash +pip install tensorflow +``` + + + +## خط الأنابيب + + + +يمثل [`pipeline`] أسهل وأسرع طريقة لاستخدام نموذج مُدرب مسبقًا للاستنتاج. يمكنك استخدام [`pipeline`] جاهزًا للعديد من المهام عبر طرق مختلفة، والتي يظهر بعضها في الجدول أدناه: + + + +للاطلاع على القائمة الكاملة للمهام المتاحة، راجع [مرجع واجهة برمجة التطبيقات الخاصة بخط الأنابيب](./main_classes/pipelines). + + + +
+ +| **المهمة** | **الوصف** | **الطريقة** | **معرف خط الأنابيب** | +|------------------------------|--------------------------------------------------------------------------------------------------------------|-----------------|-----------------------------------------------| +| تصنيف النص | تعيين تسمية إلى تسلسل نص معين | NLP | pipeline(task=“sentiment-analysis”) | +| توليد النص | توليد نص بناءً على موجه معين | NLP | pipeline(task=“text-generation”) | +| تلخيص | توليد ملخص لتسلسل نص أو مستند | NLP | pipeline(task=“summarization”) | +| تصنيف الصور | تعيين تسمية لصورة معينة | رؤية حاسوبية | pipeline(task=“image-classification”) | +| تجزئة الصورة | تعيين تسمية لكل بكسل فردي في الصورة (يدعم التجزئة الدلالية، والمجملة، وتجزئة مثيلات) | رؤية حاسوبية | pipeline(task=“image-segmentation”) | +| اكتشاف الأشياء | التنبؤ بحدود الأشياء وفئاتها في صورة معينة | رؤية حاسوبية | pipeline(task=“object-detection”) | +| تصنيف الصوت | تعيين تسمية لبيانات صوتية معينة | صوتي | pipeline(task=“audio-classification”) | +| التعرف على الكلام التلقائي | نسخ الكلام إلى نص | صوتي | pipeline(task=“automatic-speech-recognition”) | +| الإجابة على الأسئلة البصرية | الإجابة على سؤال حول الصورة، مع إعطاء صورة وسؤال | متعدد الوسائط | pipeline(task=“vqa”) | +| الإجابة على أسئلة المستندات | الإجابة على سؤال حول المستند، مع إعطاء مستند وسؤال | متعدد الوسائط | pipeline(task="document-question-answering") | +| كتابة تعليق على الصورة | إنشاء تعليق على صورة معينة | متعدد الوسائط | pipeline(task="image-to-text") | + +
+ابدأ بإنشاء مثيل من [`pipeline`] وتحديد المهمة التي تريد استخدامه لها. في هذا الدليل، ستستخدم خط الأنابيب للتحليل النصي كنموذج: + +```py +>>> from transformers import pipeline + +>>> classifier = pipeline("sentiment-analysis") +``` + +يقوم [`pipeline`] بتنزيل وتخزين نسخة احتياطية من نموذج افتراضي [مُدرب مسبقًا](https://huggingface.co/distilbert/distilbert-base-uncased-finetuned-sst-2-english) ومعالج للتحليل النصي. الآن يمكنك استخدام `classifier` على النص المستهدف: + +```py +>>> classifier("We are very happy to show you the 🤗 Transformers library.") +[{'label': 'POSITIVE', 'score': 0.9998}] +``` + +إذا كان لديك أكثر من إدخال واحد، قم بتمرير إدخالاتك كقائمة إلى [`pipeline`] لإرجاع قائمة من القواميس: + +```py +>>> results = classifier(["We are very happy to show you the 🤗 Transformers library.", "We hope you don't hate it."]) +>>> for result in results: +... print(f"label: {result['label']}, with score: {round(result['score'], 4)}") +label: POSITIVE, with score: 0.9998 +label: NEGATIVE, with score: 0.5309 +``` +يمكن لخط الأنابيب أيضًا أن يتنقل خلال مجموعة بيانات كاملة لأي مهمة تريدها. كمثال على ذلك، دعنا نختار التعرف على الكلام التلقائي كمهمة لنا: + +```py +>>> import torch +>>> from transformers import pipeline + +>>> speech_recognizer = pipeline("automatic-speech-recognition", model="facebook/wav2vec2-base-960h") +``` + +قم بتحميل مجموعة بيانات صوتية (راجع دليل البدء السريع لـ 🤗 Datasets [Quick Start](https://huggingface.co/docs/datasets/quickstart#audio) للحصول على مزيد من التفاصيل) التي تريد التنقل خلالها. على سبيل المثال، قم بتحميل مجموعة بيانات [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14): + +```py +>>> from datasets import load_dataset, Audio + +>>> dataset = load_dataset("PolyAI/minds14", name="en-US", split="train") # doctest: +IGNORE_RESULT +``` + +يجب التأكد من أن نفس الجودة الصوتية (معدل أخذ العينات) لمجموعة البيانات يتطابق مع معدل أخذ العينات الذي تم تدريب [`facebook/wav2vec2-base-960h`](https://huggingface.co/facebook/wav2vec2-base-960h) عليه: + +```py +>>> dataset = dataset.cast_column("audio", Audio(sampling_rate=speech_recognizer.feature_extractor.sampling_rate)) +``` + +يتم تحميل الملفات الصوتية وإعادة تشكيلها تلقائيًا عند استدعاء العمود "audio". +استخرج المصفوفات الموجية الخام من أول 4 عينات ومررها كقائمة إلى خط الأنابيب: + +```py +>>> result = speech_recognizer(dataset[:4]["audio"]) +>>> print([d["text"] for d in result]) +['I WOULD LIKE TO SET UP A JOINT ACCOUNT WITH MY PARTNER HOW DO I PROCEED WITH DOING THAT', "FONDERING HOW I'D SET UP A JOIN TO HELL T WITH MY WIFE AND WHERE THE AP MIGHT BE", "I I'D LIKE TOY SET UP A JOINT ACCOUNT WITH MY PARTNER I'M NOT SEEING THE OPTION TO DO IT ON THE APSO I CALLED IN TO GET SOME HELP CAN I JUST DO IT OVER THE PHONE WITH YOU AND GIVE YOU THE INFORMATION OR SHOULD I DO IT IN THE AP AN I'M MISSING SOMETHING UQUETTE HAD PREFERRED TO JUST DO IT OVER THE PHONE OF POSSIBLE THINGS", 'HOW DO I FURN A JOINA COUT'] +``` + +بالنسبة لمجموعات البيانات الكبيرة التي تحتوي على مدخلات ضخمة (كما هو الحال في البيانات الصوتية أو المرئية)، يفضل تمرير مولد (generator) بدلاً من قائمة لتحميل جميع المدخلات في الذاكرة دفعة واحدة. راجع [مرجع واجهة برمجة التطبيقات الخاصة بخط الأنابيب](./main_classes/pipelines) للحصول على مزيد من المعلومات. + +### ااستخدم نموذجًا ومجزئًا آخرين في خط الأنابيب + +يمكن لخط الأنابيب [`pipeline`] استيعاب أي نموذج من [Hub](https://huggingface.co/models)، مما يسهل التكيف مع حالات الاستخدام الأخرى. على سبيل المثال، إذا كنت تريد نموذجًا قادرًا على التعامل مع النص الفرنسي، فاستخدم العلامات على Hub لفلتره نموذج مناسب. تعيد النتيجة الأولى المرشحة نموذج BERT متعدد اللغات [BERT model](https://huggingface.co/nlptown/bert-base-multilingual-uncased-sentiment) الذي تم ضبطه مسبقًا للتحليل المشاعر والذي يمكنك استخدامه للنص الفرنسي: + +```py +>>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment" +``` + + + +استخدم [`AutoModelForSequenceClassification`] و [`AutoTokenizer`] لتحميل النموذج المُدرب مسبقًا ومعالجته المرتبط به (مزيد من المعلومات حول `AutoClass` في القسم التالي): + +```py +>>> from transformers import AutoTokenizer, AutoModelForSequenceClassification + +>>> model = AutoModelForSequenceClassification.from_pretrained(model_name) +>>> tokenizer = AutoTokenizer.from_pretrained(model_name) +``` + + +استخدم [`TFAutoModelForSequenceClassification`] و [`AutoTokenizer`] لتحميل النموذج المُدرب مسبقًا ومعالجته المرتبط به (مزيد من المعلومات حول `TFAutoClass` في القسم التالي): + +```py +>>> from transformers import AutoTokenizer, TFAutoModelForSequenceClassification + +>>> model = TFAutoModelForSequenceClassification.from_pretrained(model_name) +>>> tokenizer = AutoTokenizer.from_pretrained(model_name) +``` + + + +حدد النموذج والمعالج في [`pipeline`]. الآن يمكنك تطبيق `classifier` على النص الفرنسي: + +```py +>>> classifier = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer) +>>> classifier("Nous sommes très heureux de vous présenter la bibliothèque 🤗 Transformers.") +[{'label': '5 stars', 'score': 0.7273}] +``` +إذا لم تجد نموذجًا جاهزًا يناسب مهمتك، فستحتاج إلى ضبط نموذج مُدرب مسبقًا على بياناتك. اطلع على [دليل الضبط الدقيق](./training) للتعرف على كيفية القيام بذلك. وبعد ضبط نموذجك المُدرب مسبقًا، يرجى مراعاة [المشاركة](./model_sharing) النموذج مع المجتمع على Hub لمساعدة الجميع في مجال التعلم الآلي! 🤗 + +## AutoClass + + + +في الخلفية، تعمل فئتا [`AutoModelForSequenceClassification`] و [`AutoTokenizer`] معًا لتشغيل دالة pipeline() الذي استخدمتها أعلاه. تعتبر [AutoClass](./model_doc/auto) اختصارًا يقوم تلقائيًا باسترداد بنية نموذج مُدرب مسبقًا من اسمه أو مساره. كل ما عليك فعله هو تحديد فئة `AutoClass` المناسبة لمهمتك وفئة المعالجة المرتبطة بها. + +لنعد إلى المثال من القسم السابق ولنرى كيف يمكنك استخدام `AutoClass` لتكرار نتائج خط الأنابيب. + +### المجزئ التلقائي (AutoTokenizer) + +يتولى المجزئ مسؤولية تحويل النص إلى مصفوفة من الأرقام (رموز) يمكن للنموذج فهمها ومعالجتها. هناك قواعد متعددة تحكم عملية التجزئة، بما في ذلك كيفية تقسيم كلمة وما هو المستوى الذي يجب أن تقسيم الكلمات عنده (تعرف على المزيد حول المعالجة في [ملخص المجزئ](./tokenizer_summary)). أهم شيء يجب تذكره هو أنك تحتاج إلى إنشاء مثيل للمجزئ بنفس اسم النموذج لضمان استخدامك لقواعد التجزئة نفسها التي تم تدريب النموذج عليها. + +قم بتحميل المجزئ باستخدام [`AutoTokenizer`]: + +```py +>>> from transformers import AutoTokenizer + +>>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment" +>>> tokenizer = AutoTokenizer.from_pretrained(model_name) +``` + +مرر نصك إلى المجزئ: + +```py +>>> encoding = tokenizer("We are very happy to show you the 🤗 Transformers library.") +>>> print(encoding) +{'input_ids': [101, 11312, 10320, 12495, 19308, 10114, 11391, 10855, 10103, 100, 58263, 13299, 119, 102], + 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]} +``` + +يعيد المجزئ قاموسًا يحتوي على: + +* [input_ids](./glossary#input-ids): التمثيلات الرقمية لرموزك. +* [attention_mask](./glossary#attention-mask): تشير إلى الرموز التي يجب الانتباه بها. + +يمكن المجزئ أيضًا قبول قائمة من المدخلات، ويقوم بـ "حشو" و"تقصير" النص لإرجاع كدفعة بطول موحد: + + + + +```py +>>> pt_batch = tokenizer( +... ["We are very happy to show you the 🤗 Transformers library.", "We hope you don't hate it."], +... padding=True, +... truncation=True, +... max_length=512, +... return_tensors="pt", +... ) +``` + + + +```py +>>> tf_batch = tokenizer( +... ["We are very happy to show you the 🤗 Transformers library.", "We hope you don't hate it."], +... padding=True, +... truncation=True, +... max_length=512, +... return_tensors="tf", +... ) +``` + + + + + +اطلع على [الدليل التمهيدي للمعالجة المسبقة](./preprocessing) للحصول على مزيد من التفاصيل حول المعالجة، وكيفية استخدام [`AutoImageProcessor`] و [`AutoFeatureExtractor`] و [`AutoProcessor`] لمعالجة الصور والصوت والإدخالات متعددة الوسائط. + + + +### AutoModel + + + +تقدم مكتبة 🤗 Transformers طريقة بسيطة وموحدة لتحميل نماذج مدربة مسبقًا. وهذا يعني أنه يمكنك تحميل [`AutoModel`] كما لو كنت تقوم بتحميل [`AutoTokenizer`]. الفرق الوحيد هو اختيار فئة [`AutoModel`] المناسبة للمهمة. بالنسبة لتصنيف النص (أو التسلسل)، يجب عليك تحميل [`AutoModelForSequenceClassification`]: + +```py +>>> from transformers import AutoModelForSequenceClassification + +>>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment" +>>> pt_model = AutoModelForSequenceClassification.from_pretrained(model_name) +``` + + + +راجع [ملخص المهمة](./task_summary) للاطلاع على المهام التي تدعمها فئة [`AutoModel`]. + + + +الآن قم بتمرير دفعة المدخلات المُعالجة مسبقًا مباشرة إلى النموذج. عليك فقط فك تعبئة القاموس عن طريق إضافة `**`: + +# تدريب النموذج + +الآن، مرر دفعة المدخلات المعالجة مسبقًا مباشرة إلى النموذج. ما عليك سوى فك تعبئة القاموس عن طريق إضافة `**`: + +```py +>>> pt_outputs = pt_model(**pt_batch) +``` + +يُخرج النموذج التنشيطات النهائية في سمة `logits`. طبق دالة softmax على `logits` للحصول على الاحتمالات: + +```py +>>> from torch import nn + +>>> pt_predictions = nn.functional.softmax(pt_outputs.logits, dim=-1) +>>> print(pt_predictions) +tensor([[0.0021, 0.0018, 0.0115, 0.2121, 0.7725], + [0.2084, 0.1826, 0.1969, 0.1755, 0.2365]], grad_fn=) +``` + + +يوفر 🤗 Transformers طريقة بسيطة وموحدة لتحميل مثيلات مُدربة مسبقًا. وهذا يعني أنه يمكنك تحميل [`TFAutoModel`] مثل تحميل [`AutoTokenizer`]. والفرق الوحيد هو تحديد [`TFAutoModel`] الصحيح للمهمة. للتصنيف النصي (أو التسلسلي)، يجب تحميل [`TFAutoModelForSequenceClassification`]: + +```py +>>> from transformers import TFAutoModelForSequenceClassification + +>>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment" +>>> tf_model = TFAutoModelForSequenceClassification.from_pretrained(model_name) +``` + + + +راجع [ملخص المهام](./task_summary) للمهام المدعومة بواسطة فئة [`AutoModel`]. + + + +الآن، مرر دفعة المدخلات المعالجة مسبقًا مباشرة إلى النموذج. يمكنك تمرير المصفوفات كما هي: + +```py +>>> tf_outputs = tf_model(tf_batch) +``` + +يقوم النموذج بإخراج التنشيطات النهائية في سمة `logits`. طبق دالة softmax على `logits` لاسترداد الاحتمالات: + +```py +>>> import tensorflow as tf + +>>> tf_predictions = tf.nn.softmax(tf_outputs.logits, axis=-1) +>>> tf_predictions # doctest: +IGNORE_RESULT +``` + + + + + +تخرج جميع نماذج 🤗 Transformers (PyTorch أو TensorFlow) المصفوفات *قبل* دالة التنشيط النهائية (مثل softmax) لأن دالة التنشيط النهائية غالبًا ما تكون مدمجة مع دالة الخسارة. نواتج النموذج عبارة عن فئات بيانات خاصة، لذلك يتم استكمال سماتها تلقائيًا في IDE. وتتصرف مخرجات النموذج مثل زوج مرتب أو قاموس (يمكنك الفهرسة باستخدام عدد صحيح ، شريحة، أو سلسلة)، وفي هذه الحالة، يتم تجاهل السمات التي تساوي None. + + + +### حفظ النموذج + + + +بمجرد ضبط نموذجك، يمكنك حفظه مع برنامج الترميز الخاص به باستخدام [`PreTrainedModel.save_pretrained`]: + +```py +>>> pt_save_directory = "./pt_save_pretrained" +>>> tokenizer.save_pretrained(pt_save_directory) # doctest: +IGNORE_RESULT +>>> pt_model.save_pretrained(pt_save_directory) +``` + +عندما تكون مستعدًا لاستخدام النموذج مرة أخرى، أعد تحميله باستخدام [`PreTrainedModel.from_pretrained`]: + +```py +>>> pt_model = AutoModelForSequenceClassification.from_pretrained("./pt_save_pretrained") +``` + + +بمجرد ضبط نموذجك، يمكنك حفظه مع برنامج الترميز الخاص به باستخدام [`TFPreTrainedModel.save_pretrained`]: + +```py +>>> tf_save_directory = "./tf_save_pretrained" +>>> tokenizer.save_pretrained(tf_save_directory) # doctest: +IGNORE_RESULT +>>> tf_model.save_pretrained(tf_save_directory) +``` + +عندما تكون مستعدًا لاستخدام النموذج مرة أخرى، أعد تحميله باستخدام [`TFPreTrainedModel.from_pretrained`]: + +```py +>>> tf_model = TFAutoModelForSequenceClassification.from_pretrained("./tf_save_pretrained") +``` + + + +من الميزات الرائعة في 🤗 Transformers القدرة على حفظ نموذج وإعادة تحميله كنموذج PyTorch أو TensorFlow. يمكن أن يحول معامل `from_pt` أو `from_tf` النموذج من إطار عمل إلى آخر: + + + + +```py +>>> from transformers import AutoModel + +>>> tokenizer = AutoTokenizer.from_pretrained(pt_save_directory) +>>> pt_model = AutoModelForSequenceClassification.from_pretrained(pt_save_directory, from_pt=True) +``` + + + +```py +>>> from transformers import TFAutoModel + +>>> tokenizer = AutoTokenizer.from_pretrained(tf_save_directory) +>>> tf_model = TFAutoModelForSequenceClassification.from_pretrained(tf_save_directory, from_tf=True) +``` + + + + +## إنشاء نماذج مخصصة + +يمكنك تعديل فئة تكوين النموذج لتغيير كيفية بناء النموذج. يحدد التكوين سمات النموذج، مثل عدد الطبقات المخفية أو رؤوس الاهتمام. تبدأ من الصفر عند تهيئة نموذج من فئة تكوين مخصصة. يتم تهيئة سمات النموذج بشكل عشوائي، ويجب تدريب النموذج قبل استخدامه للحصول على نتائج ذات معنى. + +ابدأ باستيراد [`AutoConfig`]. ثم قم بتحميل النموذج المُدرب مسبقًا الذي تريد تعديله. ضمن [`AutoConfig.from_pretrained`]. يمكنك تحديد السمة التي تريد تغييرها، مثل عدد رؤوس الاهتمام: + +```py +>>> from transformers import AutoConfig + +>>> my_config = AutoConfig.from_pretrained("distilbert/distilbert-base-uncased", n_heads=12) +``` + + + +قم بإنشاء نموذج من تكوينك المخصص باستخدام [`AutoModel.from_config`]: + +```py +>>> from transformers import AutoModel + +>>> my_model = AutoModel.from_config(my_config) +``` + + +قم بإنشاء نموذج من تكوينك المخصص باستخدام [`TFAutoModel.from_config`]: + +```py +>>> from transformers import TFAutoModel + +>>> my_model = TFAutoModel.from_config(my_config) +``` + + + +الق نظرة على دليل [إنشاء بنية مخصصة](./create_a_model) لمزيد من المعلومات حول بناء التكوينات المخصصة. + +## المدرب - حلقة تدريب محسنة لـ PyTorch + +جميع النماذج عبارة عن [`torch.nn.Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) قياسية، لذا يمكنك استخدامها في أي حلقة تدريب نموذجية. في حين يمكنك كتابة حلقة التدريب الخاصة بك، يوفر 🤗 Transformers فئة [`Trainer`] لـ PyTorch، والتي تحتوي على حلقة التدريب الأساسية وتضيف وظائف إضافية لميزات مثل التدريب الموزع، والدقة المختلطة، والمزيد. + +وفقًا لمهمتك، ستقوم عادةً بتمرير المعلمات التالية إلى [`Trainer`]: + +1. ستبدأ بـ [`PreTrainedModel`] أو [`torch.nn.Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module): + + ```py + >>> from transformers import AutoModelForSequenceClassification + + >>> model = AutoModelForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased") + ``` + +2. تحتوي [`TrainingArguments`] على فرط معلمات النموذج التي يمكنك تغييرها مثل معدل التعلم، وحجم الدفعة، وعدد العصور التي يجب التدريب عليها. يتم استخدام القيم الافتراضية إذا لم تحدد أي حجج تدريب: + + ```py + >>> from transformers import TrainingArguments + + >>> training_args = TrainingArguments( + ... output_dir="path/to/save/folder/", + ... learning_rate=2e-5, + ... per_device_train_batch_size=8, + ... per_device_eval_batch_size=8, + ... num_train_epochs=2, + ... ) + ``` + +3. قم بتحميل فئة معالجة مسبقة مثل برنامج الترميز، أو معالج الصور، أو مستخرج الميزات، أو المعالج: + + ```py + >>> from transformers import AutoTokenizer + + >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased") + ``` + +4. قم بتحميل مجموعة بيانات: + + ```py + >>> from datasets import load_dataset + + >>> dataset = load_dataset("rotten_tomatoes") # doctest: +IGNORE_RESULT + ``` + +5. قم بإنشاء دالة لترميز مجموعة البيانات: + + ```py + >>> def tokenize_dataset(dataset): + ... return tokenizer(dataset["text"]) + ``` + + ثم قم بتطبيقه على مجموعة البيانات بأكملها باستخدام [`~datasets.Dataset.map`]: + + ```py + >>> dataset = dataset.map(tokenize_dataset, batched=True) + ``` + +6. [`DataCollatorWithPadding`] لإنشاء دفعة من الأمثلة من مجموعة البيانات الخاصة بك: + + ```py + >>> from transformers import DataCollatorWithPadding + + >>> data_collator = DataCollatorWithPadding(tokenizer=tokenizer) + ``` + +الآن قم بتجميع جميع هذه الفئات في [`Trainer`]: + +```py +>>> from transformers import Trainer + +>>> trainer = Trainer( +... model=model, +... args=training_args, +... train_dataset=dataset["train"], +... eval_dataset=dataset["test"], +... tokenizer=tokenizer, +... data_collator=data_collator, +... ) # doctest: +SKIP +``` +عندما تكون مستعدًا، استدعِ [`~Trainer.train`] لبدء التدريب: + +```py +>>> trainer.train() # doctest: +SKIP +``` + + + +بالنسبة للمهام - مثل الترجمة أو التلخيص - التي تستخدم نموذج تسلسل إلى تسلسل، استخدم فئات [`Seq2SeqTrainer`] و [`Seq2SeqTrainingArguments`] بدلاً من ذلك. + + + +يمكنك تخصيص سلوك حلقة التدريب عن طريق إنشاء فئة فرعية من الطرق داخل [`Trainer`]. يسمح لك ذلك بتخصيص ميزات مثل دالة الخسارة، والمحسن، والمجدول. راجع مرجع [`Trainer`] للتعرف على الطرق التي يمكن إنشاء فئات فرعية منها. + +والطريقة الأخرى لتخصيص حلقة التدريب هي باستخدام [المستدعيات](./main_classes/callback). يمكنك استخدام المستدعيات للتكامل مع المكتبات الأخرى ومراقبة حلقة التدريب للإبلاغ عن التقدم أو إيقاف التدريب مبكرًا. لا تعدل المستدعيات أي شيء في حلقة التدريب نفسها. لتخصيص شيء مثل دالة الخسارة، تحتاج إلى إنشاء فئة فرعية من [`Trainer`] بدلاً من ذلك. + +## التدريب باستخدام TensorFlow + +جميع النماذج عبارة عن [`tf.keras.Model`](https://www.tensorflow.org/api_docs/python/tf/keras/Model) قياسية، لذا يمكن تدريبها في TensorFlow باستخدام واجهة برمجة تطبيقات Keras. يوفر 🤗 Transformers طريقة [`~TFPreTrainedModel.prepare_tf_dataset`] لتحميل مجموعة البيانات الخاصة بك بسهولة كـ `tf.data.Dataset` حتى تتمكن من البدء في التدريب على الفور باستخدام دالتي `compile` و`fit` في Keras. + +1. ستبدأ بـ [`TFPreTrainedModel`] أو [`tf.keras.Model`](https://www.tensorflow.org/api_docs/python/tf/keras/Model): + + ```py + >>> from transformers import TFAutoModelForSequenceClassification + + >>> model = TFAutoModelForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased") + ``` + +2. قم بتحميل فئة معالجة مسبقة مثل برنامج الترميز، أو معالج الصور، أو مستخرج الميزات، أو المعالج: + + ```py + >>> from transformers import AutoTokenizer + + >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased") + ``` + +3. قم بإنشاء دالة لترميز مجموعة البيانات: + + ```py + >>> def tokenize_dataset(dataset): + ... return tokenizer(dataset["text"]) # doctest: +SKIP + ``` + +4. قم بتطبيق برنامج الترميز على مجموعة البيانات بأكملها باستخدام [`~datasets.Dataset.map`] ثم مرر مجموعة البيانات وبرنامج الترميز إلى [`~TFPreTrainedModel.prepare_tf_dataset`]. يمكنك أيضًا تغيير حجم الدفعة وخلط مجموعة البيانات هنا إذا أردت: + + ```py + >>> dataset = dataset.map(tokenize_dataset) # doctest: +SKIP + >>> tf_dataset = model.prepare_tf_dataset( + ... dataset["train"], batch_size=16, shuffle=True, tokenizer=tokenizer + ... ) # doctest: +SKIP + ``` + +5. عندما تكون مستعدًا، يمكنك استدعاء `compile` و`fit` لبدء التدريب. لاحظ أن جميع نماذج Transformers لديها دالة خسارة ذات صلة بالمهمة بشكل افتراضي، لذا فأنت لست بحاجة إلى تحديد واحدة ما لم ترغب في ذلك: + + ```py + >>> from tensorflow.keras.optimizers import Adam + + >>> model.compile(optimizer='adam') # لا توجد وسيطة دالة الخسارة! + >>> model.fit(tf_dataset) # doctest: +SKIP + ``` + +## ماذا بعد؟ + +الآن بعد أن أكملت الجولة السريعة في 🤗 Transformers، راجع أدلتنا لمعرفة كيفية القيام بأشياء أكثر تحديدًا مثل كتابة نموذج مخصص، وضبط نموذج مسبق التدريب لمهمة معينة، وكيفية تدريب نموذج باستخدام نص برمجي. إذا كنت مهتمًا بمعرفة المزيد عن المفاهيم الأساسية لـ 🤗 Transformers، فاحصل على فنجان من القهوة واطلع على أدلة المفاهيم الخاصة بنا! diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/run_scripts.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/run_scripts.md new file mode 100644 index 0000000000000000000000000000000000000000..f7673408ca7d012d864a4134b7d5e49ca183174d --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/run_scripts.md @@ -0,0 +1,351 @@ +# التدريب باستخدام نص برمجى + +بالإضافة إلى دفاتر الملاحظات [notebooks](./notebooks) الخاصة بـ 🤗 Transformers، هناك أيضًا نصوص برمجية توضيحية تُظهر كيفية تدريب نموذج لمهمة باستخدام [PyTorch](https://github.com/huggingface/transformers/tree/main/examples/pytorch) أو [TensorFlow](https://github.com/huggingface/transformers/tree/main/examples/tensorflow) أو [JAX/Flax](https://github.com/huggingface/transformers/tree/main/examples/flax). + +كما ستجد النصوص البرمجية التي استخدمناها في [مشاريع الأبحاث](https://github.com/huggingface/transformers-research-projects/) و [الأمثلة القديمة](https://github.com/huggingface/transformers/tree/main/examples/legacy) والتي ساهم بها المجتمع بشكل أساسي. هذه النصوص البرمجية غير مدعومة بشكل نشط وقد تتطلب إصدارًا محددًا من مكتبة 🤗 Transformers والذي من المحتمل أن يكون غير متوافق مع الإصدار الأحدث من المكتبة. + +لا يُتوقع أن تعمل النصوص البرمجية التوضيحية بشكل مباشر على كل مشكلة، وقد تحتاج إلى تكييف النص البرمجي مع المشكلة التي تحاول حلها. ولمساعدتك في ذلك، تعرض معظم النصوص البرمجية كيفية معالجة البيانات قبل التدريب بشكل كامل، مما يتيح لك تحريرها حسب الحاجة لحالتك الاستخدام. + +بالنسبة لأي ميزة ترغب في تنفيذها في نص برمجي توضيحي، يرجى مناقشتها في [المنتدى](https://discuss.huggingface.co/) أو في [قضية](https://github.com/huggingface/transformers/issues) قبل إرسال طلب سحب. وفي حين أننا نرحب بإصلاح الأخطاء، فمن غير المرجح أن نقوم بدمج طلب سحب الذي يضيف المزيد من الوظائف على حساب قابلية القراءة. + +سيوضح هذا الدليل كيفية تشغيل نص برمجي توضيحي للتدريب على التلخيص في [PyTorch](https://github.com/huggingface/transformers/tree/main/examples/pytorch/summarization) و [TensorFlow](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/summarization). يُتوقع أن تعمل جميع الأمثلة مع كلا الإطارين ما لم يُنص على خلاف ذلك. + +## الإعداد + +لتشغيل الإصدار الأحدث من النصوص البرمجية التوضيحية بنجاح، يجب عليك **تثبيت 🤗 Transformers من المصدر** في بيئة افتراضية جديدة: + +```bash +git clone https://github.com/huggingface/transformers +cd transformers +pip install . +``` + +بالنسبة للإصدارات الأقدم من النصوص البرمجية التوضيحية، انقر فوق الزر أدناه: +```bash +git clone https://github.com/huggingface/transformers +cd transformers +pip install . +``` + +بالنسبة للإصدارات الأقدم من النصوص البرمجية التوضيحية، انقر فوق الزر أدناه: + +
+ أمثلة للإصدارات الأقدم من 🤗 Transformers + +
+ +ثم قم بالتبديل إلى النسخة الحالية من 🤗 Transformers إلى إصدار محدد، مثل v3.5.1 على سبيل المثال: + +```bash +git checkout tags/v3.5.1 +``` + +بعد إعداد إصدار المكتبة الصحيح، انتقل إلى مجلد الأمثلة الذي تختاره وقم بتثبيت المتطلبات المحددة: + +```bash +pip install -r requirements.txt +``` + +## تشغيل نص برمجي + + + + +- يقوم النص البرمجي التوضيحي بتنزيل مجموعة بيانات ومعالجتها مسبقًا من مكتبة 🤗 [Datasets](https://huggingface.co/docs/datasets). +- ثم يقوم النص البرمجي بضبط نموذج بيانات دقيق باستخدام [Trainer](https://huggingface.co/docs/transformers/main_classes/trainer) على بنية تدعم الملخص. +- يوضح المثال التالي كيفية ضبط نموذج [T5-small](https://huggingface.co/google-t5/t5-small) على مجموعة بيانات [CNN/DailyMail](https://huggingface.co/datasets/cnn_dailymail). +- يتطلب نموذج T5 معامل `source_prefix` إضافية بسبب الطريقة التي تم تدريبه بها. يتيح هذا المطالبة لـ T5 معرفة أن هذه مهمة التلخيص. + +```bash +python examples/pytorch/summarization/run_summarization.py \ + --model_name_or_path google-t5/t5-small \ + --do_train \ + --do_eval \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --overwrite_output_dir \ + --predict_with_generate +``` + + + +- يقوم النص البرمجي التوضيحي بتنزيل مجموعة بيانات ومعالجتها مسبقًا من مكتبة 🤗 [Datasets](https://huggingface.co/docs/datasets/). +- ثم يقوم النص البرمجي بضبط نموذج بيانات دقيق باستخدام Keras على بنية تدعم الملخص. +- يوضح المثال التالي كيفية ضبط نموذج [T5-small](https://huggingface.co/google-t5/t5-small) على مجموعة بيانات [CNN/DailyMail](https://huggingface.co/datasets/cnn_dailymail). +- يتطلب نموذج T5 ماعمل `source_prefix` إضافية بسبب الطريقة التي تم تدريبه بها. يتيح هذا المطالبة لـ T5 معرفة أن هذه مهمة التلخيص. + +```bash +python examples/tensorflow/summarization/run_summarization.py \ + --model_name_or_path google-t5/t5-small \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size 8 \ + --per_device_eval_batch_size 16 \ + --num_train_epochs 3 \ + --do_train \ + --do_eval +``` + + + +## التدريب الموزع والدقة المختلطة + +يدعم [Trainer](https://huggingface.co/docs/transformers/main_classes/trainer) التدريب الموزع والدقة المختلطة، مما يعني أنه يمكنك أيضًا استخدامه في نص برمجي. لتمكين كلتا الميزتين: + +- أضف معامل `fp16` لتمكين الدقة المختلطة. +- قم بتعيين عدد وحدات معالجة الرسومات (GPUs) التي تريد استخدامها باستخدام حجة `nproc_per_node`. + +```bash +torchrun \ + --nproc_per_node 8 pytorch/summarization/run_summarization.py \ + --fp16 \ + --model_name_or_path google-t5/t5-small \ + --do_train \ + --do_eval \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --overwrite_output_dir \ + --predict_with_generate +``` + +تستخدم نصوص TensorFlow البرمجية استراتيجية [`MirroredStrategy`](https://www.tensorflow.org/guide/distributed_training#mirroredstrategy) للتدريب الموزع، ولا تحتاج إلى إضافة أي معامﻻت إضافية إلى النص البرمجي التدريبي. سيستخدم نص TensorFlow البرمجي وحدات معالجة الرسومات (GPUs) متعددة بشكل افتراضي إذا كانت متوفرة. + +## تشغيل نص برمجي على وحدة معالجة الدقة الفائقة (TPU) + + + + +تُعد وحدات معالجة الدقة الفائقة (TPUs) مصممة خصيصًا لتسريع الأداء. يدعم PyTorch وحدات معالجة الدقة الفائقة (TPUs) مع [XLA](https://www.tensorflow.org/xla) مجمع الدقة الفائقة للتعلم العميق (راجع [هنا](https://github.com/pytorch/xla/blob/master/README.md) لمزيد من التفاصيل). لاستخدام وحدة معالجة الدقة الفائقة (TPU)، قم بتشغيل نص `xla_spawn.py` البرمجي واستخدم معامل `num_cores` لتعيين عدد وحدات معالجة الدقة الفائقة (TPU) التي تريد استخدامها. + +```bash +python xla_spawn.py --num_cores 8 \ + summarization/run_summarization.py \ + --model_name_or_path google-t5/t5-small \ + --do_train \ + --do_eval \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --overwrite_output_dir \ + --predict_with_generate +``` + + + +تُعد وحدات معالجة الدقة الفائقة (TPUs) مصممة خصيصًا لتسريع الأداء. تستخدم نصوص TensorFlow البرمجية استراتيجية [`TPUStrategy`](https://www.tensorflow.org/guide/distributed_training#tpustrategy) للتدريب على وحدات معالجة الدقة الفائقة (TPUs). لاستخدام وحدة معالجة الدقة الفائقة (TPU)، قم بتمرير اسم مورد وحدة معالجة الدقة الفائقة (TPU) إلى حجة `tpu`. +```bash +python run_summarization.py \ + --tpu name_of_tpu_resource \ + --model_name_or_path google-t5/t5-small \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size 8 \ + --per_device_eval_batch_size 16 \ + --num_train_epochs 3 \ + --do_train \ + --do_eval +``` + + + +## تشغيل نص برمجي باستخدام 🤗 Accelerate + +🤗 [Accelerate](https://huggingface.co/docs/accelerate) هي مكتبة خاصة بـ PyTorch فقط توفر طريقة موحدة لتدريب نموذج على عدة أنواع من الإعدادات (الاعتماد على وحدة المعالجة المركزية (CPU) فقط، أو وحدات معالجة الرسومات (GPUs) المتعددة، أو وحدات معالجة الدقة الفائقة (TPUs)) مع الحفاظ على الرؤية الكاملة لحلقة تدريب PyTorch. تأكد من تثبيت 🤗 Accelerate إذا لم يكن لديك بالفعل: + +> ملاحظة: نظرًا لأن Accelerate في حالة تطوير سريع، يجب تثبيت إصدار Git من Accelerate لتشغيل النصوص البرمجية. +```bash +pip install git+https://github.com/huggingface/accelerate +``` + +بدلاً من إستخدام النص البرمجي `run_summarization.py` يجب عليك استخدام النص البرمجي `run_summarization_no_trainer.py` . ستكون النصوص البرمجية المدعومة من 🤗 Accelerate لها ملف `task_no_trainer.py` في المجلد. ابدأ بتشغيل الأمر التالي لإنشاء وحفظ ملف تكوين: + +```bash +accelerate config +``` + +اختبر إعدادك للتأكد من أنه تم تكوينه بشكل صحيح: + +```bash +accelerate test +``` + +الآن أنت مستعد لبدء التدريب: + +```bash +accelerate launch run_summarization_no_trainer.py \ + --model_name_or_path google-t5/t5-small \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --output_dir ~/tmp/tst-summarization +``` + +## استخدام مجموعة بيانات مخصصة + +يدعم النص البرمجي للتلخيص مجموعة بيانات مخصصة طالما أنها ملف CSV أو JSON Line. عندما تستخدم مجموعة بياناتك الخاصة، تحتاج إلى تحديد العديد من المعلمات الإضافية: + +- `train_file` و`validation_file` يحددان مسار ملفات التدريب والتحقق الخاصة بك. +- `text_column` النص المدخل الذي سيتم تلخيصه. +- `summary_column` النص الملخص المستهدف الذي سيتم إخراجه. + +سيبدو النص البرمجي للتلخيص الذي يستخدم مجموعة بيانات مخصصة على النحو التالي: + +```bash +python examples/pytorch/summarization/run_summarization.py \ + --model_name_or_path google-t5/t5-small \ + --do_train \ + --do_eval \ + --train_file path_to_csv_or_jsonlines_file \ + --validation_file path_to_csv_or_jsonlines_file \ + --text_column text_column_name \ + --summary_column summary_column_name \ + --source_prefix "summarize: " \ + --output_dir /tmp/tst-summarization \ + --overwrite_output_dir \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --predict_with_generate +``` + +## اختبار البرنامج النصي + +من الجيد غالبًا تشغيل نصك البرمجي على عدد أقل من أمثلة مجموعة البيانات للتأكد من أن كل شيء يعمل كما هو متوقع قبل الالتزام بمجموعة بيانات كاملة والتي قد تستغرق ساعات لإكمالها. استخدم المعلمات التالية لتقليص مجموعة البيانات إلى عدد أقصى من العينات: + +- `max_train_samples` +- `max_eval_samples` +- `max_predict_samples` + +```bash +python examples/pytorch/summarization/run_summarization.py \ + --model_name_or_path google-t5/t5-small \ + --max_train_samples 50 \ + --max_eval_samples 50 \ + --max_predict_samples 50 \ + --do_train \ + --do_eval \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --overwrite_output_dir \ + --predict_with_generate +``` + +لا تدعم جميع أمثلة النصوص البرمجية المعلمة `max_predict_samples`. إذا لم تكن متأكدًا مما إذا كان نصك البرمجي يدعم هذه المعلمة، فأضف معلمة `-h` للتحقق: + +```bash +examples/pytorch/summarization/run_summarization.py -h +``` + +## استئناف التدريب من نقطة تفتيش + +خيار آخر مفيد لتمكينه هو استئناف التدريب من نقطة تفتيش سابقة. سيضمن ذلك أنك تستطيع الاستمرار من حيث توقفت دون البدء من جديد إذا تم مقاطعة تدريبك. هناك طريقتان لاستئناف التدريب من نقطة تفتيش. + +تستخدم الطريقة الأولى المعلمة `output_dir previous_output_dir` لاستئناف التدريب من أحدث نقطة تفتيش مخزنة في `output_dir`. في هذه الحالة، يجب عليك إزالة `overwrite_output_dir`: + +```bash +python examples/pytorch/summarization/run_summarization.py + --model_name_or_path google-t5/t5-small \ + --do_train \ + --do_eval \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --output_dir previous_output_dir \ + --predict_with_generate +``` + +تستخدم الطريقة الثانية معلمة `resume_from_checkpoint path_to_specific_checkpoint` لاستئناف التدريب من مجلد نقطة تفتيش محددة. + +```bash +python examples/pytorch/summarization/run_summarization.py + --model_name_or_path google-t5/t5-small \ + --do_train \ + --do_eval \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --overwrite_output_dir \ + --resume_from_checkpoint path_to_specific_checkpoint \ + --predict_with_generate +``` + +## شارك نموذجك + +يمكن لجميع النصوص البرمجية رفع نموذجك النهائي إلى [مركز النماذج](https://huggingface.co/models). تأكد من تسجيل الدخول إلى Hugging Face قبل البدء: + +```bash +hf auth login +``` + +ثم أضف المعلمة `push_to_hub` إلى النص البرمجي . ستقوم هذه المعلمة بإنشاء مستودع باستخدام اسم مستخدم Hugging Face واسم المجلد المحدد في `output_dir`. + +لإعطاء مستودعك اسمًا محددًا، استخدم المعلمة `push_to_hub_model_id` لإضافته. سيتم عرض المستودع تلقائيًا ضمن مساحة الاسم الخاصة بك. + +يوضح المثال التالي كيفية رفع نموذج باستخدام اسم مستودع محدد: + +```bash +python examples/pytorch/summarization/run_summarization.py + --model_name_or_path google-t5/t5-small \ + --do_train \ + --do_eval \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --push_to_hub \ + --push_to_hub_model_id finetuned-t5-cnn_dailymail \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --overwrite_output_dir \ + --predict_with_generate +``` diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/sagemaker.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/sagemaker.md new file mode 100644 index 0000000000000000000000000000000000000000..6bb53816baaaee483277076a54a530bfa2e9f278 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/sagemaker.md @@ -0,0 +1,8 @@ +# تشغيل التدريب على Amazon SageMaker + +تم نقل التوثيق إلى [hf.co/docs/sagemaker](https://huggingface.co/docs/sagemaker). وسيتم إزالة هذه الصفحة في الإصدار 5.0 من برنامج Transformers. + +### جدول المحتويات + +- [تدريب نماذج Hugging Face على Amazon SageMaker باستخدام SageMaker Python SDK](https://huggingface.co/docs/sagemaker/train) +- [نشر نماذج Hugging Face على Amazon SageMaker باستخدام SageMaker Python SDK](https://huggingface.co/docs/sagemaker/inference) \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/serialization.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/serialization.md new file mode 100644 index 0000000000000000000000000000000000000000..6f437dea0681ba787b3f62aafd0f5ee723388f63 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/serialization.md @@ -0,0 +1,170 @@ +# التصدير إلى ONNX + +غالباً ما يتطلب نشر نماذج 🤗 Transformers في بيئات الإنتاج أو يمكن أن يستفيد من تصدير النماذج إلى تنسيق تسلسلي يُمكن تحميله وتنفيذه على أجهزة وبرامج تشغيل مُتخصصة. + +🤗 Optimum هو امتداد لـ Transformers يمكّن من تصدير النماذج من PyTorch أو TensorFlow إلى تنسيقات مُتسلسلة مثل ONNX و TFLite من خلال وحدة `exporters` الخاصة به. يوفر 🤗 Optimum أيضًا مجموعة من أدوات تحسين الأداء لتدريب النماذج وتشغيلها على أجهزة مستهدفة بكفاءة قصوى. + +يوضح هذا الدليل كيفية تصدير نماذج 🤗 Transformers إلى ONNX باستخدام 🤗 Optimum، وللحصول على الدليل الخاص بتصدير النماذج إلى TFLite، يُرجى الرجوع إلى صفحة [التصدير إلى TFLite](tflite). + +## التصدير إلى ONNX + +مجمد [ONNX (Open Neural Network Exchange)](http://onnx.ai) هو معيار مفتوح يُحدد مجموعة مشتركة من العوامل وتنسيق ملف مشترك لتمثيل نماذج التعلم العميق في مجموعة متنوعة واسعة من الأطر، بما في ذلك PyTorch وTensorFlow. عندما يتم تصدير نموذج إلى تنسيق ONNX، يتم استخدام هذه المشغلات لبناء رسم بياني حاسوبي (يُطلق عليه غالبًا اسم _تمثيل وسيط_) والذي يمثل تدفق البيانات عبر الشبكة العصبية. + +من خلال عرض رسم بياني بعوامل وأنواع بيانات معيارية، يُسهّل ONNX التبديل بين الأطر. على سبيل المثال، يُمكن تصدير نموذج مدرب في PyTorch إلى تنسيق ONNX ثم استيراده في TensorFlow (والعكس صحيح). + +بمجرد التصدير إلى تنسيق ONNX، يُمكن: + +- تحسين النموذج للاستدلال عبر تقنيات مثل [تحسين الرسم البياني](https://huggingface.co/docs/optimum/onnxruntime/usage_guides/optimization) و [التكميم](https://huggingface.co/docs/optimum/onnxruntime/usage_guides/quantization). +- تشغيله باستخدام ONNX Runtime عبر فئات [`ORTModelForXXX`](https://huggingface.co/docs/optimum/onnxruntime/package_reference/modeling_ort)، والتي تتبع نفس واجهة برمجة التطبيقات (API) لـ `AutoModel` التي اعتدت عليها في 🤗 Transformers. +- تشغيله باستخدام [قنوات معالجة الاستدلال مُحسّنة](https://huggingface.co/docs/optimum/main/en/onnxruntime/usage_guides/pipelines)، والتي لها نفس واجهة برمجة التطبيقات (API) مثل وظيفة [`pipeline`] في 🤗 Transformers. + +يوفر 🤗 Optimum دعمًا لتصدير ONNX من خلال الاستفادة من كائنات التكوين. تأتي كائنات التكوين هذه جاهزة لعدد من معماريات النماذج، وقد تم تصميمها لتكون قابلة للتوسعة بسهولة إلى معماريات أخرى. + +للاطلاع على قائمة بالتكوينات الجاهزة، يُرجى الرجوع إلى [وثائق 🤗 Optimum](https://huggingface.co/docs/optimum/exporters/onnx/overview). + +هناك طريقتان لتصدير نموذج 🤗 Transformers إلى ONNX، نعرض هنا كليهما: + +- التصدير باستخدام 🤗 Optimum عبر واجهة سطر الأوامر (CLI). +- التصدير باستخدام 🤗 Optimum مع `optimum.onnxruntime`. + +### تصدير نموذج 🤗 Transformers إلى ONNX باستخدام واجهة سطر الأوامر + +لتصدير نموذج 🤗 Transformers إلى ONNX، قم أولاً بتثبيت اعتماد إضافي: + +```bash +pip install optimum[exporters] +``` + +للاطلاع على جميع المعامﻻت المتاحة، يرجى الرجوع إلى [وثائق 🤗 Optimum](https://huggingface.co/docs/optimum/exporters/onnx/usage_guides/export_a_model#exporting-a-model-to-onnx-using-the-cli)، أو عرض المساعدة في سطر الأوامر: + +```bash +optimum-cli export onnx --help +``` +```bash +optimum-cli export onnx --help +``` + +لتصدير نقطة تفتيش نموذج من 🤗 Hub، على سبيل المثال، `distilbert/distilbert-base-uncased-distilled-squad`، قم بتشغيل الأمر التالي: + +```bash +optimum-cli export onnx --model distilbert/distilbert-base-uncased-distilled-squad distilbert_base_uncased_squad_onnx/ +``` + +يجب أن تشاهد السجلات التي تشير إلى التقدم المحرز وتظهر المكان الذي تم فيه حفظ ملف `model.onnx` الناتج، مثل هذا: + +```bash +Validating ONNX model distilbert_base_uncased_squad_onnx/model.onnx... + -[✓] ONNX model output names match reference model (start_logits, end_logits) + - Validating ONNX Model output "start_logits": + -[✓] (2, 16) matches (2, 16) + -[✓] all values close (atol: 0.0001) + - Validating ONNX Model output "end_logits": + -[✓] (2, 16) matches (2, 16) + -[✓] all values close (atol: 0.0001) +The ONNX export succeeded and the exported model was saved at: distilbert_base_uncased_squad_onnx +``` + +يوضح المثال أعلاه تصدير نقطة تفتيش من 🤗 Hub. عند تصدير نموذج محلي، تأكد أولاً من حفظ ملفات أوزان النموذج ومحول الرموز في نفس الدليل (`local_path`). عند استخدام واجهة سطر الأوامر، قم بتمرير `local_path` إلى وسيط `model` بدلاً من اسم نقطة التفتيش على 🤗 Hub وقدم وسيط `--task`. يمكنك مراجعة قائمة المهام المدعومة في [وثائق 🤗 Optimum](https://huggingface.co/docs/optimum/exporters/task_manager). إذا لم يتم توفير وسيط `task`، فسيتم تعيينه افتراضيًا إلى هندسة النموذج دون أي رأس محدد للمهمة. + +```bash +optimum-cli export onnx --model local_path --task question-answering distilbert_base_uncased_squad_onnx/ +``` + +يمكن بعد ذلك تشغيل ملف `model.onnx` الناتج على أحد [المسرعات](https://onnx.ai/supported-tools.html#deployModel) العديدة التي تدعم معيار ONNX. على سبيل المثال، يمكننا تحميل النموذج وتشغيله باستخدام [ONNX Runtime](https://onnxruntime.ai/) كما يلي: + +```python +>>> from transformers import AutoTokenizer +>>> from optimum.onnxruntime import ORTModelForQuestionAnswering + +>>> tokenizer = AutoTokenizer.from_pretrained("distilbert_base_uncased_squad_onnx") +>>> model = ORTModelForQuestionAnswering.from_pretrained("distilbert_base_uncased_squad_onnx") +>>> inputs = tokenizer("What am I using?", "Using DistilBERT with ONNX Runtime!", return_tensors="pt") +>>> outputs = model(**inputs) +``` + +تكون العملية مماثلة بالنسبة إلى نقاط تفتيش TensorFlow على Hub. على سبيل المثال، إليك كيفية تصدير نقطة تفتيش TensorFlow نقية من [منظمة Keras](https://huggingface.co/keras-io): + +```bash +optimum-cli export onnx --model keras-io/transformers-qa distilbert_base_cased_squad_onnx/ +``` + +### تصدير نموذج 🤗 Transformers إلى ONNX باستخدام `optimum.onnxruntime` + +كبديل لواجهة سطر الأوامر، يُمكنك تصدير نموذج 🤗 Transformers إلى ONNX برمجيًا كما يلي: + +```python +>>> from optimum.onnxruntime import ORTModelForSequenceClassification +>>> from transformers import AutoTokenizer + +>>> model_checkpoint = "distilbert_base_uncased_squad" +>>> save_directory = "onnx/" + +>>> # تحميل نموذج من transformers وتصديره إلى ONNX +>>> ort_model = ORTModelForSequenceClassification.from_pretrained(model_checkpoint, export=True) +>>> tokenizer = AutoTokenizer.from_pretrained(model_checkpoint) + +>>> # حفظ نموذج onnx ومجزىء النصوص +>>> ort_model.save_pretrained(save_directory) +>>> tokenizer.save_pretrained(save_directory) +``` + +### تصدير نموذج لهندسة غير مدعومة + +إذا كنت ترغب في المساهمة من خلال إضافة دعم لنموذج لا يُمكن تصديره حاليًا، فيجب عليك أولاً التحقق مما إذا كان مدعومًا في [`optimum.exporters.onnx`](https://huggingface.co/docs/optimum/exporters/onnx/overview)، وإذا لم يكن مدعومًا، [فيمكنك المساهمة في 🤗 Optimum](https://huggingface.co/docs/optimum/exporters/onnx/usage_guides/contribute) مُباشرةً. + +### تصدير نموذج باستخدام `transformers.onnx` + + + +لم يعد يتم دعم `transformers.onnx` يُرجى تصدير النماذج باستخدام 🤗 Optimum كما هو موضح أعلاه. سيتم إزالة هذا القسم في الإصدارات القادمة. + + + +لتصدير نموذج 🤗 Transformers إلى ONNX باستخدام `transformers.onnx`، ثبّت التبعيات الإضافية: + +```bash +pip install transformers[onnx] +``` + +استخدم حزمة `transformers.onnx` كنموذج Python لتصدير نقطة حفظ باستخدام تكوين جاهز: + +```bash +python -m transformers.onnx --model=distilbert/distilbert-base-uncased onnx/ +``` + +يُصدّر هذا رسمًا بيانيًا ONNX لنقطة الحفظ المُحددة بواسطة وسيطة `--model`. مرر أي نقطة حفظ على 🤗 Hub أو نقطة حفظ مُخزنة محليًا. +يُمكن بعد ذلك تشغيل ملف `model.onnx` الناتج على أحد المُسرعات العديدة التي تدعم معيار ONNX. على سبيل المثال، قم بتحميل وتشغيل النموذج باستخدام ONNX Runtime كما يلي: + +```python +>>> from transformers import AutoTokenizer +>>> from onnxruntime import InferenceSession + +>>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased") +>>> session = InferenceSession("onnx/model.onnx") +>>> # يتوقع ONNX Runtime مصفوفات NumPy كمدخلات +>>> inputs = tokenizer("Using DistilBERT with ONNX Runtime!", return_tensors="np") +>>> outputs = session.run(output_names=["last_hidden_state"], input_feed=dict(inputs)) +``` + +يُمكن الحصول على أسماء المخرجات المطلوبة (مثل `["last_hidden_state"]`) من خلال إلقاء نظرة على تكوين ONNX لكل نموذج. على سبيل المثال، بالنسبة لـ DistilBERT، لدينا: + +```python +>>> from transformers.models.distilbert import DistilBertConfig, DistilBertOnnxConfig + +>>> config = DistilBertConfig() +>>> onnx_config = DistilBertOnnxConfig(config) +>>> print(list(onnx_config.outputs.keys())) +["last_hidden_state"] +``` + +العمليات مُتطابقة لنقاط الحفظ TensorFlow على Hub. على سبيل المثال، صدّر نقطة حفظ TensorFlow خالصة كما يلي: + +```bash +python -m transformers.onnx --model=keras-io/transformers-qa onnx/ +``` + +لتصدير نموذج مُخزن محليًا، احفظ أوزان النموذج ومجزىء اللغوى في نفس الدليل (على سبيل المثال `local-pt-checkpoint`)، ثم قم بتصديره إلى ONNX عن طريق توجيه وسيط `--model` لحزمة `transformers.onnx` إلى الدليل المطلوب: + +```bash +python -m transformers.onnx --model=local-pt-checkpoint onnx/ +``` \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/task_summary.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/task_summary.md new file mode 100644 index 0000000000000000000000000000000000000000..d6a9d1477e10fce12c5bcf2bda9c92635b4cd985 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/task_summary.md @@ -0,0 +1,323 @@ +# ما الذي تستطيع مكتبة 🤗 Transformers القيام به؟ + +مكتبة 🤗 Transformers هي مجموعة من النماذج المُدرّبة مسبقًا الأفضل في فئتها لمهام معالجة اللغة الطبيعية (NLP)، ورؤية الحاسوب، ومعالجة الصوت والكلام. لا تحتوي المكتبة فقط على نماذج المحولات (Transformer) فحسب، بل تشمل أيضًا نماذج أخرى لا تعتمد على المحولات مثل الشبكات العصبية التلافيفية الحديثة لمهام رؤية الحاسوب. إذا نظرت إلى بعض المنتجات الاستهلاكية الأكثر شيوعًا اليوم، مثل الهواتف الذكية والتطبيقات وأجهزة التلفاز، فمن المحتمل أن تقف وراءها تقنية ما من تقنيات التعلم العميق. هل تريد إزالة جسم من خلفية صورة التقطتها بهاتفك الذكي؟ هذا مثال على مهمة التجزئة البانورامية (Panoptic Segmentation) ( لا تقلق إذا لم تفهم معناها بعد، فسوف نشرحها في الأقسام التالية!). + +توفر هذه الصفحة نظرة عامة على مختلف مهام الكلام والصوت ورؤية الحاسوب ومعالجة اللغات الطبيعية المختلفة التي يمكن حلها باستخدام مكتبة 🤗 Transformers في ثلاثة أسطر فقط من التعليمات البرمجية! + +## الصوت + +تختلف مهام معالجة الصوت والكلام قليلاً عن باقي الوسائط، ويرجع ذلك ببشكل أساسي لأن الصوت كمدخل هو إشارة متصلة. على عكس النص، لا يمكن تقسيم الموجة الصوتية الخام بشكل مرتب في أجزاء منفصلة بالطريقة التي يمكن بها تقسيم الجملة إلى كلمات. وللتغلب على هذا، يتم عادةً أخذ عينات من الإشارة الصوتية الخام على فترات زمنية منتظمة. كلما زاد عدد العينات التي تؤخذ في فترة زمنية معينة، ارتفع معدل أخذ العينات (معدل التردد)، وصار الصوت أقرب إلى مصدر الصوت الأصلي. + +قامت الطرق السابقة بمعالجة الصوت لاستخراج الميزات المفيدة منه. أصبح من الشائع الآن البدء بمهام معالجة الصوت والكلام عن طريق تغذية شكل الموجة الصوتية الخام مباشرة في مشفر الميزات (Feature Encoder) لاستخراج تمثيل صوتي له. وهذا يبسط خطوة المعالجة المسبقة ويسمح للنموذج بتعلم أهم الميزات. + +### تصنيف الصوت + +تصنيف الصوت (Audio Classification) هو مهمة يتم فيها تصنيف بيانات الصوت الصوت من مجموعة محددة مسبقًا من الفئات. إنه فئة واسعة تضم العديد من التطبيقات المحددة، والتي تشمل: + +* تصنيف المشهد الصوتي: وضع علامة على الصوت باستخدام تسمية المشهد ("المكتب"، "الشاطئ"، "الملعب") +* اكتشاف الأحداث الصوتية: وضع علامة على الصوت باستخدام تسمية حدث صوتي ("بوق السيارة"، "صوت الحوت"، "كسر زجاج") +* الوسم: وصنيف صوت يحتوي على أصوات متعددة (أصوات الطيور، وتحديد هوية المتحدث في اجتماع) +* تصنيف الموسيقى: وضع علامة على الموسيقى بتسمية النوع ("ميتال"، "هيب هوب"، "كانتري") + +```py +>>> from transformers import pipeline + +>>> classifier = pipeline(task="audio-classification", model="superb/hubert-base-superb-er") +>>> preds = classifier("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac") +>>> preds = [{"score": round(pred["score"], 4), "label": pred["label"]} for pred in preds] +>>> preds +[{'score': 0.4532, 'label': 'hap'}, + {'score': 0.3622, 'label': 'sad'}, + {'score': 0.0943, 'label': 'neu'}, + {'score': 0.0903, 'label': 'ang'}] +``` + +### التعرف التلقائي على الكلام + +يقوم التعرف التلقائي على الكلام (ASR) هو عملية تحويل الكلام إلى نص. إنه أحد أكثر المهام الصوتية شيوعًا ويرجع ذلك جزئيًا إلى أن الكلام وسيلة طبيعية للتواصل البشري. واليوم، يتم تضمين أنظمة ASR في منتجات التقنية "الذكية" مثل مكبرات الصوت والهواتف والسيارات. يمكننا أن نطلب من مساعدينا الافتراضيين تشغيل الموسيقى، وضبط التذكيرات، وإخبارنا بأحوال الطقس. +ولكن أحد التحديات الرئيسية التي ساعدت نماذج المحولات (Transformer) في التغلب عليها هو التعامل مع اللغات منخفضة الموارد. فمن خلال التدريب المسبق على كميات كبيرة من بيانات الصوتية، يُمكن ضبط النموذج بدقة (Fine-tuning) باستخدام ساعة واحدة فقط من بيانات الكلام المُوسم في لغة منخفضة الموارد إلى نتائج عالية الجودة مقارنة بأنظمة ASR السابقة التي تم تدريبها على بيانات موسومة أكثر بـ 100 مرة. + +```py +>>> from transformers import pipeline + +>>> transcriber = pipeline(task="automatic-speech-recognition", model="openai/whisper-small") +>>> transcriber("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac") +{'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.'} +``` + +## رؤية الحاسب + +كانت إحدى أوائل مهام رؤية الحاسب وأنجحها هى التعرف على صور أرقام الرموز البريدية باستخدام [شبكة عصبية تلافيفية (CNN)](glossary#convolution). تتكون الصورة من وحدات بيكسل، ولكل بكسل قيمة رقمية. وهذا يجعل من السهل تمثيل صورة كمصفوفة من قيم البكسل. يصف كل مزيج معين من قيم البكسل ألوان الصورة. + +هناك طريقتان عامتان يمكن من خلالهما حل مهام رؤية الحاسب: + +1. استخدام الالتفافات (Convolutions) لتعلم الميزات الهرمية للصورة بدءًا من الميزات منخفضة المستوى وصولًا إلى الأشياء المجردة عالية المستوى. +2. تقسيم الصورة إلى أجزاء واستخدام نموذج المحولات (Transformer) ليتعلم تدريجياً كيف ترتبط كل جزء صورة ببعضها البعض لتشكيل صورة. على عكس النهج ا التصاعدي (Bottom-Up) الذي تفضله الشبكات العصبية التلافيفية CNN، هذا يشبه إلى حد ما البدء بصورة ضبابية ثم جعلها أوضح تدريجيًا. + +### تصنيف الصور + +يقوم تصنيف الصور (Image Classification) بوضع علامة على صورة كاملة من مجموعة محددة مسبقًا من الفئات. مثل معظم مهام التصنيف، هناك العديد من التطبيقات العملية لتصنيف الصور، والتي تشمل: + +* الرعاية الصحية: تصنيف الصور الطبية للكشف عن الأمراض أو مراقبة صحة المريض +* البيئة: تصنيف صور الأقمار الصناعية لرصد إزالة الغابات، أو إبلاغ إدارة الأراضي البرية أو اكتشاف حرائق الغابات +* الزراعة: تصنيفر المحاصيل لمراقبة صحة النبات أو صور الأقمار الصناعية لمراقبة استخدام الأراضي +* علم البيئة: تصنيف صور الأنواع الحيوانية أو النباتية لرصد أعداد الكائنات الحية أو تتبع الأنواع المهددة بالانقراض + +```py +>>> from transformers import pipeline + +>>> classifier = pipeline(task="image-classification") +>>> preds = classifier( +... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg" +... ) +>>> preds = [{"score": round(pred["score"], 4), "label": pred["label"]} for pred in preds] +>>> print(*preds, sep="\n") +{'score': 0.4335, 'label': 'lynx, catamount'} +{'score': 0.0348, 'label': 'cougar, puma, catamount, mountain lion, painter, panther, Felis concolor'} +{'score': 0.0324, 'label': 'snow leopard, ounce, Panthera uncia'} +{'score': 0.0239, 'label': 'Egyptian cat'} +{'score': 0.0229, 'label': 'tiger cat'} +``` + +### كشف الأجسام + +على عكس تصنيف الصور، يقوم كشف الأجسام (Object Detection) بتحديد عدة أجسام داخل صورة ومواضع هذه الأجسام في صورة (يحددها مربع الإحاطة). بعض تطبيقات كشف الأجسام تشمل: + +* المركبات ذاتية القيادة: اكتشاف أجسام المرورية اليومية مثل المركبات الأخرى والمشاة وإشارات المرور +* الاستشعار عن بُعد: مراقبة الكوارث، والتخطيط الحضري، والتنبؤ بالطقس +* اكتشاف العيوب: اكتشاف الشقوق أو الأضرار الهيكلية في المباني، وعيوب التصنيع + +```py +>>> from transformers import pipeline + +>>> detector = pipeline(task="object-detection") +>>> preds = detector( +... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg" +... ) +>>> preds = [{"score": round(pred["score"], 4), "label": pred["label"], "box": pred["box"]} for pred in preds] +>>> preds +[{'score': 0.9865, + 'label': 'cat', + 'box': {'xmin': 178, 'ymin': 154, 'xmax': 882, 'ymax': 598}}] +``` + +### تجزئة الصور + +تجزئة الصورة (Image Segmentation) هي مهمة على مستوى البكسل تقوم بتخصيص كل بكسل في صورة لفئة معينة. إنه يختلف عن كشف الأجسام، والذي يستخدم مربعات الإحاطة (Bounding Boxes) لتصنيف والتنبؤ بالأجسام في الصورة لأن التجزئة أكثر دقة. يمكن لتجزئة الصور اكتشاف الأجسام على مستوى البكسل. هناك عدة أنواع من تجزئة الصور: + +* تجزئة مثيلات (Instance Segmentation): بالإضافة إلى تصنيف فئة كائن، فإنها تُصنّف أيضًا كل مثيل (Instance) مميز لكائن ("الكلب-1"، "الكلب-2") +* التجزئة البانورامية (Panoptic Segmentation): مزيج من التجزئة الدلالية (Semantic Segmentation) وتجزئة المثيلات؛ فهو تُصنّف كل بكسل مع فئة دلالية **و** كل مثيل مميز لكائن + +تُعد مهام تجزئة الصور مفيدة في المركبات ذاتية القيادة على إنشاء خريطة على مستوى البكسل للعالم من حولها حتى تتمكن من التنقل بأمان حول المشاة والمركبات الأخرى. كما أنها مفيدة للتصوير الطبي، حيث يمكن للدقة العالية لهذ المهمة أن تساعد في تحديد الخلايا غير الطبيعية أو خصائص الأعضاء. يمكن أيضًا استخدام تجزئة الصور في التجارة الإلكترونية لتجربة الملابس افتراضيًا أو إنشاء تجارب الواقع المُعزز من خلال تراكب الأجسام في العالم الحقيقي من خلال الكاميرا الهاتف الخاصة بك. + +```py +>>> from transformers import pipeline + +>>> segmenter = pipeline(task="image-segmentation") +>>> preds = segmenter( +... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg" +... ) +>>> preds = [{"score": round(pred["score"], 4), "label": pred["label"]} for pred in preds] +>>> print(*preds, sep="\n") +{'score': 0.9879, 'label': 'LABEL_184'} +{'score': 0.9973, 'label': 'snow'} +{'score': 0.9972, 'label': 'cat'} +``` + +### تقدير العمق + +يقوم تقدير العمق (Depth Estimation) بالتنبؤ بمسافة كل بكسل في صورة من الكاميرا. تُعد هذه المهمة لرؤية الحاسب هذه مهمة بشكل خاص لفهم وإعادة بناء المشهد. فعلى سبيل المثال، في السيارات ذاتية القيادة، تحتاج المركبات إلى فهم مدى بُعد الأجسام مثل المشاة ولافتات المرور والمركبات الأخرى لتجنب العقبات والاصطدامات. تساعد معلومات العمق أيضًا في بناء التمثيلات ثلاثية الأبعاد من الصور ثنائية الأبعاد ويمكن استخدامها لإنشاء تمثيلات ثلاثية الأبعاد عالية الجودة للهياكل البيولوجية أو المباني. + +هناك نهجان لتقدير العمق: + +* التصوير المجسم (Stereo): يتم تقدير العمق عن طريق مقارنة صورتين لنفس الصورة من زوايا مختلفة قليلاً. +* التصوير الأحادي (Monocular): يتم تقدير العمق من صورة واحدة. + +```py +>>> from transformers import pipeline + +>>> depth_estimator = pipeline(task="depth-estimation") +>>> preds = depth_estimator( +... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg" +... ) +``` + +## معالجة اللغات الطبيعية + +تُعد مهام معالجة اللغة الطبيعية (NLP) من بين أكثر أنواع المهام شيوعًا نظرًا لأن النص هو وسيلة طبيعية لنا للتواصل. ولكي يتمكن النموذج من فهم النص، يجب أولًا تحويله إلى صيغة رقمية. وهذا يعني تقسيم سلسلة النص إلى كلمات أو مقاطع كلمات منفصلة (رموز - Tokens)، ثم تحويل هذه الرموز إلى أرقام. ونتيجة لذلك، يمكنك تمثيل سلسلة من النص كتسلسل من الأرقام، وبمجرد حصولك على تسلسل من الأرقام، يمكن إدخاله إلى نموذج لحل جميع أنواع مهام معالجة اللغة الطبيعية! + +### تصنيف النصوص + +تمامًا مثل مهام التصنيف في أي مجال آخر، يقوم تصنيف النصوص (Text Classification) بتصنيف سلسلة نصية يمكن أن تكون جملة أو فقرة أو مستند) إلى فئة محددة مسبقًا. هناك العديد من التطبيقات العملية لتصنيف النصوص، والتي تشمل: + +* تحليل المشاعر (Sentiment Analysis): تصنيف النص وفقًا لمعيار معين مثل `الإيجابية` أو `السلبية` والتي يمكن أن تُعلم وتدعم عملية صنع القرار في مجالات مثل السياسة والتمويل والتسويق +* تصنيف المحتوى (Content Classification): تصنيف النص وفقًا لبعض الموضوعات للمساعدة في تنظيم وتصفية المعلومات في الأخبار وموجزات الوسائط الاجتماعية (`الطقس`، `الرياضة`، `التمويل`، إلخ). + +```py +>>> from transformers import pipeline + +>>> classifier = pipeline(task="sentiment-analysis") +>>> preds = classifier("Hugging Face is the best thing since sliced bread!") +>>> preds = [{"score": round(pred["score"], 4), "label": pred["label"]} for pred in preds] +>>> preds +[{'score': 0.9991, 'label': 'POSITIVE'}] +``` + +### تصنيف الرموز + +في أي مهمة من مهام معالجة اللغة الطبيعية NLP، تتم معالجة النص مسبقًا عن طريق تقسيمه إلى كلمات أو مقاطع كلمات فردية تُعرف باسم [الرموز](glossary#token). يقوم تصنيف الرموز (Token Classification) بتخصيص تصنيف لكل رمز من مجموعة محددة مسبقًا من التصنيفات. + +هناك نوعان شائعان من تصنيف الرموز: + +* التعرف على الكيانات المسماة (NER): تصنيف الرموز وفقًا لفئة الكيان مثل المنظمة أو الشخص أو الموقع أو التاريخ. يعد NER شائعًا بشكل خاص في الإعدادات الطبية الحيوية، حيث يُمكنه تصنيف الجينات والبروتينات وأسماء الأدوية. +* ترميز الأجزاء اللغوية (POS): تصنيف الرموز وفقًا للدورها النحوي مثل الاسم أو الفعل أو الصفة. POS مفيد لمساعدة أنظمة الترجمة على فهم كيفية اختلاف كلمتين متطابقتين نحويًا (مثل كلمة "عَلَمَ" كاسم و "عَلِمَ" كفعل). + +```py +>>> from transformers import pipeline + +>>> classifier = pipeline(task="ner") +>>> preds = classifier("Hugging Face is a French company based in New York City.") +>>> preds = [ +... { +... "entity": pred["entity"], +... "score": round(pred["score"], 4), +... "index": pred["index"], +... "word": pred["word"], +... "start": pred["start"], +... "end": pred["end"], +... } +... for pred in preds +... ] +>>> print(*preds, sep="\n") +{'entity': 'I-ORG', 'score': 0.9968, 'index': 1, 'word': 'Hu', 'start': 0, 'end': 2} +{'entity': 'I-ORG', 'score': 0.9293, 'index': 2, 'word': '##gging', 'start': 2, 'end': 7} +{'entity': 'I-ORG', 'score': 0.9763, 'index': 3, 'word': 'Face', 'start': 8, 'end': 12} +{'entity': 'I-MISC', 'score': 0.9983, 'index': 6, 'word': 'French', 'start': 18, 'end': 24} +{'entity': 'I-LOC', 'score': 0.999, 'index': 10, 'word': 'New', 'start': 42, 'end': 45} +{'entity': 'I-LOC', 'score': 0.9987, 'index': 11, 'word': 'York', 'start': 46, 'end': 50} +{'entity': 'I-LOC', 'score': 0.9992, 'index': 12, 'word': 'City', 'start': 51, 'end': 55} +``` +### الإجابة على الأسئلة + +تُعدّ مهمة الإجابة عن الأسئلة (Question Answering) مهمة أخرى على مستوى الرموز (Token-Level) تُرجع إجابة لسؤال ما، وقد تعتمد هذه الإجابة على سياق (في النطاق المفتوح - Open-Domain) أو لا تعتمد على سياق (في النطاق المغلق - Closed-Domain). تحدث هذه المهمة عندما نسأل مساعدًا افتراضيًا عن شيء ما، مثل معرفة ما إذا كان مطعمٌ ما مفتوحًا. يمكن أن تُقدّم هذه المهمة أيضًا دعمًا للعملاء أو دعمًا تقنيًا، كما تُساعد محركات البحث في استرجاع المعلومات ذات الصلة التي نبحث عنها. + +هناك نوعان شائعان من الإجابة على الأسئلة: + +* الاستخراجية (Extractive): بالنظر إلى سؤال وسياق مُعيّن، فإن الإجابة هي مقطع نصيّ مُستخرج من السياق الذي يُحلّله النموذج. +* التجريدية (Abstractive): بالنظر إلى سؤال وسياق مُعيّن، يتم إنشاء الإجابة من السياق؛ يتعامل نهج [`Text2TextGenerationPipeline`] مع هذا النهج بدلاً من [`QuestionAnsweringPipeline`] الموضح أدناه + + +```py +>>> from transformers import pipeline + +>>> question_answerer = pipeline(task="question-answering") +>>> preds = question_answerer( +... question="What is the name of the repository?", +... context="The name of the repository is huggingface/transformers", +... ) +>>> print( +... f"score: {round(preds['score'], 4)}, start: {preds['start']}, end: {preds['end']}, answer: {preds['answer']}" +... ) +score: 0.9327, start: 30, end: 54, answer: huggingface/transformers +``` + +### التلخيص + +ينشئ التلخيص (Summarization) نسخة مختصرة من نص طويل مع محاولة الحفاظ على معظم معنى النص الأصلي. التلخيص هو مهمة تسلسل إلى تسلسل(Sequence-to-Sequence)؛؛ فهو تُنتج تسلسلًا نصيًا أقصر من النص المُدخل. هناك الكثير من المستندات الطويلة التي يمكن تلخيصها لمساعدة القراء على فهم النقاط الرئيسية بسرعة. مشاريع القوانين والوثائق القانونية والمالية وبراءات الاختراع والأوراق العلمية هي مجرد أمثلة قليلة للوثائق التي يمكن تلخيصها لتوفير وقت القراء وخدمة كمساعد للقراءة. + +مثل الإجابة على الأسئلة، هناك نوعان من التلخيص: + +* الاستخراجية (Extractive): تحديد واستخراج أهم الجمل من النص الأصلي +* التجريدي (Abstractive): إنشاء ملخص مستهدف (الذي قد يتضمن كلمات جديدة غير موجودة في النص الأصلي) انطلاقًا من النص الأصلي؛ يستخدم نهج التلخيص التجريدي [`SummarizationPipeline`] + +```py +>>> from transformers import pipeline + +>>> summarizer = pipeline(task="summarization") +>>> summarizer( +... "In this work, we presented the Transformer, the first sequence transduction model based entirely on attention, replacing the recurrent layers most commonly used in encoder-decoder architectures with multi-headed self-attention. For translation tasks, the Transformer can be trained significantly faster than architectures based on recurrent or convolutional layers. On both WMT 2014 English-to-German and WMT 2014 English-to-French translation tasks, we achieve a new state of the art. In the former task our best model outperforms even all previously reported ensembles." +... ) +[{'summary_text': ' The Transformer is the first sequence transduction model based entirely on attention . It replaces the recurrent layers most commonly used in encoder-decoder architectures with multi-headed self-attention . For translation tasks, the Transformer can be trained significantly faster than architectures based on recurrent or convolutional layers .'}] +``` + +### الترجمة + +تحوّل الترجمة تسلسل نص بلغة إلى لغة أخرى. من المهم مساعدة الأشخاص من خلفيات مختلفة على التواصل مع بعضهم البعض، ومساعدة المحتوى على الوصول إلى جمهور أوسع، وحتى أن يكون أداة تعليمية لمساعدة الأشخاص على تعلم لغة جديدة. إلى جانب التلخيص، تعد الترجمة مهمة من نوع تسلسل إلى تسلسل، حيث يتلقى النموذج تسلسلًا مُدخلًا ويُعيد تسلسلًا مُخرَجًا مُستهدفًا. + +في الأيام الأولى، كانت نماذج الترجمة في الغالب أحادية اللغة، ولكن مؤخرًا، كان هناك اهتمام متزايد بالنماذج متعددة اللغات التي يمكنها الترجمة بين العديد من أزواج اللغات. + +```py +>>> from transformers import pipeline + +>>> text = "translate English to French: Hugging Face is a community-based open-source platform for machine learning." +>>> translator = pipeline(task="translation", model="google-t5/t5-small") +>>> translator(text) +[{'translation_text': "Hugging Face est une tribune communautaire de l'apprentissage des machines."}] +``` + +### نمذجة اللغة + +نمذجة اللغة (Language Modeling) هي مهمة التنبؤ بالكلمة التالية في تسلسل نصي. لقد أصبح مهمة NLP شائعة للغاية لأن النموذج اللغوي المسبق التدريب يمكن أن يتم ضبطه بشكل دقيق للعديد من مهام الأخرى. في الآونة الأخيرة، كان هناك الكثير من الاهتمام بنماذج اللغة الكبيرة (LLMs) التي توضح التعلم من الصفر أو من عدد قليل من الأمثلة (Zero-shot or Few-shot Learning). وهذا يعني أن النموذج يمكنه حل المهام التي لم يتم تدريبه عليها بشكل صريح! يمكن استخدام نماذج اللغة لإنشاء نص سلس ومقنع، على الرغم من أنه يجب أن تكون حذرًا لأن النص قد لا يكون دائمًا دقيقًا. + +هناك نوعان من نمذجة اللغة: + +* السببية(Causal): هدف النموذج هو التنبؤ بالرمز (Token) التالي في التسلسل، ويتم إخفاء الرموز المستقبلية (Masking). + +```py +>>> from transformers import pipeline + +>>> prompt = "Hugging Face is a community-based open-source platform for machine learning." +>>> generator = pipeline(task="text-generation") +>>> generator(prompt) # doctest: +SKIP +``` + +* المقنّع (Masked): هدف النموذج هو التنبؤ برمز مُخفيّ ضمن التسلسل مع الوصول الكامل إلى الرموز الأخرى في التسلسل + +```py +>>> text = "Hugging Face is a community-based open-source for machine learning." +>>> fill_mask = pipeline(task="fill-mask") +>>> preds = fill_mask(text, top_k=1) +>>> preds = [ +... { +... "score": round(pred["score"], 4), +... "token": pred["token"], +... "token_str": pred["token_str"], +... "sequence": pred["sequence"], +... } +... for pred in preds +... ] +>>> preds +[{'score': 0.2236, + 'token': 1761, + 'token_str': ' platform', + 'sequence': 'Hugging Face is a community-based open-source platform for machine learning.'}] +``` + +## متعدد الوسائط: + +تتطلب المهام متعددة الوسائط (Multimodal) من النموذج معالجة وسائط بيانات متعددة (نص أو صورة أو صوت أو فيديو) لحل مشكلة معينة. يعد وصف الصورة (Image Captioning) مثالاً على مهمة متعددة الوسائط حيث يأخذ النموذج صورة كمدخل وينتج تسلسل نصيًا يصف الصورة أو بعض خصائصها. + +على الرغم من أن النماذج متعددة الوسائط تعمل مع أنواع أو وسائط بيانات مختلفة، إلا أن خطوات المعالجة المسبقة تساعد النموذج داخليًا على تحويل جميع أنواع البيانات إلى متجهات تضمين (Embeddings) (متجهات أو قوائم من الأرقام التي تحتوي على معلومات ذات معنى حول البيانات). بالنسبة لمهمة مثل وصف الصورة، يتعلم النموذج العلاقات بين متجهات تضمين الصور ومتجهات تضمين النص. + +### الإجابة على أسئلة المستندات: + +الإجابة على أسئلة المستندات (Document Question Answering) هي مهمة تقوم بالإجابة على أسئلة اللغة الطبيعية من مستند مُعطى. على عكس مهمة الإجابة على الأسئلة على مستوى الرموز (Token-Level) التي تأخذ نصًا كمدخل، فإن الإجابة على أسئلة المستندات تأخذ صورة لمستند كمدخل بالإضافة إلى سؤال هذا حول المستند وتعيد الإجابة. يمكن استخدام الإجابة على أسئلة المستندات لتفسير المستندات المُنسّقة واستخراج المعلومات الرئيسية منها. في المثال أدناه، يمكن استخراج المبلغ الإجمالي والمبلغ المُسترد من إيصال الدفع.. + +```py +>>> from transformers import pipeline +>>> from PIL import Image +>>> import requests + +>>> url = "https://huggingface.co/datasets/hf-internal-testing/example-documents/resolve/main/jpeg_images/2.jpg" +>>> image = Image.open(requests.get(url, stream=True).raw) + +>>> doc_question_answerer = pipeline("document-question-answering", model="magorshunov/layoutlm-invoices") +>>> preds = doc_question_answerer( +... question="ما هو المبلغ الإجمالي؟", +... image=image, +... ) +>>> preds +[{'score': 0.8531, 'answer': '17,000', 'start': 4, 'end': 4}] +``` + +نأمل أن تكون هذه الصفحة قد زودتك ببعض المعلومات الأساسية حول جميع أنواع المهام في كل طريقة وأهمية كل منها العملية. في القسم التالي، ستتعلم كيف تعمل مكتبة 🤗 Transformers لحل هذه المهام. \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tasks/language_modeling.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tasks/language_modeling.md new file mode 100644 index 0000000000000000000000000000000000000000..24f2db00a7a69a446895fbf3e5c915bece3bc0c1 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tasks/language_modeling.md @@ -0,0 +1,422 @@ + + +# نمذجة اللغة السببية (Causal language modeling) + +[[open-in-colab]] + +هناك نوعان من نمذجة اللغة، السببية والمقنعة. يوضح هذا الدليل نمذجة اللغة السببية. +تُستخدم نماذج اللغة السببية غالبًا لتوليد النص. يمكنك استخدام هذه النماذج للتطبيقات الإبداعية مثل +اختيار مغامرة النص الخاصة بك أو مساعد ترميز ذكي مثل Copilot أو CodeParrot. + + + +تتنبأ نمذجة اللغة السببية بالرمز التالي في تسلسل من الرموز، ولا يمكن للنموذج سوى الاهتمام بالرموز على +اليسار. هذا يعني أن النموذج لا يمكنه رؤية الرموز المستقبلية. GPT-2 هو مثال على نموذج اللغة السببية. + +سيوضح لك هذا الدليل كيفية: + +1. ضبط دقيق [DistilRoBERTa](https://huggingface.co/distilbert/distilroberta-base) على مجموعة فرعية [r/askscience](https://www.reddit.com/r/askscience/) من مجموعة بيانات [ELI5](https://huggingface.co/datasets/eli5). +2. استخدام النموذج المدرب الخاص بك للاستنتاج. + + + +لرؤية جميع العمارات ونقاط التحقق المتوافقة مع هذه المهمة، نوصي بالتحقق من [task-page](https://huggingface.co/tasks/text-generation) + + + +قبل أن تبدأ، تأكد من تثبيت جميع المكتبات الضرورية: + +```bash +pip install transformers datasets evaluate +``` + +نحن نشجعك على تسجيل الدخول إلى حساب Hugging Face الخاص بك حتى تتمكن من تحميل ومشاركة نموذجك مع المجتمع. عند المطالبة، أدخل رمزك لتسجيل الدخول: + +```py +>>> from huggingface_hub import notebook_login + +>>> notebook_login() +``` + +## تحميل مجموعة بيانات ELI5 + +ابدأ بتحميل أول 5000 مثال من [ELI5-Category](https://huggingface.co/datasets/eli5_category) مجموعة البيانات مع مكتبة 🤗 Datasets. سيعطيك هذا فرصة للتجربة والتأكد من أن كل شيء يعمل قبل قضاء المزيد من الوقت في التدريب على مجموعة البيانات الكاملة. + +```py +>>> from datasets import load_dataset + +>>> eli5 = load_dataset("eli5_category", split="train[:5000]") +``` + +قم بتقسيم مجموعة بيانات `train` إلى مجموعتي تدريب واختبار باستخدام الخاصية [`~datasets.Dataset.train_test_split`]: + +```py +>>> eli5 = eli5.train_test_split(test_size=0.2) +``` + +ثم ألق نظرة على مثال: + +```py +>>> eli5["train"][0] +{'q_id': '7h191n', + 'title': 'What does the tax bill that was passed today mean? How will it affect Americans in each tax bracket?', + 'selftext': '', + 'category': 'Economics', + 'subreddit': 'explainlikeimfive', + 'answers': {'a_id': ['dqnds8l', 'dqnd1jl', 'dqng3i1', 'dqnku5x'], + 'text': ["The tax bill is 500 pages long and there were a lot of changes still going on right to the end. It's not just an adjustment to the income tax brackets, it's a whole bunch of changes. As such there is no good answer to your question. The big take aways are: - Big reduction in corporate income tax rate will make large companies very happy. - Pass through rate change will make certain styles of business (law firms, hedge funds) extremely happy - Income tax changes are moderate, and are set to expire (though it's the kind of thing that might just always get re-applied without being made permanent) - People in high tax states (California, New York) lose out, and many of them will end up with their taxes raised.", + 'None yet. It has to be reconciled with a vastly different house bill and then passed again.', + 'Also: does this apply to 2017 taxes? Or does it start with 2018 taxes?', + 'This article explains both the House and senate bills, including the proposed changes to your income taxes based on your income level. URL_0'], + 'score': [21, 19, 5, 3], + 'text_urls': [[], + [], + [], + ['https://www.investopedia.com/news/trumps-tax-reform-what-can-be-done/']]}, + 'title_urls': ['url'], + 'selftext_urls': ['url']} +``` + +على الرغم من أن هذا قد يبدو معقدًا، إلا أنك مهتم حقًا بحقل `text`. ما هو رائع حول مهام نمذجة اللغة +أنت لا تحتاج إلى تسميات (تُعرف أيضًا باسم المهمة غير الخاضعة للإشراف) لأن الكلمة التالية تعمل كتسمية. + +## معالجة مسبقة (Preprocess) + + + +الخطوة التالية هي تحميل مجزء النص DistilGPT2 لمعالجة حقل `text` الفرعي: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2") +``` + +ستلاحظ من المثال أعلاه، الحقل `text` هو في الواقع متداخل داخل `answers`. هذا يعني أنك ستحتاج إلى +استخراج حقل `text` الفرعي من بنيته المتداخلة باستخدام الدالة [`flatten`](https://huggingface.co/docs/datasets/process#flatten): + +```py +>>> eli5 = eli5.flatten() +>>> eli5["train"][0] +{'q_id': '7h191n', + 'title': 'What does the tax bill that was passed today mean? How will it affect Americans in each tax bracket?', + 'selftext': '', + 'category': 'Economics', + 'subreddit': 'explainlikeimfive', + 'answers.a_id': ['dqnds8l', 'dqnd1jl', 'dqng3i1', 'dqnku5x'], + 'answers.text': ["The tax bill is 500 pages long and there were a lot of changes still going on right to the end. It's not just an adjustment to the income tax brackets, it's a whole bunch of changes. As such there is no good answer to your question. The big take aways are: - Big reduction in corporate income tax rate will make large companies very happy. - Pass through rate change will make certain styles of business (law firms, hedge funds) extremely happy - Income tax changes are moderate, and are set to expire (though it's the kind of thing that might just always get re-applied without being made permanent) - People in high tax states (California, New York) lose out, and many of them will end up with their taxes raised.", + 'None yet. It has to be reconciled with a vastly different house bill and then passed again.', + 'Also: does this apply to 2017 taxes? Or does it start with 2018 taxes?', + 'This article explains both the House and senate bills, including the proposed changes to your income taxes based on your income level. URL_0'], + 'answers.score': [21, 19, 5, 3], + 'answers.text_urls': [[], + [], + [], + ['https://www.investopedia.com/news/trumps-tax-reform-what-can-be-done/']], + 'title_urls': ['url'], + 'selftext_urls': ['url']} +``` + +كل حقل فرعي هو الآن عموداً منفصلاً مسبوقاً بـ `answers`، وحقل `text` هو قائمة الآن. بدلاً من ذلك +من تجزائة نص كل جملة بشكل منفصل، قم بتحويل القائمة إلى سلسلة حتى تتمكن من تجزئة نصها بشكل مجمّع. + +هنا أول دالة معالجة مسبقة لدمج قائمة السلاسل لكل مثال ومجزىء النتيجة: + +```py +>>> def preprocess_function(examples): +... return tokenizer([" ".join(x) for x in examples["answers.text"]]) +``` + +لتطبيق دالة المعالجة المسبقة هذه على مجموعة البيانات بأكملها، استخدم الدالة 🤗 Datasets [`~datasets.Dataset.map`]. يمكنك تسريع هذه العملية `map` عن طريق تعيين `batched=True` لمعالجة عناصر متعددة من مجموعة البيانات في وقت واحد، وزيادة عدد العمليات مع `num_proc`. احذف أي أعمدة لا تحتاجها: + +```py +>>> tokenized_eli5 = eli5.map( +... preprocess_function, +... batched=True, +... num_proc=4, +... remove_columns=eli5["train"].column_names, +... ) +``` + +تحتوي هذه المجموعة من البيانات على تسلسلات الرموز، ولكن بعضها أطول من الطول الأقصى للمدخلات للنموذج. + +يمكنك الآن استخدام دالة ما قبل المعالجة ثانية لـ: + +- تجميع كل التسلسلات. +- تقسيم التسلسلات المجمّعة إلى أجزاء أقصر محددة، بحجم `block_size`، والتي يجب أن تكون أقصر من الطول الأقصى للمدخلات ومناسبة لذاكرة GPU. + +```py +>>> block_size = 128 + +>>> def group_texts(examples): +... # ربط جميع النصوص. +... concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()} +... total_length = len(concatenated_examples[list(examples.keys())[0]]) +... # نتجاهل الباقي الصغير، يمكننا إضافة الحشو إذا كان النموذج يدعمه بدلاً من هذا الإسقاط، يمكنك +... # تخصيص هذا الجزء حسب احتياجاتك. +... if total_length >= block_size: +... total_length = (total_length // block_size) * block_size +... # التقسيم إلى أجزاء بحجم block_size. +... result = { +... k: [t[i : i + block_size] for i in range(0, total_length, block_size)] +... for k, t in concatenated_examples.items() +... } +... result["labels"] = result["input_ids"].copy() +... return result +``` + +طبق دالة `group_texts` على كامل المجموعة من البيانات: + +```py +>>> lm_dataset = tokenized_eli5.map(group_texts, batched=True, num_proc=4) +``` + +الآن قم بإنشاء دفعة من الأمثلة باستخدام [`DataCollatorForLanguageModeling`]. من الأفضل أن تقوم بـ *الحشو الديناميكي* للجمل إلى الطول الأطول في الدفعة أثناء التجميع، بدلاً من حشو كامل المجموعة من البيانات إلى الطول الأقصى. + + + +استخدم رمز نهاية التسلسل كرمز للحشو، وحدد `mlm_probability` لحجب الرموز بشكل عشوائي عند كل تكرار للبيانات: + +```py +>>> from transformers import DataCollatorForLanguageModeling + +>>> tokenizer.pad_token = tokenizer.eos_token +>>> data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False) +``` + + + +استخدم رمز نهاية التسلسل كرمز للحشو، وحدد `mlm_probability` لحجب الرموز بشكل عشوائي عند كل تكرار للبيانات: + +```py +>>> from transformers import DataCollatorForLanguageModeling + +>>> data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False, return_tensors="tf") +``` + + + + +## التدريب (Train) + + + + + + +إذا لم تكن على دراية بتدريب نموذج باستخدام [`Trainer`], اطلع على [البرنامج التعليمي الأساسي](../training#train-with-pytorch-trainer)! + + + +أنت جاهز الآن لبدء تدريب نموذجك! قم بتحميل DistilGPT2 باستخدام [`AutoModelForCausalLM`]: + +```py +>>> from transformers import AutoModelForCausalLM, TrainingArguments, Trainer + +>>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2") +``` + +في هذه المرحلة، تبقى ثلاث خطوات فقط: + +1. حدد معلمات التدريب الخاصة بك في [`TrainingArguments`]. المعامل الوحيد المطلوب هو `output_dir` الذي يحدد أين سيتم حفظ نموذجك. ستقوم بدفع هذا النموذج إلى Hub بتحديد `push_to_hub=True` (يجب أن تكون مسجلاً الدخول إلى Hugging Face لتحميل نموذجك). +2. قم بتمرير معاملات التدريب إلى [`Trainer`] إلى جانب النموذج، والمجموعات من البيانات، ومجمّع البيانات. +3. قم باستدعاء [`~Trainer.train`] لتدريب نموذجك. + +```py +>>> training_args = TrainingArguments( +... output_dir="my_awesome_eli5_clm-model", +... eval_strategy="epoch", +... learning_rate=2e-5, +... weight_decay=0.01, +... push_to_hub=True, +... ) + +>>> trainer = Trainer( +... model=model, +... args=training_args, +... train_dataset=lm_dataset["train"], +... eval_dataset=lm_dataset["test"], +... data_collator=data_collator, +... tokenizer=tokenizer, +... ) + +>>> trainer.train() +``` + +بمجرد اكتمال التدريب، استخدم طريقة [`~transformers.Trainer.evaluate`] لتقييم نموذجك والحصول على احتمالية الارتباك: + +```py +>>> import math + +>>> eval_results = trainer.evaluate() +>>> print(f"Perplexity: {math.exp(eval_results['eval_loss']):.2f}") +Perplexity: 49.61 +``` + +ثم شارك نموذجك على Hub باستخدام طريقة [`~transformers.Trainer.push_to_hub`] حتى يتمكن الجميع من استخدام نموذجك: + +```py +>>> trainer.push_to_hub() +``` + + + + +إذا لم تكن على دراية بتدريب نموذج باستخدام Keras، اطلع على [البرنامج التعليمي الأساسي](../training#train-a-tensorflow-model-with-keras)! + + +لتدريب نموذج في TensorFlow، ابدأ بإعداد دالة المحسن، وجدول معدل التعلم، وبعض معاملات التدريب: + +```py +>>> from transformers import create_optimizer, AdamWeightDecay + +>>> optimizer = AdamWeightDecay(learning_rate=2e-5, weight_decay_rate=0.01) +``` + +ثم يمكنك تحميل DistilGPT2 باستخدام [`TFAutoModelForCausalLM`]: + +```py +>>> from transformers import TFAutoModelForCausalLM + +>>> model = TFAutoModelForCausalLM.from_pretrained("distilbert/distilgpt2") +``` + +حول مجموعات بياناتك إلى تنسيق `tf.data.Dataset` باستخدام [`~transformers.TFPreTrainedModel.prepare_tf_dataset`]: + +```py +>>> tf_train_set = model.prepare_tf_dataset( +... lm_dataset["train"], +... shuffle=True, +... batch_size=16, +... collate_fn=data_collator, +... ) + +>>> tf_test_set = model.prepare_tf_dataset( +... lm_dataset["test"], +... shuffle=False, +... batch_size=16, +... collate_fn=data_collator, +... ) +``` + +قم بتهيئة النموذج للتدريب باستخدام [`compile`](https://keras.io/api/models/model_training_apis/#compile-method). لاحظ أن جميع نماذج Transformers لديها دالة خسارة ذات صلة بالمهمة الافتراضية، لذلك لا تحتاج إلى تحديد واحدة ما لم ترغب في ذلك: + +```py +>>> import tensorflow as tf + +>>> model.compile(optimizer=optimizer) # لا يوجد حجة للخسارة! +``` + +يمكن القيام بذلك عن طريق تحديد مكان دفع نموذجك ومجمّع البيانات في [`~transformers.PushToHubCallback`]: + +```py +>>> from transformers.keras_callbacks import PushToHubCallback + +>>> callback = PushToHubCallback( +... output_dir="my_awesome_eli5_clm-model", +... tokenizer=tokenizer, +... ) +``` + +أخيراً، أنت جاهز لبدء تدريب نموذجك! قم باستدعاء [`fit`](https://keras.io/api/models/model_training_apis/#fit-method) مع مجموعات بيانات التدريب والتحقق من الصحة، وعدد العصور، والتعليقات الخاصة بك لتدريب النموذج: + +```py +>>> model.fit(x=tf_train_set, validation_data=tf_test_set, epochs=3, callbacks=[callback]) +``` + +بمجرد اكتمال التدريب، يتم تحميل نموذجك تلقائيًا إلى Hub حتى يتمكن الجميع من استخدامه! + + + + + +للحصول على مثال أكثر تعمقًا حول كيفية تدريب نموذج للنمذجة اللغوية السببية، اطلع على الدفتر المقابل +[دفتر PyTorch](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling.ipynb) +أو [دفتر TensorFlow](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling-tf.ipynb). + + + +## الاستدلال (Inference) + +رائع، الآن بعد أن قمت بتدريب نموذج، يمكنك استخدامه للاستدلال! + +قم بابتكار سؤال تود توليد نص منه: + +```py +>>> prompt = "Somatic hypermutation allows the immune system to" +``` + +أبسط طريقة لتجربة نموذجك المدرب للاستدلال هي استخدامه في [`pipeline`]. قم بتنفيذ `pipeline` لتوليد النص مع نموذجك، ومرر نصك إليه: + +```py +>>> from transformers import pipeline + +>>> generator = pipeline("text-generation", model="username/my_awesome_eli5_clm-model") +>>> generator(prompt) +[{'generated_text': "Somatic hypermutation allows the immune system to be able to effectively reverse the damage caused by an infection.\n\n\nThe damage caused by an infection is caused by the immune system's ability to perform its own self-correcting tasks."}] +``` + + + +قسم النص وإرجع `input_ids` كتنسورات PyTorch: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("username/my_awesome_eli5_clm-model") +>>> inputs = tokenizer(prompt, return_tensors="pt").input_ids +``` + +استخدم طريقة [`~generation.GenerationMixin.generate`] لتوليد النص. +للمزيد من التفاصيل حول استراتيجيات توليد النص المختلفة والبارامترات للتحكم في التوليد، راجع صفحة [استراتيجيات توليد النص](../generation_strategies). + +```py +>>> from transformers import AutoModelForCausalLM + +>>> model = AutoModelForCausalLM.from_pretrained("username/my_awesome_eli5_clm-model") +>>> outputs = model.generate(inputs, max_new_tokens=100, do_sample=True, top_k=50, top_p=0.95) +``` + +فك ترميز الرموز المولدة مرة أخرى إلى نص: + +```py +>>> tokenizer.batch_decode(outputs, skip_special_tokens=True) +["Somatic hypermutation allows the immune system to react to drugs with the ability to adapt to a different environmental situation. In other words, a system of 'hypermutation' can help the immune system to adapt to a different environmental situation or in some cases even a single life. In contrast, researchers at the University of Massachusetts-Boston have found that 'hypermutation' is much stronger in mice than in humans but can be found in humans, and that it's not completely unknown to the immune system. A study on how the immune system"] +``` + + +قم بتقسيم النص وإرجاع `input_ids` كـ TensorFlow tensors: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("username/my_awesome_eli5_clm-model") +>>> inputs = tokenizer(prompt, return_tensors="tf").input_ids +``` + +استخدم طريقة [`~transformers.generation_tf_utils.TFGenerationMixin.generate`] لإنشاء الملخص. للمزيد من التفاصيل حول استراتيجيات توليد النص المختلفة والبارامترات للتحكم في التوليد، راجع صفحة [استراتيجيات توليد النص](../generation_strategies). + +```py +>>> from transformers import TFAutoModelForCausalLM + +>>> model = TFAutoModelForCausalLM.from_pretrained("username/my_awesome_eli5_clm-model") +>>> outputs = model.generate(input_ids=inputs, max_new_tokens=100, do_sample=True, top_k=50, top_p=0.95) +``` + +فك ترميز الرموز المولدة مرة أخرى إلى نص: + +```py +>>> tokenizer.batch_decode(outputs, skip_special_tokens=True) +['Somatic hypermutation allows the immune system to detect the presence of other viruses as they become more prevalent. Therefore, researchers have identified a high proportion of human viruses. The proportion of virus-associated viruses in our study increases with age. Therefore, we propose a simple algorithm to detect the presence of these new viruses in our samples as a sign of improved immunity. A first study based on this algorithm, which will be published in Science on Friday, aims to show that this finding could translate into the development of a better vaccine that is more effective for'] +``` + + \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tasks/masked_language_modeling.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tasks/masked_language_modeling.md new file mode 100644 index 0000000000000000000000000000000000000000..e8382927d1e6004190ee66da843e41b684fc7971 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tasks/masked_language_modeling.md @@ -0,0 +1,442 @@ + + +# نمذجة اللغة المقنعة (Masked language modeling) + +[[open-in-colab]] + + + +تتنبأ نمذجة اللغة المقنعة برمز مقنع في تسلسل، ويمكن للنموذج الانتباه إلى الرموز بشكل ثنائي الاتجاه. هذا +يعني أن النموذج لديه إمكانية الوصول الكاملة إلى الرموز الموجودة على اليسار واليمين. تعد نمذجة اللغة المقنعة ممتازة للمهام التي +تتطلب فهمًا سياقيًا جيدًا لتسلسل كامل. BERT هو مثال على نموذج لغة مقنع. + +سيوضح لك هذا الدليل كيفية: + +1. تكييف [DistilRoBERTa](https://huggingface.co/distilbert/distilroberta-base) على مجموعة فرعية [r/askscience](https://www.reddit.com/r/askscience/) من مجموعة بيانات [ELI5](https://huggingface.co/datasets/eli5). +2. استخدام نموذج المدرب الخاص بك للاستدلال. + + + +لمعرفة جميع البنى والنسخ المتوافقة مع هذه المهمة، نوصي بالتحقق من [صفحة المهمة](https://huggingface.co/tasks/fill-mask) + + + +قبل أن تبدأ، تأكد من تثبيت جميع المكتبات الضرورية: + +```bash +pip install transformers datasets evaluate +``` + +نحن نشجعك على تسجيل الدخول إلى حساب Hugging Face الخاص بك حتى تتمكن من تحميل ومشاركة نموذجك مع المجتمع. عندما تتم مطالبتك، أدخل رمزك لتسجيل الدخول: + +```py +>>> from huggingface_hub import notebook_login + +>>> notebook_login() +``` + +## تحميل مجموعة بيانات ELI5 + +ابدأ بتحميل أول 5000 مثال من مجموعة بيانات [ELI5-Category](https://huggingface.co/datasets/eli5_category) باستخدام مكتبة 🤗 Datasets. سيعطيك هذا فرصة للتجربة والتأكد من أن كل شيء يعمل قبل قضاء المزيد من الوقت في التدريب على مجموعة البيانات الكاملة. + +```py +>>> from datasets import load_dataset + +>>> eli5 = load_dataset("eli5_category", split="train[:5000]") +``` + +قم بتقسيم مجموعة البيانات `train` إلى مجموعتي تدريب واختبار باستخدام الدالة [`~datasets.Dataset.train_test_split`]: + +```py +>>> eli5 = eli5.train_test_split(test_size=0.2) +``` + +ثم ألق نظرة على مثال: + +```py +>>> eli5["train"][0] +{'q_id': '7h191n', + 'title': 'What does the tax bill that was passed today mean? How will it affect Americans in each tax bracket?', + 'selftext': '', + 'category': 'Economics', + 'subreddit': 'explainlikeimfive', + 'answers': {'a_id': ['dqnds8l', 'dqnd1jl', 'dqng3i1', 'dqnku5x'], + 'text': ["The tax bill is 500 pages long and there were a lot of changes still going on right to the end. It's not just an adjustment to the income tax brackets, it's a whole bunch of changes. As such there is no good answer to your question. The big take aways are: - Big reduction in corporate income tax rate will make large companies very happy. - Pass through rate change will make certain styles of business (law firms, hedge funds) extremely happy - Income tax changes are moderate, and are set to expire (though it's the kind of thing that might just always get re-applied without being made permanent) - People in high tax states (California, New York) lose out, and many of them will end up with their taxes raised.", + 'None yet. It has to be reconciled with a vastly different house bill and then passed again.', + 'Also: does this apply to 2017 taxes? Or does it start with 2018 taxes?', + 'This article explains both the House and senate bills, including the proposed changes to your income taxes based on your income level. URL_0'], + 'score': [21, 19, 5, 3], + 'text_urls': [[], + [], + [], + ['https://www.investopedia.com/news/trumps-tax-reform-what-can-be-done/']]}, + 'title_urls': ['url'], + 'selftext_urls': ['url']} +``` + +على الرغم من أن هذا قد يبدو كثيرًا، إلا أنك مهتم حقًا بحقل `text`. ما هو رائع حول مهام نمذجة اللغة هو أنك لا تحتاج إلى تسميات (تُعرف أيضًا باسم المهمة غير الخاضعة للإشراف) لأن الكلمة التالية *هي* التسمية. + +## معالجة مسبقة (Preprocess) + + + +بالنسبة لنمذجة اللغة المقنعة، فإن الخطوة التالية هي تحميل معالج DistilRoBERTa لمعالجة حقل `text` الفرعي: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilroberta-base") +``` + +ستلاحظ من المثال أعلاه، أن حقل `text` موجود بالفعل داخل `answers`. هذا يعني أنك ستحتاج إلى استخراج حقل `text` الفرعي من بنيته المضمنة باستخدام الدالة [`flatten`](https://huggingface.co/docs/datasets/process#flatten): + +```py +>>> eli5 = eli5.flatten() +>>> eli5["train"][0] +{'q_id': '7h191n', + 'title': 'What does the tax bill that was passed today mean? How will it affect Americans in each tax bracket?', + 'selftext': '', + 'category': 'Economics', + 'subreddit': 'explainlikeimfive', + 'answers.a_id': ['dqnds8l', 'dqnd1jl', 'dqng3i1', 'dqnku5x'], + 'answers.text': ["The tax bill is 500 pages long and there were a lot of changes still going on right to the end. It's not just an adjustment to the income tax brackets, it's a whole bunch of changes. As such there is no good answer to your question. The big take aways are: - Big reduction in corporate income tax rate will make large companies very happy. - Pass through rate change will make certain styles of business (law firms, hedge funds) extremely happy - Income tax changes are moderate, and are set to expire (though it's the kind of thing that might just always get re-applied without being made permanent) - People in high tax states (California, New York) lose out, and many of them will end up with their taxes raised.", + 'None yet. It has to be reconciled with a vastly different house bill and then passed again.', + 'Also: does this apply to 2017 taxes? Or does it start with 2018 taxes?', + 'This article explains both the House and senate bills, including the proposed changes to your income taxes based on your income level. URL_0'], + 'answers.score': [21, 19, 5, 3], + 'answers.text_urls': [[], + [], + [], + ['https://www.investopedia.com/news/trumps-tax-reform-what-can-be-done/']], + 'title_urls': ['url'], + 'selftext_urls': ['url']} +``` + +كل حقل فرعي هو الآن عمود منفصل كما هو موضح بواسطة بادئة `answers`، وحقل `text` هو قائمة الآن. بدلاً من +معالجة كل جملة بشكل منفصل، قم بتحويل القائمة إلى سلسلة حتى تتمكن من معالجتها بشكل مشترك. + +هنا أول دالة معالجة مسبقة لربط قائمة السلاسل لكل مثال ومعالجة النتيجة: + +```py +>>> def preprocess_function(examples): +... return tokenizer([" ".join(x) for x in examples["answers.text"]]) +``` + +لتطبيق دالة المعالجة المسبقة على مجموعة البيانات بأكملها، استخدم الدالة 🤗 Datasets [`~datasets.Dataset.map`]. يمكنك تسريع دالة `map` عن طريق تعيين `batched=True` لمعالجة عدة عناصر في وقت واحد، وزيادة عدد العمليات باستخدام `num_proc`. احذف أي أعمدة غير ضرورية: + +```py +>>> tokenized_eli5 = eli5.map( +... preprocess_function, +... batched=True, +... num_proc=4, +... remove_columns=eli5["train"].column_names, +... ) +``` + + +تحتوي مجموعة البيانات هذه على تسلسلات رمزية، ولكن بعضها أطول من الطول الأقصى للمدخلات للنموذج. + +يمكنك الآن استخدام دالة معالجة مسبقة ثانية لـ: +- تجميع جميع التسلسلات +- تقسيم التسلسلات المجمّعة إلى أجزاء أقصر محددة بـ `block_size`، والتي يجب أن تكون أقصر من الحد الأقصى لطول المدخلات ومناسبة لذاكرة GPU. + +```py +>>> block_size = 128 + +>>> def group_texts(examples): +... # تجميع جميع النصوص. +... concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()} +... total_length = len(concatenated_examples[list(examples.keys())[0]]) +... # نتجاهل الجزء المتبقي الصغير، يمكننا إضافة الحشو إذا كان النموذج يدعمه بدلاً من هذا الإسقاط، يمكنك +... # تخصيص هذا الجزء حسب احتياجاتك. +... if total_length >= block_size: +... total_length = (total_length // block_size) * block_size +... # تقسيمها إلى أجزاء بحجم block_size. +... result = { +... k: [t[i : i + block_size] for i in range(0, total_length, block_size)] +... for k, t in concatenated_examples.items() +... } +... return result +``` + +طبق دالة `group_texts` على مجموعة البيانات بأكملها: + +```py +>>> lm_dataset = tokenized_eli5.map(group_texts, batched=True, num_proc=4) +``` + +الآن، قم بإنشاء دفعة من الأمثلة باستخدام [`DataCollatorForLanguageModeling`]. من الأكثر كفاءة أن تقوم بـ *الحشو الديناميكي* ليصل طولها إلى أطول جملة في الدفعة أثناء التجميع، بدلاً من حشو مجموعة البيانات بأكملها إلى الطول الأقصى. + + + + +استخدم رمز نهاية التسلسل كرمز الحشو وحدد `mlm_probability` لحجب الرموز عشوائياً كل مرة تكرر فيها البيانات: + +```py +>>> from transformers import DataCollatorForLanguageModeling + +>>> tokenizer.pad_token = tokenizer.eos_token +>>> data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm_probability=0.15) +``` + + + +استخدم رمز نهاية التسلسل كرمز الحشو وحدد `mlm_probability` لحجب الرموز عشوائياً كل مرة تكرر فيها البيانات: + +```py +>>> from transformers import DataCollatorForLanguageModeling + +>>> data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm_probability=0.15, return_tensors="tf") +``` + + + +## التدريب (Train) + + + + + + +إذا لم تكن على دراية بتعديل نموذج باستخدام [`Trainer`], ألق نظرة على الدليل الأساسي [هنا](../training#train-with-pytorch-trainer)! + + + +أنت مستعد الآن لبدء تدريب نموذجك! قم بتحميل DistilRoBERTa باستخدام [`AutoModelForMaskedLM`]: + +```py +>>> from transformers import AutoModelForMaskedLM + +>>> model = AutoModelForMaskedLM.from_pretrained("distilbert/distilroberta-base") +``` + +في هذه المرحلة، تبقى ثلاث خطوات فقط: + +1. حدد معلمات التدريب الخاصة بك في [`TrainingArguments`]. المعلمة الوحيدة المطلوبة هي `output_dir` والتي تحدد مكان حفظ نموذجك. ستقوم بدفع هذا النموذج إلى Hub عن طريق تعيين `push_to_hub=True` (يجب أن تكون مسجلاً الدخول إلى Hugging Face لتحميل نموذجك). +2. قم بتمرير معلمات التدريب إلى [`Trainer`] مع النموذج، ومجموعات البيانات، ومجمّع البيانات. +3. قم باستدعاء [`~Trainer.train`] لتعديل نموذجك. + +```py +>>> training_args = TrainingArguments( +... output_dir="my_awesome_eli5_mlm_model", +... eval_strategy="epoch", +... learning_rate=2e-5, +... num_train_epochs=3, +... weight_decay=0.01, +... push_to_hub=True, +... ) + +>>> trainer = Trainer( +... model=model, +... args=training_args, +... train_dataset=lm_dataset["train"], +... eval_dataset=lm_dataset["test"], +... data_collator=data_collator, +... tokenizer=tokenizer, +... ) + +>>> trainer.train() +``` + +بمجرد اكتمال التدريب، استخدم طريقة [`~transformers.Trainer.evaluate`] لتقييم النموذج والحصول على مقياس + الحيرة: + +```py +>>> import math + +>>> eval_results = trainer.evaluate() +>>> print(f"Perplexity: {math.exp(eval_results['eval_loss']):.2f}") +Perplexity: 8.76 +``` + +ثم شارك نموذجك على Hub باستخدام طريقة [`~transformers.Trainer.push_to_hub`] حتى يتمكن الجميع من استخدام نموذجك: + +```py +>>> trainer.push_to_hub() +``` + + + + +إذا لم تكن على دراية بتعديل نموذج باستخدام Keras، ألق نظرة على الدليل الأساسي [هنا](../training#train-a-tensorflow-model-with-keras)! + + +لتعديل نموذج في TensorFlow، ابدأ بإعداد دالة محسن، وجدول معدل التعلم، وبعض معلمات التدريب: + +```py +>>> from transformers import create_optimizer, AdamWeightDecay + +>>> optimizer = AdamWeightDecay(learning_rate=2e-5, weight_decay_rate=0.01) +``` + +ثم يمكنك تحميل DistilRoBERTa باستخدام [`TFAutoModelForMaskedLM`]: + +```py +>>> from transformers import TFAutoModelForMaskedLM + +>>> model = TFAutoModelForMaskedLM.from_pretrained("distilbert/distilroberta-base") +``` + +قم بتحويل مجموعات بياناتك إلى تنسيق `tf.data.Dataset` باستخدام [`~transformers.TFPreTrainedModel.prepare_tf_dataset`]: + +```py +>>> tf_train_set = model.prepare_tf_dataset( +... lm_dataset["train"], +... shuffle=True, +... batch_size=16, +... collate_fn=data_collator, +... ) + +>>> tf_test_set = model.prepare_tf_dataset( +... lm_dataset["test"], +... shuffle=False, +... batch_size=16, +... collate_fn=data_collator, +... ) +``` + +قم بتهيئة النموذج للتدريب باستخدام [`compile`](https://keras.io/api/models/model_training_apis/#compile-method). لاحظ أن نماذج Transformers لديها جميعها دالة خسارة افتراضية ذات صلة بالمهمة، لذلك لا تحتاج إلى تحديد واحدة ما لم تكن تريد ذلك: + +```py +>>> import tensorflow as tf + +>>> model.compile(optimizer=optimizer) # لا توجد حجة للخسارة! +``` + +يمكن القيام بذلك عن طريق تحديد مكان دفع نموذجك ومعالج الرموز في [`~transformers.PushToHubCallback`]: + +```py +>>> from transformers.keras_callbacks import PushToHubCallback + +>>> callback = PushToHubCallback( +... output_dir="my_awesome_eli5_mlm_model", +... tokenizer=tokenizer, +... ) +``` + +أخيراً، أنت مستعد لبدء تدريب نموذجك! قم باستدعاء [`fit`](https://keras.io/api/models/model_training_apis/#fit-method) مع مجموعات بيانات التدريب والتحقق، وعدد العصور، والتعليقات الخاصة بك لتعديل النموذج: + +```py +>>> model.fit(x=tf_train_set, validation_data=tf_test_set, epochs=3, callbacks=[callback]) +``` + +بمجرد اكتمال التدريب، يتم تحميل نموذجك تلقائياً إلى Hub حتى يتمكن الجميع من استخدامه! + + + + + +لمثال أكثر تفصيلاً حول كيفية تعديل نموذج للنمذجة اللغوية المقنعة، ألق نظرة على الدفتر المقابل +[دفتر PyTorch](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling.ipynb) +أو [دفتر TensorFlow](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling-tf.ipynb). + + + +## الاستدلال + +رائع، الآن بعد أن قمت بتعديل نموذج، يمكنك استخدامه للاستدلال! + +جهّز بعض النصوص التي تريد أن يملأ النموذج الفراغات فيها، واستخدم الرمز الخاص `` للإشارة إلى الفراغ: + +```py +>>> text = "The Milky Way is a galaxy." +``` + +أبسط طريقة لتجربة نموذجك المعدل للاستدلال هي استخدامه في [`pipeline`]. قم بإنشاء كائن `pipeline` لملء الفراغ مع نموذجك، ومرر نصك إليه. إذا أردت، يمكنك استخدام معلمة `top_k` لتحديد عدد التنبؤات التي تريد إرجاعها: + +```py +>>> from transformers import pipeline + +>>> mask_filler = pipeline("fill-mask", "username/my_awesome_eli5_mlm_model") +>>> mask_filler(text, top_k=3) +[{'score': 0.5150994658470154, + 'token': 21300, + 'token_str': ' spiral', + 'sequence': 'The Milky Way is a spiral galaxy.'}, + {'score': 0.07087188959121704, + 'token': 2232, + 'token_str': ' massive', + 'sequence': 'The Milky Way is a massive galaxy.'}, + {'score': 0.06434620916843414, + 'token': 650, + 'token_str': ' small', + 'sequence': 'The Milky Way is a small galaxy.'}] +``` + + + +قم بتجزئة النص وإرجاع `input_ids` كمتجهات PyTorch. ستحتاج أيضًا إلى تحديد موضع رمز ``: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("username/my_awesome_eli5_mlm_model") +>>> inputs = tokenizer(text, return_tensors="pt") +>>> mask_token_index = torch.where(inputs["input_ids"] == tokenizer.mask_token_id)[1] +``` + +قم بتمرير المدخلات إلى النموذج وإرجاع `logits` للرمز المقنع: + +```py +>>> from transformers import AutoModelForMaskedLM + +>>> model = AutoModelForMaskedLM.from_pretrained("username/my_awesome_eli5_mlm_model") +>>> logits = model(**inputs).logits +>>> mask_token_logits = logits[0, mask_token_index, :] +``` + +ثم قم بإرجاع الرموز الثلاثة المقنعة ذات الاحتمالية الأعلى وطباعتها: + +```py +>>> top_3_tokens = torch.topk(mask_token_logits, 3, dim=1).indices[0].tolist() + +>>> for token in top_3_tokens: +... print(text.replace(tokenizer.mask_token, tokenizer.decode([token]))) +The Milky Way is a spiral galaxy. +The Milky Way is a massive galaxy. +The Milky Way is a small galaxy. +``` + + +قم بتقسيم النص إلى رموز وإرجاع `input_ids` كـ TensorFlow tensors. ستحتاج أيضًا إلى تحديد موضع رمز ``: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("username/my_awesome_eli5_mlm_model") +>>> inputs = tokenizer(text, return_tensors="tf") +>>> mask_token_index = tf.where(inputs["input_ids"] == tokenizer.mask_token_id)[0, 1] +``` + +قم بتمرير المدخلات إلى النموذج وإرجاع `logits` للرمز المقنع: + +```py +>>> from transformers import TFAutoModelForMaskedLM + +>>> model = TFAutoModelForMaskedLM.from_pretrained("username/my_awesome_eli5_mlm_model") +>>> logits = model(**inputs).logits +>>> mask_token_logits = logits[0, mask_token_index, :] +``` + +ثم قم بإرجاع الرموز الثلاثة المقنعة ذات الاحتمالية الأعلى وطباعتها: + +```py +>>> top_3_tokens = tf.math.top_k(mask_token_logits, 3).indices.numpy() + +>>> for token in top_3_tokens: +... print(text.replace(tokenizer.mask_token, tokenizer.decode([token]))) +The Milky Way is a spiral galaxy. +The Milky Way is a massive galaxy. +The Milky Way is a small galaxy. +``` + + \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tasks/multiple_choice.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tasks/multiple_choice.md new file mode 100644 index 0000000000000000000000000000000000000000..78f98560754f11d79394fb64881f676506a40db0 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tasks/multiple_choice.md @@ -0,0 +1,452 @@ + + +# الاختيار من متعدد (Multiple choice) + +[[open-in-colab]] + +مهمة الاختيار من متعدد مشابهة لمهمة الإجابة على الأسئلة، ولكن مع توفير عدة إجابات محتملة مع سياق، ويُدرّب النموذج على تحديد الإجابة الصحيحة. + +سيوضح لك هذا الدليل كيفية: + +1. ضبط نموذج [BERT](https://huggingface.co/google-bert/bert-base-uncased) باستخدام الإعداد `regular` لمجموعة بيانات [SWAG](https://huggingface.co/datasets/swag) لاختيار الإجابة الأفضل من بين الخيارات المتعددة المتاحة مع السياق. +2. استخدام النموذج المضبوط للاستدلال. + +قبل البدء، تأكد من تثبيت جميع المكتبات الضرورية: + +```bash +pip install transformers datasets evaluate +``` + +نشجعك على تسجيل الدخول إلى حساب Hugging Face الخاص بك حتى تتمكن من تحميل نموذجك ومشاركته مع المجتمع. عند المطالبة، أدخل الرمز المميز الخاص بك لتسجيل الدخول: + +```py +>>> from huggingface_hub import notebook_login + +>>> notebook_login() +``` + +## تحميل مجموعة بيانات SWAG + +ابدأ بتحميل تهيئة `regular` لمجموعة بيانات SWAG من مكتبة 🤗 Datasets: + +```py +>>> from datasets import load_dataset + +>>> swag = load_dataset("swag", "regular") +``` + +ثم ألق نظرة على مثال: + +```py +>>> swag["train"][0] +{'ending0': 'passes by walking down the street playing their instruments.', + 'ending1': 'has heard approaching them.', + 'ending2': "arrives and they're outside dancing and asleep.", + 'ending3': 'turns the lead singer watches the performance.', + 'fold-ind': '3416', + 'gold-source': 'gold', + 'label': 0, + 'sent1': 'Members of the procession walk down the street holding small horn brass instruments.', + 'sent2': 'A drum line', + 'startphrase': 'Members of the procession walk down the street holding small horn brass instruments. A drum line', + 'video-id': 'anetv_jkn6uvmqwh4'} +``` + +على الرغم من أن الحقول تبدو كثيرة، إلا أنها في الواقع بسيطة جداً: + +- `sent1` و `sent2`: يعرض هذان الحقلان بداية الجملة، وبدمجهما معًا، نحصل على حقل `startphrase`. +- `ending`: يقترح نهاية محتملة للجملة، واحدة منها فقط هي الصحيحة. +- `label`: يحدد نهاية الجملة الصحيحة. + +## المعالجة المسبقة (Preprocess) + +الخطوة التالية هي استدعاء مُجزئ BERT لمعالجة بدايات الجمل والنهايات الأربع المحتملة: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased") +``` + +تحتاج دالة المعالجة المسبقة التي تريد إنشاءها إلى: + +1. إنشاء أربع نسخ من حقل `sent1` ودمج كل منها مع `sent2` لإعادة إنشاء كيفية بدء الجملة. +2. دمج `sent2` مع كل من نهايات الجمل الأربع المحتملة. +3. تتجميع هاتين القائمتين لتتمكن من تجزئتهما، ثم إعادة ترتيبها بعد ذلك بحيث يكون لكل مثال حقول `input_ids` و `attention_mask` و `labels` مقابلة. + + +```py +>>> ending_names = ["ending0", "ending1", "ending2", "ending3"] + +>>> def preprocess_function(examples): +... first_sentences = [[context] * 4 for context in examples["sent1"]] +... question_headers = examples["sent2"] +... second_sentences = [ +... [f"{header} {examples[end][i]}" for end in ending_names] for i, header in enumerate(question_headers) +... ] + +... first_sentences = sum(first_sentences, []) +... second_sentences = sum(second_sentences, []) + +... tokenized_examples = tokenizer(first_sentences, second_sentences, truncation=True) +... return {k: [v[i : i + 4] for i in range(0, len(v), 4)] for k, v in tokenized_examples.items()} +``` + +لتطبيق دالة المعالجة المسبقة على مجموعة البيانات بأكملها، استخدم طريقة [`~datasets.Dataset.map`] الخاصة بـ 🤗 Datasets. يمكنك تسريع دالة `map` عن طريق تعيين `batched=True` لمعالجة عناصر متعددة من مجموعة البيانات في وقت واحد: + +```py +tokenized_swag = swag.map(preprocess_function, batched=True) +``` + +لا يحتوي 🤗 Transformers على مجمع بيانات للاختيار من متعدد، لذلك ستحتاج إلى تكييف [`DataCollatorWithPadding`] لإنشاء دفعة من الأمثلة. من الأكفأ إضافة حشو (padding) ديناميكي للجمل إلى أطول طول في دفعة أثناء التجميع، بدلاً من حشو مجموعة البيانات بأكملها إلى الحد الأقصى للطول. + +يقوم `DataCollatorForMultipleChoice` بتجميع جميع مدخلات النموذج، ويطبق الحشو، ثم يعيد تجميع النتائج في شكلها الأصلي: + + + + +```py +>>> from dataclasses import dataclass +>>> from transformers.tokenization_utils_base import PreTrainedTokenizerBase, PaddingStrategy +>>> from typing import Optional, Union +>>> import torch + +>>> @dataclass +... class DataCollatorForMultipleChoice: +... """ +... Data collator that will dynamically pad the inputs for multiple choice received. +... """ + +... tokenizer: PreTrainedTokenizerBase +... padding: Union[bool, str, PaddingStrategy] = True +... max_length: Optional[int] = None +... pad_to_multiple_of: Optional[int] = None + +... def __call__(self, features): +... label_name = "label" if "label" in features[0].keys() else "labels" +... labels = [feature.pop(label_name) for feature in features] +... batch_size = len(features) +... num_choices = len(features[0]["input_ids"]) +... flattened_features = [ +... [{k: v[i] for k, v in feature.items()} for i in range(num_choices)] for feature in features +... ] +... flattened_features = sum(flattened_features, []) + +... batch = self.tokenizer.pad( +... flattened_features, +... padding=self.padding, +... max_length=self.max_length, +... pad_to_multiple_of=self.pad_to_multiple_of, +... return_tensors="pt", +... ) + +... batch = {k: v.view(batch_size, num_choices, -1) for k, v in batch.items()} +... batch["labels"] = torch.tensor(labels, dtype=torch.int64) +... return batch +``` + + + +```py +>>> from dataclasses import dataclass +>>> from transformers.tokenization_utils_base import PreTrainedTokenizerBase, PaddingStrategy +>>> from typing import Optional, Union +>>> import tensorflow as tf + +>>> @dataclass +... class DataCollatorForMultipleChoice: +... """ +... Data collator that will dynamically pad the inputs for multiple choice received. +... """ + +... tokenizer: PreTrainedTokenizerBase +... padding: Union[bool, str, PaddingStrategy] = True +... max_length: Optional[int] = None +... pad_to_multiple_of: Optional[int] = None + +... def __call__(self, features): +... label_name = "label" if "label" in features[0].keys() else "labels" +... labels = [feature.pop(label_name) for feature in features] +... batch_size = len(features) +... num_choices = len(features[0]["input_ids"]) +... flattened_features = [ +... [{k: v[i] for k, v in feature.items()} for i in range(num_choices)] for feature in features +... ] +... flattened_features = sum(flattened_features, []) + +... batch = self.tokenizer.pad( +... flattened_features, +... padding=self.padding, +... max_length=self.max_length, +... pad_to_multiple_of=self.pad_to_multiple_of, +... return_tensors="tf", +... ) + +... batch = {k: tf.reshape(v, (batch_size, num_choices, -1)) for k, v in batch.items()} +... batch["labels"] = tf.convert_to_tensor(labels, dtype=tf.int64) +... return batch +``` + + + +## التقييم (Evaluate) + +يُفضل غالبًا تضمين مقياس أثناء التدريب لتقييم أداء نموذجك. يمكنك تحميل طريقة تقييم بسرعة باستخدام مكتبة 🤗 [Evaluate](https://huggingface.co/docs/evaluate/index). لهذه المهمة، قم بتحميل مقياس [الدقة](https://huggingface.co/spaces/evaluate-metric/accuracy) (انظر إلى [الجولة السريعة](https://huggingface.co/docs/evaluate/a_quick_tour) لـ 🤗 Evaluate لمعرفة المزيد حول كيفية تحميل المقياس وحسابه): + +```py +>>> import evaluate + +>>> accuracy = evaluate.load("accuracy") +``` + +ثم أنشئ دالة لتمرير التنبؤات والتسميات إلى [`~evaluate.EvaluationModule.compute`] لحساب الدقة: + +```py +>>> import numpy as np + +>>> def compute_metrics(eval_pred): +... predictions, labels = eval_pred +... predictions = np.argmax(predictions, axis=1) +... return accuracy.compute(predictions=predictions, references=labels) +``` + +دالتك `compute_metrics` جاهزة الآن، وستعود إليها عند إعداد تدريبك. + +## التدريب (Train) + + + + + + +إذا لم تكن معتادًا على ضبط نموذج باستخدام [`Trainer`], فراجع الدرس الأساسي [هنا](../training#train-with-pytorch-trainer)! + + + +أنت جاهز لبدء تدريب نموذجك الآن! قم بتحميل BERT باستخدام [`AutoModelForMultipleChoice`]: + +```py +>>> from transformers import AutoModelForMultipleChoice, TrainingArguments, Trainer + +>>> model = AutoModelForMultipleChoice.from_pretrained("google-bert/bert-base-uncased") +``` + +في هذه المرحلة، تبقى ثلاث خطوات فقط: + +1. حدد معلمات التدريب الخاصة بك في [`TrainingArguments`]. المعلمة الوحيدة المطلوبة هي `output_dir` التي تحدد مكان حفظ نموذجك. ستدفع هذا النموذج إلى Hub عن طريق تعيين `push_to_hub=True` (يجب عليك تسجيل الدخول إلى Hugging Face لتحميل نموذجك). في نهاية كل حقبة، سيقوم [`Trainer`] بتقييم الدقة وحفظ نقطة فحص التدريب. +2. مرر معلمات التدريب إلى [`Trainer`] جنبًا إلى جنب مع النموذج ومُجمِّع البيانات والمعالج ودالة تجميع البيانات ودالة `compute_metrics`. +3. استدعي [`~Trainer.train`] لضبط نموذجك. + +```py +>>> training_args = TrainingArguments( +... output_dir="my_awesome_swag_model", +... eval_strategy="epoch", +... save_strategy="epoch", +... load_best_model_at_end=True, +... learning_rate=5e-5, +... per_device_train_batch_size=16, +... per_device_eval_batch_size=16, +... num_train_epochs=3, +... weight_decay=0.01, +... push_to_hub=True, +... ) + +>>> trainer = Trainer( +... model=model, +... args=training_args, +... train_dataset=tokenized_swag["train"], +... eval_dataset=tokenized_swag["validation"], +... processing_class=tokenizer, +... data_collator=DataCollatorForMultipleChoice(tokenizer=tokenizer), +... compute_metrics=compute_metrics, +... ) + +>>> trainer.train() +``` + +بمجرد اكتمال التدريب، شارك نموذجك مع Hub باستخدام طريقة [`~transformers.Trainer.push_to_hub`] حتى يتمكن الجميع من استخدام نموذجك: + +```py +>>> trainer.push_to_hub() +``` + + + + +إذا لم تكن معتادًا على ضبط نموذج باستخدام Keras، فراجع الدرس الأساسي [هنا](../training#train-a-tensorflow-model-with-keras)! + + +لضبط نموذج في TensorFlow، ابدأ بإعداد دالة مُحسِّن وجدول معدل التعلم وبعض معلمات التدريب: + +```py +>>> from transformers import create_optimizer + +>>> batch_size = 16 +>>> num_train_epochs = 2 +>>> total_train_steps = (len(tokenized_swag["train"]) // batch_size) * num_train_epochs +>>> optimizer, schedule = create_optimizer(init_lr=5e-5, num_warmup_steps=0, num_train_steps=total_train_steps) +``` + +ثم يمكنك تحميل BERT باستخدام [`TFAutoModelForMultipleChoice`]: + +```py +>>> from transformers import TFAutoModelForMultipleChoice + +>>> model = TFAutoModelForMultipleChoice.from_pretrained("google-bert/bert-base-uncased") +``` + +حوّل مجموعات البيانات الخاصة بك إلى تنسيق `tf.data.Dataset` باستخدام [`~transformers.TFPreTrainedModel.prepare_tf_dataset`]: + +```py +>>> data_collator = DataCollatorForMultipleChoice(tokenizer=tokenizer) +>>> tf_train_set = model.prepare_tf_dataset( +... tokenized_swag["train"], +... shuffle=True, +... batch_size=batch_size, +... collate_fn=data_collator, +... ) + +>>> tf_validation_set = model.prepare_tf_dataset( +... tokenized_swag["validation"], +... shuffle=False, +... batch_size=batch_size, +... collate_fn=data_collator, +... ) +``` + +قم بتهيئة النموذج للتدريب باستخدام [`compile`](https://keras.io/api/models/model_training_apis/#compile-method). لاحظ أن جميع نماذج Transformers تحتوي على دالة خسارة مناسبة للمهمة بشكل افتراضي، لذلك لا تحتاج إلى تحديد واحدة ما لم ترغب في ذلك: + +```py +>>> model.compile(optimizer=optimizer) # لا توجد وسيطة خسارة! +``` + +الخطوتان الأخيرتان قبل بدء التدريب هما: حساب دقة التنبؤات، وتوفير طريقة لرفع النموذج إلى Hub. ويمكن تحقيق ذلك باستخدام [استدعاءات Keras](../main_classes/keras_callbacks) + +مرر دالتك `compute_metrics` إلى [`~transformers.KerasMetricCallback`]: + +```py +>>> from transformers.keras_callbacks import KerasMetricCallback + +>>> metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_validation_set) +``` + +حدد مكان دفع نموذجك ومعالجك في [`~transformers.PushToHubCallback`]: + +```py +>>> from transformers.keras_callbacks import PushToHubCallback + +>>> push_to_hub_callback = PushToHubCallback( +... output_dir="my_awesome_model", +... tokenizer=tokenizer, +... ) +``` + +ثم قم بتضمين الاستدعاءات معًا: + +```py +>>> callbacks = [metric_callback, push_to_hub_callback] +``` + +أخيرًا، أنت جاهز لبدء تدريب نموذجك! استدعِ[`fit`](https://keras.io/api/models/model_training_apis/#fit-method) مع مجموعات بيانات التدريب والتحقق من الصحة وعدد الحقب والاستدعاءات لضبط النموذج: + +```py +>>> model.fit(x=tf_train_set, validation_data=tf_validation_set, epochs=2, callbacks=callbacks) +``` + +بمجرد اكتمال التدريب، يتم تحميل نموذجك تلقائيًا إلى Hub حتى يتمكن الجميع من استخدامه! + + + + + +للحصول على مثال أكثر تعمقًا حول كيفية ضبط نموذج للاختيار من متعدد، ألق نظرة على [دفتر ملاحظات PyTorch](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/multiple_choice.ipynb) +أو [دفتر ملاحظات TensorFlow](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/multiple_choice-tf.ipynb) المقابل. + + + +## الاستدلال (Inference) + +رائع، الآن بعد أن قمت بضبط نموذج، يمكنك استخدامه للاستدلال! + +قم بإنشاء نص واقتراح إجابتين محتملتين: + +```py +>>> prompt = "France has a bread law, Le Décret Pain, with strict rules on what is allowed in a traditional baguette." +>>> candidate1 = "The law does not apply to croissants and brioche." +>>> candidate2 = "The law applies to baguettes." +``` + + + +قم بتحليل كل مطالبة وزوج إجابة مرشح وأعد تنسورات PyTorch. يجب عليك أيضًا إنشاء بعض `العلامات`: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("username/my_awesome_swag_model") +>>> inputs = tokenizer([[prompt, candidate1], [prompt, candidate2]], return_tensors="pt", padding=True) +>>> labels = torch.tensor(0).unsqueeze(0) +``` + +مرر مدخلاتك والعلامات إلى النموذج وأرجع`logits`: + +```py +>>> from transformers import AutoModelForMultipleChoice + +>>> model = AutoModelForMultipleChoice.from_pretrained("username/my_awesome_swag_model") +>>> outputs = model(**{k: v.unsqueeze(0) for k, v in inputs.items()}, labels=labels) +>>> logits = outputs.logits +``` + +استخرج الفئة ذات الاحتمالية الأكبر: + +```py +>>> predicted_class = logits.argmax().item() +>>> predicted_class +0 +``` + + +قم بتحليل كل مطالبة وزوج إجابة مرشح وأعد موترات TensorFlow: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("username/my_awesome_swag_model") +>>> inputs = tokenizer([[prompt, candidate1], [prompt, candidate2]], return_tensors="tf", padding=True) +``` + +مرر مدخلاتك إلى النموذج وأعد القيم logits: + +```py +>>> from transformers import TFAutoModelForMultipleChoice + +>>> model = TFAutoModelForMultipleChoice.from_pretrained("username/my_awesome_swag_model") +>>> inputs = {k: tf.expand_dims(v, 0) for k, v in inputs.items()} +>>> outputs = model(inputs) +>>> logits = outputs.logits +``` + +استخرج الفئة ذات الاحتمالية الأكبر: + +```py +>>> predicted_class = int(tf.math.argmax(logits, axis=-1)[0]) +>>> predicted_class +0 +``` + + diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tasks/question_answering.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tasks/question_answering.md new file mode 100644 index 0000000000000000000000000000000000000000..0c4b66443d814aff4416221497ae409c7aa77655 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tasks/question_answering.md @@ -0,0 +1,432 @@ + + +# الإجابة على الأسئلة (Question answering) + +[[open-in-colab]] + + + +تُقدّم مهام الإجابة على الأسئلة إجابةً بناءً على سؤال. إذا سبق لك أن سألت مساعدًا افتراضيًا مثل Alexa أو Siri أو Google عن حالة الطقس، فأنت قد استخدمت نموذج للإجابة على الأسئلة من قبل. هناك نوعان شائعان لمهام الإجابة على الأسئلة: + +- الاستخراجية: استخراج الإجابة من السياق المحدد. +- التلخيصية: إنشاء إجابة من السياق تجيب على السؤال بشكل صحيح. + +سيوضح لك هذا الدليل كيفية: + +1. ضبط [DistilBERT](https://huggingface.co/distilbert/distilbert-base-uncased) على مجموعة بيانات [SQuAD](https://huggingface.co/datasets/squad) للإجابة على الأسئلة الاستخراجية. +2. استخدام النموذج المضبوط للاستدلال. + + + +لمشاهدة جميع الهياكل والنسخ المتوافقة مع هذه المهمة، نوصي بالرجوع إلى [صفحة المهمة](https://huggingface.co/tasks/question-answering) + + + +قبل البدء، تأكد من تثبيت جميع المكتبات الضرورية: + +```bash +pip install transformers datasets evaluate +``` + +نشجعك على تسجيل الدخول إلى حساب Hugging Face الخاص بك حتى تتمكن من تحميل نموذجك ومشاركته مع المجتمع. عند المطالبة، أدخل الرمز المميز الخاص بك لتسجيل الدخول: + +```py +>>> from huggingface_hub import notebook_login + +>>> notebook_login() +``` + +## تحميل مجموعة بيانات SQuAD + +ابدأ بتحميل جزء أصغر من مجموعة بيانات SQuAD من مكتبة 🤗 Datasets. سيتيح لك ذلك فرصة للتجربة والتحقق من عمل كل شيء بشكل صحيح قبل قضاء المزيد من الوقت في التدريب على مجموعة البيانات الكاملة. + +```py +>>> from datasets import load_dataset + +>>> squad = load_dataset("squad", split="train[:5000]") +``` + +قم بتقسيم تقسيم `train` لمجموعة البيانات إلى مجموعة تدريب واختبار باستخدام طريقة [`~datasets.Dataset.train_test_split`]: + +```py +>>> squad = squad.train_test_split(test_size=0.2) +``` + +ثم ألق نظرة على مثال: + +```py +>>> squad["train"][0] +{'answers': {'answer_start': [515], 'text': ['Saint Bernadette Soubirous']}, + 'context': 'Architecturally, the school has a Catholic character. Atop the Main Building\'s gold dome is a golden statue of the Virgin Mary. Immediately in front of the Main Building and facing it, is a copper statue of Christ with arms upraised with the legend "Venite Ad Me Omnes". Next to the Main Building is the Basilica of the Sacred Heart. Immediately behind the basilica is the Grotto, a Marian place of prayer and reflection. It is a replica of the grotto at Lourdes, France where the Virgin Mary reputedly appeared to Saint Bernadette Soubirous in 1858. At the end of the main drive (and in a direct line that connects through 3 statues and the Gold Dome), is a simple, modern stone statue of Mary.', + 'id': '5733be284776f41900661182', + 'question': 'To whom did the Virgin Mary allegedly appear in 1858 in Lourdes France?', + 'title': 'University_of_Notre_Dame' +} +``` + +هناك العديد من الحقول المهمة هنا: + +- `answers`: موقع بداية الرمز المميز للإجابة ونص الإجابة. +- `context`: معلومات أساسية يحتاج النموذج إلى استخراج الإجابة منها. +- `question`: السؤال الذي يجب على النموذج الإجابة عليه. + +## المعالجة المسبقة (Preprocess) + + + +الخطوة التالية هي تحميل المحلل اللغوى DistilBERT لمعالجة حقلي `question` و `context`: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased") +``` + +هناك بعض خطوات المعالجة المسبقة الخاصة بمهام الإجابة على الأسئلة التي يجب أن تكون على دراية بها: + +1. قد تحتوي بعض الأمثلة في مجموعة البيانات على `context` طويلًا يتجاوز الحد الأقصى لطول مدخل النموذج. للتعامل مع النصوص الأطول، يتم اقتطاع `context` فقط عن طريق تعيين `truncation="only_second"`. +2. بعد ذلك، يتم تحديد مواضع بداية ونهاية الإجابة في `context` الأصلي عن طريق تعيين + `return_offset_mapping=True`. +3. باستخدام التعيين، يمكن الآن تحديد رموز بداية ونهاية الإجابة. استخدم طريقة [`~tokenizers.Encoding.sequence_ids`] + لتحديد أجزاء الإزاحة التي تتوافق مع `question` و `context`. + +فيما يلي كيفية إنشاء دالة لقص وتعيين رموز البداية والنهاية لـ `answer` إلى `context`: + +```py +>>> def preprocess_function(examples): +... questions = [q.strip() for q in examples["question"]] +... inputs = tokenizer( +... questions, +... examples["context"], +... max_length=384, +... truncation="only_second", +... return_offsets_mapping=True, +... padding="max_length", +... ) + +... offset_mapping = inputs.pop("offset_mapping") +... answers = examples["answers"] +... start_positions = [] +... end_positions = [] + +... for i, offset in enumerate(offset_mapping): +... answer = answers[i] +... start_char = answer["answer_start"][0] +... end_char = answer["answer_start"][0] + len(answer["text"][0]) +... sequence_ids = inputs.sequence_ids(i) + +... # Find the start and end of the context +... idx = 0 +... while sequence_ids[idx] != 1: +... idx += 1 +... context_start = idx +... while sequence_ids[idx] == 1: +... idx += 1 +... context_end = idx - 1 + +... # If the answer is not fully inside the context, label it (0, 0) +... if offset[context_start][0] > end_char or offset[context_end][1] < start_char: +... start_positions.append(0) +... end_positions.append(0) +... else: +... # Otherwise it's the start and end token positions +... idx = context_start +... while idx <= context_end and offset[idx][0] <= start_char: +... idx += 1 +... start_positions.append(idx - 1) + +... idx = context_end +... while idx >= context_start and offset[idx][1] >= end_char: +... idx -= 1 +... end_positions.append(idx + 1) + +... inputs["start_positions"] = start_positions +... inputs["end_positions"] = end_positions +... return inputs +``` + +لتطبيق المعالجة المسبقة على كامل مجموعة البيانات، استخدم [`~datasets.Dataset.map`] من مكتبة 🤗 Datasets. يمكنك تسريع دالة `map` عن طريق تعيين `batched=True` لمعالجة عناصر متعددة من مجموعة البيانات دفعة واحدة. قم بإزالة أي أعمدة لا تحتاجها: + +```py +>>> tokenized_squad = squad.map(preprocess_function, batched=True, remove_columns=squad["train"].column_names) +``` + +الآن قم بإنشاء دفعة من الأمثلة باستخدام [`DefaultDataCollator`]. بخلاف مجمّعات البيانات الأخرى في 🤗 Transformers، لا يطبق [`DefaultDataCollator`] أي معالجة مسبقة إضافية مثل الحشو. + + + + +```py +>>> from transformers import DefaultDataCollator + +>>> data_collator = DefaultDataCollator() +``` + + + +```py +>>> from transformers import DefaultDataCollator + +>>> data_collator = DefaultDataCollator(return_tensors="tf") +``` + + + +## التدريب (Train) + + + + + + +إذا لم تكن معتادًا على ضبط نموذج باستخدام [`Trainer`], ألق نظرة على البرنامج التعليمي الأساسي [هنا](../training#train-with-pytorch-trainer)! + + + +أنت جاهز لبدء تدريب نموذجك الآن! قم بتحميل DistilBERT باستخدام [`AutoModelForQuestionAnswering`]: + +```py +>>> from transformers import AutoModelForQuestionAnswering, TrainingArguments, Trainer + +>>> model = AutoModelForQuestionAnswering.from_pretrained("distilbert/distilbert-base-uncased") +``` + +في هذه المرحلة، تبقى ثلاث خطوات فقط: + +1. حدد المعاملات الفائقة للتدريب في [`TrainingArguments`]. المعامل الوحيد المطلوب هو `output_dir` الذي يحدد مكان حفظ نموذجك. ستدفع هذا النموذج إلى Hub عن طريق تعيين `push_to_hub=True` (يجب عليك تسجيل الدخول إلى Hugging Face لتحميل نموذجك). +2. مرر معاملات التدريب إلى [`Trainer`] جنبًا إلى جنب مع النموذج، ومجموعة البيانات، والمُحلّل النصي، ومُجمّع البيانات. +3. استدعِ ـ [`~Trainer.train`] لضبط النموذج. + +```py +>>> training_args = TrainingArguments( +... output_dir="my_awesome_qa_model", +... eval_strategy="epoch", +... learning_rate=2e-5, +... per_device_train_batch_size=16, +... per_device_eval_batch_size=16, +... num_train_epochs=3, +... weight_decay=0.01, +... push_to_hub=True, +... ) + +>>> trainer = Trainer( +... model=model, +... args=training_args, +... train_dataset=tokenized_squad["train"], +... eval_dataset=tokenized_squad["test"], +... processing_class=tokenizer, +... data_collator=data_collator, +... ) + +>>> trainer.train() +``` + +بمجرد اكتمال التدريب، شارك نموذجك في Hub باستخدام الدالة [`~transformers.Trainer.push_to_hub`] حتى يتمكن الجميع من استخدام نموذجك: + +```py +>>> trainer.push_to_hub() +``` + + + + + +إذا لم تكن معتادًا على ضبط نموذج باستخدام Keras، فألق نظرة على البرنامج التعليمي الأساسي [هنا](../training#train-a-tensorflow-model-with-keras)! + + +لضبط نموذج في TensorFlow، ابدأ بإعداد دالة مُحسِّن، وجدول معدل التعلم، وبعض المعاملات الفائقة للتدريب: + +```py +>>> from transformers import create_optimizer + +>>> batch_size = 16 +>>> num_epochs = 2 +>>> total_train_steps = (len(tokenized_squad["train"]) // batch_size) * num_epochs +>>> optimizer, schedule = create_optimizer( +... init_lr=2e-5, +... num_warmup_steps=0, +... num_train_steps=total_train_steps, +... ) +``` + +ثم يمكنك تحميل DistilBERT باستخدام [`TFAutoModelForQuestionAnswering`]: + +```py +>>> from transformers import TFAutoModelForQuestionAnswering + +>>> model = TFAutoModelForQuestionAnswering.from_pretrained("distilbert/distilbert-base-uncased") +``` + +حوّل مجموعات البيانات الخاصة بك إلى تنسيق `tf.data.Dataset` باستخدام [`~transformers.TFPreTrainedModel.prepare_tf_dataset`]: + +```py +>>> tf_train_set = model.prepare_tf_dataset( +... tokenized_squad["train"], +... shuffle=True, +... batch_size=16, +... collate_fn=data_collator, +... ) + +>>> tf_validation_set = model.prepare_tf_dataset( +... tokenized_squad["test"], +... shuffle=False, +... batch_size=16, +... collate_fn=data_collator, +... ) +``` + +قم بتكوين النموذج للتدريب باستخدام [`compile`](https://keras.io/api/models/model_training_apis/#compile-method): + +```py +>>> import tensorflow as tf + +>>> model.compile(optimizer=optimizer) +``` + +آخر شيء يجب إعداده قبل بدء التدريب هو توفير طريقة لدفع نموذجك إلى Hub. يمكن القيام بذلك عن طريق تحديد مكان دفع نموذجك ومعالجك المعجمي في [`~transformers.PushToHubCallback`]: + +```py +>>> from transformers.keras_callbacks import PushToHubCallback + +>>> callback = PushToHubCallback( +... output_dir="my_awesome_qa_model", +... tokenizer=tokenizer, +... ) +``` + +أخيرًا، أنت جاهز لبدء تدريب نموذجك! اتصل بـ [`fit`](https://keras.io/api/models/model_training_apis/#fit-method) مع مجموعات بيانات التدريب والتحقق من الصحة، وعدد العهود، ومعاودة الاتصال الخاصة بك لضبط النموذج: + +```py +>>> model.fit(x=tf_train_set, validation_data=tf_validation_set, epochs=3, callbacks=[callback]) +``` +بمجرد اكتمال التدريب، يتم تحميل نموذجك تلقائيًا إلى Hub حتى يتمكن الجميع من استخدامه! + + + + + + +للحصول على مثال أكثر تعمقًا حول كيفية ضبط نموذج للإجابة على الأسئلة، ألق نظرة على [دفتر ملاحظات PyTorch](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/question_answering.ipynb) المقابل +أو [دفتر ملاحظات TensorFlow](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/question_answering-tf.ipynb). + + + +## التقييم (Evaluate) + +يتطلب التقييم للإجابة على الأسئلة قدرًا كبيرًا من المعالجة اللاحقة. لتوفير وقتك، يتخطى هذا الدليل خطوة التقييم. لا يزال [`Trainer`] يحسب خسارة التقييم أثناء التدريب، مما يعني أنك لست تجهل تمامًا أداء نموذجك. + +إذا كان لديك المزيد من الوقت وتهتم بكيفية تقييم نموذجك للإجابة على الأسئلة، فألق نظرة على فصل [الإجابة على الأسئلة](https://huggingface.co/course/chapter7/7?fw=pt#post-processing) من دورة 🤗 Hugging Face! + +## الاستدلال (Inference) + +رائع، الآن بعد أن قمت بضبط نموذج، يمكنك استخدامه للاستدلال! + +حدد سؤالًا وسياقًا ليقوم النموذج بالتنبؤ بالإجابة عليه: + +```py +>>> question = "How many programming languages does BLOOM support?" +>>> context = "BLOOM has 176 billion parameters and can generate text in 46 languages natural languages and 13 programming languages." +``` + +أبسط طريقة لتجربة نموذجك المُدرَّب للاستدلال هي استخدامه في [`pipeline`]. قم بإنشاء كائن لـ `pipeline` للإجابة على الأسئلة باستخدام نموذجك، ومرِّر النص إليه: + +```py +>>> from transformers import pipeline + +>>> question_answerer = pipeline("question-answering", model="my_awesome_qa_model") +>>> question_answerer(question=question, context=context) +{'score': 0.2058267742395401, + 'start': 10, + 'end': 95, + 'answer': '176 مليار معامل ويمكنه إنشاء نصوص بـ 46 لغة طبيعية و 13'} +``` + +يمكنك أيضًا تكرار نتائج `pipeline` يدويًا إذا أردت: + + + + + قسّم النص وأرجع تنسورات PyTorch: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("my_awesome_qa_model") +>>> inputs = tokenizer(question, context, return_tensors="pt") +``` + +مرر مدخلاتك إلى النموذج وأرجع `logits`: + +```py +>>> import torch +>>> from transformers import AutoModelForQuestionAnswering + +>>> model = AutoModelForQuestionAnswering.from_pretrained("my_awesome_qa_model") +>>> with torch.no_grad(): +... outputs = model(**inputs) +``` + +احصل على أعلى احتمال من مخرجات النموذج لموضعي البداية والنهاية: + +```py +>>> answer_start_index = outputs.start_logits.argmax() +>>> answer_end_index = outputs.end_logits.argmax() +``` + +استخلاص الإجابة من الرموز المتوقعة: + +```py +>>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1] +>>> tokenizer.decode(predict_answer_tokens) +'176 billion parameters and can generate text in 46 languages natural languages and 13' +``` + + +قم بتحليل النص المعجمي وأعد موترات TensorFlow: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("my_awesome_qa_model") +>>> inputs = tokenizer(question, context, return_tensors="tf") +``` + +مرر مدخلاتك إلى النموذج وأعد `logits`: + +```py +>>> from transformers import TFAutoModelForQuestionAnswering + +>>> model = TFAutoModelForQuestionAnswering.from_pretrained("my_awesome_qa_model") +>>> outputs = model(**inputs) +``` + +احصل على أعلى احتمال من مخرجات النموذج لموضعي البداية والنهاية: + +```py +>>> answer_start_index = int(tf.math.argmax(outputs.start_logits, axis=-1)[0]) +>>> answer_end_index = int(tf.math.argmax(outputs.end_logits, axis=-1)[0]) +``` + +استخلاص الإجابة من الرموز المتوقعة: + +```py +>>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1] +>>> tokenizer.decode(predict_answer_tokens) +'176 billion parameters and can generate text in 46 languages natural languages and 13' +``` + + diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tasks/sequence_classification.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tasks/sequence_classification.md new file mode 100644 index 0000000000000000000000000000000000000000..a98964957b47c92bc4a43db701db99b650a2dfce --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tasks/sequence_classification.md @@ -0,0 +1,387 @@ + + +# تصنيف النص(Text classification) + +[[open-in-colab]] + + + +تصنيف النص هو مهمة NLP شائعة حيث يُعيّن تصنيفًا أو فئة للنص. تستخدم بعض أكبر الشركات تصنيف النصوص في الإنتاج لمجموعة واسعة من التطبيقات العملية. أحد أكثر أشكال تصنيف النص شيوعًا هو تحليل المشاعر، والذي يقوم بتعيين تسمية مثل 🙂 إيجابية، 🙁 سلبية، أو 😐 محايدة لتسلسل نصي. + +سيوضح لك هذا الدليل كيفية: + +1. ضبط [DistilBERT](https://huggingface.co/distilbert/distilbert-base-uncased) على مجموعة بيانات [IMDb](https://huggingface.co/datasets/imdb) لتحديد ما إذا كانت مراجعة الفيلم إيجابية أو سلبية. +2. استخدام نموذج الضبط الدقيق للتنبؤ. + + + +لرؤية جميع البنى ونقاط التحقق المتوافقة مع هذه المهمة، نوصي بالتحقق من [صفحة المهمة](https://huggingface.co/tasks/text-classification). + + + +قبل أن تبدأ، تأكد من تثبيت جميع المكتبات الضرورية: + +```bash +pip install transformers datasets evaluate accelerate +``` + +نحن نشجعك على تسجيل الدخول إلى حساب Hugging Face الخاص بك حتى تتمكن من تحميل ومشاركة نموذجك مع المجتمع. عند المطالبة، أدخل رمزك لتسجيل الدخول: + +```py +>>> from huggingface_hub import notebook_login + +>>> notebook_login() +``` + +## تحميل مجموعة بيانات IMDb + +ابدأ بتحميل مجموعة بيانات IMDb من مكتبة 🤗 Datasets: + +```py +>>> from datasets import load_dataset + +>>> imdb = load_dataset("imdb") +``` + +ثم ألق نظرة على مثال: + +```py +>>> imdb["test"][0] +{ + "label": 0, + "text": "I love sci-fi and am willing to put up with a lot. Sci-fi movies/TV are usually underfunded, under-appreciated and misunderstood. I tried to like this, I really did, but it is to good TV sci-fi as Babylon 5 is to Star Trek (the original). Silly prosthetics, cheap cardboard sets, stilted dialogues, CG that doesn't match the background, and painfully one-dimensional characters cannot be overcome with a 'sci-fi' setting. (I'm sure there are those of you out there who think Babylon 5 is good sci-fi TV. It's not. It's clichéd and uninspiring.) While US viewers might like emotion and character development, sci-fi is a genre that does not take itself seriously (cf. Star Trek). It may treat important issues, yet not as a serious philosophy. It's really difficult to care about the characters here as they are not simply foolish, just missing a spark of life. Their actions and reactions are wooden and predictable, often painful to watch. The makers of Earth KNOW it's rubbish as they have to always say \"Gene Roddenberry's Earth...\" otherwise people would not continue watching. Roddenberry's ashes must be turning in their orbit as this dull, cheap, poorly edited (watching it without advert breaks really brings this home) trudging Trabant of a show lumbers into space. Spoiler. So, kill off a main character. And then bring him back as another actor. Jeeez! Dallas all over again.", +} +``` + +هناك حقولان في هذه المجموعة من البيانات: + +- `text`: نص مراجعة الفيلم. +- `label`: قيمة إما `0` لمراجعة سلبية أو `1` لمراجعة إيجابية. + +## المعالجة المسبقة(Preprocess) + +الخطوة التالية هي تحميل المُجزِّئ النص DistilBERT لتهيئة لحقل `text`: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased") +``` + +أنشئ دالة لتهيئة حقل `text` وتقصير السلاسل النصية بحيث لا يتجاوز طولها الحد الأقصى لإدخالات DistilBERT: + +```py +>>> def preprocess_function(examples): +... return tokenizer(examples["text"], truncation=True) +``` + +لتطبيق دالة التهيئة على مجموعة البيانات بأكملها، استخدم دالة 🤗 Datasets [`~datasets.Dataset.map`] . يمكنك تسريع `map` باستخدام `batched=True` لمعالجة دفعات من البيانات: + +```py +tokenized_imdb = imdb.map(preprocess_function, batched=True) +``` + +الآن قم بإنشاء دفعة من الأمثلة باستخدام [`DataCollatorWithPadding`]. الأكثر كفاءة هو استخدام الحشو الديناميكي لجعل الجمل متساوية في الطول داخل كل دفعة، بدلًا من حشو كامل البيانات إلى الحد الأقصى للطول. + + + + +```py +>>> from transformers import DataCollatorWithPadding + +>>> data_collator = DataCollatorWithPadding(tokenizer=tokenizer) +``` + + + +```py +>>> from transformers import DataCollatorWithPadding + +>>> data_collator = DataCollatorWithPadding(tokenizer=tokenizer, return_tensors="tf") +``` + + + +## التقييم(Evaluate) + +يُعدّ تضمين مقياس أثناء التدريب مفيدًا لتقييم أداء النموذج. يمكنك تحميل طريقة تقييم بسرعة باستخدام مكتبة 🤗 [Evaluate](https://huggingface.co/docs/evaluate/index) . بالنسبة لهذه المهمة، قم بتحميل مقياس [الدقة](https://huggingface.co/spaces/evaluate-metric/accuracy) (راجع جولة 🤗 Evaluate [السريعة](https://huggingface.co/docs/evaluate/a_quick_tour) لمعرفة المزيد حول كيفية تحميل وحساب مقياس): + +```py +>>> import evaluate + +>>> accuracy = evaluate.load("accuracy") +``` + +ثم أنشئ دالة تقوم بتمرير تنبؤاتك وتصنيفاتك إلى [`~evaluate.EvaluationModule.compute`] لحساب الدقة: + +```py +>>> import numpy as np + +>>> def compute_metrics(eval_pred): +... predictions, labels = eval_pred +... predictions = np.argmax(predictions, axis=1) +... return accuracy.compute(predictions=predictions, references=labels) +``` + +دالة `compute_metrics` جاهزة الآن، وستعود إليها عند إعداد التدريب. + +## التدريب(Train) + +قبل أن تبدأ في تدريب نموذجك، قم بإنشاء خريطة من المعرفات المتوقعة إلى تسمياتها باستخدام `id2label` و `label2id`: + +```py +>>> id2label = {0: "NEGATIVE", 1: "POSITIVE"} +>>> label2id = {"NEGATIVE": 0, "POSITIVE": 1} +``` + + + + + +إذا لم تكن على دراية بضبط نموذج دقيق باستخدام [`Trainer`], فالق نظرة على البرنامج التعليمي الأساسي [هنا](../training#train-with-pytorch-trainer)! + + + +أنت مستعد الآن لبدء تدريب نموذجك! قم بتحميل DistilBERT مع [`AutoModelForSequenceClassification`] جنبًا إلى جنب مع عدد التصنيفات المتوقعة، وتصنيفات الخرائط: + +```py +>>> from transformers import AutoModelForSequenceClassification, TrainingArguments, Trainer + +>>> model = AutoModelForSequenceClassification.from_pretrained( +... "distilbert/distilbert-base-uncased", num_labels=2, id2label=id2label, label2id=label2id +... ) +``` + +في هذه المرحلة، هناك ثلاث خطوات فقط متبقية: + +1. حدد مُعامِلات التدريب في [`TrainingArguments`]. المُعامل المطلوب الوحيد هو `output_dir`، لتحديد مكان حفظ النموذج. يمكنك رفع النموذج إلى Hub بتعيين `push_to_hub=True` (يجب تسجيل الدخول إلى Hugging Face لرفع النموذج). سيقوم `Trainer` بتقييم الدقة وحفظ نقاط التحقق في نهاية كل حقبة. +2. مرر مُعامِلات التدريب إلى `Trainer` مع النموذج، ومجموعة البيانات، والمحلل اللغوي، ومُجمِّع البيانات، ووظيفة `compute_metrics`. +3. استدعِ [`~Trainer.train`] لضبط النموذج. + +```py +>>> training_args = TrainingArguments( +... output_dir="my_awesome_model", +... learning_rate=2e-5, +... per_device_train_batch_size=16, +... per_device_eval_batch_size=16, +... num_train_epochs=2, +... weight_decay=0.01, +... eval_strategy="epoch", +... save_strategy="epoch", +... load_best_model_at_end=True, +... push_to_hub=True, +... ) + +>>> trainer = Trainer( +... model=model, +... args=training_args, +... train_dataset=tokenized_imdb["train"], +... eval_dataset=tokenized_imdb["test"], +... processing_class=tokenizer, +... data_collator=data_collator, +... compute_metrics=compute_metrics, +... ) + +>>> trainer.train() +``` + + + +يستخدم [`Trainer`] الحشو الديناميكي افتراضيًا عند تمرير `tokenizer` إليه. في هذه الحالة، لا تحتاج لتحديد مُجمِّع البيانات صراحةً. + + + +بعد اكتمال التدريب، شارك نموذجك على Hub باستخدام الطريقة [`~transformers.Trainer.push_to_hub`] ليستخدمه الجميع: + +```py +>>> trainer.push_to_hub() +``` + + + + +إذا لم تكن على دراية بضبط نموذج باستخدام Keras، قم بالاطلاع على البرنامج التعليمي الأساسي [هنا](../training#train-a-tensorflow-model-with-keras)! + + +لضبط نموذج في TensorFlow، ابدأ بإعداد دالة المحسن، وجدول معدل التعلم، وبعض معلمات التدريب: + +```py +>>> from transformers import create_optimizer +>>> import tensorflow as tf + +>>> batch_size = 16 +>>> num_epochs = 5 +>>> batches_per_epoch = len(tokenized_imdb["train"]) // batch_size +>>> total_train_steps = int(batches_per_epoch * num_epochs) +>>> optimizer, schedule = create_optimizer(init_lr=2e-5, num_warmup_steps=0, num_train_steps=total_train_steps) +``` + +ثم يمكنك تحميل DistilBERT مع [`TFAutoModelForSequenceClassification`] بالإضافة إلى عدد التصنيفات المتوقعة، وتعيينات التسميات: + +```py +>>> from transformers import TFAutoModelForSequenceClassification + +>>> model = TFAutoModelForSequenceClassification.from_pretrained( +... "distilbert/distilbert-base-uncased", num_labels=2, id2label=id2label, label2id=label2id +... ) +``` + +قم بتحويل مجموعات بياناتك إلى تنسيق `tf.data.Dataset` باستخدام [`~transformers.TFPreTrainedModel.prepare_tf_dataset`]: + +```py +>>> tf_train_set = model.prepare_tf_dataset( +... tokenized_imdb["train"], +... shuffle=True, +... batch_size=16, +... collate_fn=data_collator, +... ) + +>>> tf_validation_set = model.prepare_tf_dataset( +... tokenized_imdb["test"], +... shuffle=False, +... batch_size=16, +... collate_fn=data_collator, +... ) +``` + +قم بتهيئة النموذج للتدريب باستخدام [`compile`](https://keras.io/api/models/model_training_apis/#compile-method). لاحظ أن جميع نماذج Transformers لديها دالة خسارة ذات صلة بالمهمة بشكل افتراضي، لذلك لا تحتاج إلى تحديد واحدة ما لم ترغب في ذلك: + +```py +>>> import tensorflow as tf + +>>> model.compile(optimizer=optimizer) # No loss argument! +``` + +آخر أمرين يجب إعدادهما قبل بدء التدريب هو حساب الدقة من التوقعات، وتوفير طريقة لدفع نموذجك إلى Hub. يتم ذلك باستخدام [Keras callbacks](../main_classes/keras_callbacks). + +قم بتمرير دالة `compute_metrics` الخاصة بك إلى [`~transformers.KerasMetricCallback`]: + +```py +>>> from transformers.keras_callbacks import KerasMetricCallback + +>>> metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_validation_set) +``` + +حدد مكان دفع نموذجك والمجزئ اللغوي في [`~transformers.PushToHubCallback`]: + +```py +>>> from transformers.keras_callbacks import PushToHubCallback + +>>> push_to_hub_callback = PushToHubCallback( +... output_dir="my_awesome_model", +... tokenizer=tokenizer, +... ) +``` + +ثم اجمع الاستدعاءات معًا: + +```py +>>> callbacks = [metric_callback, push_to_hub_callback] +``` + +أخيرًا، أنت مستعد لبدء تدريب نموذجك! قم باستدعاء [`fit`](https://keras.io/api/models/model_training_apis/#fit-method) مع مجموعات بيانات التدريب والتحقق، وعدد الحقبات، واستدعاءاتك لضبط النموذج: + +```py +>>> model.fit(x=tf_train_set, validation_data=tf_validation_set, epochs=3, callbacks=callbacks) +``` + +بمجرد اكتمال التدريب، يتم تحميل نموذجك تلقائيًا إلى Hub حتى يتمكن الجميع من استخدامه! + + + + + +للحصول على مثال أكثر عمقًا حول كيفية ضبط نموذج لتصنيف النصوص، قم بالاطلاع على الدفتر المقابل +[دفتر PyTorch](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification.ipynb) +أو [دفتر TensorFlow](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification-tf.ipynb). + + + +## الاستدلال(Inference) + +رائع، الآن بعد أن قمت بضبط نموذج، يمكنك استخدامه للاستدلال! + +احصل على بعض النصوص التي ترغب في إجراء الاستدلال عليها: + +```py +>>> text = "This was a masterpiece. Not completely faithful to the books, but enthralling from beginning to end. Might be my favorite of the three." +``` + +أسهل طريقة لتجربة النموذج المضبوط للاستدلال هي استخدامه ضمن [`pipeline`]. قم بإنشاء `pipeline` لتحليل المشاعر مع نموذجك، ومرر نصك إليه: + +```py +>>> from transformers import pipeline + +>>> classifier = pipeline("sentiment-analysis", model="stevhliu/my_awesome_model") +>>> classifier(text) +[{'label': 'POSITIVE', 'score': 0.9994940757751465}] +``` + +يمكنك أيضًا تكرار نتائج `pipeline` يدويًا إذا أردت: + + + +قم يتجزئة النص وإرجاع تنسورات PyTorch: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_model") +>>> inputs = tokenizer(text, return_tensors="pt") +``` + +مرر المدخلات إلى النموذج واسترجع `logits`: + +```py +>>> from transformers import AutoModelForSequenceClassification + +>>> model = AutoModelForSequenceClassification.from_pretrained("stevhliu/my_awesome_model") +>>> with torch.no_grad(): +... logits = model(**inputs).logits +``` + +استخرج الفئة ذات الاحتمالية الأعلى، واستخدم `id2label` لتحويلها إلى تصنيف نصي: + +```py +>>> predicted_class_id = logits.argmax().item() +>>> model.config.id2label[predicted_class_id] +'POSITIVE' +``` + + +قم بتحليل النص وإرجاع تنسيقات TensorFlow: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_model") +>>> inputs = tokenizer(text, return_tensors="tf") +``` + +قم بتمرير مدخلاتك إلى النموذج وإرجاع `logits`: + +```py +>>> from transformers import TFAutoModelForSequenceClassification + +>>> model = TFAutoModelForSequenceClassification.from_pretrained("stevhliu/my_awesome_model") +>>> logits = model(**inputs).logits +``` + +استخرج الفئة ذات الاحتمالية الأعلى، واستخدم `id2label` لتحويلها إلى تصنيف نصي: + +```py +>>> predicted_class_id = int(tf.math.argmax(logits, axis=-1)[0]) +>>> model.config.id2label[predicted_class_id] +'POSITIVE' +``` + + diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tasks/summarization.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tasks/summarization.md new file mode 100644 index 0000000000000000000000000000000000000000..17dbcb42e8374e6ed43b1ccb43d46afdbbb90635 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tasks/summarization.md @@ -0,0 +1,397 @@ + + +# التلخيص (Summarization) + +[[open-in-colab]] + + + +يقوم التلخيص بإنشاء نسخة مختصرة من مستند أو مقال، حيث يلتقط جميع المعلومات المهمة. بالإضافة إلى الترجمة، يعتبر التلخيص مثالاً آخر على مهمة يمكن صياغتها كتسلسل إلى تسلسل. يمكن أن يكون التلخيص: + +- استخراجي: استخراج أهم المعلومات من مستند. +- تجريدي: إنشاء نص جديد يلخص أهم المعلومات. + +سيوضح لك هذا الدليل كيفية: + +1. ضبط دقيق [T5](https://huggingface.co/google-t5/t5-small) على مجموعة فرعية من مشاريع قوانين ولاية كاليفورنيا من مجموعة بيانات [BillSum](https://huggingface.co/datasets/billsum) للتلخيص التجريدي. +2. استخدام النموذج المضبوط بدقة للتنبؤ. + + + +لمشاهدة جميع البنى ونقاط التفتيش المتوافقة مع هذه المهمة، نوصي بالتحقق من [صفحة المهمة](https://huggingface.co/tasks/summarization) + + + +قبل البدء، تأكد من تثبيت جميع المكتبات الضرورية: + +```bash +pip install transformers datasets evaluate rouge_score +``` + +نشجعك على تسجيل الدخول إلى حساب Hugging Face الخاص بك حتى تتمكن من تحميل نموذجك ومشاركته مع المجتمع. عند المطالبة، أدخل الرمز المميز لتسجيل الدخول: + +```py +>>> from huggingface_hub import notebook_login + +>>> notebook_login() +``` + +## تحميل مجموعة بيانات BillSum + +ابدأ بتحميل جزء صغير من بيانات مشاريع القوانين الخاصة بولاية كاليفورنيا من مجموعة بيانات BillSum في مكتبة 🤗 Datasets: + +```py +>>> from datasets import load_dataset + +>>> billsum = load_dataset("billsum", split="ca_test") +``` + +قسّم مجموعة البيانات إلى مجموعتي تدريب واختبار باستخدام الدالة [`~datasets.Dataset.train_test_split`]: + +```py +>>> billsum = billsum.train_test_split(test_size=0.2) +``` + +ثم ألقِ نظرة على مثال: + +```py +>>> billsum["train"][0] +{'summary': 'Existing law authorizes state agencies to enter into contracts for the acquisition of goods or services upon approval by the Department of General Services. Existing law sets forth various requirements and prohibitions for those contracts, including, but not limited to, a prohibition on entering into contracts for the acquisition of goods or services of $100,000 or more with a contractor that discriminates between spouses and domestic partners or same-sex and different-sex couples in the provision of benefits. Existing law provides that a contract entered into in violation of those requirements and prohibitions is void and authorizes the state or any person acting on behalf of the state to bring a civil action seeking a determination that a contract is in violation and therefore void. Under existing law, a willful violation of those requirements and prohibitions is a misdemeanor.\nThis bill would also prohibit a state agency from entering into contracts for the acquisition of goods or services of $100,000 or more with a contractor that discriminates between employees on the basis of gender identity in the provision of benefits, as specified. By expanding the scope of a crime, this bill would impose a state-mandated local program.\nThe California Constitution requires the state to reimburse local agencies and school districts for certain costs mandated by the state. Statutory provisions establish procedures for making that reimbursement.\nThis bill would provide that no reimbursement is required by this act for a specified reason.', + 'text': 'The people of the State of California do enact as follows:\n\n\nSECTION 1.\nSection 10295.35 is added to the Public Contract Code, to read:\n10295.35.\n(a) (1) Notwithstanding any other law, a state agency shall not enter into any contract for the acquisition of goods or services in the amount of one hundred thousand dollars ($100,000) or more with a contractor that, in the provision of benefits, discriminates between employees on the basis of an employee’s or dependent’s actual or perceived gender identity, including, but not limited to, the employee’s or dependent’s identification as transgender.\n(2) For purposes of this section, “contract” includes contracts with a cumulative amount of one hundred thousand dollars ($100,000) or more per contractor in each fiscal year.\n(3) For purposes of this section, an employee health plan is discriminatory if the plan is not consistent with Section 1365.5 of the Health and Safety Code and Section 10140 of the Insurance Code.\n(4) The requirements of this section shall apply only to those portions of a contractor’s operations that occur under any of the following conditions:\n(A) Within the state.\n(B) On real property outside the state if the property is owned by the state or if the state has a right to occupy the property, and if the contractor’s presence at that location is connected to a contract with the state.\n(C) Elsewhere in the United States where work related to a state contract is being performed.\n(b) Contractors shall treat as confidential, to the maximum extent allowed by law or by the requirement of the contractor’s insurance provider, any request by an employee or applicant for employment benefits or any documentation of eligibility for benefits submitted by an employee or applicant for employment.\n(c) After taking all reasonable measures to find a contractor that complies with this section, as determined by the state agency, the requirements of this section may be waived under any of the following circumstances:\n(1) There is only one prospective contractor willing to enter into a specific contract with the state agency.\n(2) The contract is necessary to respond to an emergency, as determined by the state agency, that endangers the public health, welfare, or safety, or the contract is necessary for the provision of essential services, and no entity that complies with the requirements of this section capable of responding to the emergency is immediately available.\n(3) The requirements of this section violate, or are inconsistent with, the terms or conditions of a grant, subvention, or agreement, if the agency has made a good faith attempt to change the terms or conditions of any grant, subvention, or agreement to authorize application of this section.\n(4) The contractor is providing wholesale or bulk water, power, or natural gas, the conveyance or transmission of the same, or ancillary services, as required for ensuring reliable services in accordance with good utility practice, if the purchase of the same cannot practically be accomplished through the standard competitive bidding procedures and the contractor is not providing direct retail services to end users.\n(d) (1) A contractor shall not be deemed to discriminate in the provision of benefits if the contractor, in providing the benefits, pays the actual costs incurred in obtaining the benefit.\n(2) If a contractor is unable to provide a certain benefit, despite taking reasonable measures to do so, the contractor shall not be deemed to discriminate in the provision of benefits.\n(e) (1) Every contract subject to this chapter shall contain a statement by which the contractor certifies that the contractor is in compliance with this section.\n(2) The department or other contracting agency shall enforce this section pursuant to its existing enforcement powers.\n(3) (A) If a contractor falsely certifies that it is in compliance with this section, the contract with that contractor shall be subject to Article 9 (commencing with Section 10420), unless, within a time period specified by the department or other contracting agency, the contractor provides to the department or agency proof that it has complied, or is in the process of complying, with this section.\n(B) The application of the remedies or penalties contained in Article 9 (commencing with Section 10420) to a contract subject to this chapter shall not preclude the application of any existing remedies otherwise available to the department or other contracting agency under its existing enforcement powers.\n(f) Nothing in this section is intended to regulate the contracting practices of any local jurisdiction.\n(g) This section shall be construed so as not to conflict with applicable federal laws, rules, or regulations. In the event that a court or agency of competent jurisdiction holds that federal law, rule, or regulation invalidates any clause, sentence, paragraph, or section of this code or the application thereof to any person or circumstances, it is the intent of the state that the court or agency sever that clause, sentence, paragraph, or section so that the remainder of this section shall remain in effect.\nSEC. 2.\nSection 10295.35 of the Public Contract Code shall not be construed to create any new enforcement authority or responsibility in the Department of General Services or any other contracting agency.\nSEC. 3.\nNo reimbursement is required by this act pursuant to Section 6 of Article XIII\u2009B of the California Constitution because the only costs that may be incurred by a local agency or school district will be incurred because this act creates a new crime or infraction, eliminates a crime or infraction, or changes the penalty for a crime or infraction, within the meaning of Section 17556 of the Government Code, or changes the definition of a crime within the meaning of Section 6 of Article XIII\u2009B of the California Constitution.', + 'title': 'An act to add Section 10295.35 to the Public Contract Code, relating to public contracts.'} +``` + +هناك مُدخلان سترغب في استخدامهما: + +- `text`: نص القانون الذي سيكون مُدخلًا للنموذج. +- `summary`: نسخة مُختصرة من `text` والتي ستكون هدف النموذج. + +## المعالجة المسبقة (Preprocess) + +الخطوة التالية هي تحميل مجزء النصوص T5 لمعالجة `text` و `summary`: + +```py +>>> from transformers import AutoTokenizer + +>>> checkpoint = "google-t5/t5-small" +>>> tokenizer = AutoTokenizer.from_pretrained(checkpoint) +``` + +وظيفة المعالجة المسبقة التي تريد إنشاءها تحتاج إلى: + +1. إضافة بادئة للمُدخل باستخدام توجيه حتى يعرف T5 أن هذه مهمة تلخيص. تتطلب بعض النماذج القادرة على مهام البرمجة اللغوية العصبية المتعددة توجيهات لمهام مُحددة. +2. استخدام مُعامل الكلمة الرئيسية `text_target` عند ترميز التصنيفات. +3. قصّ التسلسلات بحيث لا يزيد طولها عن الحد الأقصى الذي تم تعيينه بواسطة مُعامل `max_length`. + +```py +>>> prefix = "summarize: " + +>>> def preprocess_function(examples): +... inputs = [prefix + doc for doc in examples["text"]] +... model_inputs = tokenizer(inputs, max_length=1024, truncation=True) + +... labels = tokenizer(text_target=examples["summary"], max_length=128, truncation=True) + +... model_inputs["labels"] = labels["input_ids"] +... return model_inputs +``` + +لتطبيق دالة المعالجة المسبقة على مجموعة البيانات بأكملها، استخدم طريقة [`~datasets.Dataset.map`] الخاصة بـ 🤗 Datasets. يمكنك تسريع دالة `map` عن طريق تعيين `batched=True` لمعالجة عناصر متعددة من مجموعة البيانات في وقت واحد: + +```py +>>> tokenized_billsum = billsum.map(preprocess_function, batched=True) +``` + +الآن قم بإنشاء دفعة من الأمثلة باستخدام [`DataCollatorForSeq2Seq`]. الأكثر كفاءة *الحشو الديناميكي* للجمل إلى أطول طول في دفعة أثناء عملية التجميع، بدلاً من حشو مجموعة البيانات بأكملها إلى الحد الأقصى للطول. + + + + +```py +>>> from transformers import DataCollatorForSeq2Seq + +>>> data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=checkpoint) +``` + + + +```py +>>> from transformers import DataCollatorForSeq2Seq + +>>> data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=checkpoint, return_tensors="tf") +``` + + + +## التقييم (Evaluate) + +يُعد تضمين مقياس أثناء التدريب مفيدًا غالبًا لتقييم أداء نموذجك. يمكنك تحميل طريقة تقييم بسرعة باستخدام مكتبة 🤗 [Evaluate](https://huggingface.co/docs/evaluate/index). لهذه المهمة، قم بتحميل مقياس [ROUGE](https://huggingface.co/spaces/evaluate-metric/rouge) (راجع [الجولة السريعة](https://huggingface.co/docs/evaluate/a_quick_tour) الخاصة بـ 🤗 Evaluate لمعرفة المزيد حول كيفية تحميل وحساب مقياس): + +```py +>>> import evaluate + +>>> rouge = evaluate.load("rouge") +``` + +ثم قم بإنشاء دالة تُمرر تنبؤاتك وتصنيفاتك إلى [`~evaluate.EvaluationModule.compute`] لحساب مقياس ROUGE: + +```py +>>> import numpy as np + +>>> def compute_metrics(eval_pred): +... predictions, labels = eval_pred +... decoded_preds = tokenizer.batch_decode(predictions, skip_special_tokens=True) +... labels = np.where(labels != -100, labels, tokenizer.pad_token_id) +... decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True) + +... result = rouge.compute(predictions=decoded_preds, references=decoded_labels, use_stemmer=True) + +... prediction_lens = [np.count_nonzero(pred != tokenizer.pad_token_id) for pred in predictions] +... result["gen_len"] = np.mean(prediction_lens) + +... return {k: round(v, 4) for k, v in result.items()} +``` + +دالة `compute_metrics` الخاصة بك جاهزة الآن، وستعود إليها عند إعداد التدريب الخاص بك. + +## التدريب (Train) + + + + + + +إذا لم تكن معتادًا على ضبط نموذج باستخدام [`Trainer`]، فألق نظرة على البرنامج التعليمي الأساسي [هنا](../training#train-with-pytorch-trainer)! + + + +أنت جاهز لبدء تدريب نموذجك الآن! قم بتحميل T5 باستخدام [`AutoModelForSeq2SeqLM`]: + +```py +>>> from transformers import AutoModelForSeq2SeqLM, Seq2SeqTrainingArguments, Seq2SeqTrainer + +>>> model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint) +``` + +في هذه المرحلة، لم يتبق سوى ثلاث خطوات: + +1. حدد مُعامِلات التدريب الخاصة بك في [`Seq2SeqTrainingArguments`]. المعامل الوحيد المطلوب هو `output_dir` الذي يُحدد مكان حفظ نموذجك. ستدفع هذا النموذج إلى Hub عن طريق تعيين `push_to_hub=True` (تحتاج إلى تسجيل الدخول إلى Hugging Face لتحميل نموذجك). في نهاية كل حقبة، سيقوم [`Trainer`] بتقييم مقياس ROUGE وحفظ نقطة تفتيش التدريب. +2. مرر مُعامِلات التدريب إلى [`Seq2SeqTrainer`] جنبًا إلى جنب مع النموذج ومجموعة البيانات والمُحلِّل اللغوي وجامع البيانات ودالة `compute_metrics`. +3. استدعِ [`~Trainer.train`] لضبط نموذجك. + +```py +>>> training_args = Seq2SeqTrainingArguments( +... output_dir="my_awesome_billsum_model", +... eval_strategy="epoch", +... learning_rate=2e-5, +... per_device_train_batch_size=16, +... per_device_eval_batch_size=16, +... weight_decay=0.01, +... save_total_limit=3, +... num_train_epochs=4, +... predict_with_generate=True, +... fp16=True, #change to bf16=True for XPU +... push_to_hub=True, +... ) + +>>> trainer = Seq2SeqTrainer( +... model=model, +... args=training_args, +... train_dataset=tokenized_billsum["train"], +... eval_dataset=tokenized_billsum["test"], +... processing_class=tokenizer, +... data_collator=data_collator, +... compute_metrics=compute_metrics, +... ) + +>>> trainer.train() +``` + +بمجرد اكتمال التدريب، شارك نموذجك مع Hub باستخدام طريقة [`~transformers.Trainer.push_to_hub`] حتى يتمكن الجميع من استخدام نموذجك: + +```py +>>> trainer.push_to_hub() +``` + + + + +إذا لم تكن معتادًا على ضبط نموذج باستخدام Keras، فألق نظرة على البرنامج التعليمي الأساسي [هنا](../training#train-a-tensorflow-model-with-keras)! + + +لضبط نموذج في TensorFlow، ابدأ بإعداد دالة مُحسِّن وجدول معدل التعلم وبعض معلمات التدريب: + +```py +>>> from transformers import create_optimizer, AdamWeightDecay + +>>> optimizer = AdamWeightDecay(learning_rate=2e-5, weight_decay_rate=0.01) +``` + +ثم يمكنك تحميل T5 باستخدام [`TFAutoModelForSeq2SeqLM`]: + +```py +>>> from transformers import TFAutoModelForSeq2SeqLM + +>>> model = TFAutoModelForSeq2SeqLM.from_pretrained(checkpoint) +``` + +حوّل مجموعات البيانات الخاصة بك إلى تنسيق `tf.data.Dataset` باستخدام [`~transformers.TFPreTrainedModel.prepare_tf_dataset`]: + +```py +>>> tf_train_set = model.prepare_tf_dataset( +... tokenized_billsum["train"], +... shuffle=True, +... batch_size=16, +... collate_fn=data_collator, +... ) + +>>> tf_test_set = model.prepare_tf_dataset( +... tokenized_billsum["test"], +... shuffle=False, +... batch_size=16, +... collate_fn=data_collator, +... ) +``` + +قم بتكوين النموذج للتدريب باستخدام [`compile`](https://keras.io/api/models/model_training_apis/#compile-method). لاحظ أن جميع نماذج Transformers لديها دالة خسارة ذات صلة بالمهمة افتراضيًا، لذلك لست بحاجة إلى تحديد واحدة ما لم تكن ترغب في ذلك: + +```py +>>> import tensorflow as tf + +>>> model.compile(optimizer=optimizer) # No loss argument! +``` + +آخر شيئين يجب إعدادهما قبل بدء التدريب هما حساب درجة ROUGE من التنبؤات، وتوفير طريقة لدفع نموذجك إلى Hub. يتم كلاهما باستخدام [استدعاءات Keras](../main_classes/keras_callbacks). + +مرر دالة `compute_metrics` الخاصة بك إلى [`~transformers.KerasMetricCallback`]: + +```py +>>> from transformers.keras_callbacks import KerasMetricCallback + +>>> metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_test_set) +``` + +حدد مكان دفع نموذجك ومُحلِّلك اللغوي في [`~transformers.PushToHubCallback`]: + +```py +>>> from transformers.keras_callbacks import PushToHubCallback + +>>> push_to_hub_callback = PushToHubCallback( +... output_dir="my_awesome_billsum_model", +... tokenizer=tokenizer, +... ) +``` + +ثم اجمع استدعاءاتك معًا: + +```py +>>> callbacks = [metric_callback, push_to_hub_callback] +``` + +أخيرًا، أنت جاهز لبدء تدريب نموذجك! اتصل بـ [`fit`](https://keras.io/api/models/model_training_apis/#fit-method) مع مجموعات بيانات التدريب والتحقق من الصحة وعدد الحقب واستدعاءاتك لضبط النموذج: + +```py +>>> model.fit(x=tf_train_set, validation_data=tf_test_set, epochs=3, callbacks=callbacks) +``` + +بمجرد اكتمال التدريب، يتم تحميل نموذجك تلقائيًا إلى Hub حتى يتمكن الجميع من استخدامه! + + + + + +للحصول على مثال أكثر تعمقًا حول كيفية ضبط نموذج للتجميع، ألقِ نظرة على [دفتر ملاحظات PyTorch](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/summarization.ipynb) +أو [دفتر ملاحظات TensorFlow](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/summarization-tf.ipynb) المقابل. + + + +## الاستدلال (Inference) + +رائع، الآن بعد أن قمت بضبط نموذج، يمكنك استخدامه للاستدلال! + +خدد بعض النصوص الذي ترغب في تلخيصها. بالنسبة لـ T5، تحتاج إلى إضافة بادئة إلى مُدخلاتك اعتمادًا على المهمة التي تعمل عليها. بالنسبة التلخيص، يجب عليك إضافة بادئة إلى مُدخلاتك كما هو موضح أدناه: + +```py +>>> text = "summarize: The Inflation Reduction Act lowers prescription drug costs, health care costs, and energy costs. It's the most aggressive action on tackling the climate crisis in American history, which will lift up American workers and create good-paying, union jobs across the country. It'll lower the deficit and ask the ultra-wealthy and corporations to pay their fair share. And no one making under $400,000 per year will pay a penny more in taxes." +``` + +أبسط طريقة لتجربة نموذجك المضبوط للاستدلال هي استخدامه في [`pipeline`]. استخدم `pipeline` للتلخيص باستخدام نموذجك، ومرر نصك إليه: + +```py +>>> from transformers import pipeline + +>>> summarizer = pipeline("summarization", model="username/my_awesome_billsum_model") +>>> summarizer(text) +[{"summary_text": "The Inflation Reduction Act lowers prescription drug costs, health care costs, and energy costs. It's the most aggressive action on tackling the climate crisis in American history, which will lift up American workers and create good-paying, union jobs across the country."}] +``` + +يمكنك أيضًا تكرار نتائج `pipeline` يدويًا إذا أردت: + + + +قسم النص وإرجع `input_ids` كتنسورات PyTorch: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("username/my_awesome_billsum_model") +>>> inputs = tokenizer(text, return_tensors="pt").input_ids +``` + +استخدم طريقة [`~generation.GenerationMixin.generate`] لإنشاء التلخيص. لمزيد من التفاصيل حول استراتيجيات توليد النص المختلفة والمعلمات للتحكم في التوليد، راجع واجهة برمجة تطبيقات [توليد النص](../main_classes/text_generation). + +```py +>>> from transformers import AutoModelForSeq2SeqLM + +>>> model = AutoModelForSeq2SeqLM.from_pretrained("username/my_awesome_billsum_model") +>>> outputs = model.generate(inputs, max_new_tokens=100, do_sample=False) +``` + +فك تشفير معرفات الرموز المولدة مرة أخرى إلى نص: + +```py +>>> tokenizer.decode(outputs[0], skip_special_tokens=True) +'the inflation reduction act lowers prescription drug costs, health care costs, and energy costs. it's the most aggressive action on tackling the climate crisis in american history. it will ask the ultra-wealthy and corporations to pay their fair share.' +``` + + +قسم النص وإرجع `input_ids` كتنسورات TensorFlow: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("username/my_awesome_billsum_model") +>>> inputs = tokenizer(text, return_tensors="tf").input_ids +``` + +استخدم طريقة [`~transformers.generation_tf_utils.TFGenerationMixin.generate`] لإنشاء التلخيص. لمزيد من التفاصيل حول استراتيجيات توليد النص المختلفة والمعلمات للتحكم في التوليد، راجع واجهة برمجة تطبيقات [توليد النص](../main_classes/text_generation). + +```py +>>> from transformers import TFAutoModelForSeq2SeqLM + +>>> model = TFAutoModelForSeq2SeqLM.from_pretrained("username/my_awesome_billsum_model") +>>> outputs = model.generate(inputs, max_new_tokens=100, do_sample=False) +``` + +فك تشفير معرفات الرموز المولدة مرة أخرى إلى نص: + +```py +>>> tokenizer.decode(outputs[0], skip_special_tokens=True) +'the inflation reduction act lowers prescription drug costs, health care costs, and energy costs. it's the most aggressive action on tackling the climate crisis in american history. it will ask the ultra-wealthy and corporations to pay their fair share.' +``` + + \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tasks/token_classification.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tasks/token_classification.md new file mode 100644 index 0000000000000000000000000000000000000000..e311482aeccb061a703144e2c7325b90971d883b --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tasks/token_classification.md @@ -0,0 +1,550 @@ + + +# تصنيف الرموز(Token classification) + +[[open-in-colab]] + + + +يهدف تصنيف الرموز إلى إعطاء تسمية لكل رمز على حدة في الجملة. من أكثر مهام تصنيف الرموز شيوعًا هو التعرف على الكيانات المسماة (NER). يحاول NER تحديد تسمية لكل كيان في الجملة، مثل شخص، أو مكان، أو منظمة. + +سيوضح لك هذا الدليل كيفية: + +1. ضبط [DistilBERT](https://huggingface.co/distilbert/distilbert-base-uncased) على مجموعة بيانات [WNUT 17](https://huggingface.co/datasets/wnut_17) للكشف عن كيانات جديدة. +2. استخدام نموذجك المضبوط بدقة للاستدلال. + + + +للاطلاع جميع البنى والنقاط المتوافقة مع هذه المهمة، نوصي بالرجوع من [صفحة المهمة](https://huggingface.co/tasks/token-classification). + + + +قبل أن تبدأ، تأكد من تثبيت جميع المكتبات الضرورية: + +```bash +pip install transformers datasets evaluate seqeval +``` + +نحن نشجعك على تسجيل الدخول إلى حساب HuggingFace الخاص بك حتى تتمكن من تحميل ومشاركة نموذجك مع المجتمع. عندما يُطلب منك، أدخل رمزك لتسجيل الدخول: + +```py +>>> from huggingface_hub import notebook_login + +>>> notebook_login() +``` + +## تحميل مجموعة بيانات WNUT 17 + +ابدأ بتحميل مجموعة بيانات WNUT 17 من مكتبة 🤗 Datasets: + +```py +>>> from datasets import load_dataset + +>>> wnut = load_dataset("wnut_17") +``` + +ثم ألق نظرة على مثال: + +```py +>>> wnut["train"][0] +{'id': '0', + 'ner_tags': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0], + 'tokens': ['@paulwalk', 'It', "'s", 'the', 'view', 'from', 'where', 'I', "'m", 'living', 'for', 'two', 'weeks', '.', 'Empire', 'State', 'Building', '=', 'ESB', '.', 'Pretty', 'bad', 'storm', 'here', 'last', 'evening', '.'] +} +``` + +يمثل كل رقم في `ner_tags` كياناً. حوّل الأرقام إلى أسماء التصنيفات لمعرفة ماهية الكيانات: + +```py +>>> label_list = wnut["train"].features[f"ner_tags"].feature.names +>>> label_list +[ + "O", + "B-corporation", + "I-corporation", + "B-creative-work", + "I-creative-work", + "B-group", + "I-group", + "B-location", + "I-location", + "B-person", + "I-person", + "B-product", + "I-product", +] +``` + +يشير الحرف الذي يسبق كل `ner_tag` إلى موضع الرمز للكيان: + +- `B-` يشير إلى بداية الكيان. +- `I-` يشير إلى أن الرمز يقع ضمن نفس الكيان (على سبيل المثال، الرمز `State` هو جزء من كيان مثل `Empire State Building`). +- `0` يشير إلى أن الرمز لا يمثل أي كيان. + +## المعالجة المسبقة(Preprocess) + + + +الخطوة التالية هي تحميل مُجزِّئ النصوص DistilBERT للمعالجة المسبقة لحقل `tokens`: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased") +``` + +كما رأيت في حقل `tokens` المثال أعلاه، يبدو أن المدخل قد تم تحليله بالفعل. لكن المدخل لم يُجزأ بعد ويتعيّن عليك ضبط `is_split_into_words=True` لتقسيم الكلمات إلى كلمات فرعية. على سبيل المثال: + +```py +>>> example = wnut["train"][0] +>>> tokenized_input = tokenizer(example["tokens"], is_split_into_words=True) +>>> tokens = tokenizer.convert_ids_to_tokens(tokenized_input["input_ids"]) +>>> tokens +['[CLS]', '@', 'paul', '##walk', 'it', "'", 's', 'the', 'view', 'from', 'where', 'i', "'", 'm', 'living', 'for', 'two', 'weeks', '.', 'empire', 'state', 'building', '=', 'es', '##b', '.', 'pretty', 'bad', 'storm', 'here', 'last', 'evening', '.', '[SEP]'] +``` + +ومع ذلك، يضيف هذا بعض الرموز الخاصة `[CLS]` و`[SEP]` وتقسيم الكلمات إلى أجزاء يُنشئ عدم تطابق بين المُدخلات والتسميات. قد يتم تقسيم كلمة واحدة تقابل تسمية واحدة الآن إلى كلمتين فرعيتين. ستحتاج إلى إعادة محاذاة الرموز والتسميات عن طريق: + +1. ربط كل رمز بالكلمة الأصلية باستخدام الخاصية [`word_ids`](https://huggingface.co/docs/transformers/main_classes/tokenizer#transformers.BatchEncoding.word_ids). +2. تعيين التسمية `-100` للرموز الخاصة `[CLS]` و`[SEP]` بحيث يتم تجاهلها بواسطة دالة الخسارة PyTorch (انظر [CrossEntropyLoss](https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html)). +3. تسمية الرمز الأول فقط لكلمة معينة. قم بتعيين `-100` لأجزاء الكلمة الأخرى. + +هنا كيف يمكنك إنشاء وظيفة لإعادة محاذاة الرموز والتسميات، وقص الجمل لتتجاوز الحد الأقصى لطول مُدخلات DistilBERT: + +```py +>>> def tokenize_and_align_labels(examples): +... tokenized_inputs = tokenizer(examples["tokens"], truncation=True, is_split_into_words=True) + +... labels = [] +... for i, label in enumerate(examples[f"ner_tags"]): +... word_ids = tokenized_inputs.word_ids(batch_index=i) # تعيين الرموز إلى كلماتهم المقابلة. +... previous_word_idx = None +... label_ids = [] +... for word_idx in word_ids: # تعيين الرموز الخاصة إلى -100. +... if word_idx is None: +... label_ids.append(-100) +... elif word_idx != previous_word_idx: # تسمية الرمز الأول فقط لكلمة معينة. +... label_ids.append(label[word_idx]) +... else: +... label_ids.append(-100) +... previous_word_idx = word_idx +... labels.append(label_ids) + +... tokenized_inputs["labels"] = labels +... return tokenized_inputs +``` + +لتطبيق هذه العملية على كامل مجموعة البيانات، استخدم الدالة [`~datasets.Dataset.map`] لمجموعة بيانات 🤗. يمكنك تسريع الدالة `map` عن طريق تعيين `batched=True` لمعالجة عناصر متعددة من مجموعة البيانات في وقت واحد: + +```py +>>> tokenized_wnut = wnut.map(tokenize_and_align_labels, batched=True) +``` + +الآن قم بإنشاء دفعة من الأمثلة باستخدام [`DataCollatorWithPadding`].من الأفضل استخدام *الحشو الديناميكي* للجمل إلى أطول طول في دفعة أثناء التجميع، بدلاً من حشو مجموعة البيانات بالكامل إلى الطول الأقصى. + + + +```py +>>> from transformers import DataCollatorForTokenClassification + +>>> data_collator = DataCollatorForTokenClassification(tokenizer=tokenizer) +``` + + +```py +>>> from transformers import DataCollatorForTokenClassification + +>>> data_collator = DataCollatorForTokenClassification(tokenizer=tokenizer, return_tensors="tf") +``` + + + +## التقييم(Evaluate) + +يُعدّ تضمين مقياس أثناء التدريب مفيدًا في تقييم أداء نموذجك. يمكنك تحميل طريقة تقييم بسرعة مع مكتبة 🤗 [Evaluate](https://huggingface.co/docs/evaluate/index). لهذه المهمة، قم بتحميل إطار [seqeval](https://huggingface.co/spaces/evaluate-metric/seqeval) (انظر جولة 🤗 Evaluate [quick tour](https://huggingface.co/docs/evaluate/a_quick_tour) لمعرفة المزيد حول كيفية تحميل وحساب مقياس). يُخرج seqeval عدة نتائج: الدقة، والاستذكار، ومقياس F1، والدقة. + +```py +>>> import evaluate + +>>> seqeval = evaluate.load("seqeval") +``` + +احصل على تسميات الكيانات المسماة (NER) أولاً،ثم أنشئ دالة تُمرر تنبؤاتك وتسمياتك الصحيحة إلى [`~evaluate.EvaluationModule.compute`] لحساب النتائج: + +```py +>>> import numpy as np + +>>> labels = [label_list[i] for i in example[f"ner_tags"]] + +>>> def compute_metrics(p): +... predictions, labels = p +... predictions = np.argmax(predictions, axis=2) + +... true_predictions = [ +... [label_list[p] for (p, l) in zip(prediction, label) if l != -100] +... for prediction, label in zip(predictions, labels) +... ] +... true_labels = [ +... [label_list[l] for (p, l) in zip(prediction, label) if l != -100] +... for prediction, label in zip(predictions, labels) +... ] + +... results = seqeval.compute(predictions=true_predictions, references=true_labels) +... return { +... "precision": results["overall_precision"], +... "recall": results["overall_recall"], +... "f1": results["overall_f1"], +... "accuracy": results["overall_accuracy"], +... } +``` + +دالة `compute_metrics` جاهزة للاستخدام، وستحتاج إليها عند إعداد التدريب. + +## التدريب(Train) + +قبل تدريب النموذج، جهّز خريطة تربط بين المعرّفات المتوقعة وتسمياتها باستخدام `id2label` و `label2id`: + +```py +>>> id2label = { +... 0: "O", +... 1: "B-corporation", +... 2: "I-corporation", +... 3: "B-creative-work", +... 4: "I-creative-work", +... 5: "B-group", +... 6: "I-group", +... 7: "B-location", +... 8: "I-location", +... 9: "B-person", +... 10: "I-person", +... 11: "B-product", +... 12: "I-product", +... } +>>> label2id = { +... "O": 0, +... "B-corporation": 1, +... "I-corporation": 2, +... "B-creative-work": 3, +... "I-creative-work": 4, +... "B-group": 5, +... "I-group": 6, +... "B-location": 7, +... "I-location": 8, +... "B-person": 9, +... "I-person": 10, +... "B-product": 11, +... "I-product": 12, +... } +``` + + + + + +إذا لم تكن على دراية بتعديل نموذج باستخدام [`Trainer`], ألق نظرة على الدليل التعليمي الأساسي [هنا](../training#train-with-pytorch-trainer)! + + + +أنت مستعد الآن لبدء تدريب نموذجك! قم بتحميل DistilBERT مع [`AutoModelForTokenClassification`] إلى جانب عدد التصنيفات المتوقعة، وخريطة التسميات: + +```py +>>> from transformers import AutoModelForTokenClassification, TrainingArguments, Trainer + +>>> model = AutoModelForTokenClassification.from_pretrained( +... "distilbert/distilbert-base-uncased", num_labels=13, id2label=id2label, label2id=label2id +... ) +``` + +في هذه المرحلة، هناك ثلاث خطوات فقط متبقية: + +1. حدد معلمات التدريب الخاصة بك في [`TrainingArguments`]. المعامل الوحيد المطلوب هو `output_dir` الذي يحدد مكان حفظ نموذجك. ستقوم بدفع هذا النموذج إلى Hub عن طريق تعيين `push_to_hub=True` (يجب أن تكون مسجلاً الدخول إلى Hugging Face لتحميل نموذجك). في نهاية كل حقبة، سيقوم [`Trainer`] بتقييم درجات seqeval وحفظ تسخة التدريب. +2. قم بتمرير معاملات التدريب إلى [`Trainer`] إلى جانب النموذج، ومجموعة البيانات، والمُجزِّئ اللغوي، و`data collator`، ودالة `compute_metrics`. +3.استدعِ [`~Trainer.train`] لتدريب نموذجك. + +```py +>>> training_args = TrainingArguments( +... output_dir="my_awesome_wnut_model", +... learning_rate=2e-5, +... per_device_train_batch_size=16, +... per_device_eval_batch_size=16, +... num_train_epochs=2, +... weight_decay=0.01, +... eval_strategy="epoch", +... save_strategy="epoch", +... load_best_model_at_end=True, +... push_to_hub=True, +... ) + +>>> trainer = Trainer( +... model=model, +... args=training_args, +... train_dataset=tokenized_wnut["train"], +... eval_dataset=tokenized_wnut["test"], +... processing_class=tokenizer, +... data_collator=data_collator, +... compute_metrics=compute_metrics, +... ) + +>>> trainer.train() +``` + +بمجرد اكتمال التدريب، شارك نموذجك على Hub باستخدام طريقة [`~transformers.Trainer.push_to_hub`] حتى يتمكن الجميع من استخدام نموذجك: + +```py +>>> trainer.push_to_hub() +``` + + + + +إذا لم تكن على دراية بتعديل نموذج باستخدام Keras، ألق نظرة على الدليل التعليمي الأساسي [هنا](../training#train-a-tensorflow-model-with-keras)! + + +للتعديل على نموذج في TensorFlow، ابدأ بإعداد دالة محسن، وجدول معدل التعلم، وبعض معلمات التدريب: + +```py +>>> from transformers import create_optimizer + +>>> batch_size = 16 +>>> num_train_epochs = 3 +>>> num_train_steps = (len(tokenized_wnut["train"]) // batch_size) * num_train_epochs +>>> optimizer, lr_schedule = create_optimizer( +... init_lr=2e-5, +... num_train_steps=num_train_steps, +... weight_decay_rate=0.01, +... num_warmup_steps=0, +... ) +``` + +ثم يمكنك تحميل DistilBERT مع [`TFAutoModelForTokenClassification`] إلى جانب عدد التسميات المتوقعة، وتخطيطات التسميات: + +```py +>>> from transformers import TFAutoModelForTokenClassification + +>>> model = TFAutoModelForTokenClassification.from_pretrained( +... "distilbert/distilbert-base-uncased", num_labels=13, id2label=id2label, label2id=label2id +... ) +``` + +قم بتحويل مجموعات بياناتك إلى تنسيق `tf.data.Dataset` مع [`~transformers.TFPreTrainedModel.prepare_tf_dataset`]: + +```py +>>> tf_train_set = model.prepare_tf_dataset( +... tokenized_wnut["train"], +... shuffle=True, +... batch_size=16, +... collate_fn=data_collator, +... ) + +>>> tf_validation_set = model.prepare_tf_dataset( +... tokenized_wnut["validation"], +... shuffle=False, +... batch_size=16, +... collate_fn=data_collator, +... ) +``` + +هيّئ النموذج للتدريب باستخدام [`compile`](https://keras.io/api/models/model_training_apis/#compile-method). لاحظ أن نماذج Transformers تتضمن دالة خسارة افتراضية مرتبطة بالمهمة، لذلك لا تحتاج إلى تحديد واحدة إلا إذا كنت ترغب في ذلك: + +```py +>>> import tensorflow as tf + +>>> model.compile(optimizer=optimizer) # No loss argument! +``` + +آخر أمرين يجب إعدادهما قبل بدء التدريب هو حساب درجات seqeval من التنبؤات، وتوفير طريقة لدفع نموذجك إلى Hub. يتم ذلك باستخدام [Keras callbacks](../main_classes/keras_callbacks). + +مرر دالة `compute_metrics` الخاصة بك إلى [`~transformers.KerasMetricCallback`]: + +```py +>>> from transformers.keras_callbacks import KerasMetricCallback + +>>> metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_validation_set) +``` + +حدد مكان دفع نموذجك والمحلل اللغوي في [`~transformers.PushToHubCallback`]: + +```py +>>> from transformers.keras_callbacks import PushToHubCallback + +>>> push_to_hub_callback = PushToHubCallback( +... output_dir="my_awesome_wnut_model", +... tokenizer=tokenizer, +... ) +``` + +ثم جمّع callbacks الخاصة بك معًا: + +```py +>>> callbacks = [metric_callback, push_to_hub_callback] +``` + +أخيرًا، أنت جاهز الآن لبدء تدريب نموذجك! قم باستدعاء [`fit`](https://keras.io/api/models/model_training_apis/#fit-method) مع بيانات التدريب والتحقق، وعدد الحقبات، وcallbacks لتعديل النموذج: + +```py +>>> model.fit(x=tf_train_set, validation_data=tf_validation_set, epochs=3, callbacks=callbacks) +``` + +بمجرد اكتمال التدريب، يتم تحميل نموذجك تلقائيًا إلى Hub حتى يتمكن الجميع من استخدامه! + + + + + +للحصول على مثال أكثر تفصيلاً حول كيفية تعديل نموذج لتصنيف الرموز، ألق نظرة على الدفتر المقابل +[دفتر PyTorch](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification.ipynb) +أو [دفتر TensorFlow](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification-tf.ipynb). + + + +## الاستدلال(Inference) + +رائع، الآن بعد أن قمت بتعديل نموذج، يمكنك استخدامه للاستدلال! + +احصل على بعض النصوص التي تريد تشغيل الاستدلال عليها: + +```py +>>> text = "The Golden State Warriors are an American professional basketball team based in San Francisco." +``` + +أبسط طريقة لتجربة نموذجك المُدرب مسبقًا للاستدلال هي استخدامه في [`pipeline`]. قم بتنفيذ `pipeline` لتصنيف الكيانات المسماة مع نموذجك، ومرر نصك إليه: + +```py +>>> from transformers import pipeline + +>>> classifier = pipeline("ner", model="stevhliu/my_awesome_wnut_model") +>>> classifier(text) +[{'entity': 'B-location', + 'score': 0.42658573, + 'index': 2, + 'word': 'golden', + 'start': 4, + 'end': 10}, + {'entity': 'I-location', + 'score': 0.35856336, + 'index': 3, + 'word': 'state', + 'start': 11, + 'end': 16}, + {'entity': 'B-group', + 'score': 0.3064001, + 'index': 4, + 'word': 'warriors', + 'start': 17, + 'end': 25}, + {'entity': 'B-location', + 'score': 0.65523505, + 'index': 13, + 'word': 'san', + 'start': 80, + 'end': 83}, + {'entity': 'B-location', + 'score': 0.4668663, + 'index': 14, + 'word': 'francisco', + 'start': 84, + 'end': 93}] +``` + +يمكنك أيضًا تكرار نتائج `pipeline` يدويًا إذا أردت: + + + +قسّم النص إلى رموز وأرجع المُوتّرات بلغة PyTorch: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_wnut_model") +>>> inputs = tokenizer(text, return_tensors="pt") +``` + +مرر مدخلاتك إلى النموذج واحصل على `logits`: + +```py +>>> from transformers import AutoModelForTokenClassification + +>>> model = AutoModelForTokenClassification.from_pretrained("stevhliu/my_awesome_wnut_model") +>>> with torch.no_grad(): +... logits = model(**inputs).logits +``` + +استخرج الفئة ذات الاحتمالية الأعلى، واستخدم جدول `id2label` الخاصة بالنموذج لتحويلها إلى تسمية نصية: + +```py +>>> predictions = torch.argmax(logits, dim=2) +>>> predicted_token_class = [model.config.id2label[t.item()] for t in predictions[0]] +>>> predicted_token_class +['O', + 'O', + 'B-location', + 'I-location', + 'B-group', + 'O', + 'O', + 'O', + 'O', + 'O', + 'O', + 'O', + 'O', + 'B-location', + 'B-location', + 'O', + 'O'] +``` + + +قسّم النص إلى رموز وأرجع المُوتّرات ب TensorFlow: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_wnut_model") +>>> inputs = tokenizer(text, return_tensors="tf") +``` + +مرر مدخلاتك إلى النموذج واحصل على `logits`: + +```py +>>> from transformers import TFAutoModelForTokenClassification + +>>> model = TFAutoModelForTokenClassification.from_pretrained("stevhliu/my_awesome_wnut_model") +>>> logits = model(**inputs).logits +``` + +استخرج الفئة ذات الاحتمالية الأعلى، واستخدم جدول `id2label` الخاصة بالنموذج لتحويلها إلى تسمية نصية: + +```py +>>> predicted_token_class_ids = tf.math.argmax(logits, axis=-1) +>>> predicted_token_class = [model.config.id2label[t] for t in predicted_token_class_ids[0].numpy().tolist()] +>>> predicted_token_class +['O', + 'O', + 'B-location', + 'I-location', + 'B-group', + 'O', + 'O', + 'O', + 'O', + 'O', + 'O', + 'O', + 'O', + 'B-location', + 'B-location', + 'O', + 'O'] +``` + + diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tasks/translation.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tasks/translation.md new file mode 100644 index 0000000000000000000000000000000000000000..6245b903c22d63ef295cff91a98bb505ef6ee2ca --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tasks/translation.md @@ -0,0 +1,407 @@ + + +# الترجمة(Translation) + +[[open-in-colab]] + + + +الترجمة هي عملية تحويل سلسلة نصية من لغة إلى أخرى. وهي إحدى المهام التي يمكن صياغتها كمسألة تسلسل إلى تسلسل، وهو إطار عمل قوي لإنتاج مخرجات من مدخلات، مثل الترجمة أو التلخيص. تُستخدم أنظمة الترجمة عادةً للترجمة بين نصوص لغات مختلفة، ويمكن استخدامها أيضًا لترجمة الكلام أو لمهام تجمع بين النصوص والكلام، مثل تحويل النص إلى كلام أو تحويل الكلام إلى نص. + +سيوضح لك هذا الدليل كيفية: + +1. ضبط دقيق لنموذج [T5](https://huggingface.co/google-t5/t5-small) على المجموعة الفرعية الإنجليزية-الفرنسية من مجموعة بيانات [OPUS Books](https://huggingface.co/datasets/opus_books) لترجمة النص الإنجليزي إلى الفرنسية. +2. استخدام النموذج المضبوط بدقة للاستدلال. + + + +لمشاهدة جميع البنى والنسخ المتوافقة مع هذه المهمة، نوصي بالتحقق من [صفحة المهمة](https://huggingface.co/tasks/translation). + + + +قبل البدء، تأكد من تثبيت جميع المكتبات الضرورية: + +```bash +pip install transformers datasets evaluate sacrebleu +``` + +نشجعك على تسجيل الدخول إلى حساب Hugging Face الخاص بك حتى تتمكن من تحميل نموذجك ومشاركته مع المجتمع. عند الطلب، أدخل الرمز المميز الخاص بك لتسجيل الدخول: + +```py +>>> from huggingface_hub import notebook_login + +>>> notebook_login() +``` + +## تحميل مجموعة بيانات OPUS Books + +ابدأ بتحميل المجموعة الفرعية الإنجليزية-الفرنسية من مجموعة بيانات [OPUS Books](https://huggingface.co/datasets/opus_books) من مكتبة 🤗 Datasets: + +```py +>>> from datasets import load_dataset + +>>> books = load_dataset("opus_books", "en-fr") +``` + +قسّم مجموعة البيانات إلى مجموعة تدريب ومجموعة اختبار باستخدام طريقة [`~datasets.Dataset.train_test_split`]: + +```py +>>> books = books["train"].train_test_split(test_size=0.2) +``` + +ثم ألقِ نظرة على مثال: + +```py +>>> books["train"][0] +{'id': '90560', + 'translation': {'en': 'But this lofty plateau measured only a few fathoms, and soon we reentered Our Element.', + 'fr': 'Mais ce plateau élevé ne mesurait que quelques toises, et bientôt nous fûmes rentrés dans notre élément.'}} +``` + +`translation`: ترجمة إنجليزية وفرنسية للنص. + +## المعالجة المسبقة(Preprocess) + + + +الخطوة التالية هي تحميل مُجزئ T5 لمعالجة أزواج اللغة الإنجليزية-الفرنسية: + +```py +>>> from transformers import AutoTokenizer + +>>> checkpoint = "google-t5/t5-small" +>>> tokenizer = AutoTokenizer.from_pretrained(checkpoint) +``` + +يجب أن تقوم دالة المعالجة المسبقة التي تُريد إنشاءها بما يلي: + +1. إضافة بادئة إلى المُدخل بمُوجه حتى يعرف T5 أن هذه مهمة ترجمة. تتطلب بعض النماذج القادرة على أداء مهام متعددة توجيهًا لمهام مُحددة. +2. تعيين اللغة الهدف (الفرنسية) في معامل `text_target` لضمان معالجة المُجزئ للنص بشكل صحيح. إذا لم تُعيّن `text_target`، فسيُعالج المُجزئ النص على أنه إنجليزي. +3. اقتطاع التسلسلات بحيث لا يزيد طولها عن الحد الأقصى الذي يحدده معامل `max_length`. + +```py +>>> source_lang = "en" +>>> target_lang = "fr" +>>> prefix = "translate English to French: " + +>>> def preprocess_function(examples): +... inputs = [prefix + example[source_lang] for example in examples["translation"]] +... targets = [example[target_lang] for example in examples["translation"]] +... model_inputs = tokenizer(inputs, text_target=targets, max_length=128, truncation=True) +... return model_inputs +``` + +لتطبيق دالة المعالجة المسبقة على مجموعة البيانات بأكملها، استخدم طريقة [`~datasets.Dataset.map`] من 🤗 Datasets. يمكنك تسريع دالة `map` عن طريق تعيين `batched=True` لمعالجة عناصر متعددة من مجموعة البيانات في وقت واحد: + +```py +>>> tokenized_books = books.map(preprocess_function, batched=True) +``` + +الآن أنشئ دفعة من الأمثلة باستخدام [`DataCollatorForSeq2Seq`]. من الأكثر كفاءة *الحشو الديناميكي* للجمل إلى أطول طول في دفعة أثناء التجميع، بدلاً من حشو مجموعة البيانات بأكملها إلى الحد الأقصى للطول. + + + + +```py +>>> from transformers import DataCollatorForSeq2Seq + +>>> data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=checkpoint) +``` + + + +```py +>>> from transformers import DataCollatorForSeq2Seq + +>>> data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=checkpoint, return_tensors="tf") +``` + + + +## التقييم (Evaluate) + +غالباً ما يكون تضمين مقياس أثناء التدريب مفيداً لتقييم أداء نموذجك. يمكنك تحميل طريقة تقييم بسرعة باستخدام مكتبة 🤗 [Evaluate](https://huggingface.co/docs/evaluate/index). لهذه المهمة، حمّل مقياس [SacreBLEU](https://huggingface.co/spaces/evaluate-metric/sacrebleu) (راجع [الجولة السريعة](https://huggingface.co/docs/evaluate/a_quick_tour) لـ 🤗 Evaluate لمعرفة المزيد حول كيفية تحميل وحساب مقياس): + +```py +>>> import evaluate + +>>> metric = evaluate.load("sacrebleu") +``` + +ثم أنشئ دالة تُمرر تنبؤاتك وتسمياتك إلى [`~evaluate.EvaluationModule.compute`] لحساب درجة SacreBLEU: + +```py +>>> import numpy as np + +>>> def postprocess_text(preds, labels): +... preds = [pred.strip() for pred in preds] +... labels = [[label.strip()] for label in labels] + +... return preds, labels + +>>> def compute_metrics(eval_preds): +... preds, labels = eval_preds +... if isinstance(preds, tuple): +... preds = preds[0] +... decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True) + +... labels = np.where(labels != -100, labels, tokenizer.pad_token_id) +... decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True) + +... decoded_preds, decoded_labels = postprocess_text(decoded_preds, decoded_labels) + +... result = metric.compute(predictions=decoded_preds, references=decoded_labels) +... result = {"bleu": result["score"]} + +... prediction_lens = [np.count_nonzero(pred != tokenizer.pad_token_id) for pred in preds] +... result["gen_len"] = np.mean(prediction_lens) +... result = {k: round(v, 4) for k, v in result.items()} +... return result +``` + +دالة `compute_metrics` الخاصة بك جاهزة الآن، وسوف تعود إليها عند إعداد التدريب. + +## التدريب (Train) + + + + + + +إذا لم تكن معتادًا على ضبط دقيق نموذج باستخدام [`Trainer`], فألقِ نظرة على البرنامج التعليمي الأساسي [هنا](../training#train-with-pytorch-trainer)! + + + +أنت جاهز لبدء تدريب نموذجك الآن! حمّل T5 باستخدام [`AutoModelForSeq2SeqLM`]: + +```py +>>> from transformers import AutoModelForSeq2SeqLM, Seq2SeqTrainingArguments, Seq2SeqTrainer + +>>> model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint) +``` + +في هذه المرحلة، تبقى ثلاث خطوات فقط: + +1. حدد مُعاملات للتدريب في [`Seq2SeqTrainingArguments`]. المُعامل الوحيدة المطلوبة هي `output_dir` التي تحدد مكان حفظ النموذج الخاص بك. ستقوم بدفع هذا النموذج إلى Hub عن طريق تعيين `push_to_hub=True` (يجب عليك تسجيل الدخول إلى Hugging Face لتحميل نموذجك). في نهاية كل حقبة، سيقوم [`Trainer`] بتقييم مقياس SacreBLEU وحفظ نقطة تدقيق التدريب. +2. مرر مُعاملات التدريب إلى [`Seq2SeqTrainer`] جنبًا إلى جنب مع النموذج ومجموعة البيانات والمعالج اللغوي وجامع البيانات ووظيفة `compute_metrics`. +3. نفّذ [`~Trainer.train`] لضبط نموذجك. + +```py +>>> training_args = Seq2SeqTrainingArguments( +... output_dir="my_awesome_opus_books_model", +... eval_strategy="epoch", +... learning_rate=2e-5, +... per_device_train_batch_size=16, +... per_device_eval_batch_size=16, +... weight_decay=0.01, +... save_total_limit=3, +... num_train_epochs=2, +... predict_with_generate=True, +... fp16=True, #change to bf16=True for XPU +... push_to_hub=True, +... ) + +>>> trainer = Seq2SeqTrainer( +... model=model, +... args=training_args, +... train_dataset=tokenized_books["train"], +... eval_dataset=tokenized_books["test"], +... processing_class=tokenizer, +... data_collator=data_collator, +... compute_metrics=compute_metrics, +... ) + +>>> trainer.train() +``` + +بمجرد اكتمال التدريب، شارك نموذجك مع Hub باستخدام طريقة [`~transformers.Trainer.push_to_hub`] حتى يتمكن الجميع من استخدام نموذجك: + +```py +>>> trainer.push_to_hub() +``` + + + + +إذا لم تكن معتادًا على ضبط نموذج باستخدام Keras، فألق نظرة على البرنامج التعليمي الأساسي [هنا](../training#train-a-tensorflow-model-with-keras)! + + +لضبط نموذج في TensorFlow، ابدأ بإعداد دالة مُحسِّن وجدول معدل تعلم وبعض المعلمات الفائقة للتدريب: + +```py +>>> from transformers import AdamWeightDecay + +>>> optimizer = AdamWeightDecay(learning_rate=2e-5, weight_decay_rate=0.01) +``` + +ثم يمكنك تحميل T5 باستخدام [`TFAutoModelForSeq2SeqLM`]: + +```py +>>> from transformers import TFAutoModelForSeq2SeqLM + +>>> model = TFAutoModelForSeq2SeqLM.from_pretrained(checkpoint) +``` + +حوّل مجموعات البيانات الخاصة بك إلى تنسيق `tf.data.Dataset` باستخدام [`~transformers.TFPreTrainedModel.prepare_tf_dataset`]: + +```py +>>> tf_train_set = model.prepare_tf_dataset( +... tokenized_books["train"], +... shuffle=True, +... batch_size=16, +... collate_fn=data_collator, +... ) + +>>> tf_test_set = model.prepare_tf_dataset( +... tokenized_books["test"], +... shuffle=False, +... batch_size=16, +... collate_fn=data_collator, +... ) +``` + +قم بتكوين النموذج للتدريب باستخدام [`compile`](https://keras.io/api/models/model_training_apis/#compile-method). لاحظ أن جميع نماذج Transformers تحتوي على دالة خسارة ذات صلة بالمهمة بشكل افتراضي، لذلك لا تحتاج إلى تحديد واحدة إلا إذا كنت ترغب في ذلك: + +```py +>>> import tensorflow as tf + +>>> model.compile(optimizer=optimizer) # No loss argument! +``` + +آخر شيئين يجب إعدادهما قبل بدء التدريب هما حساب مقياس SacreBLEU من التوقعات، وتوفير طريقة لدفع نموذجك إلى Hub. يتم كلاهما باستخدام [استدعاءات Keras](../main_classes/keras_callbacks). + +مرر دالة `compute_metrics` الخاصة بك إلى [`~transformers.KerasMetricCallback`]: + +```py +>>> from transformers.keras_callbacks import KerasMetricCallback + +>>> metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_test_set) +``` + +حدد مكان دفع نموذجك ومعالجك اللغوي في [`~transformers.PushToHubCallback`]: + +```py +>>> from transformers.keras_callbacks import PushToHubCallback + +>>> push_to_hub_callback = PushToHubCallback( +... output_dir="my_awesome_opus_books_model", +... tokenizer=tokenizer, +... ) +``` + +ثم اجمع استدعاءاتك معًا: + +```py +>>> callbacks = [metric_callback, push_to_hub_callback] +``` + +أخيرًا، أنت جاهز لبدء تدريب نموذجك! اتصل بـ [`fit`](https://keras.io/api/models/model_training_apis/#fit-method) مع مجموعات بيانات التدريب والتحقق من الصحة وعدد الحقب واستدعاءاتك لضبط النموذج: + +```py +>>> model.fit(x=tf_train_set, validation_data=tf_test_set, epochs=3, callbacks=callbacks) +``` + +بمجرد اكتمال التدريب، يتم تحميل نموذجك تلقائيًا إلى Hub حتى يتمكن الجميع من استخدامه! + + + + + +للحصول على مثال أكثر تعمقًا لكيفية ضبط نموذج للترجمة، ألق نظرة على [دفتر ملاحظات PyTorch](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/translation.ipynb) المقابل +أو [دفتر ملاحظات TensorFlow](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/translation-tf.ipynb). + + + +## الاستدلال (Inference) + +رائع، الآن بعد أن قمت بضبط نموذج، يمكنك استخدامه للاستدلال! + +أحضر بعض النصوص التي ترغب في ترجمتها إلى لغة أخرى. بالنسبة لـ T5، تحتاج إلى إضافة بادئة إلى مدخلاتك اعتمادًا على المهمة التي تعمل عليها. للترجمة من الإنجليزية إلى الفرنسية، يجب عليك إضافة بادئة إلى مدخلاتك كما هو موضح أدناه: + +```py +>>> text = "translate English to French: Legumes share resources with nitrogen-fixing bacteria." +``` + +أبسط طريقة لتجربة نموذجك المضبوط للاستدلال هي استخدامه في [`pipeline`]. قم بإنشاء مثيل لـ `pipeline` للترجمة باستخدام نموذجك، ومرر النص الخاص بك إليه: + +```py +>>> from transformers import pipeline + +# تغيير `xx` إلى لغة الإدخال و `yy` إلى لغة المخرجات المطلوبة. +# أمثلة: "en" للغة الإنجليزية، "fr" للغة الفرنسية، "de" للغة الألمانية، "es" للغة الإسبانية، "zh" للغة الصينية، إلخ؛ translation_en_to_fr تترجم من الإنجليزية إلى الفرنسية +# يمكنك عرض جميع قوائم اللغات هنا - https://huggingface.co/languages +>>> translator = pipeline("translation_xx_to_yy", model="username/my_awesome_opus_books_model") +>>> translator(text) +[{'translation_text': 'Legumes partagent des ressources avec des bactéries azotantes.'}] +``` + +يمكنك أيضًا تكرار نتائج `pipeline` يدويًا إذا أردت: + + + +قم بتحويل النص إلى رموز وإرجاع `input_ids` كموترات PyTorch: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("username/my_awesome_opus_books_model") +>>> inputs = tokenizer(text, return_tensors="pt").input_ids +``` + +استخدم الدالة [`~generation.GenerationMixin.generate`] لإنشاء الترجمة. لمزيد من التفاصيل حول استراتيجيات توليد النصوص المختلفة والمعلمات للتحكم في التوليد، تحقق من واجهة برمجة تطبيقات [توليد النصوص](../main_classes/text_generation). + +```py +>>> from transformers import AutoModelForSeq2SeqLM + +>>> model = AutoModelForSeq2SeqLM.from_pretrained("username/my_awesome_opus_books_model") +>>> outputs = model.generate(inputs, max_new_tokens=40, do_sample=True, top_k=30, top_p=0.95) +``` + +فك تشفير معرفات الرموز المولدة مرة أخرى إلى نص: + +```py +>>> tokenizer.decode(outputs[0], skip_special_tokens=True) +'Les lignées partagent des ressources avec des bactéries enfixant l'azote.' +``` + + +قم بتحويل النص إلى رموز وإرجاع `input_ids` كموترات TensorFlow: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("username/my_awesome_opus_books_model") +>>> inputs = tokenizer(text, return_tensors="tf").input_ids +``` + +استخدم طريقة [`~transformers.generation_tf_utils.TFGenerationMixin.generate`] لإنشاء الترجمة. لمزيد من التفاصيل حول استراتيجيات توليد النصوص المختلفة والمعلمات للتحكم في التوليد، تحقق من واجهة برمجة تطبيقات [توليد النصوص](../main_classes/text_generation). + +```py +>>> from transformers import TFAutoModelForSeq2SeqLM + +>>> model = TFAutoModelForSeq2SeqLM.from_pretrained("username/my_awesome_opus_books_model") +>>> outputs = model.generate(inputs, max_new_tokens=40, do_sample=True, top_k=30, top_p=0.95) +``` + +فك تشفير معرفات الرموز المولدة مرة أخرى إلى نص: + +```py +>>> tokenizer.decode(outputs[0], skip_special_tokens=True) +'Les lugumes partagent les ressources avec des bactéries fixatrices d'azote.' +``` + + \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tasks_explained.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tasks_explained.md new file mode 100644 index 0000000000000000000000000000000000000000..dbc50192b4e3d4bfdd5cce4cec96961aab6b58d6 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tasks_explained.md @@ -0,0 +1,279 @@ +# كيف تُنجز نماذج 🤗 Transformers المهام؟ + +في [ما الذي يمكن أن تفعله نماذج 🤗 Transformers](task_summary)، تعلمت عن معالجة اللغات الطبيعية (NLP)، والخطاب والصوت، ورؤية الحاسب، وبعض تطبيقاتها المهمة. ستلقي هذه الصفحة نظرة فاحصة على كيفية حل النماذج لهذه المهام وتوضيح ما يحدث ما يحدث وراء الكواليس. هناك العديد من الطرق لحل مهمة معينة، وقد تنفذ بعض النماذج تقنيات معينة أو حتى تتناول المهمة من زاوية جديدة، ولكن بالنسبة لنماذج Transformer، فإن الفكرة العامة هي نفسها. وبفضل تصميمها المرن، فنظراً لهيكلها المرن، تُعدّ معظم النماذج عبارة عن متغير من بنية المُشفّر (Encoder) أو المُفكّك (Decoder) أو المُشفّر - المُفكّك (Encoder-Decoder). بالإضافة إلى نماذج Transformer، تحتوي مكتبتنا أيضًا على العديد من الشبكات العصبية التلافيفية (CNNs)، والتي لا تزال تستخدم حتى اليوم لمهام رؤية الحاسب. سنشرح أيضًا كيف تعمل شبكة عصبية تلافيفية CNN الحديثة. + +لشرح كيفية حل المهام، سنشرح ما يحدث داخل النموذج لإخراج تنبؤات مفيدة. + +- [Wav2Vec2](model_doc/wav2vec2) لتصنيف الصوت والتعرف التلقائي على الكلام (ASR) +- [Vision Transformer (ViT)](model_doc/vit) و [ConvNeXT](model_doc/convnext) لتصنيف الصور +- [DETR](model_doc/detr) للكشف عن الأجسام +- [Mask2Former](model_doc/mask2former) لتجزئة الصورة +- [GLPN](model_doc/glpn) لتقدير العمق +- [BERT](model_doc/bert) لمهام NLP مثل تصنيف النصوص، وتصنيف الرموز، والإجابة على الأسئلة التي تستخدم مشفرًا +- [GPT2](model_doc/gpt2) لمهام NLP مثل توليد النصوص التي تستخدم فك تشفير +- [BART](model_doc/bart) لمهام NLP مثل الملخص والترجمة التي تستخدم ترميز-فك تشفير + + + +قبل المتابعة، من الجيد أن يكون لديك بعض المعرفة الأساسية بهيكلية المحولات (Transformer Architecture) الأصلية. إن معرفة كيفية عمل المُشفّرات (Encoders) والمُفكّكات (Decoders) وآلية الانتباه (Attention Mechanism) سوف تساعدك في فهم كيفية عمل نماذج Transformer المختلفة. إذا كنت مبتدئًا أو بحاجة إلى مراجعة، فراجع [دورتنا](https://huggingface.co/course/chapter1/4؟fw=pt) لمزيد من المعلومات! + + + +## الكلام والصوت (Speech and audio) + +يُعدّ [Wav2Vec2](model_doc/wav2vec2) نموذجًا مُدرَّبًا ذاتيًا (Self-Supervised) على بيانات الكلام غير المُصنّفة، ويُمكن ضبطه بدقة (Fine-tuning) على بيانات موسومة لأداء مهام تصنيف الصوت والتعرف التلقائي على الكلام. + +
+ +
+ +يتكون هذا النموذج على أربعة مكونات رئيسية: + +1. *مشفّر الميزات (Feature Encoder)* يأخذ الموجة الصوتية الخام، ويقوم بتطبيعها (Normalization) إلى متوسط صفري وانحراف معياري وحدوي، وتحويلها إلى تسلسل من متجهات الميزات التي يبلغ طول كل منها 20 مللي ثانية. + +2. *وحدة التكميم (Quantization Module):** تتميز أشكال الموجات الصوتية بطبيعتها المُستمرة،، لذلك لا يمكن تقسيمها إلى وحدات منفصلة كما يمكن تقسيم التسلسل النصّي إلى كلمات ولهذا السبب يتم تمرير متجهات الميزات إلى *وحدة التكميم*، والتي تهدف إلى تعلم وحدات الكلام المنفصلة. يتم اختيار وحدة الكلام من مجموعة من الرموز، والمعروفة باسم *كتاب الرموز* (يمكنك اعتبار هذا بمثابة المفردات). ومن كتاب الرموز،يتم اختيار المتجه أو وحدة الكلام التي تُمثّل مدخل الصوت المُستمر على أفضل وجه، ويتم تمريرها عبر النموذج. +3. **شبكة السياق (Context Network):** يتم إخفاء حوالي نصف متجهات الميزات بشكل عشوائي، ويتم تغذية متجه الميزة المُقنّع إلى *شبكة السياق*، والتي تعد مُشفّر محوّلات (Transformer Encoder) الذي يضيف أيضًا تضمينات موضعية نسبية (Relative Positional Embeddings).. + +4. **مهمة التناقضية:** يتمثل الهدف من التدريب المسبق لشبكة السياق هو *مهمة تناقضية*. يجب على النموذج التنبؤ بالتمثيل الصحيح للكلام المُكمّم للتنبؤ المقنع من مجموعة من التمثيلات الخاطئة، مما يشجع النموذج على ا إيجاد متجه السياق ووحدة الكلام المُكمّمة الأكثر تشابهًا (التصنيف المستهدف). + +بمجرد تدريب Wav2Vec2 مسبقًا، يمكنك ضبط دقته على بياناتك لتصنيف الصوت أو التعرف التلقائي على الكلام! + +### تصنيف الصوت (Audio classification) + +لاستخدام النموذج الذي تم تدريبه مسبقًا لتصنيف الصوت، أضف رأس تصنيف تسلسلي أعلى نموذج Wav2Vec2 الأساسي. رأس التصنيف هو طبقة خطية تستقبل الحالات المخفية للمشفر. تمثل الحالات المخفية الميزات التي تم تعلمها من كل إطار صوتي والذي يمكن أن يكون له أطوال مختلفة. لتحويلها إلى متجه واحد ثابت الطول، يتم تجميع الحالات المخفية أولاً ثم تحويلها إلى احتمالات عبر تصنيفات الفئات. يتم حساب التكلفة (الخسارة المتقاطعة) بين الاحتمالات والتصنيف المستهدف للعثور على الفئة الأكثر احتمالًا. + +هل أنت مستعد لتجربة تصنيف الصوت؟ تحقق من دليلنا الشامل [تصنيف الصوت](tasks/audio_classification) لمعرفة كيفية ضبط دقة نموذج Wav2Vec2 واستخدامه للاستدلال! + +### التعرف التلقائي على الكلام (Automatic speech recognition - ASR) + +لاستخدام النموذج الذي تم تدريبه مسبقًا للتعرف التلقائي على الكلام، أضف رأس نمذجة لغوية أعلى نموذج Wav2Vec2 الأساسي لـ [[التصنيف الزمني الترابطي (CTC)](glossary#connectionist-temporal-classification-ctc). رأس النمذجة اللغوية عبارة عن طبقة خطية تقبل الحالات المخفية للمُشفّر وتحويلها إلى احتمالات. يمثل كل احتمال فئة رمزية (يأتي عدد الرموز من مفردات المهمة). يتم حساب تكلفة CTC بين الاحتمالات والأهداف للعثور على تسلسل الرموز الأكثر احتمالًا، والتي يتم فك تشفيرها بعد ذلك إلى نص مكتوب. + +هل أنت مستعد لتجربة التعرف التلقائي على الكلام؟ تحقق من دليلنا الشامل [التعرف التلقائي على الكلام](tasks/asr) لمعرفة كيفية ضبط دقة نموذج Wav2Vec2 واستخدامه للاستدلال! + +## رؤية الحاسب (Computer vision) + +هناك طريقتان لتناول مهام رؤية الحاسب: + +1. قم بتقسيم الصورة إلى تسلسل من الرقع ومعالجتها بالتوازي باستخدام مُحوّل Transformer. +2. استخدم شبكة عصبية تلافيفية CNN) حديثة، مثل [ConvNeXT](model_doc/convnext)، والتي تعتمد على الطبقات التلافيفية ولكنها تعتمد تصميمات حديثة للشبكات. + + + +يقوم النهج الثالث بمزج المحولات مع التلافيف (على سبيل المثال، [Convolutional Vision Transformer](model_doc/cvt) أو [LeViT](model_doc/levit)). لن نناقشها لأنها تجمع ببساطة بين النهجين اللذين نستعرضهما هنا. + + + +يتم استخدام ViT و ConvNeXT بشكل شائع لتصنيف الصور، ولكن بالنسبة لمهام الرؤية الأخرى مثل اكتشاف الكائنات والتجزئة وتقدير العمق، سنلقي نظرة على DETR و Mask2Former و GLPN، على التوالي؛ فهذه النماذج هي الأنسب لتلك المهام. + +### تصنيف الصور (Image classification) + +يمكن استخدام كل من ViT و ConvNeXT لتصنيف الصور؛ الاختلاف الرئيسي هو أن ViT يستخدم آلية انتباه بينما يستخدم ConvNeXT الالتفافات. + +#### المحول Transformer + +[ViT](model_doc/vit) يستبدل التلافيف تمامًا بهندسة Transformer نقية. إذا كنت على دراية بـ Transformer الأصلي، فأنت بالفعل في طريقك إلى فهم ViT. + +
+ +
+ +كان التغيير الرئيسي الذي قدمه ViT هو كيفية تغذية الصور إلى Transformer: + +1. يتم تقسيم الصورة إلى رقع مربعة غير متداخلة، يتم تحويل كل منها إلى متجه أو يُسمى *تمثيل الرقعة*. يتم إنشاء تضمينات الرقع من طبقة تلافيفية ثنائية الأبعاد 2D والتي تقوم بإنشاء أبعاد الإدخال الصحيحة (والتي بالنسبة إلى Transformer الأساسي هي 768 قيمة لكل تضمين رقعة). إذا كان لديك صورة 224x224 بكسل، فيمكنك تقسيمها إلى 196 رقعة صورة 16x16. تمامًا مثل كيفية تجزئة النص إلى كلمات، يتم "تجزئة" الصورة إلى سلسلة من الرقع. + +2. يتم إضافة *رمز قابل للتعلم* - تتم إضافة رمز خاص `[CLS]` - إلى بداية تمثيلات الرقع تمامًا مثل BERT. يتم استخدام الحالة المخفية النهائية للرمز `[CLS]` كمدخل لرأس التصنيف المُرفق؛ يتم تجاهل المخرجات الأخرى. تساعد هذه الرموز النموذج على تعلم كيفية ترميز تمثيل الصورة. + +3. الشيء الأخير تتم إضافة "تمثيلات تموضع" إلى تمثيلات الرقع والرمز القابل للتعلم لأن النموذج لا يعرف كيفية ترتيب رقع الصورة. تكون تمثيلات التموضع قابلة للتعلم أيضًا ولها نفس حجم تمثيلات الرقع. وأخيرًا، يتم تمرير جميع التمثيلات إلى مُشفّر Transformer. + +4. يتم تمرير الإخراج، وتحديدًا مخرج الرمز `[CLS]`، إلى رأس الإدراك المتعدد الطبقات (MLP). الهدف من التدريب المسبق لـ ViT هو التصنيف فقط. يقوم رأس MLP، مثل رؤوس التصنيف الأخرى، يحول رأس MLP المخرجات إلى احتمالات عبر تصنيفات الفئات ويحسب دالة التكلفة (الخسارة المتقاطعة) للعثور على الفئة الأكثر احتمالًا. + +هل أنت مستعد لتجربة تصنيف الصور؟ تحقق من دليلنا الشامل [تصنيف الصور](tasks/image_classification) لمعرفة كيفية ضبط دقة نموذج ViT واستخدامه للاستدلال! + +#### الشبكات العصبية التلافيفية (CNN) + + + +يشرح هذا القسم بإيجاز الالتفافات، ولكن سيكون من المفيد أن يكون لديك فهم مسبق لكيفية تغيير شكل الصورة وحجمها. إذا كنت غير معتاد على الالتفافات، تحقق من [فصل الشبكات العصبية التلافيفية](https://github.com/fastai/fastbook/blob/master/13_convolutions.ipynb) من كتاب fastai! + + + +[ConvNeXT](model_doc/convnext) هو بنية CNN تعتمد تصاميم الشبكات الجديدة والحديثة لتحسين الأداء. ومع ذلك، لا تزال الالتفافات هي جوهر النموذج. من منظور عام، [الالتفاف](glossary#convolution) هو عملية حيث يتم ضرب مصفوفة أصغر (*نواة*) بمقطع صغير من وحدات بكسل الصورة. يحسب بعض الميزات منه، مثل نسيج معين أو انحناء خط. ثم ينزلق إلى النافذة التالية من البكسلات؛ المسافة التي تقطعها الالتفاف تسمى *الخطوة*. + +
+ +
+ +عملية التفاف أساسية بدون حشو أو خطو خطوة واسعة، مأخوذة من دليل لحساب الالتفاف للتعلم العميق. + +يمكنك تغذية هذا الناتج إلى طبقة التفاف أخرى، ومع كل طبقة متتالية، تتعلم الشبكة أشياء أكثر تعقيدًا وتجريدية مثل النقانق أو الصواريخ. بين طبقات الالتفاف، من الشائع إضافة طبقة تجميع لتقليل الأبعاد وجعل النموذج أكثر قوة للتغيرات في موضع الميزة. + +
+ +
+ +يقوم ConvNeXT بتحديث شبكة CNN بطرق خمس: + +1. تغيير عدد الكتل في كل مرحلة و"ترقيع" الصورة باستخدام خطوة أكبر وحجم نواة المقابل. تجعل استراتيجية التجزئة غير المتداخلة استراتيجية الترقيع مشابهة للطريقة التي يقسم بها ViT للصورة إلى رقع. + +2. تقلص طبقة *العنق الزجاجي* عدد القنوات ثم تعيدها لأنها أسرع في إجراء التفاف 1x1، ويمكنك زيادة العمق. يقوم عنق الزجاجة المقلوب بالعكس عن طريق توسيع عدد القنوات وتقلصها، وهو أكثر كفاءة من حيث الذاكرة. + +3. استبدل طبقة الالتفاف النموذجية 3x3 في طبقة عنق الزجاجة بـ *الالتفاف بالعمق*، والذي يطبق الالتفاف على كل قناة إدخال بشكل منفصل ثم يقوم بتكديسها معًا مرة أخرى في النهاية. هذا يوسع عرض الشبكة لتحسين الأداء. + +4. لدى ViT مجال استقبال عالمي مما يعني أنه يمكنه رؤية المزيد من الصورة في وقت واحد بفضل آلية الانتباه الخاصة به. تحاول ConvNeXT محاكاة هذا التأثير عن طريق زيادة حجم النواة إلى 7x7. + +5. يقوم ConvNeXT أيضًا بإجراء العديد من تغييرات تصميم الطبقة التي تُحاكي نماذج المحولات. هناك عدد أقل من طبقات التنشيط والطبقات التطبيع، يتم تبديل دالة التنشيط إلى GELU بدلاً من ReLU، ويستخدم LayerNorm بدلاً من BatchNorm. + +يتم تمرير الإخراج من كتل الالتفاف إلى رأس تصنيف يحول المخرجات إلى احتمالات ويحسب دالة التكلفة (الخسارة المتقاطعة) للعثور على التصنيف الأكثر احتمالاً. + +### اكتشاف الكائنات (Object detection) + +[DETR](model_doc/detr)، *DEtection TRansformer*، هو نموذج اكتشاف كائنات من البداية إلى النهاية يجمع بين CNN مع محول المشفر-فك التشفير. + +
+ +
+ +1. يأخذ العمود الفقري CNN *المدرب مسبقًا* صورة، ممثلة بقيم بكسلاتها، وينشئ خريطة ميزات منخفضة الدقة لها. يتم تطبيق التفاف 1x1 على خريطة الميزات لتقليل الأبعاد، و إنشاء خريطة ميزات جديدة بتمثيل صورة عالي المستوى. نظرًا لأن المحول (Transformer) هو نموذج تسلسلي، يتم تسوية خريطة الميزات إلى تسلسل من متجهات الميزات التي يتم دمجها مع تمثيلات التموضع. + +2. يتم تمرير متجهات الميزات إلى المشفر، والذي يتعلم تمثيلات الصورة باستخدام طبقات الانتباه الخاصة به. بعد ذلك، يتم دمج الحالات المخفية للمُشفّر مع *استعلامات الكائنات* في فك التشفير. استعلامات الكائنات هي تمثيلات مكتسبة تركز على مناطق مختلفة من الصورة، ويتم تحديثها أثناء مرورها عبر كل طبقة انتباه. يتم تمرير الحالات المخفية لفك التشفير إلى شبكة تغذية أمامية التي تتنبأ بإحداثيات مربعات الإحاطة وتصنيف العلامة لكل استعلام كائن، أو `بدون كائن` إذا لم يكن هناك أي كائن. + + يقوم DETR بفك تشفير كل استعلام كائن بالتوازي لإخراج *N* من التنبؤات النهائية، حيث *N* هو عدد الاستعلامات. على عكس النموذج التلقائي الذي يتنبأ بعنصر واحد في كل مرة، فإن "اكتشاف الكائنات" هو مهمة تنبؤ بمجموعة من التنبؤات (مثل `مربع إحاطة`، `تصنيف`) تقوم بإجراء *N* من التنبؤات في مرور واحدة. + +3. يستخدم DETR دالة *خسارة المطابقة ثنائية الفئات* أثناء التدريب لمقارنة عدد ثابت من التنبؤات بمجموعة ثابتة من تصنيفات البيانات الحقيقية. إذا كان هناك عدد أقل من تصنيفات البيانات الحقيقية في مجموعة *N* من التصنيفات، فيتم حشوها بفئة "بدون كائن". تشجع دالة الخسارة هذه DETR على العثور على تعيين واحد لواحد بين التنبؤات وتصنيفات البيانات الحقيقية. إذا لم تكن مربعات الإحاطة أو تصنيفات الفئات صحيحة، يتم تكبد خسارة. وبالمثل، إذا تنبأ DETR بكائن غير موجود، فإنه يتم معاقبته. وهذا يشجع DETR على العثور على كائنات أخرى في الصورة بدلاً من التركيز على كائن بارز حقًا. + +يتم إضافة رأس اكتشاف كائن أعلى DETR للعثور على تصنيف الكائن وإحداثيات مربع الإحاطة. هناك مكونان لرأس اكتشاف الكائنات: طبقة خطية لتحويل حالات فك التشفير المخفية إلى احتمالات عبر تصنيفات الفئات، وشبكةMLP للتنبؤ بمربع الإحاطة. + +هل أنت مستعد لتجربة اكتشاف الكائنات؟ تحقق من دليلنا الشامل [دليل اكتشاف الكائنات](tasks/object_detection) لمعرفة كيفية ضبط نموذج DETR واستخدامه للاستدلال! + +### تجزئة الصورة (Image segmentation) + +يُعد [Mask2Former](model_doc/mask2former) بنيةً شاملةً لحل جميع أنواع مهام تجزئة الصور. عادةً ما تُصمم نماذج التجزئة التقليدية لمهمة فرعية محددة من مهام تجزئة الصور، مثل تجزئة المثيل أو التجزئة الدلالية أو التجزئة الشاملة. يصوغ Mask2Former كل مهمة من تلك المهام على أنها مشكلة *تصنيف الأقنعة*. يقوم تصنيف القناع بتجميع وحدات البكسل في *N* قطعة، ويتنبأ بـ *N* أقنعة وتصنيف الفئة المقابل لها لصورة معينة. سنشرح في هذا القسم كيفية عمل Mask2Former، ويمكنك بعد ذلك تجربة ضبط SegFormer في النهاية. + +
+ +
+ +هناك ثلاثة مكونات رئيسية لـ Mask2Former: + +1. العمود الفقري [Swin](model_doc/swin) يقبل صورة وينشئ خريطة ميزات منخفضة الدقة من 3 عمليات التفافات متتالية 3x3. + +2. يتم تمرير خريطة الميزات إلى *فك تشفير البكسل* الذي يقوم تدريجياً بزيادة الميزات منخفضة الدقة إلى تمثيلات عالية الدقة لكل بكسل. في الواقع، يقوم فك تشفير البكسل بإنشاء ميزات متعددة المقاييس (تحتوي على كل من الميزات منخفضة وعالية الدقة) بدقة 1/32 و1/16 و1/8 من الصورة الأصلية. + +3. يتم تغذية كل من خرائط الميزات ذات المقاييس المختلفة على التوالي إلى طبقة واحدة من طبقات فك التشفير في كل مرة لالتقاط الأجسام الصغيرة من ميزات الدقة العالية. يتمثل مفتاح Mask2Former آلية *الاهتمام المقنع* في فك التشفير. على عكس الانتباه المتقاطع الذي يمكن أن يركز على الصورة بأكملها، يركز الانتباه المقنع فقط على منطقة معينة من الصورة. هذا أسرع ويؤدي إلى أداء أفضل لأن الميزات المحلية لصورة كافية للنموذج للتعلم منها. + +4. مثل [DETR](tasks_explained#object-detection)، يستخدم Mask2Former أيضًا استعلامات كائن مكتسبة ويجمعها مع ميزات الصورة من فك تشفير البكسل لإجراء تنبؤ مجموعة (`تصنيف الفئة`، `التنبؤ بالقناع`). يتم تمرير حالات فك التشفير المخفية إلى طبقة خطية وتحويلها إلى احتمالات عبر علامات التصنيف. يتم حساب دالة التكلفة (الخسارة المتقاطعة) بين الاحتمالات وتصنيف الفئة لتحديد الأكثر احتمالاً. + + يتم إنشاء تنبؤات الأقنعة عن طريق الجمع بين تمثيلات البكسل وحالات فك التشفير المخفية النهائية. يتم حساب دالة الخسارة المتقاطعة سيجمويد وخسارة النرد بين الاحتمالات والقناع البيانات الحقيقية للعثور على القناع الأكثر احتمالاً. + +هل أنت مستعد لتجربة يدك في اكتشاف الكائنات؟ تحقق من دليلنا الشامل [دليل تجزئة الصورة](tasks/semantic_segmentation) لمعرفة كيفية ضبط SegFormer واستخدامه للاستدلال! + +### تقدير العمق (Depth estimation) + +[GLPN](model_doc/glpn)، شبكة المسار العالمية المحلية، هي محول ل تقدير العمق الذي يجمع بين مشفر [SegFormer](model_doc/segformer) مع فك تشفير خفيف الوزن. + +
+ +
+ +1. مثل ViT، يتم تقسيم الصورة إلى تسلسل من الرقع، باستثناء أن هذه رقع الصورة أصغر. هذا أفضل لمهام التنبؤ الكثيفة مثل التجزئة أو تقدير العمق. يتم تحويل رقع الصورة إلى تمثيلات للرقع (راجع قسم [تصنيف الصور](#image-classification) لمزيد من التفاصيل حول كيفية إنشاء تمثيلات الرقع)، والتي يتم تغذيتها إلى المشفر. + +2. يقبل المشفر تمثيلات الرقع، ويمررها عبر عدة كتل مشفرة. يتكون كل كتلة من طبقات انتباه وMix-FFN. الغرض من هذا الأخير هو توفير معلومات موضعية. في نهاية كل كتلة مشفرة توجد طبقة *دمج الرقع* لإنشاء تمثيلات هرمية. يتم دمج ميزات كل مجموعة من الرقع المجاورة، ويتم تطبيق طبقة خطية على الميزات المدمجة لتقليل عدد الرقع إلى دقة 1/4. يصبح هذا المُدخل للكتلة المشفرة التالية، حيث تتكرر هذه العملية بأكملها حتى تحصل على ميزات الصورة بدقة 1/8 و1/16 و1/32. + +3. يقوم فك تشفير خفيف الوزن بأخذ خريطة الميزات الأخيرة (مقياس 1/32) من المشفر وزيادة حجمها إلى مقياس 1/16. من هنا، يتم تمرير الميزة إلى وحدة *دمج الميزات الانتقائية (SFF)*، والتي تقوم باختيار ودمج الميزات المحلية والعالمية من خريطة انتباه لكل ميزة ثم زيادة حجمها إلى 1/8. تتم إعادة هذه العملية حتى تصبح الميزات فك التشفير بنفس حجم الصورة الأصلية. يتم تمرير الإخراج عبر طبقتين تلافيفتين ثم يتم تطبيق تنشيط سيجمويد للتنبؤ بعمق كل بكسل. + +## معالجة اللغات الطبيعية (Natural language processing -NLP) + +تم تصميم نموذج المحول Transformer في الأصل للترجمة الآلية، ومنذ ذلك الحين أصبح في الواقع البنية الافتراضية لحل جميع مهام NLP. تناسب بعض المهام بنية المشفر في نموذج المحول، في حين أن البعض الآخر أكثر ملاءمة لفك التشفير. لا تزال مهام أخرى تستخدم بنية المشفر-فك التشفير في نموذج المحول. + +### تصنيف النصوص (Text classification) + +يعد [BERT](model_doc/bert) نموذج يعتمد على المُشفّر فقط، وهو أول نموذج يُطبق بشكل فعال ثنائية الاتجاه العميقة لتعلم تمثيلات أكثر ثراءً للنص من خلال الانتباه إلى الكلمات على كلا الجانبين. + +1. يستخدم BERT تجزئة [WordPiece](tokenizer_summary#wordpiece) لإنشاء تمثيل رمزي للنص. للتمييز بين جملة واحدة وزوج من الجمل، تتم إضافة رمز خاص `[SEP]` للتفريق بينهما. تتم إضافة رمز خاص `[CLS]` إلى بداية كل تسلسل نصي. ويتم استخدام الإخراج النهائي مع الرمز `[CLS]` كمدخل لرأس التصنيف لمهام التصنيف. كما يضيف BERT تضمينًا للمقطع للإشارة إلى ما إذا كان الرمز ينتمي إلى الجملة الأولى أو الثانية في زوج من الجمل. + +2. يتم تدريب BERT المسبق باستخدام هدفين: نمذجة اللغة المقنعة وتنبؤ الجملة التالية. في نمذجة اللغة المقنعة، يتم إخفاء نسبة مئوية مُعيّنة من رموز الإدخال بشكل عشوائي، ويجب على النموذج التنبؤ بها. يحل هذا مشكلة ثنائية الاتجاه، حيث يمكن للنموذج أن يغش ويرى جميع الكلمات و"يتنبأ" بالكلمة التالية. تتم تمرير الحالات المخفية النهائية للرموز المقنعة المتوقعة إلى شبكة تغذية أمامية مع دالة Softmax عبر مفردات اللغة للتنبؤ بالكلمة المقنعة. + + الهدف الثاني من التدريب المسبق هو توقع الجملة التالية. يجب على النموذج التنبؤ بما إذا كانت الجملة "ب" تتبع الجملة"أ". نصف الوقت تكون الجملة "ب" هي الجملة التالية، والنصف الآخر من الوقت، تكون الجملة "ب" عبارة عشوائية. يتم تمرير التنبؤ، سواء كانت الجملة التالية أم لا، إلى شبكة تغذية أمامية مع دالة Softmax عبر الفئتين (`IsNext` و`NotNext`). + +3. يتم تمرير تمثيلات الإدخال عبر عدة طبقات مشفرة لإخراج بعض الحالات المخفية النهائية. + +لاستخدام النموذج المسبق التدريب لتصنيف النصوص، أضف رأس تصنيف تسلسلي أعلى نموذج BERT الأساسي. رأس تصنيف التسلسلي هو طبقة خطية تقبل الحالات المخفية النهائية وتجري تحويلًا خطيًا لتحويلها إلى احتمالات logits. يتم حساب دالة التكلفة (الخسارة المتقاطعة) بين logits والهدف للعثور على التصنيف الأكثر احتمالًا. + +هل أنت مستعد لتجربة تصنيف النصوص؟ تحقق من [دليل تصنيف النصوص](tasks/sequence_classification) الشامل الخاص بنا لمعرفة كيفية ضبط نموذج DistilBERT واستخدامه للاستنتاج! + +### تصنيف الرموز (Token classification) + +لاستخدام BERT لمهام تصنيف الرموز مثل التعرف على الكيانات المسماة (NER)، أضف رأس تصنيف الرموز أعلى نموذج BERT الأساسي. رأس تصنيف الرموز هو طبقة خطية تقبل الحالات المخفية النهائية وتجري تحويلًا خطيًا لتحويلها إلى logits. يتم حساب دالة التكلفة (الخسارة المتقاطعة) بين logits وكل رمز للعثور على التصنيف الأكثر احتمالًا. + +هل أنت مستعد لتجربة تصنيف الرموز؟ تحقق من [دليل تصنيف الرموز](tasks/token_classification) الشامل الخاص بنا لمعرفة كيفية ضبط نموذج DistilBERT واستخدامه للاستنتاج! + +### الإجابة على الأسئلة (Question answering) + +لاستخدام BERT للإجابة على الأسئلة، أضف رأس تصنيف المدى أعلى نموذج BERT الأساسي. تقبل هذه الطبقة الخطية الحالات المخفية النهائية وتُجري تحويلًا خطيًا لحساب داية ونهاية `الامتداد` logits `span` البداية والنهاية المقابلة للإجابة. يتم حسابدالة التكلفة (الخسارة المتقاطعة) بين logits وموقع التصنيف للعثور على الامتداد الأكثر احتمالًا من النص المقابل للإجابة. + +هل أنت مستعد لتجربة الإجابة على الأسئلة؟ راجع [دليل الإجابة على الأسئلة](tasks/question_answering) الشامل الخاص بنا لمعرفة كيفية ضبط نموذج DistilBERT واستخدامه في الاستدلال! + + + + +💡 لاحظ مدى سهولة استخدام BERT لمهام مختلفة بمجرد تدريبه مسبقًا. كل ما تحتاج إليه هو إضافة رأس محدد إلى النموذج المسبق التدريب للتلاعب بالحالات المخفية إلى الإخراج المطلوب! + + + +### توليد النصوص (Text generation) + +يُعد [GPT-2](model_doc/gpt2) نموذجًا قائم على فك التشفير فقط تم تدريبه المسبق على كمية كبيرة من النصوص. يمكنه توليد نص مقنع (على الرغم من أنه ليس دائمًا صحيحًا!) بناءً على مُحفّز معين واستكمال مهام NLP الأخرى مثل الإجابة على الأسئلة على الرغم من أنه لم يتم تدريبه بشكل صريح على ذلك. + +
+ +
+ +1. يستخدم GPT-2 [ترميز الأزواج البايتية (BPE)](tokenizer_summary#byte-pair-encoding-bpe) لتجزئة الكلمات وإنشاء تمثيل رمزى. يتم إضافة تمثيلات موضعية إلى تمثيلات الرموز للإشارة إلى موضع كل رمز في التسلسل. يتم تمرير تمثيلات الإدخال عبر عدة كتل فك تشفير لإخراج بعض الحالات المخفية النهائية. داخل كل كتلة فك تشفير، يستخدم GPT-2 طبقة *انتباه ذاتي مقنع* مما يعني أن GPT-2 لا يمكنه الانتباه بالرموز المستقبلية. يُسمح له فقط بالاهتمام بالرموز الموجودة على اليسار. يختلف هذا عن رمز [`mask`] الخاص بـ BERT لأنه، في الانتباه الذاتي المقنع، يتم استخدام قناع انتباه لتعيين النتيجة إلى `0` للرموز المستقبلية. + +2. يتم تمرير الإخراج من فك التشفير إلى رأس نمذجة اللغة، والتي تُجري تحويلًا خطيًا لتحويل الحالات المخفية إلى احتمالات logits. التصنيف هو الرمز التالي في التسلسل، والذي يتم إنشاؤه عن طريق تغيير موضع logits إلى اليمين بمقدار واحد. يتم حساب دالة التكلفة (الخسارة المتقاطعة) بين logits التي تم تغيير موضعها والتصنيفات لإخراج الرمز التالي الأكثر احتمالًا. + +يستند هدف التدريب المسبق لـ GPT-2 بالكامل إلى [نمذجة اللغة السببية](glossary#causal-language-modeling)، والتنبؤ بالكلمة التالية في تسلسل. يجعل هذا GPT-2 جيدًا بشكل خاص في المهام التي تتضمن توليد النص. + +هل أنت مستعد لتجربة توليد النصوص؟ تحقق من دليل [دليل نمذجة اللغة السببية](tasks/language_modeling#causal- الشامل الخاص بنا لمعرفة كيفية ضبط نموذج DistilGPT-2 واستخدامه للاستنتاج! + + + +للحصول على مزيد من المعلومات حول توليد النص، راجع دليل [استراتيجيات توليد النصوص](generation_strategies)! + + + +### التلخيص (Summarization) + +تم تصميم نماذج المشفر-فك التشفير مثل [BART](model_doc/bart) و [T5](model_doc/t5) لنمط تسلسل إلى تسلسل لمهمة التلخيص. سنشرح كيف يعمل BART في هذا القسم، ثم يمكنك تجربة ضبط T5 في النهاية. + +
+ +
+ +1. تتشابه بنية المشفر BART كثيرًا مع BERT وتقبل رمزًا وتمثيلًا موضعيًا للنص. يتم تدريب BART مسبقًا عن طريق إتلاف المُدخلات ثم إعادة بنائه باستخدام فك التشفير. على عكس المشفرات الأخرى ذات استراتيجيات الإتلاف المحددة، يمكن لـ BART تطبيق أي نوع من الإتلاف. ومع ذلك، فإن استراتيجية إتلاف "ملء النص" تعمل بشكل أفضل. في ملء النص، يتم استبدال عدد من امتدادات النص برمز **واحد** [`mask`]. هذا أمر مهم لأن النموذج يجب أن يتنبأ بالرموز المقنعة، ويعلّم النموذج التنبؤ بعدد الرموز المفقودة. يتم تمرير تمثيلات الإدخال والامتدادات المقنعة عبر المشفر لإخراج بعض الحالات المخفية النهائية، ولكن على عكس BERT، لا يضيف BART شبكة تغذية أمامية نهائية في النهاية للتنبؤ بكلمة. + +2. يتم تمرير إخراج المشفر إلى فك التشفير، والذي يجب أن يتنبأ بالرموز المقنعة وأي رموز غير تالفة من ناتج المشفر. يمنح هذا فك التشفير سياقًا إضافيًا للمساعدة في استعادة النص الأصلي. يتم تمرير ناتج فك التشفير إلى رأس نمذجة اللغوية، والذي يجري تحويلًا خطيًا لتحويل الحالات المخفية إلى احتمالات(logits). يتم حساب دالة التكلفة (الخسارة المتقاطعة) بين الاحتمالات logits والتصنيف، وهو مجرد الرمز الذي تم تغيير موضعه إلى اليمين. + +هل أنت مستعد لتجربة التلخيص؟ تحقق من دليل التلخيص الشامل الخاص بنا لمعرفة كيفية ضبط نموذج T5 واستخدامه للاستنتاج! + + + +للحصول على مزيد من المعلومات حول توليد النص، راجع دليل استراتيجيات توليد النص! + + + +### الترجمة (Translation) + +تُعد الترجمة مثالًا آخر على مهام التسلسل إلى التسلسل، مما يعني أنه يمكنك استخدام نموذج المشفر-فك التشفير مثل [BART](model_doc/bart) أو [T5](model_doc/t5) للقيام بذلك. سنشرح كيف يعمل BART في هذا القسم، ثم يمكنك تجربة ضبط T5 في النهاية. + +يتكيف BART مع الترجمة عن طريق إضافة مشفر منفصل يتم تهيئته بشكل عشوائي لتعيين لغة المصدر بمدخلات يمكن فك تشفيرها إلى لغة الهدف. يتم تمرير تمثيلات هذا المشفر الجديد إلى المشفر المسبق التدريب بدلاً من تمثيلات الكلمات الأصلية. يتم تدريب مشفر المصدر عن طريق تحديث مشفر المصدر وتمثيلات التموضع وتمثيلات الإدخال باستخدام دالة التكلفة (الخسارة المتقاطعة) من ناتج النموذج. يتم تجميد معلمات النموذج في هذه الخطوة الأولى، ويتم تدريب جميع معلمات النموذج معًا في الخطوة الثانية. + +تم إصدار نسخة متعددة اللغات من BART، تسمى mBART، مُخصصة للترجمة ومُدرّبة مسبقًا على العديد من اللغات المختلفة. + +هل أنت مستعد لتجربة الترجمة؟ تحقق من دليل الترجمة الشامل الخاص بنا لمعرفة كيفية ضبط نموذج T5 واستخدامه للاستنتاج! + + + + **للحصول على مزيد من المعلومات حول توليد النصوص، راجع دليل [استراتيجيات توليد النصوص](generation_strategies)!** + + diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tflite.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tflite.md new file mode 100644 index 0000000000000000000000000000000000000000..5e75c7a10a3c66d0eec7b87246269f632b057d2e --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tflite.md @@ -0,0 +1,40 @@ +# التصدير إلى TFLite + +[TensorFlow Lite](https://www.tensorflow.org/lite/guide) هو إطار عمل خفيف الوزن لنشر نماذج التعلم الآلي على الأجهزة المحدودة الموارد، مثل الهواتف المحمولة، والأنظمة المدمجة، وأجهزة إنترنت الأشياء (IoT). تم تصميم TFLite لتشغيل النماذج وتحسينها بكفاءة على هذه الأجهزة ذات الطاقة الحاسوبية والذاكرة واستهلاك الطاقة المحدودة. + +يُمثَّل نموذج TensorFlow Lite بتنسيق محمول فعال خاص يُعرَّف بامتداد الملف `.tflite`. + +🤗 Optimum يقدم وظيفة لتصدير نماذج 🤗 Transformers إلى TFLite من خلال الوحدة النمطية `exporters.tflite`. بالنسبة لقائمة هندسات النماذج المدعومة، يرجى الرجوع إلى [وثائق 🤗 Optimum](https://huggingface.co/docs/optimum/exporters/tflite/overview). + +لتصدير نموذج إلى TFLite، قم بتثبيت متطلبات البرنامج المطلوبة: + +```bash +pip install optimum[exporters-tf] +``` + +للاطلاع على جميع المغامﻻت المتاحة، راجع [وثائق 🤗 Optimum](https://huggingface.co/docs/optimum/main/en/exporters/tflite/usage_guides/export_a_model)، أو عرض المساعدة في سطر الأوامر: + +```bash +optimum-cli export tflite --help +``` + +لتصدير نسخة النموذج ل 🤗 Hub، على سبيل المثال، `google-bert/bert-base-uncased`، قم بتشغيل الأمر التالي: + +```bash +optimum-cli export tflite --model google-bert/bert-base-uncased --sequence_length 128 bert_tflite/ +``` + +ستظهر لك السجلات التي تُبيّن التقدم وموقع حفظ ملف `model.tflite` الناتج، كما في المثال التالي: + +```bash +Validating TFLite model... + -[✓] TFLite model output names match reference model (logits) + - Validating TFLite Model output "logits": + -[✓] (1, 128, 30522) matches (1, 128, 30522) + -[x] values not close enough, max diff: 5.817413330078125e-05 (atol: 1e-05) +The TensorFlow Lite export succeeded with the warning: The maximum absolute difference between the output of the reference model and the TFLite exported model is not within the set tolerance 1e-05: +- logits: max diff = 5.817413330078125e-05. + The exported model was saved at: bert_tflite +``` + +يُبيّن المثال أعلاه كيفية تصدير نسخة من النموذج ل 🤗 Hub. عند تصدير نموذج محلي، تأكد أولاً من حفظ ملفات أوزان النموذج المجزء اللغوى في نفس المسار (`local_path`). عند استخدام CLI، قم بتمرير `local_path` إلى معامل `model` بدلاً من اسم النسخة على 🤗 Hub. \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tiktoken.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tiktoken.md new file mode 100644 index 0000000000000000000000000000000000000000..6f3755d8670cdc75885662477f018ab8bfd4b0a4 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tiktoken.md @@ -0,0 +1,41 @@ +# Tiktoken والتفاعل مع Transformers + +يتم دمج دعم ملفات نموذج tiktoken بسلاسة في 🤗 transformers عند تحميل النماذج +`from_pretrained` مع ملف `tokenizer.model` tiktoken على Hub، والذي يتم تحويله تلقائيًا إلى [المحلل اللغوي السريع](https://huggingface.co/docs/transformers/main/en/main_classes/tokenizer#transformers.PreTrainedTokenizerFast). + +### النماذج المعروفة التي تم إصدارها مع `tiktoken.model`: + - gpt2 + - llama3 + +## مثال على الاستخدام + +من أجل تحميل ملفات `tiktoken` في `transformers`، تأكد من أن ملف `tokenizer.model` هو ملف tiktoken وسيتم تحميله تلقائيًا عند التحميل `from_pretrained`. إليك كيفية تحميل مجزىء لغوي ونموذج، والذي +يمكن تحميله من نفس الملف بالضبط: + +```py +from transformers import AutoTokenizer + +model_id = "meta-llama/Meta-Llama-3-8B-Instruct" +tokenizer = AutoTokenizer.from_pretrained(model_id, subfolder="original") +``` +## إنشاء مجزىء لغوي tiktoken + +لا يحتوي ملف `tokenizer.model` على أي معلومات حول الرموز أو الأنماط الإضافية. إذا كانت هذه الأمور مهمة، قم بتحويل المحلل اللغوي إلى `tokenizer.json`، وهو التنسيق المناسب لـ [`PreTrainedTokenizerFast`]. + +قم بتوليد ملف `tokenizer.model` باستخدام [tiktoken.get_encoding](https://github.com/openai/tiktoken/blob/63527649963def8c759b0f91f2eb69a40934e468/tiktoken/registry.py#L63) ثم قم بتحويله إلى `tokenizer.json` باستخدام [`convert_tiktoken_to_fast`]. + +```py + +from transformers.integrations.tiktoken import convert_tiktoken_to_fast +from tiktoken import get_encoding + +# يمكنك تحميل ترميزك المخصص أو الترميز الذي توفره OpenAI +encoding = get_encoding("gpt2") +convert_tiktoken_to_fast(encoding, "config/save/dir") +``` + +يتم حفظ ملف `tokenizer.json` الناتج في الدليل المحدد ويمكن تحميله باستخدام [`PreTrainedTokenizerFast`]. + +```py +tokenizer = PreTrainedTokenizerFast.from_pretrained("config/save/dir") +``` diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tokenizer_summary.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tokenizer_summary.md new file mode 100644 index 0000000000000000000000000000000000000000..5b0f24aba1143ae17478b3ebf6d27a4f4c3a29a1 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/tokenizer_summary.md @@ -0,0 +1,198 @@ +# ملخص عن المجزئات اللغوية + +[[open-in-colab]] + +في هذه الصفحة، سنتناول بالتفصيل عملية التجزئة. + + + +كما رأينا في [برنامج تعليمي حول المعالجة المسبقة](preprocessing)، فإن تجزئة النص يقسمه إلى كلمات أو +الرموز الفرعية (كلمات جزئية)، والتي يتم بعد ذلك تحويلها إلى معرفات من خلال قائمة بحث. يعد تحويل الكلمات أو الرموز الفرعية إلى معرفات مباشرًا، لذا في هذا الملخص، سنركز على تقسيم النص إلى كلمات أو رموز فرعية (أي تجزئة النص). +وبشكل أكثر تحديدًا، سنلقي نظرة على الأنواع الثلاثة الرئيسية من المُجزئات اللغوية المستخدمة في 🤗 المحولات: [ترميز الأزواج البايتية (BPE)](#byte-pair-encoding)، [WordPiece](#wordpiece)، و [SentencePiece](#sentencepiece)، ونعرض أمثلة +على نوع المُجزئة الذي يستخدمه كل نموذج. + +لاحظ أنه في كل صفحة نموذج، يمكنك الاطلاع على وثائق المُجزئة المرتبط لمعرفة نوع المُجزئ +الذي استخدمه النموذج المُدرب مسبقًا. على سبيل المثال، إذا نظرنا إلى [`BertTokenizer`]، يمكننا أن نرى أن النموذج يستخدم [WordPiece](#wordpiece). + +## مقدمة + +إن تقسيم النص إلى أجزاء أصغر هو مهمة أصعب مما تبدو، وهناك طرق متعددة للقيام بذلك. +على سبيل المثال، دعنا نلقي نظرة على الجملة `"Don't you love 🤗 Transformers? We sure do."` + + + +يمكن تقسيم هذه الجملة ببساطة عن طريق المسافات، مما سينتج عنه ما يلي:``` + +``` +["Don't", "you", "love", "🤗", "Transformers?", "We", "sure", "do."] +``` + +هذه خطوة أولى منطقية، ولكن إذا نظرنا إلى الرموز `"Transformers?"` و `"do."`، فإننا نلاحظ أن علامات الترقيم مُرفقة بالكلمات `"Transformer"` و `"do"`، وهو أمر ليس مثالي. يجب أن نأخذ علامات الترقيم في الاعتبار حتى لا يضطر النموذج إلى تعلم تمثيل مختلف للكلمة وكل رمز ترقيم مُحتمل قد يليها، الأمر الذي من شأنه أن يزيد بشكل هائل عدد التمثيلات التي يجب على النموذج تعلمها. +مع مراعاة علامات الترقيم، سيُصبح تقسيم نصنا على النحو التالي: + +``` +["Don", "'", "t", "you", "love", "🤗", "Transformers", "?", "We", "sure", "do", "."] +``` + +أفضل. ومع ذلك، من غير الملائم كيفية تقسيم الكلمة `"Don't"`. `"Don't"` تعني `"do not"`، لذا سيكون من الأفضل تحليلها على أنها كلمتين مُدمجتين `["Do"، "n't"]`. هنا تبدأ الأمور في التعقيد، وهو جزء من سبب امتلاك كل نموذج لنوّعه الخاص من مُجزّئ النصوص (tokenizer). اعتمادًا على القواعد التي نطبقها لتقسيم النص، يسيتم إنشاء مخرجات مُجزّأة مُختلفة لنفس النص. ولن يؤدي النموذج المُدرب مسبقًا إلى الأداء بشكل صحيح إلا إذا قُدّم له مُدخل تم تقسيمه بنفس القواعد التي تم استخدامها لتقسيم بيانات التدريب الخاصة به. + +يُعد كل من [spaCy](https://spacy.io/) و [Moses](http://www.statmt.org/moses/?n=Development.GetStarted) هما مجزّئي النصوص التي تعتمد على القواعد +الشائعة. عند تطبيقها على مثالنا، فإن *spaCy* و *Moses* ستخرج نّصًا مثل: + +``` +["Do", "n't", "you", "love", "🤗", "Transformers", "?", "We", "sure", "do", "."] +``` + +كما يمكنك أن ترى، يتم هنا استخدام التقسيم المكاني والترقيم، وكذلك تقسيم الكلمات القائم على القواعد. يعد التقسيم المكاني والترقيم والتحليل القائم على القواعد كلاهما مثالين على تقسيم الكلمات، والذي يُعرّف بشكل غير مُحدد على أنه تقسيم الجُمل إلى كلمات. في حين أنها الطريقة الأكثر بديهية لتقسيم النصوص إلى أجزاء أصغر، +يمكن أنها تؤدى إلى مشكلات لمجموعات النصوص الضخمة. في هذه الحالة، عادةً ما يؤدي التقسيم المكاني والترقيم +إلى إنشاء مفردات كبيرة جدًا (مجموعة من جميع الكلمات والرموز الفريدة المستخدمة). على سبيل المثال، يستخدم [Transformer XL](model_doc/transfo-xl) التقسيم المكاني والترقيم، مما يؤدي إلى حجم مُفردات يبلغ 267735! + +يفرض حجم المُفردات الكبير هذا على النموذج أن يكون لديه مصفوفة تضمين (embedding matrix) ضخمة كطبقة إدخال وإخراج، مما يؤدي إلى زيادة كل من التعقيد الزمني والذاكرة. بشكل عام، نادرًا ما يكون لدى نماذج المحولات حجم مفردات +أكبر من 50000، خاصة إذا تم تدريبها مسبقًا على لغة واحدة فقط. + +لذا إذا كان التقسيم المكاني و الترقيم البسيط غير مرضٍ، فلماذا لا نقسّم الحروف ببساطة؟ + + + +في حين أن تقسيم الأحرف بسيط للغاية ومن شأنه أن يقلل بشكل كبير من التعقيد الزمني والذاكرة، إلا أنه يجعل من الصعب +على النموذج تعلم تمثيلات المدخلات ذات معنى. على سبيل المثال، يعد تعلم تمثيل مستقل عن السياق للحرف "t" أكثر صعوبة من تعلم تمثيل مستقل عن السياق لكلمة "اليوم". لذلك، غالبًا ما يكون تحليل الأحرف مصحوبًا بفقدان الأداء. لذا للحصول على أفضل ما في العالمين، تستخدم نماذج المحولات نظامًا هجينًا بين تقسيم على مستوى الكلمة وتقسيم علي مستوى الأحرف يسمى **تقسيم الوحدات الفرعية للّغة** (subword tokenization). + +## تقسيم الوحدات الفرعية للّغة (Subword Tokenization) + + + +تعتمد خوارزميات تقسيم الوحدات الفرعية subword على المبدأ القائل بأن الكلمات الشائعة الاستخدام لا ينبغي تقسيمها إلى وحدات فرعية أصغر، ولكن يجب تفكيك الكلمات النادرة إلى رموز فرعية ذات معنى. على سبيل المثال، قد يتم اعتبار "annoyingly" +كلمة نادرة ويمكن تحليلها إلى "annoying" و "ly". كل من "annoying" و "ly" كـ subwords مستقلة ستظهر بشكل متكرر أكثر في حين أن معنى "annoyingly" يتم الاحتفاظ به من خلال المعنى المركب لـ "annoying" و "ly". هذا مفيد بشكل خاص في اللغات التلصيقية مثل التركية، حيث يمكنك تشكيل كلمات مُركبة طويلة (تقريبًا) بشكل تعسفي عن طريق ضم الرموز الفرعية معًا. + +يسمح تقسيم subword للنموذج بأن يكون له حجم مفردات معقول مع القدرة على تعلم تمثيلات مستقلة عن السياق ذات معنى. بالإضافة إلى ذلك، يمكّن تقسيم subword النموذج من معالجة الكلمات التي لم يسبق له رؤيتها من قبل، عن طريق تحليلها إلى رموز فرعية معروفة. على سبيل المثال، يقوم المحلل [`~transformers.BertTokenizer`] بتحليل"I have a new GPU!" كما يلي: + +```py +>>> from transformers import BertTokenizer + +>>> tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-uncased") +>>> tokenizer.tokenize("I have a new GPU!") +["i", "have", "a", "new", "gp", "##u", "!"] +``` + +نظرًا لأننا نستخدم نموذجًا غير حساس لحالة الأحرف (uncased model)، فقد تم تحويل الجملة إلى أحرف صغيرة أولاً. يمكننا أن نرى أن الكلمات `["i"، "have"، "a"، "new"]` موجودة في مفردات مُجزّئ النصوص، ولكن الكلمة "gpu" غير موجودة. وبالتالي، يقوم مُجزّئ النصوص بتقسيم "gpu" إلى رموز فرعية معروفة: `["gp" و "##u"]`. يعني "##" أنه يجب ربط بقية الرمز بالرمز السابق، دون مسافة (للترميز أو عكس عملية تقسيم الرموز). + +كمثال آخر، يقوم المحلل [`~transformers.XLNetTokenizer`] بتقسيم نّص مثالنا السابق كما يلي: + +```py +>>> from transformers import XLNetTokenizer + +>>> tokenizer = XLNetTokenizer.from_pretrained("xlnet/xlnet-base-cased") +>>> tokenizer.tokenize("Don't you love 🤗 Transformers? We sure do.") +["▁Don", "'", "t", "▁you", "▁love", "▁"، "🤗"، "▁"، "Transform"، "ers"، "؟"، "▁We"، "▁sure"، "▁do"، "."] +``` +سنعود إلى معنى تلك `"▁"` عندما نلقي نظرة على [SentencePiece](#sentencepiece). كما يمكنك أن ترى، +تم تقسيم الكلمة النادرة "Transformers" إلى الرموز الفرعية الأكثر تكرارًا `"Transform"` و `"ers"`. + +دعنا الآن نلقي نظرة على كيفية عمل خوارزميات تقسيم subword المختلفة. لاحظ أن جميع خوارزميات التقسيم هذه تعتمد على بعض أشكال التدريب الذي يتم عادةً على مجموعة البيانات التي سيتم تدريبها النموذج عليها. + + + +### ترميز الأزواج البايتية (BPE) + +تم تقديم رميز أزواج البايت (BPE) في ورقة بحثية بعنوان [الترجمة الآلية العصبية للكلمات النادرة باستخدام وحدات subword (Sennrich et al.، 2015)](https://huggingface.co/papers/1508.07909). يعتمد BPE على مُجزّئ أولي يقسم بيانات التدريب إلى +كلمات. يمكن أن يكون التحليل المسبق بسيطًا مثل التقسيم المكاني، على سبيل المثال [GPT-2](model_doc/gpt2)، [RoBERTa](model_doc/roberta). تشمل التقسيم الأكثر تقدمًا معتمد على التحليل القائم على القواعد، على سبيل المثال [XLM](model_doc/xlm)، [FlauBERT](model_doc/flaubert) الذي يستخدم Moses لمعظم اللغات، أو [GPT](model_doc/openai-gpt) الذي يستخدم spaCy و ftfy، لحساب تكرار كل كلمة في مجموعة بيانات التدريب. + +بعد التحليل المسبق، يتم إنشاء مجموعة من الكلمات الفريدة وقد تم تحديد تكرار كل كلمة في تم تحديد بيانات التدريب. بعد ذلك، يقوم BPE بإنشاء مفردات أساسية تتكون من جميع الرموز التي تحدث في مجموعة الكلمات الفريدة ويتعلم قواعد الدمج لتشكيل رمز جديد من رمزين من المفردات الأساسية. إنه يفعل ذلك حتى تصل المفردات إلى حجم المفردات المطلوب. لاحظ أن حجم المفردات هو فرط معلمة لتحديد قبل تدريب مُجزّئ النصوص. + +كمثال، دعنا نفترض أنه بعد التقسيم الأولي، تم تحديد مجموعة الكلمات التالية بما في ذلك تكرارها: + +``` +("hug", 10), ("pug", 5), ("pun", 12), ("bun", 4), ("hugs", 5) +``` + +وبالتالي، فإن المفردات الأساسية هي `["b"، "g"، "h"، "n"، "p"، "s"، "u"]`. من خلال تقسيم جميع الكلمات إلى رموز من +المفردات الأساسية، نحصل على: + +``` +("h" "u" "g"، 10)، ("p" "u" "g"، 5)، ("p" "u" "n"، 12)، ("b" "u" "n"، 4)، ("h" "u" "g" "s"، 5) +``` + +بعد ذلك، يقوم BPE بعدد مرات حدوث كل زوج من الرموز المحتملة ويختار زوج الرموز الذي يحدث بشكل متكرر. في +في المثال أعلاه، يحدث "h" متبوعًا بـ "u" _10 + 5 = 15_ مرة (10 مرات في 10 مرات +حدوث "hug"، 5 مرات في 5 مرات حدوث "hugs"). ومع ذلك، فإن أكثر أزواج الرموز شيوعًا هو "u" متبوعًا +بواسطة "g"، والتي تحدث _10 + 5 + 5 = 20_ مرة في المجموع. وبالتالي، فإن أول قاعدة دمج يتعلمها المحلل هي تجميع جميع +رموز "u" التي تتبعها "g" معًا. بعد ذلك، يتم إضافة "ug" إلى المفردات. تصبح مجموعة الكلمات + +``` +("h" "ug"، 10)، ("p" "ug"، 5)، ("p" "u" "n"، 12)، ("b" "u" "n"، 4)، ("h" "ug" "s"، 5) +``` + +بعد ذلك، يحدد BPE ثاني أكثر أزواج الرموز شيوعًا. إنه "u" متبوعًا بـ "n"، والذي يحدث 16 مرة. "u"، +يتم دمج "n" في "un" ويضاف إلى المفردات. ثالث أكثر أزواج الرموز شيوعًا هو "h" متبوعًا +بواسطة "ug"، والتي تحدث 15 مرة. مرة أخرى يتم دمج الزوج ويتم إضافة "hug" إلى المفردات. + +في هذه المرحلة، تكون المفردات هي `["b"، "g"، "h"، "n"، "p"، "s"، "u"، "ug"، "un"، "hug"]` ومجموعة الكلمات الفريدة لدينا +تمثيله كما يلي: + +``` +("hug", 10), ("p" "ug", 5), ("p" "un", 12), ("b" "un", 4), ("hug" "s", 5) +``` + +بافتراض أن تدريب ترميز الأزواج البايت سيتوقف عند هذه النقطة، فسيتم تطبيق قواعد الدمج التي تم تعلمها بعد ذلك على الكلمات الجديدة (طالما أن هذه الكلمات الجديدة لا تشمل رموزًا لم تكن في المفردات الأساسية). على سبيل المثال، سيتم تقسيم كلمة "bug" إلى `["b"، "ug"]` ولكن سيتم تقسيم "mug" على أنها `[""، "ug"]` نظرًا لأن الرمز "m" غير موجود في المفردات الأساسية. بشكل عام، لا يتم استبدال الأحرف الفردية مثل "m" بالرمز "" لأن بيانات التدريب تتضمن عادةً ظهورًا واحدًا على الأقل لكل حرف، ولكن من المحتمل أن يحدث ذلك لرموز خاصة جدًا مثل الرموز التعبيرية. + +كما ذكرنا سابقًا، فإن حجم المفردات، أي حجم المفردات الأساسية + عدد عمليات الدمج، هو معامل يجب اختياره. على سبيل المثال، لدى [GPT](model_doc/openai-gpt) حجم مفردات يبلغ 40478 منذ أن كان لديهم 478 حرفًا أساسيًا واختاروا التوقف عن التدريب بعد 40,000 عملية دمج. + +#### ترميز الأزواج البايتية على مستوى البايت + +قد تكون المفردات الأساسية التي تتضمن جميع الأحرف الأساسية كبيرة جدًا إذا *على سبيل المثال* تم اعتبار جميع أحرف اليونيكود +كأحرف أساسية. لذا، ليكون لديك مفردات أساسية أفضل، يستخدم [GPT-2](https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf) البايتات كمفردات أساسية، وهي حيلة ذكية لإجبار المفردات الأساسية على أن تكون بحجم 256 مع ضمان أن يتم تضمين كل حرف أساسي في المفردات. مع بعض القواعد الإضافية للتعامل مع علامات الترقيم، يمكن لمُجزّئ النصوص GPT2 تجزئة أي نص دون الحاجة إلى رمز . لدى [GPT-2](model_doc/gpt) حجم مفردات يبلغ 50257، والذي يتوافق مع رموز 256 base byte، ورمز خاص لنهاية النص والرموز التي تم تعلمها باستخدام 50000 عملية دمج. + + + +### WordPiece + +تعتبر WordPiece خوارزمية تجزئة الكلمات الفرعية subword المستخدمة لـ [BERT](model_doc/bert)، [DistilBERT](model_doc/distilbert)، و [Electra](model_doc/electra). تم توضيح الخوارزمية في [البحث الصوتي الياباني والكوري +(Schuster et al.، 2012)](https://static.googleusercontent.com/media/research.google.com/ja//pubs/archive/37842.pdf) وهو مشابه جدًا +BPE. أولاً، يقوم WordPiece بتكوين المفردات لتضمين كل حرف موجود في بيانات التدريب +وتعلم تدريجياً عددًا معينًا من قواعد الدمج. على عكس BPE، لا يختار WordPiece أكثر زوج الرموز المتكررة، ولكن تلك التي تزيد من احتمال بيانات التدريب بمجرد إضافتها إلى المفردات. + +لذا، ماذا يعني هذا بالضبط؟ بالإشارة إلى المثال السابق، فإن زيادة احتمال بيانات التدريب تعادل إيجاد زوج الرموز، الذي يكون احتمال تقسيمه على احتمالات رمزه الأول تليها رمزه الثاني هو الأكبر بين جميع أزواج الرموز. *مثال* `"u"`، تليها `"g"` كانت قد اندمجت فقط إذا كان احتمال `"ug"` مقسومًا على `"u"`، `"g"` كان سيكون أكبر من أي زوج آخر من الرموز. بديهيًا، WordPiece مختلف قليلاً عن BPE في أنه يقيم ما يفقده عن طريق دمج رمزين للتأكد من أنه يستحق ذلك. + + + +### Unigram + +Unigram هو خوارزمية توكنيز subword التي تم تقديمها في [تنظيم subword: تحسين نماذج الترجمة الشبكة العصبية +نماذج مع مرشحين subword متعددة (Kudo، 2018)](https://huggingface.co/papers/1804.10959). على عكس BPE أو +WordPiece، يقوم Unigram بتكوين مفرداته الأساسية إلى عدد كبير من الرموز ويقللها تدريجياً للحصول على مفردات أصغر. يمكن أن تتوافق المفردات الأساسية على سبيل المثال مع جميع الكلمات المسبقة التوكنز والسلاسل الفرعية الأكثر شيوعًا. لا يتم استخدام Unigram مباشرة لأي من النماذج في المحولات، ولكنه يستخدم بالاقتران مع [SentencePiece](#sentencepiece). + +في كل خطوة تدريب، يحدد خوارزمية Unigram خسارة (غالبًا ما يتم تعريفها على أنها اللوغاريتم) عبر بيانات التدريب بالنظر إلى المفردات الحالية ونموذج اللغة unigram. بعد ذلك، بالنسبة لكل رمز في المفردات، يحسب الخوارزمية مقدار زيادة الخسارة الإجمالية إذا تم إزالة الرمز من المفردات. ثم يقوم Unigram بإزالة p (مع p عادة ما تكون 10% أو 20%) في المائة من الرموز التي تكون زيادة الخسارة فيها هي الأدنى، *أي* تلك +الرموز التي تؤثر أقل على الخسارة الإجمالية عبر بيانات التدريب. تتكرر هذه العملية حتى تصل المفردات إلى الحجم المطلوب. يحتفظ خوارزمية Unigram دائمًا بالشخصيات الأساسية بحيث يمكن توكنز أي كلمة. + +نظرًا لأن Unigram لا يعتمد على قواعد الدمج (على عكس BPE وWordPiece)، فإن للخوارزمية عدة طرق +توكنز نص جديد بعد التدريب. على سبيل المثال، إذا كان محول Unigram المدرب يعرض المفردات: + +``` +["b"، "g"، "h"، "n"، "p"، "s"، "u"، "ug"، "un"، "hug"]، +``` + +يمكن توكنز `"hugs"` على أنه `["hug"، "s"]`، أو `["h"، "ug"، "s"]` أو `["h"، "u"، "g"، "s"]`. إذن ماذا +لاختيار؟ يحفظ Unigram احتمال كل رمز في فيلق التدريب بالإضافة إلى حفظ المفردات بحيث +يمكن حساب احتمال كل توكنز ممكن بعد التدريب. ببساطة، يختار الخوارزمية الأكثر +توكنز المحتملة في الممارسة، ولكنه يوفر أيضًا إمكانية أخذ عينات من توكنز ممكن وفقًا لاحتمالاتها. + +تتم تعريف هذه الاحتمالات بواسطة الخسارة التي يتم تدريب المحول عليها. بافتراض أن بيانات التدريب تتكون +من الكلمات \\(x_{1}، \dots، x_{N}\\) وأن مجموعة جميع التوكنزات الممكنة لكلمة \\(x_{i}\\) هي +يتم تعريفها على أنها \\(S(x_{i})\\)، ثم يتم تعريف الخسارة الإجمالية على النحو التالي + +$$\mathcal{L} = -\sum_{i=1}^{N} \log \left ( \sum_{x \in S(x_{i})} p(x) \right )$$ + + + +### SentencePiece + +تحتوي جميع خوارزميات توكنز الموصوفة حتى الآن على نفس المشكلة: من المفترض أن النص المدخل يستخدم المسافات لفصل الكلمات. ومع ذلك، لا تستخدم جميع اللغات المسافات لفصل الكلمات. أحد الحلول الممكنة هو استخداممعالج مسبق للغة محدد، *مثال* [XLM](model_doc/xlm) يلذي يستخدم معالجات مسبقة محددة للصينية واليابانية والتايلاندية. +لحل هذه المشكلة بشكل أعم، [SentencePiece: A simple and language independent subword tokenizer and +detokenizer for Neural Text Processing (Kudo et al.، 2018)](https://huggingface.co/papers/1808.06226) يتعامل مع المدخلات +كتدفق بيانات خام، وبالتالي يشمل المسافة في مجموعة الأحرف التي سيتم استخدامها. ثم يستخدم خوارزمية BPE أو unigram +لبناء المفردات المناسبة. + +يستخدم [`XLNetTokenizer`] SentencePiece على سبيل المثال، وهو أيضًا سبب تضمين تم تضمين حرف `"▁"` في المفردات. عملية فك التشفير باستخدام SentencePiece سهلة للغاية نظرًا لأنه يمكن دائمًا دمج الرموز معًا واستبدال `"▁"` بمسافة. + +تستخدم جميع نماذج المحولات في المكتبة التي تستخدم SentencePiece بالاقتران مع unigram. أمثلة على النماذج +باستخدام SentencePiece هي [ALBERT](model_doc/albert)، [XLNet](model_doc/xlnet)، [Marian](model_doc/marian)، و [T5](model_doc/t5). diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/torchscript.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/torchscript.md new file mode 100644 index 0000000000000000000000000000000000000000..bf0bc0dde04b629932d32f85e15529a6c0128305 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/torchscript.md @@ -0,0 +1,154 @@ +# التصدير إلى TorchScript + + + +هذه هي بداية تجاربنا مع TorchScript ولا زلنا نستكشف قدراته مع نماذج المدخلات المتغيرة الحجم. إنه مجال اهتمامنا وسنعمق تحليلنا في الإصدارات القادمة، مع المزيد من الأمثلة البرمجية، وتنفيذ أكثر مرونة، ومقاييس مقارنة بين الأكواد القائمة على Python مع أكواد TorchScript المُجمّعة. + + + +وفقًا لـ [وثائق TorchScript](https://pytorch.org/docs/stable/jit.html): + +> TorchScript هي طريقة لإنشاء نماذج قابلة للتسلسل والتحسين من تعليمات PyTorch البرمجية. + +هناك وحدتان من PyTorch، [JIT and TRACE](https://pytorch.org/docs/stable/jit.html)، تتيحان للمطورين تصدير نماذجهم لإعادة استخدامها في برامج أخرى مثل برامج C++ المُحسّنة للأداء. + +نقدم واجهة تتيح لك تصدير نماذج 🤗 Transformers إلى TorchScript بحيث يمكن إعادة استخدامها في بيئة مختلفة عن برامج Python القائمة إلى PyTorch. هنا نشرح كيفية تصدير نماذجنا واستخدامها باستخدام TorchScript. + +يتطلب تصدير نموذج أمرين: + +- تهيئة مثيل للنموذج باستخدام علامة `torchscript` +- تمرير مُدخلات وهمية (dummy inputs) خلال النموذج + +تنطوي هذه الضرورات على عدة أمور يجب على المطورين توخي الحذر بشأنها كما هو مفصل أدناه. + +## علامة TorchScript والأوزان المرتبطة + +علامة `torchscript` ضرورية لأن معظم نماذج اللغة 🤗 Transformers لها أوزان مرتبطة بين طبقة `Embedding` وطبقة `Decoding`. لا يسمح لك TorchScript بتصدير النماذج ذات الأوزان المرتبطة، لذلك من الضروري فصل الأوزان ونسخها مسبقًا. + +النماذج المُهيأة باستخدام علامة `torchscript` لها طبقة `Embedding` وطبقة`Decoding` منفصلتين، مما يعني أنه لا ينبغي تدريبها لاحقًا. سيؤدي التدريب إلى عدم تزامن الطبقتين، مما يؤدي إلى نتائج غير متوقعة. + +هذا لا ينطبق على النماذج التي لا تحتوي على رأس نموذج اللغة، حيث لا تملك أوزانًا مرتبطة. يمكن تصدير هذه النماذج بأمان دون علامة `torchscript`. + +## المدخلات الوهمية والأطوال القياسية + +تُستخدم المُدخلات الوهمية لتمرير أمامي خلال النموذج. أثناء انتشار قيم المُدخلات عبر الطبقات، يتتبع PyTorch العمليات المختلفة التي يتم تنفيذها على كل مصفوفة(tensor). ثم يتم استخدام هذه العمليات المُسجلة بعد ذلك لإنشاء *أثر* النموذج. + +يتم إنشاء التتبع بالنسبة لأبعاد المُدخلات. وبالتالي، فهو مُقيّد بأبعاد المُدخلات الوهمية، ولن يعمل لأي طول تسلسل أو حجم دفعة مختلف. عند المحاولة بحجم مختلف، يتم رفع الخطأ التالي: + +``` +`The expanded size of the tensor (3) must match the existing size (7) at non-singleton dimension 2` +``` + +نوصي بتتبع النموذج باستخدام حجم مُدخلات وهمية لا يقل عن أكبر مُدخل سيتم تقديمه للنموذج أثناء الاستدلال. يمكن أن تساعد الحشوة(padding) في ملء القيم المفقودة. ومع ذلك، نظرًا لتتبع النموذج بحجم مُدخل أكبر، ستكون أبعاد المصفوفة ستكون كبيرة أيضًا، مما يؤدي عنه المزيد من الحسابات. + +انتبه إلى إجمالي عدد العمليات المُنفذة على كل مُدخل وتابع الأداء عن كثب عند تصدير نماذج متغيرة طول التسلسل. + +## استخدام TorchScript في Python + +يوضح هذا القسم كيفية حفظ النماذج وتحميلها، بالإضافة إلى كيفية استخدام التتبع للاستدلال. + +### حفظ نموذج + +لتصدير `BertModel` باستخدام TorchScript، قم بتهيئة ـ `BertModel` من فئة `BertConfig` ثم احفظه على القرص تحت اسم الملف `traced_bert.pt`: + +```python +from transformers import BertModel, BertTokenizer, BertConfig +import torch + +enc = BertTokenizer.from_pretrained("google-bert/bert-base-uncased") + +# Tokenizing input text +text = "[CLS] Who was Jim Henson ? [SEP] Jim Henson was a puppeteer [SEP]" +tokenized_text = enc.tokenize(text) + +# Masking one of the input tokens +masked_index = 8 +tokenized_text[masked_index] = "[MASK]" +indexed_tokens = enc.convert_tokens_to_ids(tokenized_text) +segments_ids = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1] + +# Creating a dummy input +tokens_tensor = torch.tensor([indexed_tokens]) +segments_tensors = torch.tensor([segments_ids]) +dummy_input = [tokens_tensor, segments_tensors] + +# Initializing the model with the torchscript flag +# Flag set to True even though it is not necessary as this model does not have an LM Head. +config = BertConfig( + vocab_size_or_config_json_file=32000, + hidden_size=768, + num_hidden_layers=12, + num_attention_heads=12, + intermediate_size=3072, + torchscript=True, +) + +# Instantiating the model +model = BertModel(config) + +# The model needs to be in evaluation mode +model.eval() + +# If you are instantiating the model with *from_pretrained* you can also easily set the TorchScript flag +model = BertModel.from_pretrained("google-bert/bert-base-uncased", torchscript=True) + +# Creating the trace +traced_model = torch.jit.trace(model, [tokens_tensor, segments_tensors]) +torch.jit.save(traced_model, "traced_bert.pt") +``` + +### تحميل نموذج + +يمكنك الآن تحميل `BertModel` المُحفظ سابقًا، `traced_bert.pt`، من القرص واستخدامه على `dummy_input` المُهيأ سابقًا: + +```python +loaded_model = torch.jit.load("traced_bert.pt") +loaded_model.eval() + +all_encoder_layers, pooled_output = loaded_model(*dummy_input) +``` + +### استخدام نموذج مُتتبع للاستدلال + +استخدم النموذج المُتتبع للاستدلال باستخدام أسلوب `__call__` الخاص به: + +```python +traced_model(tokens_tensor, segments_tensors) +``` + +## نشر نماذج Hugging Face TorchScript على AWS باستخدام Neuron SDK + +قدمت AWS عائلة [Amazon EC2 Inf1](https://aws.amazon.com/ec2/instance-types/inf1/) من اﻷجهزة لخفض التكلفة وأداء التعلم الآلي عالي الأداء في البيئة السحابية. تعمل أجهزة Inf1 بواسطة شريحة Inferentia من AWS، وهي مُسرّع أجهزة مُخصص، متخصص في أعباء عمل الاستدلال للتعلم العميق. [AWS Neuron](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/#) هي SDK لـ Inferentia التي تدعم تتبع نماذج المحولات وتحسينها للنشر على Inf1. توفر Neuron SDK ما يلي: + +1. واجهة برمجة تطبيقات سهلة الاستخدام مع تغيير سطر واحد من التعليمات البرمجية لتتبع نموذج TorchScript وتحسينه للاستدلال في البيئة السحابية. +2. تحسينات الأداء الجاهزة للاستخدام [تحسين التكلفة والأداء](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-guide/benchmark/>). +3. دعم نماذج Hugging Face المحولات المبنية باستخدام إما [PyTorch](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/src/examples/pytorch/bert_tutorial/tutorial_pretrained_bert.html) أو [TensorFlow](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/src/examples/tensorflow/huggingface_bert/huggingface_bert.html). + +### الآثار المترتبة + +تعمل نماذج المحولات المستندة إلى بنية [BERT (تمثيلات الترميز ثنائية الاتجاه من المحولات)](https://huggingface.co/docs/transformers/main/model_doc/bert) أو متغيراتها مثل [distilBERT](https://huggingface.co/docs/transformers/main/model_doc/distilbert) و [roBERTa](https://huggingface.co/docs/transformers/main/model_doc/roberta) بشكل أفضل على Inf1 للمهام غير التوليدية مثل الإجابة على الأسئلة الاستخراجية، وتصنيف التسلسلات، وتصنيف الرموز (tokens). ومع ذلك، يمكن تكييف مهام توليد النصوص للعمل على Inf1 وفقًا لهذا [برنامج تعليمي AWS Neuron MarianMT](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/src/examples/pytorch/transformers-marianmt.html). يمكن العثور على مزيد من المعلومات حول النماذج التي يمكن تحويلها جاهزة على Inferentia في قسم [ملاءمة بنية النموذج](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-guide/models/models-inferentia.html#models-inferentia) من وثائق Neuron. + +### التبعيات (Dependencies) + +يتطلب استخدام AWS Neuron لتحويل النماذج [بيئة SDK Neuron](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-guide/neuron-frameworks/pytorch-neuron/index.html#installation-guide) والتي تأتي مسبقًا على [AMI للتعلم العميق من AWS](https://docs.aws.amazon.com/dlami/latest/devguide/tutorial-inferentia-launching.html). + +### تحويل نموذج لـ AWS Neuron + +قم بتحويل نموذج لـ AWS NEURON باستخدام نفس التعليمات البرمجية من [استخدام TorchScript في Python](torchscript#using-torchscript-in-python) لتتبع `BertModel`. قم باستيراد امتداد إطار عمل `torch.neuron` للوصول إلى مكونات Neuron SDK من خلال واجهة برمجة تطبيقات Python: + +```python +from transformers import BertModel, BertTokenizer, BertConfig +import torch +import torch.neuron +``` + +كل ما عليك فعله هو تعديل السطر التالي: + +```diff +- torch.jit.trace(model, [tokens_tensor, segments_tensors]) ++ torch.neuron.trace(model, [token_tensor, segments_tensors]) +``` + +يتيح ذلك لـ Neuron SDK تتبع النموذج وتحسينه لمثيلات Inf1. + +لمعرفة المزيد حول ميزات AWS Neuron SDK والأدوات ودروس البرامج التعليمية والتحديثات الأخيرة، يرجى الاطلاع على [وثائق AWS NeuronSDK](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/index.html). diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/trainer.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/trainer.md new file mode 100644 index 0000000000000000000000000000000000000000..1784d76a4ecb58ee382c3da75c6bcb9dba3a87c6 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/trainer.md @@ -0,0 +1,640 @@ +# Trainer + +تُتيح وحدة [`Trainer`] حلقة تدريب وتقييم متكاملة لنماذج PyTorch المطبقة في مكتبة Transformers. تحتاج فقط إلى تمرير المكونات الضرورية للتدريب (النموذج، والمجزىء النصى، ومجموعة البيانات، دالة التقييم، معلمات التدريب الفائقة، إلخ)، وستتولى فئة [`Trainer`] الباقي. هذا يُسهّل بدء التدريب بشكل أسرع دون كتابة حلقة التدريب الخاصة بك يدويًا. ولكن في الوقت نفسه، فإن [`Trainer`] قابل للتخصيص بدرجة كبيرة ويوفر العديد من خيارات التدريب حتى تتمكن من تخصيصه وفقًا لاحتياجات التدريب الخاصة بك بدقة. + + + +بالإضافة إلى فئة [`Trainer`], توفر مكتبة Transformers أيضًا فئة [`Seq2SeqTrainer`] للمهام التسلسلية مثل الترجمة أو التلخيص. هناك أيضًا فئة [`~trl.SFTTrainer`] من مكتبة [TRL](https://hf.co/docs/trl) التي تغلّف فئة [`Trainer`] وهي مُحُسَّنة لتدريب نماذج اللغة مثل Llama-2 وMistral باستخدام تقنيات التوليد اللغوي. كما يدعم [`~trl.SFTTrainer`] ميزات مثل حزم التسلسلات، وLoRA، والقياس الكمي، وDeepSpeed مما يُمكّن من التدريب بكفاءة على نماذج ضخمة الحجم. + +
+ +لا تتردد في الاطلاع على [مرجع API](./main_classes/trainer) لهذه الفئات الأخرى من النوع [`Trainer`] لمعرفة المزيد حول متى يتم استخدام كل منها. بشكل عام، [`Trainer`] هو الخيار الأكثر تنوعًا ومناسبًا لمجموعة واسعة من المهام. تم تصميم [`Seq2SeqTrainer`] للمهام التسلسلية ، و [`~trl.SFTTrainer`] مُصمم لتدريب نماذج اللغة الكبيرة. + +
+ +قبل البدء، تأكد من تثبيت مكتبة [Accelerate](https://hf.co/docs/accelerate) - وهي مكتبة تُمكّن تشغيل تدريب PyTorch في بيئات مُوزعة. + +```bash +pip install accelerate + +# upgrade +pip install accelerate --upgrade +``` + +يوفر هذا الدليل نظرة عامة على فئة [`Trainer`]. + +## الاستخدام الأساسي + +يتضمن [`Trainer`] جميع التعليمات البرمجية التي ستجدها في حلقة التدريب الأساسية: + +1. قم بتنفيذ خطوة تدريب لحساب الخسارة +2. احسب المشتقات باستخدام طريقة [`~accelerate.Accelerator.backward`] +3. تحديث الأوزان بناءً على المشتقات +4. كرر هذه العملية حتى تصل إلى عدد محدد مسبقًا من الدورات (epochs). + +تُجرد فئة [`Trainer`] كل هذه التعليمات البرمجية حتى لا تضطر إلى القلق بشأن كتابة حلقة تدريب يدويًا في كل مرة أما إذا كنت بدأت للتو في PyTorch والتدريب. كل ما عليك فعله هو توفير المكونات الأساسية اللازمة للتدريب، مثل النموذج ومجموعة بيانات، وتتعامل فئة [`Trainer`] مع كل شيء آخر. + +إذا كنت تُريد تحديد أي خيارات تدريب أو معلمات فائقة، فيمكنك العثور عليها في فئة [`TrainingArguments`]. على سبيل المثال، دعنا نحدد أين يتم حفظ النموذج في `output_dir` ورفع النموذج إلى Hub بعد التدريب باستخدام `push_to_hub=True`. + +```py +from transformers import TrainingArguments + +training_args = TrainingArguments( + output_dir="your-model"، + learning_rate=2e-5, + per_device_train_batch_size=16, + per_device_eval_batch_size=16, + num_train_epochs=2, + weight_decay=0.01, + eval_strategy="epoch"، + save_strategy="epoch"، + load_best_model_at_end=True, + push_to_hub=True, +) +``` +مرر `training_args` إلى [`Trainer`] جنبًا إلى جنب مع النموذج، ومجموعة بيانات، وشئ لمعالجة مجموعة البيانات مسبقًا (حسب نوع البيانات، فقد يكون محللًا رمزيًا أو مستخرج ميزات أو معالج صور)، وجامع بيانات، ودالة لحساب المقاييس التي تُريد تتبعها أثناء التدريب. + +أخيرًا، استدعِ [`~Trainer.train`] لبدء التدريب! + +```py +from transformers import Trainer + +trainer = Trainer( + model=model, + args=training_args, + train_dataset=dataset["train"]، + eval_dataset=dataset["test"]، + tokenizer=tokenizer, + data_collator=data_collator, + compute_metrics=compute_metrics, +) + +trainer.train() +``` + +### نقاط الحفظ + +تحفظ فئة [`Trainer`] نقاط الحفظ النموذج في الدليل المحدد في معامل `output_dir` من [`TrainingArguments`]. ستجد نقاط الحفظ في مجلد فرعي يسمى `checkpoint-000` حيث تتوافق الأرقام في النهاية مع خطوة التدريب. إن حفظ نقاط الحفظ مفيد لاستئناف التدريب لاحقًا. + +```py +# استأنف من أحدث نقطة حفظ +trainer.train(resume_from_checkpoint=True) + +# استأنف من نقطة حفظ محددة محفوظة في دليل الإخراج +trainer.train(resume_from_checkpoint="your-model/checkpoint-1000") +``` + +يمكنك حفظ نقاط الحفظ الخاصة بك (لا يتم حفظ حالة المُجزىء اللغوى تقائيًا) إلى Hub عن طريق تعيين `push_to_hub=True` في [`TrainingArguments`] لرفعها. الخيارات الأخرى لاتخاذ القرار بشأن كيفية حفظ هذة النقاط الخاصة بك هي الإعداد في معامل [`hub_strategy`](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments.hub_strategy): + +* `hub_strategy="checkpoint"` يدفع أحدث نقطة حفظ إلى مجلد فرعي يسمى "last-checkpoint" يمكنك استئناف التدريب منه +* `hub_strategy="all_checkpoints"` يدفع جميع نقاط الحفظ إلى الدليل المحدد في `output_dir` (سترى نقطة حفظ واحدة لكل مجلد في مستودع النموذج الخاص بك) + +عند استئناف التدريب من نقطة حفظ، تُحاول [`Trainer`] الحفاظ على حالات RNG Python وNumPy وPyTorch كما كانت عندما تم حفظ نقطة الحفظ. ولكن لأن PyTorch لديها العديد من الإعدادات الافتراضية غير الحتمية مُتنوعة، فإن حالات RNG ليست مضمونة لتكون هي نفسها. إذا كنت تريد تمكين الحتمية الكاملة، فراجع دليل [التحكم في مصادر العشوائية](https://pytorch.org/docs/stable/notes/randomness#controlling-sources-of-randomness) لمعرفة ما يُمكنك تمكينه لجعل تدريبك حتميًا تمامًا. ضع في اعتبارك أنه من خلال جعل إعدادات معينة حتمية، فقد يكون التدريب أبطأ. + +## تخصيص المدرب + +في حين أن فئة [`Trainer`] مُصممة لتكون سهلة الوصول وسهلة الاستخدام، فإنها توفر أيضًا الكثير من قابلية التخصيص للمستخدمين المغامرين. يُمكن إنشاء فئات فرعية من العديد من أساليب [`Trainer`] وتجاوزها لدعم الوظائف التي تُريدها، دون الحاجة إلى إعادة كتابة حلقة التدريب بأكملها من البداية لاستيعابها. تتضمن هذه الأساليب: + +* [`~Trainer.get_train_dataloader`] ينشئ DataLoader للتدريب +* [`~Trainer.get_eval_dataloader`] ينشئ DataLoader للتقييم +* [`~Trainer.get_test_dataloader`] ينشئ DataLoader للاختبار +* [`~Trainer.log`] يسجل معلومات حول مختلف الكائنات التي تراقب التدريب +* [`~Trainer.create_optimizer_and_scheduler`] ينشئ محسنًا ومخططًا لمُعدل التعلم إذا لم يتم تمريرهما في `__init__`؛ يمكن أيضًا تخصيص هذه الوظائف بشكل منفصل باستخدام [`~Trainer.create_optimizer`] و [`~Trainer.create_scheduler`] على التوالي +* [`~Trainer.compute_loss`] يحسب دالة الخسارة على دفعة من مُدخلات التدريب +* [`~Trainer.training_step`] يُنفذ خطوة التدريب +* [`~Trainer.prediction_step`] يُنفذ خطوة التنبؤ والاختبار +* [`~Trainer.evaluate`] يُقيّم النموذج ويعيد مقاييس التقييم +* [`~Trainer.predict`] يُجري التنبؤات (مع المقاييس إذا كانت العلامات متاحة) على مجموعة الاختبار + +على سبيل المثال، إذا كنت تريد تخصيص طريقة [`~Trainer.compute_loss`] لاستخدام دالة خسارة ذات ترجيح بدلاً من ذلك. + + +```py +from torch import nn +from transformers import Trainer + +class CustomTrainer(Trainer): + def compute_loss(self, model, inputs, return_outputs=False): + labels = inputs.pop("labels") + # forward pass + outputs = model(**inputs) + logits = outputs.get("logits") + # compute custom loss for 3 labels with different weights + loss_fct = nn.CrossEntropyLoss(weight=torch.tensor([1.0, 2.0, 3.0], device=model.device)) + loss = loss_fct(logits.view(-1, self.model.config.num_labels), labels.view(-1)) + return (loss, outputs) if return_outputs else loss +``` + +### دوال الاستدعاء Callbacks + +خيار آخر لتخصيص [`Trainer`] هو استخدام [دوال الاستدعاء](callbacks). لا *تغير* دوال الاستدعاء أي شيء في حلقة التدريب. إنهم تفحص حالة حلقة التدريب ثم تُنفذ بعض الإجراءات (مثل الإيقاف المبكر أو تسجيل النتائج، إلخ) اعتمادًا على الحالة. وبعبارة أخرى، لا يمكن استخدام دالة الاستدعاء لتنفيذ شيء مثل دالة خسارة مخصصة، ويجب عليك تجاوز دالة [`~Trainer.compute_loss`] لذلك. + +على سبيل المثال، إذا كنت تريد إضافة دالة استدعاء إيقاف مبكر إلى حلقة التدريب بعد 10 خطوات. + +```py +from transformers import TrainerCallback + +class EarlyStoppingCallback(TrainerCallback): + def __init__(self, num_steps=10): + self.num_steps = num_steps + + def on_step_end(self, args, state, control, **kwargs): + if state.global_step >= self.num_steps: + return {"should_training_stop": True} + else: + return {} +``` + +ثم مرره إلى معامل `callback` في [`Trainer`]. + +```py +from transformers import Trainer + +trainer = Trainer( + model=model, + args=training_args, + train_dataset=dataset["train"]، + eval_dataset=dataset["test"]، + tokenizer=tokenizer, + data_collator=data_collator, + compute_metrics=compute_metrics, + callback=[EarlyStoppingCallback()], +) +``` + +## تسجيل الأحداث (Logging) + + + +راجع مرجع [API](./main_classes/logging) للتسجيل للحصول على مزيد من المعلومات حول مستويات التسجيل المختلفة للأحداث. + + + +يتم تعيين [`Trainer`] إلى `logging.INFO` افتراضيًا والذي يُبلغ عن الأخطاء والتحذيرات ومعلومات أساسية أخرى. يتم تعيين نسخة [`Trainer`] - في البيئات الموزعة - إلى `logging.WARNING` والتي يُبلغ فقط عن الأخطاء والتحذيرات. يمكنك تغيير مستوى تسجيل الأحداث باستخدام معاملي [`log_level`](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments.log_level) و [`log_level_replica`](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments.log_level_replica) في [`TrainingArguments`]. + +لتهيئة إعداد مُستوى تسجيل اﻷحداث لكل عقدة، استخدم معامل [`log_on_each_node`](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.TrainingArguments.log_on_each_node) لتحديد ما إذا كان سيتم استخدام مُستوى السجل على كل عقدة أو فقط على العقدة الرئيسية. + + + +يحدد [`Trainer`] مُستوى التسجيل بشكل مُنفصل لكل عقدة في طريقة [`Trainer.__init__`]، لذا فقد ترغب في التفكير في تعيين هذا الإعداد في وقت سابق إذا كنت تستخدم وظائف Transformers الأخرى قبل إنشاء كائن [`Trainer`]. + + + +على سبيل المثال، لتعيين التعليمات البرمجية والوحدات النمطية الرئيسية الخاصة بك لاستخدام نفس مُستوى التسجيل وفقًا لكل عقدة: + +```py +logger = logging.getLogger(__name__) + +logging.basicConfig( + format="%(asctime)s - %(levelname)s - %(name)s - %(message)s"، + datefmt="%m/%d/%Y %H:%M:%S"، + handlers=[logging.StreamHandler(sys.stdout)], +) + +log_level = training_args.get_process_log_level() +logger.setLevel(log_level) +datasets.utils.logging.set_verbosity(log_level) +transformers.utils.logging.set_verbosity(log_level) + +trainer = Trainer(...) +``` + +استخدم تركيبات مختلفة من `log_level` و `log_level_replica` لتهيئة ما يتم تسجيله على كل من العقد. + + + + + +```bash +my_app.py ... --log_level warning --log_level_replica error +``` + + + + +أضف معلمة `log_on_each_node 0` لبيئات متعددة العقد. + +```bash +my_app.py ... --log_level warning --log_level_replica error --log_on_each_node 0 + +# set to only report errors +my_app.py ... --log_level error --log_level_replica error --log_on_each_node 0 +``` + + + + +## NEFTune + +[NEFTune](https://hf.co/papers/2310.05914) هي تقنية يمكن أن تحسن الأداء عن طريق إضافة ضوضاء إلى مُتجهات التعلم أثناء التدريب. لتمكينه في [`Trainer`], قم بتعيين معامل `neftune_noise_alpha` في [`TrainingArguments`] للتحكم في مقدار الضوضاء المُضافة. + +```py +from transformers import TrainingArguments, Trainer + +training_args = TrainingArguments(..., neftune_noise_alpha=0.1) +trainer = Trainer(..., args=training_args) +``` + +يتم تعطيل NEFTune بعد التدريب لاستعادة طبقة التعلم الأصلية لتجنب أي سلوك غير متوقع. + +## نواة Liger +[Liger-Kernel](https://github.com/linkedin/Liger-Kernel) Kernel هي مجموعة من نوى Triton التي طورتها Linkedin مُصممة خصيصًا لتدريب نماذج اللغة الكبيرة (LLM). لقد قمنا بتنفيذ RMSNorm و RoPE و SwiGLU و CrossEntropy و FusedLinearCrossEntropy مُتوافقة مع Hugging Face، والمزيد قادم. يُمكنها زيادة إنتاجية التدريب متعدد وحدات معالجة الرسومات (GPU) بنسبة 20٪ وتقليل استخدام الذاكرة بنسبة 60٪. تعمل النواة بشكل تلقائي مع flash attention و PyTorch FSDP و Microsoft DeepSpeed. + +احصل على زيادة في الإنتاجية بنسبة 20٪ وتقليل استخدام الذاكرة بنسبة 60٪ على تدريب نماذج LLaMA 3-8B. حقق أطوال سياق أكبر وأحجام دفعات أكبر. كما أنها مُفيدة إذا كنت تُريد زيادة حجم نموذجك إلى تدريب بنماذج متعددة الرؤوس أو أحجام مُفردات ضخمة. أطلق العنان للتدريب بنماذج متعددة الرؤوس (medusa) والمزيد. راجع التفاصيل والأمثلة في [Liger](https://github.com/linkedin/Liger-Kernel/tree/main/examples) +تأكد أولاً من تثبيت مستودع Liger الرسمي: +```bash +pip install liger-kernel +``` +يجب عليك تمرير `use_liger_kernel=True` لتطبيق نواة `liger` على نموذجك، على سبيل المثال: + +```python +from transformers import TrainingArguments + +training_args = TrainingArguments( + output_dir="your-model", + learning_rate=2e-5, + per_device_train_batch_size=16, + per_device_eval_batch_size=16, + num_train_epochs=2, + weight_decay=0.01, + eval_strategy="epoch", + save_strategy="epoch", + load_best_model_at_end=True, + push_to_hub=True, + use_liger_kernel=True +) +``` + +تدعم النواة معماريات نماذج Llama و Gemma و Mistral و Mixtral. يُمكن العثور على أحدث قائمة بالنمائج المدعومة [هنا](https://github.com/linkedin/Liger-Kernel). عندما يتم تعيين `use_liger_kernel` إلى `True`، سيتم تصحيح الطبقات المُقابلة في النموذج الأصلي باستخدام تطبيق Liger الفعال، لذلك لا تحتاج إلى فعل أي شيء إضافي بخلاف تعيين قيمة المعامل. + +## المُحسِّنات +يمكنك اختيار مُحسِّن مدمج للتدريب باستخدام: +```python +from transformers import TrainingArguments +training_args = TrainingArguments(..., optim="adamw_torch") +``` +اطلع على [`OptimizerNames`](https://github.com/huggingface/transformers/blob/main/src/transformers/training_args.py) للاطلاع على القائمة الكاملة للخيارات. نُدرج أمثلة مُتقدمة في الأقسام أدناه. + +يمكنك أيضًا استخدام مُحسِّن PyTorch عشوائي عبر: +```python +import torch + +optimizer_cls = torch.optim.AdamW +optimizer_kwargs = { + "lr": 4e-3, + "betas": (0.9, 0.999), + "weight_decay": 0.05, +} + +from transformers import Trainer +trainer = Trainer(..., optimizer_cls_and_kwargs=(optimizer_cls, optimizer_kwargs)) +``` + + + + +### GaLore + +إسقاط التدرج ذو الرتبة المنخفضة (GaLore) هو إستراتيجية تدريب ذات رتبة منخفضة فعّالة من حيث الذاكرة، تسمح بتعلم المعلمات الكاملة ولكنها أكثر كفاءة من حيث الذاكرة من أساليب التكيّف الشائعة ذات الرتبة المنخفضة، مثل LoRA. + +أولاً، تأكد من تثبيت المستودع الرسمي لـ GaLore: + +```bash +pip install galore-torch +``` + +ثم أضف ببساطة أحد `["galore_adamw"، "galore_adafactor"، "galore_adamw_8bit"]` في `optim` جنبًا إلى جنب مع `optim_target_modules`، والتي يمكن أن تكون قائمة من السلاسل أو التعبيرات النمطية regex أو المسار الكامل المطابق لأسماء الوحدات المستهدفة التي تريد تكييفها. فيما يلي مثال على النص البرمجي كامل(تأكد من `pip install trl datasets`): + +```python +import datasets +from trl import SFTConfig, SFTTrainer + +train_dataset = datasets.load_dataset('imdb', split='train') +args = SFTConfig( + output_dir="./test-galore", + max_steps=100, + optim="galore_adamw", + optim_target_modules=[r".*.attn.*", r".*.mlp.*"], + gradient_checkpointing=True, +) +trainer = SFTTrainer( + model="google/gemma-2b", + args=args, + train_dataset=train_dataset, +) +trainer.train() +``` + +لتمرير معامﻻت إضافية يدعمها GaLore، يجب عليك تمرير `optim_args` بشكل صحيح، على سبيل المثال: + +```python +import datasets +from trl import SFTConfig, SFTTrainer + +train_dataset = datasets.load_dataset('imdb', split='train') +args = SFTConfig( + output_dir="./test-galore", + max_steps=100, + optim="galore_adamw", + optim_target_modules=[r".*.attn.*", r".*.mlp.*"], + optim_args="rank=64, update_proj_gap=100, scale=0.10", + gradient_checkpointing=True, +) +trainer = SFTTrainer( + model="google/gemma-2b", + args=args, + train_dataset=train_dataset, +) +trainer.train() +``` +يمكنك قراءة المزيد حول الطريقة في [المستودع الأصلي](https://github.com/jiaweizzhao/GaLore) أو [الورقة البحثية](https://huggingface.co/papers/2403.03507). + +حاليًا، يمكنك فقط تدريب الطبقات الخطية التي تعتبر طبقات GaLore وستستخدم التحلل ذو الرتبة المنخفضة للتدريب بينما سيتم تحسين الطبقات المتبقية بالطريقة التقليدية. + +لاحظ أنه سيستغرق الأمر بعض الوقت قبل بدء التدريب (~3 دقائق لنموذج 2B على NVIDIA A100)، ولكن يجب أن يسير التدريب بسلاسة بعد ذلك. + +يمكنك أيضًا إجراء تحسين طبقة تلو الأخرى عن طريق إضافة `layerwise` إلى اسم المُحسِّن كما هو موضح أدناه: + +```python +import datasets +from trl import SFTConfig, SFTTrainer + +train_dataset = datasets.load_dataset('imdb', split='train') +args = SFTConfig( + output_dir="./test-galore", + max_steps=100, + optim="galore_adamw_layerwise", + optim_target_modules=[r".*.attn.*", r".*.mlp.*"], + gradient_checkpointing=True, +) +trainer = SFTTrainer( + model="google/gemma-2b", + args=args, + train_dataset=train_dataset, +) +trainer.train() +``` + +لاحظ أن تحسين الطبقة تجريبي إلى حد ما ولا يدعم DDP (Distributed Data Parallel)، وبالتالي يمكنك تشغيل التعليمات البرمجية للتدريب على وحدة معالجة الرسومات (GPU) واحدة فقط. يرجى الاطلاع على [هذا القسم المناسب](https://github.com/jiaweizzhao/GaLore?tab=readme-ov-file#train-7b-model-with-a-single-gpu-with-24gb-memory) لمزيد من التفاصيل. قد لا تدعم الميزات الأخرى مثل تقليم التدرجات أو DeepSpeed، إلخ. من الصندوق. يرجى [تقديم تقرير عن المشكلة على GitHub](https://github.com/huggingface/transformers/issues) إذا واجهتك مثل هذه المشكلة. + +### محسنات LOMO + +تم تقديم مُحسِّنات LOMO في [التدريب على المعلمات الكاملة لنماذج اللغة الكبيرة باستخدام موارد محدودة](https://hf.co/papers/2306.09782) و [AdaLomo: تحسين ذاكرة منخفضة بمعدل تعلم متكيف](https://hf.co/papers/2310.10195). +يتكون كلاهما من طريقة فعالة لضبط المعلمات الكاملة. تدمج محسنات LOMO حساب الاشتقاق وتحديث المعلمات في خطوة واحدة لتقليل استخدام الذاكرة. محسنات LOMO المدعومة هي `"lomo"` و `"adalomo"`. أولاً قم بتثبيت LOMO من pypi `pip install lomo-optim` أو قم بتثبيته من المصدر باستخدام `pip install git+https://github.com/OpenLMLab/LOMO.git`. + + + +وفقًا للمؤلفين، يوصى باستخدام `AdaLomo` بدون `grad_norm` للحصول على أداء أفضل وسرعة أعلى. + + + +فيما يلي نص برمجي بسيط يوضح كيفية ضبط نموذج [google/gemma-2b](https://huggingface.co/google/gemma-2b) على مجموعة بيانات IMDB في الدقة الكاملة: + +```python +import datasets +from trl import SFTConfig, SFTTrainer + +train_dataset = datasets.load_dataset('imdb', split='train') +args = SFTConfig( + output_dir="./test-lomo", + max_steps=100, + optim="adalomo", + gradient_checkpointing=True, +) +trainer = SFTTrainer( + model="google/gemma-2b", + args=args, + train_dataset=train_dataset, +) +trainer.train() +``` + +### مُحسِّن GrokAdamW +تم تصميم مُحسِّن GrokAdamW لتعزيز أداء التدريب واستقراره، خاصةً للنماذج التي تستفيد من دوال إشارة `grokking`. لاستخدام `GrokAdamW`، قم أولاً بتثبيت حزمة المُحسِّن باستخدام `pip install grokadamw`. + +يُعد GrokAdamW مفيدًا بشكل خاص للنماذج التي تتطلب تقنيات تحسين مُتقدمة لتحقيق أداء واستقرار أفضل. + + +فيما يلي نص برمجى بسيط لشرح كيفية ضبط [google/gemma-2b](https://huggingface.co/google/gemma-2b) بدقة على مجموعة بيانات IMDB باستخدام مُحسِّن GrokAdamW: +```python +import torch +import datasets +from transformers import TrainingArguments, AutoTokenizer, AutoModelForCausalLM, Trainer + +# تحميل مجموعة البيانات IMDB +train_dataset = datasets.load_dataset('imdb', split='train') + +# تعريف معامﻻت التدريب +args = TrainingArguments( + output_dir="./test-grokadamw", + max_steps=1000, + per_device_train_batch_size=4, + optim="grokadamw", + logging_strategy="steps", + logging_steps=1, + learning_rate=2e-5, + save_strategy="no", + run_name="grokadamw-imdb", +) + +# تحميل النموذج والمجزىء اللغوي +model_id = "google/gemma-2b" +tokenizer = AutoTokenizer.from_pretrained(model_id) +model = AutoModelForCausalLM.from_pretrained(model_id).to(0) + +# تهيئة المدرب +trainer = Trainer( + model=model, + args=args, + train_dataset=train_dataset, +) + +# تدريب النموذج +trainer.train() +``` +يوضح هذا النص البرمجى كيفية ضبط نموذج google/gemma-2b بدقة على مجموعة بيانات IMDB باستخدام مُحسِّن GrokAdamW. يتم تكوين TrainingArguments لاستخدام GrokAdamW، ويتم تمرير مجموعة البيانات إلى Trainer للتدريب. + +### مُحسِّن بدون جدوله (Schedule Free Optimizer) +تم تقديم مُحسِّنات بدون جدوله في [The Road Less Scheduled](https://hf.co/papers/2405.15682). +يستبدل التعلم بدون جدوله زخم المُحسِّن الأساسي بمزيج من المتوسط ​​والتداخل، لإزالة الحاجة تمامًا إلى تخفيف مُعدل التعلم باستخدام جدوله تقليديه. +المُحسِّنات المدعومة لـ SFO هي "schedule_free_adamw" و "schedule_free_sgd". قم أولاً بتثبيت `schedulefree` من pypi باستخدام الأمر `pip install schedulefree`. + +فيما يلي نص برمجى بسيط لشرح كيفية ضبط [google/gemma-2b](https://huggingface.co/google/gemma-2b) بدقة على مجموعة بيانات IMDB بدقة كاملة: +```python +import datasets +from trl import SFTConfig, SFTTrainer + +train_dataset = datasets.load_dataset('imdb', split='train') +args = SFTConfig( + output_dir="./test-galore", + max_steps=100, + optim="schedule_free_adamw", + gradient_checkpointing=True, +) +trainer = SFTTrainer( + model="google/gemma-2b", + args=args, + train_dataset=train_dataset, +) +trainer.train() +``` +## تسريع ومدرب + +يتم تشغيل فئة [`Trainer`] بواسطة [تسريع](https://hf.co/docs/accelerate)، وهي مكتبة لتدريب نماذج PyTorch بسهولة في بيئات موزعة مع دعم عمليات التكامل مثل [FullyShardedDataParallel (FSDP)](https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/) و [DeepSpeed](https://www.deepspeed.ai/). + + + +تعرف على المزيد حول استراتيجيات تجزئة FSDP، وتفريغ وحدة المعالجة المركزية (CPU)، والمزيد مع [`Trainer`] في [دليل Fully Sharded Data Parallel](fsdp). + + + +لاستخدام Accelerate مع [`Trainer`]]، قم بتشغيل الأمر [`accelerate.config`](https://huggingface.co/docs/accelerate/package_reference/cli#accelerate-config) لإعداد التدريب لبيئة التدريب الخاصة بك. نشئ هذا الأمر ملف `config_file.yaml` الذي سيتم استخدامه عند تشغيل نص للتدريب البرمجى. على سبيل المثال، بعض تكوينات المثال التي يمكنك إعدادها هي: + + + + +```yml +compute_environment: LOCAL_MACHINE +distributed_type: MULTI_GPU +downcast_bf16: 'no' +gpu_ids: all +machine_rank: 0 #change rank as per the node +main_process_ip: 192.168.20.1 +main_process_port: 9898 +main_training_function: main +mixed_precision: fp16 +num_machines: 2 +num_processes: 8 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false +``` + + + + +```yml +compute_environment: LOCAL_MACHINE +distributed_type: FSDP +downcast_bf16: 'no' +fsdp_config: + fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP + fsdp_backward_prefetch_policy: BACKWARD_PRE + fsdp_forward_prefetch: true + fsdp_offload_params: false + fsdp_sharding_strategy: 1 + fsdp_state_dict_type: FULL_STATE_DICT + fsdp_sync_module_states: true + fsdp_transformer_layer_cls_to_wrap: BertLayer + fsdp_use_orig_params: true +machine_rank: 0 +main_training_function: main +mixed_precision: bf16 +num_machines: 1 +num_processes: 2 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false +``` + + + + +```yml +compute_environment: LOCAL_MACHINE +deepspeed_config: + deepspeed_config_file: /home/user/configs/ds_zero3_config.json + zero3_init_flag: true +distributed_type: DEEPSPEED +downcast_bf16: 'no' +machine_rank: 0 +main_training_function: main +num_machines: 1 +num_processes: 4 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false +``` + + + + +```yml +compute_environment: LOCAL_MACHINE +deepspeed_config: + gradient_accumulation_steps: 1 + gradient_clipping: 0.7 + offload_optimizer_device: cpu + offload_param_device: cpu + zero3_init_flag: true + zero_stage: 2 +distributed_type: DEEPSPEED +downcast_bf16: 'no' +machine_rank: 0 +main_training_function: main +mixed_precision: bf16 +num_machines: 1 +num_processes: 4 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false +``` + + + + +يُعد أمر [`accelerate_launch`](https://huggingface.co/docs/accelerate/package_reference/cli#accelerate-launch) هو الطريقة المُوصى بها لتشغيل نص البرمجى للتدريب على نظام موزع باستخدام Accelerate و [`Trainer`] مع المعلمات المحددة في `config_file.yaml`. يتم حفظ هذا الملف في مجلد ذاكرة التخزين المؤقت لـ Accelerate ويتم تحميله تلقائيًا عند تشغيل `accelerate_launch`. + +على سبيل المثال، لتشغيل النص البرنامجي للتدريب [run_glue.py](https://github.com/huggingface/transformers/blob/f4db565b695582891e43a5e042e5d318e28f20b8/examples/pytorch/text-classification/run_glue.py#L4) مع تكوين FSDP: + +```bash +accelerate launch \ + ./examples/pytorch/text-classification/run_glue.py \ + --model_name_or_path google-bert/bert-base-cased \ + --task_name $TASK_NAME \ + --do_train \ + --do_eval \ + --max_seq_length 128 \ + --per_device_train_batch_size 16 \ + --learning_rate 5e-5 \ + --num_train_epochs 3 \ + --output_dir /tmp/$TASK_NAME/ \ + --overwrite_output_dir +``` + +يمكنك أيضًا تحديد المعلمات من ملف `config_file.yaml` مباشرة في سطر الأوامر: + +```bash +accelerate launch --num_processes=2 \ + --use_fsdp \ + --mixed_precision=bf16 \ + --fsdp_auto_wrap_policy=TRANSFORMER_BASED_WRAP \ + --fsdp_transformer_layer_cls_to_wrap="BertLayer" \ + --fsdp_sharding_strategy=1 \ + --fsdp_state_dict_type=FULL_STATE_DICT \ + ./examples/pytorch/text-classification/run_glue.py + --model_name_or_path google-bert/bert-base-cased \ + --task_name $TASK_NAME \ + --do_train \ + --do_eval \ + --max_seq_length 128 \ + --per_device_train_batch_size 16 \ + --learning_rate 5e-5 \ + --num_train_epochs 3 \ + --output_dir /tmp/$TASK_NAME/ \ + --overwrite_output_dir +``` + +اطلع على برنامج تعليمي [Launching your Accelerate scripts](https://huggingface.co/docs/accelerate/basic_tutorials/launch) لمعرفة المزيد حول `accelerate_launch` والتكوينات المخصصة. diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/training.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/training.md new file mode 100644 index 0000000000000000000000000000000000000000..d3e354ff8b1af3b58a72a7a24070452ac49c5d48 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/training.md @@ -0,0 +1,412 @@ +# ضبط نموذج مُدرب مسبقًا + +هناك فوائد كبيرة لاستخدام نموذج مُدرب مسبقًا. فهو يقلل من تكاليف الحوسبة، ويحد من أثرنا البيئي، ويتيح لك استخدام أحدث النماذج دون الحاجة إلى تدريبها من الصفر. توفر مكتبة 🤗 Transformers إمكانية الوصول إلى آلاف النماذج المُدربة مسبقًا لمجموعة واسعة من المهام. عندما تستخدم نموذجًا مُدربًا مسبقًا، فإنك تقوم بتدريبه على مجموعة بيانات خاصة بمهمتك. يُعرف ذلك بالضبط الدقيق، وهي تقنية تدريب قوية للغاية. في هذا البرنامج التعليمي، سوف تقوم بضبط نموذج مُدرب مسبقًا باستخدام إطار عمل للتعلم العميق الذي تختاره: + +* ضبط نموذج مُدرب مسبقًا باستخدام 🤗 Transformers [`Trainer`]. +* ضبط نموذج مُدرب مسبقًا في TensorFlow باستخدام Keras. +* ضبط نموذج مُدرب مسبقًا في PyTorch الأصلي. + + + +## إعداد مجموعة بيانات + +قبل أن تتمكن من ضبط نموذج مُدرب مسبقًا، قم بتنزيل مجموعة بيانات وإعدادها للتدريب. أظهر البرنامج التعليمي السابق كيفية معالجة البيانات للتدريب، والآن لديك الفرصة لاختبار تلك المهارات! + +ابدأ بتحميل مجموعة بيانات [Yelp Reviews](https://huggingface.co/datasets/yelp_review_full): + +```py +>>> from datasets import load_dataset + +>>> dataset = load_dataset("yelp_review_full") +>>> dataset["train"][100] +{'label': 0, + 'text': 'My expectations for McDonalds are t rarely high. But for one to still fail so spectacularly...that takes something special!\\nThe cashier took my friends\'s order, then promptly ignored me. I had to force myself in front of a cashier who opened his register to wait on the person BEHIND me. I waited over five minutes for a gigantic order that included precisely one kid\'s meal. After watching two people who ordered after me be handed their food, I asked where mine was. The manager started yelling at the cashiers for \\"serving off their orders\\" when they didn\'t have their food. But neither cashier was anywhere near those controls, and the manager was the one serving food to customers and clearing the boards.\\nThe manager was rude when giving me my order. She didn\'t make sure that I had everything ON MY RECEIPT, and never even had the decency to apologize that I felt I was getting poor service.\\nI\'ve eaten at various McDonalds restaurants for over 30 years. I\'ve worked at more than one location. I expect bad days, bad moods, and the occasional mistake. But I have yet to have a decent experience at this store. It will remain a place I avoid unless someone in my party needs to avoid illness from low blood sugar. Perhaps I should go back to the racially biased service of Steak n Shake instead!'} +``` + +كما تعلم الآن، تحتاج إلى محول نص إلى رمز (tokenizer) لمعالجة النص وتضمين استراتيجيات للحشو والقص للتعامل مع أي أطوال متسلسلة متغيرة. لمعالجة مجموعة البيانات الخاصة بك في خطوة واحدة، استخدم طريقة 🤗 Datasets [`map`](https://huggingface.co/docs/datasets/process#map) لتطبيق دالة معالجة مسبقة على مجموعة البيانات بأكملها: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased") + + +>>> def tokenize_function(examples): +... return tokenizer(examples["text"], padding="max_length", truncation=True) +>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased") + + +>>> def tokenize_function(examples): +... return tokenizer(examples["text"], padding="max_length", truncation=True) + + +>>> tokenized_datasets = dataset.map(tokenize_function, batched=True) +``` + +إذا كنت ترغب، يمكنك إنشاء مجموعة فرعية أصغر من مجموعة البيانات الكاملة لضبطها لتقليل الوقت الذي تستغرقه: + +```py +>>> small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000)) +>>> small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000)) +``` + + + +## التدريب + +في هذه المرحلة، يجب عليك اتباع القسم الذي يتوافق مع الإطار الذي تريد استخدامه. يمكنك استخدام الروابط +في شريط التنقل الأيمن للقفز إلى الإطار الذي تريده - وإذا كنت تريد إخفاء كل المحتوى لإطار معين، +فاستخدم الزر في الركن العلوي الأيمن من كتلة الإطار! + + + + + +## التدريب باستخدام PyTorch Trainer + +تقدم مكتبة 🤗 Transformers فئة [`Trainer`] مُحسّنة لتدريب نماذج 🤗 Transformers، مما يسهل بدء التدريب دون الحاجة إلى كتابة حلقة التدريب الخاصة بك يدويًا. تدعم واجهة برمجة تطبيقات [`Trainer`] مجموعة واسعة من خيارات التدريب والميزات مثل التسجيل، وتراكم التدرجات، والدقة المختلطة. + +ابدأ بتحميل نموذجك وتحديد عدد التصنيفات المتوقعة. من بطاقة مجموعة بيانات Yelp Review [dataset card](https://huggingface.co/datasets/yelp_review_full#data-fields)، تعرف أنه يوجد خمسة تصنيفات: + +```py +>>> from transformers import AutoModelForSequenceClassification + +>>> model = AutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-cased", num_labels=5) +``` + + + +سترى تحذيرًا بشأن بعض أوزان النموذج المُدرب مسبقًا لن تُستخدم وبعض الأوزان الأخرى ستُبدء بشكل عشوائي. لا تقلق، هذا أمر طبيعي تمامًا! يتم التخلص من رأس النموذج المُدرب مسبقًا لشبكة BERT، ويتم استبداله برأس تصنيف يُبدء بشكل عشوائي. سوف تقوم بضبط الرأس الجديد للنموذج بدقة على مهمة تصنيف التسلسلات الخاصة بك، مما ينقل المعرفة من النموذج المُدرب مسبقًا إليه. + + + +### اختيار أحسن العوامل والمتغيرات للتدريب (Training hyperparameters) + +بعد ذلك، قم بإنشاء كائن من فئة [`TrainingArguments`] والتي تحتوي على جميع العوامل والمتغيرات التي يمكنك ضبطها بالإضافة إلى خيارات تنشيط التدريب المختلفة. بالنسبة لهذا البرنامج التعليمي، يمكنك البدء بمعاملات التدريب الافتراضية [hyperparameters](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments)، ولكن لا تتردد في تجربتها للعثور على الإعدادات المثلى. + +حدد مكان حفظ النسخ من تدريبك: + +```py +>>> from transformers import TrainingArguments + +>>> training_args = TrainingArguments(output_dir="test_trainer") +``` + +### التقييم + +لا يقوم [`Trainer`] تلقائيًا بتقييم أداء النموذج أثناء التدريب. ستحتاج إلى تمرير دالة إلى [`Trainer`] لحساب وإبلاغ المقاييس. توفر مكتبة [🤗 Evaluate](https://huggingface.co/docs/evaluate/index) دالة [`accuracy`](https://huggingface.co/spaces/evaluate-metric/accuracy) بسيطة يمكنك تحميلها باستخدام الدالة [`evaluate.load`] (راجع هذا [الدليل السريع](https://huggingface.co/docs/evaluate/a_quick_tour) لمزيد من المعلومات): + +```py +>>> import numpy as np +>>> import evaluate + +>>> metric = evaluate.load("accuracy") +``` + +استدعِ دالة [`~evaluate.compute`] على `metric` لحساب دقة تنبؤاتك. قبل تمرير تنبؤاتك إلى دالة `compute`، تحتاج إلى تحويل النتائج الخام logits إلى تنبؤات نهائية (تذكر أن جميع نماذج 🤗 Transformers تعيد نتائج الخام logits): + +```py +>>> def compute_metrics(eval_pred): +... logits، labels = eval_pred +... predictions = np.argmax(logits, axis=-1) +... return metric.compute(predictions=predictions, references=labels) +``` + +إذا كنت ترغب في مراقبة مقاييس التقييم الخاصة بك أثناء الضبط الدقيق، فحدد معلمة `eval_strategy` في معاملات التدريب الخاصة بك لإظهار مقياس التقييم في نهاية كل حقبة تدريبه: + +```py +>>> from transformers import TrainingArguments, Trainer + +>>> training_args = TrainingArguments(output_dir="test_trainer", eval_strategy="epoch") +``` + +### المدرب + +قم بإنشاء كائن [`Trainer`] باستخدام نموذجك، ومعاملات التدريب، ومجموعات البيانات التدريبية والاختبارية، ودالة التقييم: + +```py +>>> trainer = Trainer( +... model=model, +... args=training_args, +... train_dataset=small_train_dataset, +... eval_dataset=small_eval_dataset, +... compute_metrics=compute_metrics, +... ) +``` + +ثم قم بضبط نموذجك عن طريق استدعاء [`~transformers.Trainer.train`]: + +```py +>>> trainer.train() +``` + + + + + + +## تدريب نموذج TensorFlow باستخدام Keras + +يمكنك أيضًا تدريب نماذج 🤗 Transformers في TensorFlow باستخدام واجهة برمجة تطبيقات Keras! + +### تحميل البيانات لـ Keras + +عندما تريد تدريب نموذج 🤗 Transformers باستخدام واجهة برمجة تطبيقات Keras، فأنت بحاجة إلى تحويل مجموعة البيانات الخاصة بك إلى تنسيق يفهمه +Keras. إذا كانت مجموعة البيانات الخاصة بك صغيرة، فيمكنك ببساطة تحويلها بالكامل إلى مصفوفات NumPy وإرسالها إلى Keras. +دعونا نجرب ذلك أولاً قبل أن نقوم بأي شيء أكثر تعقيدًا. + +أولاً، قم بتحميل مجموعة بيانات. سنستخدم مجموعة بيانات CoLA من معيار [GLUE benchmark](https://huggingface.co/datasets/glue)، +نظرًا لأنه مهمة تصنيف نص ثنائي بسيطة، وسنأخذ فقط قسم التدريب الآن. + +```py +from datasets import load_dataset + +dataset = load_dataset("glue"، "cola") +dataset = dataset ["train"] # خذ فقط قسم التدريب الآن +``` + +بعد ذلك، قم بتحميل أداة المُجزّئ اللغوي وقم بترميز البيانات كمصفوفات NumPy. لاحظ أن التصنيفات هي بالفعل قائمة من 0 و 1، +لذا يمكننا ببساطة تحويل ذلك مباشرة إلى مصفوفة NumPy بدون ترميز! + +```py +from transformers import AutoTokenizer +import numpy as np + +tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased") +tokenized_data = tokenizer(dataset["sentence"], return_tensors="np", padding=True) +# Tokenizer returns a BatchEncoding, but we convert that to a dict for Keras +tokenized_data = dict(tokenized_data) + +labels = np.array(dataset["label"]) # Label is already an array of 0 and 1 +``` + +أخيرًا، قم بتحميل وتجميع وتناسب النموذج. لاحظ أن نماذج Transformers تحتوي جميعها على دالة خسارة ذات صلة بالمهمة بشكل افتراضي، لذا فأنت لست بحاجة إلى تحديد واحدة ما لم ترغب في ذلك: + +```py +from transformers import TFAutoModelForSequenceClassification +from tensorflow.keras.optimizers import Adam + +# تحميل وتجميع النموذج الخاص بنا +model = TFAutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-cased") +# معدلات التعلم المنخفضة أفضل غالبًا لضبط النماذج الدقيقة +model.compile(optimizer=Adam(3e-5)) # لا توجد دالة خسارة! + +model.fit(tokenized_data, labels) +``` + + + +أنت لست مضطرًا لتمرير دالة خسارة إلى نماذجك عند تجميعها! تختار نماذج Hugging Face تلقائيًا +دالة خسارة مناسبة لمهمتها وهندسة نموذجها إذا تُركت هذه الحجة فارغة. يمكنك دائمًا +تجاوز ذلك عن طريق تحديد دالة خسارة بنفسك إذا كنت تريد ذلك! + + + +يعمل هذا النهج بشكل رائع لمجموعات البيانات الصغيرة، ولكن بالنسبة لمجموعات البيانات الأكبر، فقد تجد أنه يصبح مشكلة. لماذا؟ +لأن المصفوفة المرمزة والتصنيفات يجب أن يتم تحميلها بالكامل في الذاكرة، ولأن NumPy لا يتعامل مع +المصفوفات"غير المنتظمة"، لذا حشو كل عينة إلى طول أطول عينة في مجموعة البيانات بأكملها. سيؤدي ذلك إلى زيادة حجم المصفوفة لديك، وستبطئ الرموز الزائده من عملية التدريب أيضًا! + +### تحميل البيانات كـ tf.data.Dataset + +إذا كنت تريد تجنب إبطاء التدريب، فيمكنك تحميل بياناتك كـ `tf.data.Dataset` بدلاً من ذلك. على الرغم من أنه يمكنك كتابة خط أنابيب `tf.data` الخاص بك إذا كنت تريد، إلا أن لدينا طريقتين مختصرتين للقيام بذلك: +- [`~TFPreTrainedModel.prepare_tf_dataset`]: هذه هي الطريقة التي نوصي بها في معظم الحالات. نظرًا لأنه طريقة +على نموذجك، فيمكنه فحص النموذج لتحديد الأعمدة القابلة للاستخدام كمدخلات للنموذج تلقائيًا، +واستبعاد الأعمدة الأخرى لإنشاء مجموعة بيانات أبسط وأكثر كفاءة. +- [`~datasets.Dataset.to_tf_dataset`]: هذه الطريقة أكثر أساسية، وهي مفيدة عندما تريد التحكم بدقة في كيفية +إنشاء مجموعة البيانات الخاصة بك، عن طريق تحديد أعمدة `columns` و `label_cols` المحددة التي سيتم تضمينها. + +قبل أن تتمكن من استخدام [`~TFPreTrainedModel.prepare_tf_dataset`]، ستحتاج إلى إضافة مخرجات المُجزئ إلى مجموعة البيانات الخاصة بك كأعمدة، كما هو موضح في +عينة التعليمات البرمجية التالية: + +```py +def tokenize_dataset (data): +# ستتم إضافة مفاتيح القاموس الذي تمت إعادته كأعمدة إلى مجموعة البيانات +return tokenizer(data["text"]) + + +dataset = dataset.map(tokenize_dataset) +``` + +تذكر أن مجموعات بيانات Hugging Face يتم تخزينها على القرص بشكل افتراضي، لذا فلن يؤدي ذلك إلى تضخيم استخدام الذاكرة لديك! بمجرد إضافة الأعمدة، يمكنك بث الدفعات من مجموعة البيانات وإضافة الترميز إلى كل دفعة، مما يقلل بشكل كبير من عدد رموز الترقيم مقارنة بترميز مجموعة البيانات بأكملها. + + +```py +>>> tf_dataset = model.prepare_tf_dataset(dataset["train"], batch_size=16, shuffle=True, tokenizer=tokenizer) +``` + +لاحظ أنه في عينة التعليمات البرمجية أعلاه، تحتاج إلى تمرير المُجزئ اللغوي إلى `prepare_tf_dataset` حتى تتمكن من حشو الدُفعات بشكل صحيح أثناء تحميلها. +إذا كانت جميع العينات في مجموعة البيانات الخاصة بك بنفس الطول ولم يكن الترميز ضروريًا، فيمكنك تخطي هذا المعامل. +إذا كنت بحاجة إلى القيام بشيء أكثر تعقيدًا من مجرد ترميز العينات (على سبيل المثال، إفساد الرموز للنمذجة اللغوية المُقنعة)، +فيمكنك استخدام معامل `collate_fn` بدلاً من ذلك لتمرير دالة يتم استدعاؤها لتحويل +قائمة العينات إلى دفعة وتطبيق أي معالجة مسبقة تريدها. راجع أمثلةنا [examples](https://github.com/huggingface/transformers/tree/main/examples) أو +[دفاتر الملاحظات](https://huggingface.co/docs/transformers/notebooks) لرؤية هذا النهج في العمل. + +بمجرد إنشاء `tf.data.Dataset`، يمكنك تجميع النموذج وتناسبه كما هو الحال من قبل: + +```py +model.compile(optimizer=Adam(3e-5)) # No loss argument! + +model.fit(tf_dataset) +``` + + + + + +## تدريب في PyTorch الأصلي + + + + + +[`Trainer`] يهتم بحلقة التدريب ويسمح لك بضبط نموذج في سطر واحد من التعليمات البرمجية. بالنسبة للمستخدمين الذين يفضلون كتابة حلقة التدريب الخاصة بهم، يمكنك أيضًا ضبط نموذج 🤗 Transformers في PyTorch الأصلي. + +في هذه المرحلة، قد تحتاج إلى إعادة تشغيل دفتر الملاحظات الخاص بك أو تنفيذ التعليمات البرمجية التالية لتحرير بعض الذاكرة: + +```py +del model +del trainer +torch.cuda.empty_cache() +``` + +بعد ذلك، قم بمعالجة `tokenized_dataset` يدويًا لإعداده للتدريب. + +1. إزالة عمود `text` لأن النموذج لا يقبل النص الخام كإدخال: + + ```py + >>> tokenized_datasets = tokenized_datasets.remove_columns(["text"]) + ``` + +2. إعادة تسمية عمود `label` إلى `labels` لأن النموذج يتوقع أن يكون الاسم `labels`: + + ```py + >>> tokenized_datasets = tokenized_datasets.rename_column("label"، "labels") + ``` + +3. قم بتعيين تنسيق مجموعة البيانات لإرجاع مؤشرات PyTorch بدلاً من القوائم: + + ```py + >>> tokenized_datasets.set_format("torch") + ``` + +بعد ذلك، قم بإنشاء مجموعة فرعية أصغر من مجموعة البيانات كما هو موضح سابقًا لتسريع الضبط الدقيق: + +```py +>>> small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000)) +>>> small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000)) +``` + +### DataLoader + +قم بإنشاء `DataLoader` لمجموعات بيانات التدريب والاختبار الخاصة بك حتى تتمكن من التكرار عبر دفعات البيانات: + +```py +>>> from torch.utils.data import DataLoader + +>>> train_dataloader = DataLoader(small_train_dataset، shuffle=True، batch_size=8) +>>> eval_dataloader = DataLoader(small_eval_dataset، batch_size=8) +``` + +قم بتحميل نموذجك مع عدد التصنيفات المتوقعة: + +```py +>>> from transformers import AutoModelForSequenceClassification + +>>> model = AutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-cased"، num_labels=5) +``` + +### المحسن ومخطط معدل التعلم + +قم بإنشاء محسن ومخطط معدل تعلم لضبط النموذج الدقيق. دعنا نستخدم [`AdamW`](https://pytorch.org/docs/stable/generated/torch.optim.AdamW.html) المحسن من PyTorch: + +```py +>>> from torch.optim import AdamW + +>>> optimizer = AdamW(model.parameters()، lr=5e-5) +``` + +قم بإنشاء مخطط معدل التعلم الافتراضي من [`Trainer`]: + +```py +>>> from transformers import get_scheduler + +>>> num_epochs = 3 +>>> num_training_steps = num_epochs * len(train_dataloader) +>>> lr_scheduler = get_scheduler( +... name="linear"، optimizer=optimizer، num_warmup_steps=0، num_training_steps=num_training_steps +... ) +``` + +أخيرًا، حدد `device` لاستخدام وحدة معالجة الرسومات (GPU) إذا كان لديك حق الوصول إليها. وإلا، فقد يستغرق التدريب على وحدة المعالجة المركزية (CPU) عدة ساعات بدلاً من دقائق قليلة. + +```py +>>> import torch + +>>> device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") +>>> model.to(device) +``` + + + +احصل على وصول مجاني إلى وحدة معالجة رسومات سحابية إذا لم يكن لديك واحدة مع دفتر ملاحظات مستضاف مثل [Colaboratory](https://colab.research.google.com/) أو [SageMaker StudioLab](https://studiolab.sagemaker.aws/). + + + +رائع، الآن أنت مستعد للتدريب! 🥳 + +### حلقة التدريب + +لمراقبة تقدم التدريب الخاص بك، استخدم مكتبة [tqdm](https://tqdm.github.io/) لإضافة شريط تقدم فوق عدد خطوات التدريب: + +```py +>>> from tqdm.auto import tqdm + +>>> progress_bar = tqdm(range(num_training_steps)) + +>>> model.train() +>>> for epoch in range(num_epochs): +... for batch in train_dataloader: +... batch = {k: v.to(device) for k، v in batch.items()} +... outputs = model(**batch) +... loss = outputs.loss +... loss.backward() + +... optimizer.step() +... lr_scheduler.step() +... optimizer.zero_grad() +... progress_bar.update(1) +``` + +### تقييم + +تمامًا كما أضفت وظيفة تقييم إلى [`Trainer`]]، تحتاج إلى القيام بنفس الشيء عندما تكتب حلقة التدريب الخاصة بك. ولكن بدلاً من حساب الإبلاغ عن المقياس في نهاية كل حقبة، هذه المرة ستقوم بتجميع جميع الدفعات باستخدام [`~evaluate.add_batch`] وحساب المقياس في النهاية. + +```py +>>> import evaluate + +>>> metric = evaluate.load("accuracy") +>>> model.eval() +>>> for batch in eval_dataloader: +... batch = {k: v.to(device) for k، v in batch.items()} +... with torch.no_grad(): +... outputs = model(**batch) + +... logits = outputs.logits +... predictions = torch.argmax(logits، dim=-1) +... metric.add_batch(predictions=predictions، references=batch["labels"]) + +>>> metric.compute() +``` + + + + + +## موارد إضافية + +لمزيد من الأمثلة على الضبط الدقيق، راجع: + +- [🤗 أمثلة المحولات](https://github.com/huggingface/transformers/tree/main/examples) تتضمن + النصوص البرمجية لتدريب مهام NLP الشائعة في PyTorch وTensorFlow. + +- [🤗 دفاتر ملاحظات المحولات](notebooks) يحتوي على دفاتر ملاحظات مختلفة حول كيفية ضبط نموذج لمهمة محددة في PyTorch وTensorFlow. \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/troubleshooting.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/troubleshooting.md new file mode 100644 index 0000000000000000000000000000000000000000..7874a9fad13304a859967b79d9117da8dc34a545 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/ar/troubleshooting.md @@ -0,0 +1,171 @@ +# استكشاف الأخطاء وإصلاحها + +تحدث الأخطاء أحيانًا، لكننا هنا للمساعدة! يغطي هذا الدليل بعض المشكلات الأكثر شيوعًا التي واجهناها وكيفية حلها. مع ذلك، لا يُقصد بهذا الدليل أن يكون مجموعة شاملة لكل مشكلات 🤗 Transformers. لمزيد من المساعدة في استكشاف مشكلتك وإصلاحها، جرب ما يلي: + + + +1. اطلب المساعدة على [المنتديات](https://discuss.huggingface.co/). هناك فئات محددة يمكنك نشر سؤالك فيها، مثل [المبتدئين](https://discuss.huggingface.co/c/beginners/5) أو [🤗 Transformers](https://discuss.huggingface.co/c/transformers/9). تأكد من كتابة منشور جيد وواضح على المنتدى مع بعض التعليمات البرمجية القابلة للتكرار لزيادة احتمالية حل مشكلتك! + + +2. قم بإنشاء [مشكلة](https://github.com/huggingface/transformers/issues/new/choose) في مستودع 🤗 Transformers إذا كانت هناك مشكلة متعلقة بالمكتبة. حاول تضمين أكبر قدر ممكن من المعلومات التي تصف المشكلة لمساعدتنا في معرفة ما هو الخطأ وكيفية إصلاحه. + +3. تحقق من دليل [الترحيل](migration) إذا كنت تستخدم إصدارًا أقدم من مكتبة 🤗 Transformers حيث تم إدخال بعض التغييرات المهمة بين الإصدارات. + + +للحصول على مزيد من التفاصيل حول استكشاف الأخطاء وإصلاحها والحصول على المساعدة، راجع [الفصل 8](https://huggingface.co/course/chapter8/1?fw=pt) من دورة Hugging Face. + +## بيئات جدار الحماية + +بعض وحدات معالجة الرسومات (GPU) على السحابة وإعدادات الشبكة الداخلية محمية بجدار حماية من الاتصالات الخارجية، مما يؤدي إلى حدوث خطأ في الاتصال. عندما تحاول تعليمات البرنامج النصي تنزيل أوزان النموذج أو مجموعات البيانات، سيتوقف التنزيل ثم ينتهي بخطأ مثل: + +``` +ValueError: Connection error, and we cannot find the requested files in the cached path. +Please try again or make sure your Internet connection is on. +``` + +في هذه الحالة، يجب محاولة تشغيل 🤗 Transformers في [وضع عدم الاتصال](installation#offline-mode) لتجنب خطأ الاتصال. + +## CUDA نفاد الذاكرة + +يمكن أن يكون تدريب النماذج الكبيرة التي تحتوي على ملايين المعلمات أمرًا صعبًا بدون الأجهزة المناسبة. أحد الأخطاء الشائعة التي قد تواجهها عند نفاد ذاكرة GPU هو: + +``` +CUDA out of memory. Tried to allocate 256.00 MiB (GPU 0; 11.17 GiB total capacity; 9.70 GiB already allocated; 179.81 MiB free; 9.85 GiB reserved in total by PyTorch) +``` + +فيما يلي بعض الحلول المحتملة التي يمكنك تجربتها لتقليل استخدام الذاكرة: + +- قلل من قيمة [`per_device_train_batch_size`](main_classes/trainer#transformers.TrainingArguments.per_device_train_batch_size) في [`TrainingArguments`]. + +- حاول استخدام [`gradient_accumulation_steps`](main_classes/trainer#transformers.TrainingArguments.gradient_accumulation_steps) في [`TrainingArguments`] لزيادة حجم الدُفعة بشكل فعال. + + +راجع دليل [الأداء](performance) لمزيد من التفاصيل حول تقنيات توفير الذاكرة. + + +## عدم القدرة على تحميل نموذج TensorFlow محفوظ + +تقوم طريقة TensorFlow [model.save](https://www.tensorflow.org/tutorials/keras/save_and_load#save_the_entire_model) بحفظ النموذج بالكامل - الهندسة المعمارية، الأوزان، تكوين التدريب - في ملف واحد. ومع ذلك، عند تحميل ملف النموذج مرة أخرى، قد تواجه خطأ لأن مكتبة 🤗 Transformers قد لا تقوم بتحميل جميع الكائنات المتعلقة بـ TensorFlow في ملف النموذج. لتجنب المشكلات المتعلقة بحفظ وتحميل نماذج TensorFlow، نوصي بما يلي: + +- احفظ أوزان النموذج كملف `h5` باستخدام [`model.save_weights`](https://www.tensorflow.org/tutorials/keras/save_and_load#save_the_entire_model) ثم أعد تحميل النموذج باستخدام [`~TFPreTrainedModel.from_pretrained`]: + +```python +>>> from transformers import TFPreTrainedModel +>>> from tensorflow import keras + +>>> model.save_weights("some_folder/tf_model.h5") +>>> model = TFPreTrainedModel.from_pretrained("some_folder") +``` + +- احفظ النموذج باستخدام [`~TFPretrainedModel.save_pretrained`] وقم بتحميله مرة أخرى باستخدام [`~TFPreTrainedModel.from_pretrained`]: + +```python +>>> from transformers import TFPreTrainedModel + +>>> model.save_pretrained("path_to/model") +>>> model = TFPreTrainedModel.from_pretrained("path_to/model") +``` + +## ImportError + +خطأ شائع آخر قد تواجهه، خاصة إذا كان نموذجًا تم إصداره حديثًا، هو `ImportError`: + +``` +ImportError: cannot import name 'ImageGPTImageProcessor' from 'transformers' (unknown location) +``` + +بالنسبة لأنواع الأخطاء هذه، تحقق من أن لديك أحدث إصدار من مكتبة Hugging Face Transformers مثبتًا للوصول إلى أحدث النماذج: + +```bash +pip install transformers --upgrade +``` + +## خطأ CUDA: تم تشغيل التأكيد على جانب الجهاز + +في بعض الأحيان، قد تواجه خطأ CUDA عامًا حول خطأ في كود الجهاز. + +``` +RuntimeError: CUDA error: device-side assert triggered +``` + +يجب عليك محاولة تشغيل الكود على وحدة المعالجة المركزية (CPU) أولاً للحصول على رسالة خطأ أكثر دقة. أضف متغير البيئة التالي في بداية كودك للتبديل إلى وحدة المعالجة المركزية: + +```python +>>> import os + +>>> os.environ["CUDA_VISIBLE_DEVICES"] = "" +``` + +الخيار الآخر هو الحصول على تتبع مكدس أفضل من GPU. أضف متغير البيئة التالي في بداية كودك للحصول على تتبع المكدس للإشارة إلى مصدر الخطأ: + +```python +>>> import os + +>>> os.environ["CUDA_LAUNCH_BLOCKING"] = "1" +``` + +## إخراج غير صحيح عند عدم إخفاء رموز الحشو + +في بعض الحالات، قد يكون `hidden_state` غير صحيحة إذا تضمنت `input_ids` رموز حشو. ولإثبات ذلك، قم بتحميل نموذج ومجزىء لغوى. يمكنك الوصول إلى `pad_token_id` للنموذج لمعرفة قيمته. قد تكون `pad_token_id` `None` لبعض النماذج، ولكن يمكنك دائمًا تعيينها يدويًا. + +```python +>>> from transformers import AutoModelForSequenceClassification +>>> import torch + +>>> model = AutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-uncased") +>>> model.config.pad_token_id +0 +``` + +يوضح المثال التالي المُخرجات بدون إخفاء رموز الحشو: + +```python +>>> input_ids = torch.tensor([[7592, 2057, 2097, 2393, 9611, 2115], [7592, 0, 0, 0, 0, 0]]) +>>> output = model(input_ids) +>>> print(output.logits) +tensor([[ 0.0082, -0.2307], +[ 0.1317, -0.1683]], grad_fn=) +``` + +هنا المُخرجات الفعلية للتسلسل الثاني: + +```python +>>> input_ids = torch.tensor([[7592]]) +>>> output = model(input_ids) +>>> print(output.logits) +tensor([[-0.1008, -0.4061]], grad_fn=) +``` + +يجب عليك في معظم الوقت توفير `attention_mask` للنموذج لتجاهل رموز الحشو لتجنب هذا الخطأ الصامت. الآن يتطابق مُخرجات التسلسل الثاني مع مُخرجاته الفعلية: + + +بشكل افتراضي، ينشئ مجزىء النصوص `attention_mask` لك استنادًا إلى إعدادات المجزىء المحدد. + + +```python +>>> attention_mask = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 0]]) +>>> output = model(input_ids, attention_mask=attention_mask) +>>> print(output.logits) +tensor([[ 0.0082, -0.2307], +[-0.1008, -0.4061]], grad_fn=) +``` + +لا ينشئ 🤗 Transformers تلقائيًا `attention_mask` لإخفاء رمز الحشو إذا تم توفيره لأن: + +- بعض النماذج ليس لها رمز حشو. + +- بالنسبة لبعض الاستخدامات، يريد المستخدمون أن ينتبه النموذج إلى رمز الحشو. +## ValueError: فئة التكوين غير المعترف بها XYZ لهذا النوع من AutoModel + +بشكل عام، نوصي باستخدام فئة [`AutoModel`] لتحميل النسخ المدربة مسبقًا من النماذج. يمكن لهذه الفئة أن تستنتج وتُحمل تلقائيًا البنية الصحيحة من نسخ معينة بناءً على التكوين. إذا رأيت هذا الخطأ `ValueError` عند تحميل نموذج من نسخة، فهذا يعني أن الفئة التلقائية (Auto) لم تتمكن من العثور على خريطة من التكوين في نقطة التفتيش المعطاة إلى نوع النموذج الذي تُحاول تحميله. وغالبًا ما يحدث هذا عندما لا تدعم نقطة التفتيش مهمة معينة. + +على سبيل المثال، سترى هذا الخطأ في المثال التالي لأنه لا يوجد GPT2 للإجابة على الأسئلة: + +```py +>>> from transformers import AutoProcessor, AutoModelForQuestionAnswering + +>>> processor = AutoProcessor.from_pretrained("openai-community/gpt2-medium") +>>> model = AutoModelForQuestionAnswering.from_pretrained("openai-community/gpt2-medium") +ValueError: Unrecognized configuration class for this kind of AutoModel: AutoModelForQuestionAnswering. +Model type should be one of AlbertConfig, BartConfig, BertConfig, BigBirdConfig, BigBirdPegasusConfig, BloomConfig, ... +``` diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/_config.py b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/_config.py new file mode 100644 index 0000000000000000000000000000000000000000..f49e4e4731965a504b8da443c2cd979638cd22bb --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/_config.py @@ -0,0 +1,14 @@ +# docstyle-ignore +INSTALL_CONTENT = """ +# Transformers installation +! pip install transformers datasets evaluate accelerate +# To install from source instead of the last release, comment the command above and uncomment the following one. +# ! pip install git+https://github.com/huggingface/transformers.git +""" + +notebook_first_cells = [{"type": "code", "content": INSTALL_CONTENT}] +black_avoid_patterns = { + "{processor_class}": "FakeProcessorClass", + "{model_class}": "FakeModelClass", + "{object_class}": "FakeObjectClass", +} diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/_toctree.yml b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/_toctree.yml new file mode 100644 index 0000000000000000000000000000000000000000..df772c6c788f5ffeb9c6bd9f0a81ce3bc8ad82e4 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/_toctree.yml @@ -0,0 +1,40 @@ +- sections: + - local: index + title: 🤗 Transformers + - local: quicktour + title: Schnellstart + - local: installation + title: Installation + title: Erste Schritte +- sections: + - local: pipeline_tutorial + title: Pipelines für Inferenzen + - local: autoclass_tutorial + title: Laden von vortrainierten Instanzen mit einer AutoClass + - local: preprocessing + title: Vorverarbeiten + - local: training + title: Optimierung eines vortrainierten Modells + - local: run_scripts + title: Trainieren mit einem Skript + - local: accelerate + title: Verteiltes Training mit 🤗 Accelerate + - local: peft + title: Laden und Trainieren von Adaptern mit 🤗 PEFT + - local: model_sharing + title: Ein Modell teilen + - local: llm_tutorial + title: Generation with LLMs + title: Tutorials +- sections: + - local: contributing + title: Wie kann man zu 🤗 Transformers beitragen? + - local: add_new_model + title: Wie fügt man ein Modell zu 🤗 Transformers hinzu? + - local: add_new_pipeline + title: Wie fügt man eine Pipeline zu 🤗 Transformers hinzu? + - local: testing + title: Testen + - local: pr_checks + title: Überprüfung einer Pull Request + title: Contribute diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/accelerate.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/accelerate.md new file mode 100644 index 0000000000000000000000000000000000000000..98a11cbdc4177170fd5b02c29fc19b36ebf259cb --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/accelerate.md @@ -0,0 +1,136 @@ + + +# Verteiltes Training mit 🤗 Accelerate + +Da die Modelle immer größer werden, hat sich die Parallelität als Strategie zum Trainieren größerer Modelle auf begrenzter Hardware und zur Beschleunigung der Trainingsgeschwindigkeit um mehrere Größenordnungen erwiesen. Bei Hugging Face haben wir die Bibliothek [🤗 Accelerate](https://huggingface.co/docs/accelerate) entwickelt, um Nutzern zu helfen, ein 🤗 Transformers-Modell auf jeder Art von verteiltem Setup zu trainieren, egal ob es sich um mehrere GPUs auf einer Maschine oder mehrere GPUs auf mehreren Maschinen handelt. In diesem Tutorial lernen Sie, wie Sie Ihre native PyTorch-Trainingsschleife anpassen, um das Training in einer verteilten Umgebung zu ermöglichen. + +## Einrichtung + +Beginnen Sie mit der Installation von 🤗 Accelerate: + +```bash +pip install accelerate +``` + +Dann importieren und erstellen Sie ein [`~accelerate.Accelerator`]-Objekt. Der [`~accelerate.Accelerator`] wird automatisch Ihre Art der verteilten Einrichtung erkennen und alle notwendigen Komponenten für das Training initialisieren. Sie müssen Ihr Modell nicht explizit auf einem Gerät platzieren. + +```py +>>> from accelerate import Accelerator + +>>> accelerator = Accelerator() +``` + +## Vorbereiten auf die Beschleunigung + +Der nächste Schritt ist die Übergabe aller relevanten Trainingsobjekte an die Methode [`~accelerate.Accelerator.prepare`]. Dazu gehören Ihre Trainings- und Evaluierungs-DataLoader, ein Modell und ein Optimierer: + +```py +>>> train_dataloader, eval_dataloader, model, optimizer = accelerator.prepare( +... train_dataloader, eval_dataloader, model, optimizer +... ) +``` + +## Rückwärts + +Die letzte Ergänzung besteht darin, das typische `loss.backward()` in der Trainingsschleife durch die 🤗 Accelerate-Methode [`~accelerate.Accelerator.backward`] zu ersetzen: + +```py +>>> for epoch in range(num_epochs): +... for batch in train_dataloader: +... outputs = model(**batch) +... loss = outputs.loss +... accelerator.backward(loss) + +... optimizer.step() +... lr_scheduler.step() +... optimizer.zero_grad() +... progress_bar.update(1) +``` + +Wie Sie im folgenden Code sehen können, müssen Sie nur vier zusätzliche Codezeilen zu Ihrer Trainingsschleife hinzufügen, um verteiltes Training zu ermöglichen! + +```diff ++ from accelerate import Accelerator + from transformers import AdamW, AutoModelForSequenceClassification, get_scheduler + ++ accelerator = Accelerator() + + model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2) + optimizer = AdamW(model.parameters(), lr=3e-5) + +- device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") +- model.to(device) + ++ train_dataloader, eval_dataloader, model, optimizer = accelerator.prepare( ++ train_dataloader, eval_dataloader, model, optimizer ++ ) + + num_epochs = 3 + num_training_steps = num_epochs * len(train_dataloader) + lr_scheduler = get_scheduler( + "linear", + optimizer=optimizer, + num_warmup_steps=0, + num_training_steps=num_training_steps + ) + + progress_bar = tqdm(range(num_training_steps)) + + model.train() + for epoch in range(num_epochs): + for batch in train_dataloader: +- batch = {k: v.to(device) for k, v in batch.items()} + outputs = model(**batch) + loss = outputs.loss +- loss.backward() ++ accelerator.backward(loss) + + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + progress_bar.update(1) +``` + +## Trainieren + +Sobald Sie die entsprechenden Codezeilen hinzugefügt haben, starten Sie Ihr Training in einem Skript oder einem Notebook wie Colaboratory. + +### Trainieren mit einem Skript + +Wenn Sie Ihr Training mit einem Skript durchführen, führen Sie den folgenden Befehl aus, um eine Konfigurationsdatei zu erstellen und zu speichern: + +```bash +accelerate config +``` + +Dann starten Sie Ihr Training mit: + +```bash +accelerate launch train.py +``` + +### Trainieren mit einem Notebook + +🤗 Accelerate kann auch in einem Notebook laufen, wenn Sie planen, die TPUs von Colaboratory zu verwenden. Verpacken Sie den gesamten Code, der für das Training verantwortlich ist, in eine Funktion und übergeben Sie diese an [`~accelerate.notebook_launcher`]: + +```py +>>> from accelerate import notebook_launcher + +>>> notebook_launcher(training_function) +``` + +Weitere Informationen über 🤗 Accelerate und seine umfangreichen Funktionen finden Sie in der [Dokumentation](https://huggingface.co/docs/accelerate). \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/add_new_model.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/add_new_model.md new file mode 100644 index 0000000000000000000000000000000000000000..e5ef4234319fead8fc59766b57b8bfb690e7d810 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/add_new_model.md @@ -0,0 +1,891 @@ + + +# Wie kann ich ein Modell zu 🤗 Transformers hinzufügen? + +Die 🤗 Transformers-Bibliothek ist dank der Beiträge der Community oft in der Lage, neue Modelle anzubieten. Aber das kann ein anspruchsvolles Projekt sein und erfordert eine eingehende Kenntnis der 🤗 Transformers-Bibliothek und des zu implementierenden Modells. Bei Hugging Face versuchen wir, mehr Mitgliedern der Community die Möglichkeit zu geben, aktiv Modelle hinzuzufügen, und wir haben diese Anleitung zusammengestellt, die Sie durch den Prozess des Hinzufügens eines PyTorch-Modells führt (stellen Sie sicher, dass Sie [PyTorch installiert haben](https://pytorch.org/get-started/locally/)). + +Auf dem Weg dorthin, werden Sie: + +- Einblicke in bewährte Open-Source-Verfahren erhalten +- die Konstruktionsprinzipien hinter einer der beliebtesten Deep-Learning-Bibliotheken verstehen +- lernen Sie, wie Sie große Modelle effizient testen können +- lernen Sie, wie Sie Python-Hilfsprogramme wie `black`, `ruff` und `make fix-copies` integrieren, um sauberen und lesbaren Code zu gewährleisten + +Ein Mitglied des Hugging Face-Teams wird Ihnen dabei zur Seite stehen, damit Sie nicht alleine sind. 🤗 ❤️ + +Um loszulegen, öffnen Sie eine [New model addition](https://github.com/huggingface/transformers/issues/new?assignees=&labels=New+model&template=new-model-addition.yml) Ausgabe für das Modell, das Sie in 🤗 Transformers sehen möchten. Wenn Sie nicht besonders wählerisch sind, wenn es darum geht, ein bestimmtes Modell beizusteuern, können Sie nach dem [New model label](https://github.com/huggingface/transformers/labels/New%20model) filtern, um zu sehen, ob es noch unbeanspruchte Modellanfragen gibt, und daran arbeiten. + +Sobald Sie eine neue Modellanfrage eröffnet haben, sollten Sie sich zunächst mit 🤗 Transformers vertraut machen, falls Sie das noch nicht sind! + +## Allgemeiner Überblick über 🤗 Transformers + +Zunächst sollten Sie sich einen allgemeinen Überblick über 🤗 Transformers verschaffen. 🤗 Transformers ist eine sehr meinungsfreudige Bibliothek, es ist also möglich, dass +Es besteht also die Möglichkeit, dass Sie mit einigen der Philosophien oder Designentscheidungen der Bibliothek nicht einverstanden sind. Aus unserer Erfahrung heraus haben wir jedoch +dass die grundlegenden Designentscheidungen und Philosophien der Bibliothek entscheidend sind, um 🤗 Transformers effizient zu skalieren. +Transformatoren zu skalieren und gleichzeitig die Wartungskosten auf einem vernünftigen Niveau zu halten. + +Ein guter erster Ansatzpunkt, um die Bibliothek besser zu verstehen, ist die Lektüre der [Dokumentation unserer Philosophie](Philosophie). Als Ergebnis unserer Arbeitsweise gibt es einige Entscheidungen, die wir versuchen, auf alle Modelle anzuwenden: + +- Komposition wird im Allgemeinen gegenüber Abstraktion bevorzugt +- Die Duplizierung von Code ist nicht immer schlecht, wenn sie die Lesbarkeit oder Zugänglichkeit eines Modells stark verbessert +- Modelldateien sind so in sich geschlossen wie möglich, so dass Sie, wenn Sie den Code eines bestimmten Modells lesen, idealerweise nur + in die entsprechende Datei `modeling_....py` schauen müssen. + +Unserer Meinung nach ist der Code der Bibliothek nicht nur ein Mittel, um ein Produkt bereitzustellen, *z.B.* die Möglichkeit, BERT für +Inferenz zu verwenden, sondern auch als das Produkt selbst, das wir verbessern wollen. Wenn Sie also ein Modell hinzufügen, ist der Benutzer nicht nur die +Person, die Ihr Modell verwenden wird, sondern auch jeder, der Ihren Code liest, zu verstehen versucht und ihn möglicherweise verbessert. + +Lassen Sie uns daher ein wenig tiefer in das allgemeine Design der Bibliothek einsteigen. + +### Überblick über die Modelle + +Um ein Modell erfolgreich hinzuzufügen, ist es wichtig, die Interaktion zwischen Ihrem Modell und seiner Konfiguration zu verstehen, +[`PreTrainedModel`] und [`PretrainedConfig`]. Als Beispiel werden wir +das Modell, das zu 🤗 Transformers hinzugefügt werden soll, `BrandNewBert` nennen. + +Schauen wir uns das mal an: + + + +Wie Sie sehen, machen wir in 🤗 Transformers von der Vererbung Gebrauch, aber wir beschränken die Abstraktionsebene auf ein absolutes Minimum. +Minimum. Es gibt nie mehr als zwei Abstraktionsebenen für ein Modell in der Bibliothek. `BrandNewBertModel` +erbt von `BrandNewBertPreTrainedModel`, das wiederum von [`PreTrainedModel`] erbt und +das war's. In der Regel wollen wir sicherstellen, dass ein neues Modell nur von +[`PreTrainedModel`] abhängt. Die wichtigen Funktionalitäten, die jedem neuen Modell automatisch zur Verfügung gestellt werden, sind +Modell automatisch bereitgestellt werden, sind [`~PreTrainedModel.from_pretrained`] und +[`~PreTrainedModel.save_pretrained`], die für die Serialisierung und Deserialisierung verwendet werden. Alle +anderen wichtigen Funktionalitäten, wie `BrandNewBertModel.forward` sollten vollständig in der neuen +Skript `modeling_brand_new_bert.py` definiert werden. Als nächstes wollen wir sicherstellen, dass ein Modell mit einer bestimmten Kopfebene, wie z.B. +`BrandNewBertForMaskedLM` nicht von `BrandNewBertModel` erbt, sondern `BrandNewBertModel` verwendet +als Komponente, die im Forward Pass aufgerufen werden kann, um die Abstraktionsebene niedrig zu halten. Jedes neue Modell erfordert eine +Konfigurationsklasse, genannt `BrandNewBertConfig`. Diese Konfiguration wird immer als ein Attribut in +[PreTrainedModel] gespeichert und kann daher über das Attribut `config` für alle Klassen aufgerufen werden +die von `BrandNewBertPreTrainedModel` erben: + +```python +model = BrandNewBertModel.from_pretrained("brandy/brand_new_bert") +model.config # model has access to its config +``` + +Ähnlich wie das Modell erbt die Konfiguration grundlegende Serialisierungs- und Deserialisierungsfunktionalitäten von +[`PretrainedConfig`]. Beachten Sie, dass die Konfiguration und das Modell immer in zwei verschiedene Formate serialisiert werden +unterschiedliche Formate serialisiert werden - das Modell in eine *pytorch_model.bin* Datei und die Konfiguration in eine *config.json* Datei. Aufruf von +[`~PreTrainedModel.save_pretrained`] wird automatisch +[`~PretrainedConfig.save_pretrained`] auf, so dass sowohl das Modell als auch die Konfiguration gespeichert werden. + + +### Code-Stil + +Wenn Sie Ihr neues Modell kodieren, sollten Sie daran denken, dass Transformers eine Bibliothek mit vielen Meinungen ist und dass wir selbst ein paar Macken haben +wie der Code geschrieben werden sollte :-) + +1. Der Vorwärtsdurchlauf Ihres Modells sollte vollständig in die Modellierungsdatei geschrieben werden und dabei völlig unabhängig von anderen + Modellen in der Bibliothek. Wenn Sie einen Block aus einem anderen Modell wiederverwenden möchten, kopieren Sie den Code und fügen ihn mit einem + `# Kopiert von` ein (siehe [hier](https://github.com/huggingface/transformers/blob/v4.17.0/src/transformers/models/roberta/modeling_roberta.py#L160) + für ein gutes Beispiel und [hier](pr_checks#check-copies) für weitere Dokumentation zu Copied from). +2. Der Code sollte vollständig verständlich sein, auch für einen Nicht-Muttersprachler. Das heißt, Sie sollten + beschreibende Variablennamen wählen und Abkürzungen vermeiden. Ein Beispiel: `activation` ist `act` vorzuziehen. + Von Variablennamen mit nur einem Buchstaben wird dringend abgeraten, es sei denn, es handelt sich um einen Index in einer for-Schleife. +3. Generell ziehen wir längeren expliziten Code einem kurzen magischen Code vor. +4. Vermeiden Sie die Unterklassifizierung von `nn.Sequential` in PyTorch, sondern unterklassifizieren Sie `nn.Module` und schreiben Sie den Vorwärtspass, so dass jeder + so dass jeder, der Ihren Code verwendet, ihn schnell debuggen kann, indem er Druckanweisungen oder Haltepunkte hinzufügt. +5. Ihre Funktionssignatur sollte mit einer Typ-Annotation versehen sein. Im Übrigen sind gute Variablennamen viel lesbarer und verständlicher + verständlicher als Typ-Anmerkungen. + +### Übersicht der Tokenizer + +Noch nicht ganz fertig :-( Dieser Abschnitt wird bald hinzugefügt! + +## Schritt-für-Schritt-Rezept zum Hinzufügen eines Modells zu 🤗 Transformers + +Jeder hat andere Vorlieben, was die Portierung eines Modells angeht. Daher kann es sehr hilfreich sein, wenn Sie sich Zusammenfassungen ansehen +wie andere Mitwirkende Modelle auf Hugging Face portiert haben. Hier ist eine Liste von Blogbeiträgen aus der Community, wie man ein Modell portiert: + +1. [Portierung eines GPT2-Modells](https://medium.com/huggingface/from-tensorflow-to-pytorch-265f40ef2a28) von [Thomas](https://huggingface.co/thomwolf) +2. [Portierung des WMT19 MT-Modells](https://huggingface.co/blog/porting-fsmt) von [Stas](https://huggingface.co/stas) + +Aus Erfahrung können wir Ihnen sagen, dass die wichtigsten Dinge, die Sie beim Hinzufügen eines Modells beachten müssen, sind: + +- Erfinden Sie das Rad nicht neu! Die meisten Teile des Codes, den Sie für das neue 🤗 Transformers-Modell hinzufügen werden, existieren bereits + irgendwo in 🤗 Transformers. Nehmen Sie sich etwas Zeit, um ähnliche, bereits vorhandene Modelle und Tokenizer zu finden, die Sie kopieren können + von. [grep](https://www.gnu.org/software/grep/) und [rg](https://github.com/BurntSushi/ripgrep) sind Ihre + Freunde. Beachten Sie, dass es sehr gut möglich ist, dass der Tokenizer Ihres Modells auf einer Modellimplementierung basiert und + und der Modellierungscode Ihres Modells auf einer anderen. *Z.B.* Der Modellierungscode von FSMT basiert auf BART, während der Tokenizer-Code von FSMT + auf XLM basiert. +- Es handelt sich eher um eine technische als um eine wissenschaftliche Herausforderung. Sie sollten mehr Zeit auf die Schaffung einer + eine effiziente Debugging-Umgebung zu schaffen, als zu versuchen, alle theoretischen Aspekte des Modells in dem Papier zu verstehen. +- Bitten Sie um Hilfe, wenn Sie nicht weiterkommen! Modelle sind der Kernbestandteil von 🤗 Transformers, so dass wir bei Hugging Face mehr als + mehr als glücklich, Ihnen bei jedem Schritt zu helfen, um Ihr Modell hinzuzufügen. Zögern Sie nicht zu fragen, wenn Sie merken, dass Sie nicht weiterkommen. + Fortschritte machen. + +Im Folgenden versuchen wir, Ihnen ein allgemeines Rezept an die Hand zu geben, das uns bei der Portierung eines Modells auf 🤗 Transformers am nützlichsten erschien. + +Die folgende Liste ist eine Zusammenfassung all dessen, was getan werden muss, um ein Modell hinzuzufügen und kann von Ihnen als To-Do verwendet werden +Liste verwenden: + +☐ (Optional) Verstehen der theoretischen Aspekte des Modells
+☐ Vorbereiten der 🤗 Transformers-Entwicklungsumgebung
+☐ Debugging-Umgebung des ursprünglichen Repositorys eingerichtet
+☐ Skript erstellt, das den Durchlauf `forward()` unter Verwendung des ursprünglichen Repositorys und des Checkpoints erfolgreich durchführt
+☐ Erfolgreich das Modellskelett zu 🤗 Transformers hinzugefügt
+☐ Erfolgreiche Umwandlung des ursprünglichen Prüfpunkts in den 🤗 Transformers-Prüfpunkt
+☐ Erfolgreich den Durchlauf `forward()` in 🤗 Transformers ausgeführt, der eine identische Ausgabe wie der ursprüngliche Prüfpunkt liefert
+☐ Modell-Tests in 🤗 Transformers abgeschlossen
+☐ Erfolgreich Tokenizer in 🤗 Transformers hinzugefügt
+☐ End-to-End-Integrationstests ausgeführt
+☐ Docs fertiggestellt
+☐ Modellgewichte in den Hub hochgeladen
+☐ Die Pull-Anfrage eingereicht
+☐ (Optional) Hinzufügen eines Demo-Notizbuchs + +Für den Anfang empfehlen wir in der Regel, mit einem guten theoretischen Verständnis von `BrandNewBert` zu beginnen. Wie auch immer, +wenn Sie es vorziehen, die theoretischen Aspekte des Modells *on-the-job* zu verstehen, dann ist es völlig in Ordnung, direkt in die +in die Code-Basis von `BrandNewBert` einzutauchen. Diese Option könnte für Sie besser geeignet sein, wenn Ihre technischen Fähigkeiten besser sind als +als Ihre theoretischen Fähigkeiten, wenn Sie Schwierigkeiten haben, die Arbeit von `BrandNewBert` zu verstehen, oder wenn Sie einfach Spaß am Programmieren +mehr Spaß am Programmieren haben als am Lesen wissenschaftlicher Abhandlungen. + +### 1. (Optional) Theoretische Aspekte von BrandNewBert + +Sie sollten sich etwas Zeit nehmen, um die Abhandlung von *BrandNewBert* zu lesen, falls eine solche Beschreibung existiert. Möglicherweise gibt es große +Abschnitte des Papiers, die schwer zu verstehen sind. Wenn das der Fall ist, ist das in Ordnung - machen Sie sich keine Sorgen! Das Ziel ist +ist es nicht, ein tiefes theoretisches Verständnis des Papiers zu erlangen, sondern die notwendigen Informationen zu extrahieren, um +das Modell effektiv in 🤗 Transformers zu implementieren. Das heißt, Sie müssen nicht zu viel Zeit auf die +theoretischen Aspekten verbringen, sondern sich lieber auf die praktischen Aspekte konzentrieren, nämlich: + +- Welche Art von Modell ist *brand_new_bert*? BERT-ähnliches Modell nur für den Encoder? GPT2-ähnliches reines Decoder-Modell? BART-ähnliches + Encoder-Decoder-Modell? Sehen Sie sich die [model_summary](model_summary) an, wenn Sie mit den Unterschieden zwischen diesen Modellen nicht vertraut sind. +- Was sind die Anwendungen von *brand_new_bert*? Textklassifizierung? Texterzeugung? Seq2Seq-Aufgaben, *z.B.,* + Zusammenfassungen? +- Was ist die neue Eigenschaft des Modells, die es von BERT/GPT-2/BART unterscheidet? +- Welches der bereits existierenden [🤗 Transformers-Modelle](https://huggingface.co/transformers/#contents) ist am ähnlichsten + ähnlich wie *brand_new_bert*? +- Welche Art von Tokenizer wird verwendet? Ein Satzteil-Tokenisierer? Ein Wortstück-Tokenisierer? Ist es derselbe Tokenisierer, der für + für BERT oder BART? + +Nachdem Sie das Gefühl haben, einen guten Überblick über die Architektur des Modells erhalten zu haben, können Sie dem +Hugging Face Team schreiben und Ihre Fragen stellen. Dazu können Fragen zur Architektur des Modells gehören, +seiner Aufmerksamkeitsebene usw. Wir werden Ihnen gerne weiterhelfen. + +### 2. Bereiten Sie als nächstes Ihre Umgebung vor + +1. Forken Sie das [Repository](https://github.com/huggingface/transformers), indem Sie auf der Seite des Repositorys auf die Schaltfläche 'Fork' klicken. + Seite des Repositorys klicken. Dadurch wird eine Kopie des Codes unter Ihrem GitHub-Benutzerkonto erstellt. + +2. Klonen Sie Ihren `transformers` Fork auf Ihre lokale Festplatte und fügen Sie das Basis-Repository als Remote hinzu: + +```bash +git clone https://github.com/[your Github handle]/transformers.git +cd transformers +git remote add upstream https://github.com/huggingface/transformers.git +``` + +3. Richten Sie eine Entwicklungsumgebung ein, indem Sie z.B. den folgenden Befehl ausführen: + +```bash +python -m venv .env +source .env/bin/activate +pip install -e ".[dev]" +``` + +Abhängig von Ihrem Betriebssystem und da die Anzahl der optionalen Abhängigkeiten von Transformers wächst, kann es sein, dass Sie bei diesem Befehl einen +Fehler mit diesem Befehl. Stellen Sie in diesem Fall sicher, dass Sie das Deep Learning Framework, mit dem Sie arbeiten, installieren +(PyTorch, TensorFlow und/oder Flax) und führen Sie es aus: + +```bash +pip install -e ".[quality]" +``` + +was für die meisten Anwendungsfälle ausreichend sein sollte. Sie können dann zum übergeordneten Verzeichnis zurückkehren + +```bash +cd .. +``` + +4. Wir empfehlen, die PyTorch-Version von *brand_new_bert* zu Transformers hinzuzufügen. Um PyTorch zu installieren, folgen Sie bitte den + Anweisungen auf https://pytorch.org/get-started/locally/. + +**Anmerkung:** Sie müssen CUDA nicht installiert haben. Es reicht aus, das neue Modell auf der CPU zum Laufen zu bringen. + +5. Um *brand_new_bert* zu portieren, benötigen Sie außerdem Zugriff auf das Original-Repository: + +```bash +git clone https://github.com/org_that_created_brand_new_bert_org/brand_new_bert.git +cd brand_new_bert +pip install -e . +``` + +Jetzt haben Sie eine Entwicklungsumgebung eingerichtet, um *brand_new_bert* auf 🤗 Transformers zu portieren. + +### 3.-4. Führen Sie einen Pre-Training-Checkpoint mit dem Original-Repository durch + +Zunächst werden Sie mit dem ursprünglichen *brand_new_bert* Repository arbeiten. Oft ist die ursprüngliche Implementierung sehr +"forschungslastig". Das bedeutet, dass es an Dokumentation mangeln kann und der Code schwer zu verstehen sein kann. Aber das sollte +genau Ihre Motivation sein, *brand_new_bert* neu zu implementieren. Eines unserer Hauptziele bei Hugging Face ist es, *die Menschen dazu zu bringen +auf den Schultern von Giganten zu stehen*, was sich hier sehr gut darin ausdrückt, dass wir ein funktionierendes Modell nehmen und es umschreiben, um es so +es so **zugänglich, benutzerfreundlich und schön** wie möglich zu machen. Dies ist die wichtigste Motivation für die Neuimplementierung von +Modelle in 🤗 Transformers umzuwandeln - der Versuch, komplexe neue NLP-Technologie für **jeden** zugänglich zu machen. + +Sie sollten damit beginnen, indem Sie in das Original-Repository eintauchen. + +Die erfolgreiche Ausführung des offiziellen Pre-Trainingsmodells im Original-Repository ist oft **der schwierigste** Schritt. +Unserer Erfahrung nach ist es sehr wichtig, dass Sie einige Zeit damit verbringen, sich mit der ursprünglichen Code-Basis vertraut zu machen. Sie müssen +das Folgende herausfinden: + +- Wo finden Sie die vortrainierten Gewichte? +- Wie lädt man die vorab trainierten Gewichte in das entsprechende Modell? +- Wie kann der Tokenizer unabhängig vom Modell ausgeführt werden? +- Verfolgen Sie einen Forward Pass, damit Sie wissen, welche Klassen und Funktionen für einen einfachen Forward Pass erforderlich sind. Normalerweise, + müssen Sie nur diese Funktionen reimplementieren. +- Sie müssen in der Lage sein, die wichtigen Komponenten des Modells zu finden: Wo befindet sich die Klasse des Modells? Gibt es Unterklassen des Modells, + *z.B.* EncoderModel, DecoderModel? Wo befindet sich die Selbstaufmerksamkeitsschicht? Gibt es mehrere verschiedene Aufmerksamkeitsebenen, + *z.B.* *Selbstaufmerksamkeit*, *Kreuzaufmerksamkeit*...? +- Wie können Sie das Modell in der ursprünglichen Umgebung des Repo debuggen? Müssen Sie *print* Anweisungen hinzufügen, können Sie + mit einem interaktiven Debugger wie *ipdb* arbeiten oder sollten Sie eine effiziente IDE zum Debuggen des Modells verwenden, wie z.B. PyCharm? + +Es ist sehr wichtig, dass Sie, bevor Sie mit der Portierung beginnen, den Code im Original-Repository **effizient** debuggen können +Repository können! Denken Sie auch daran, dass Sie mit einer Open-Source-Bibliothek arbeiten, also zögern Sie nicht, ein Problem oder +oder sogar eine Pull-Anfrage im Original-Repository zu stellen. Die Betreuer dieses Repositorys sind wahrscheinlich sehr froh darüber +dass jemand in ihren Code schaut! + +An diesem Punkt liegt es wirklich an Ihnen, welche Debugging-Umgebung und Strategie Sie zum Debuggen des ursprünglichen +Modell zu debuggen. Wir raten dringend davon ab, eine kostspielige GPU-Umgebung einzurichten, sondern arbeiten Sie einfach auf einer CPU, sowohl wenn Sie mit dem +in das ursprüngliche Repository einzutauchen und auch, wenn Sie beginnen, die 🤗 Transformers-Implementierung des Modells zu schreiben. Nur +ganz am Ende, wenn das Modell bereits erfolgreich auf 🤗 Transformers portiert wurde, sollte man überprüfen, ob das +Modell auch auf der GPU wie erwartet funktioniert. + +Im Allgemeinen gibt es zwei mögliche Debugging-Umgebungen für die Ausführung des Originalmodells + +- [Jupyter notebooks](https://jupyter.org/) / [google colab](https://colab.research.google.com/notebooks/intro.ipynb) +- Lokale Python-Skripte. + +Jupyter-Notebooks haben den Vorteil, dass sie eine zellenweise Ausführung ermöglichen, was hilfreich sein kann, um logische Komponenten besser voneinander zu trennen und +logische Komponenten voneinander zu trennen und schnellere Debugging-Zyklen zu haben, da Zwischenergebnisse gespeichert werden können. Außerdem, +Außerdem lassen sich Notebooks oft leichter mit anderen Mitwirkenden teilen, was sehr hilfreich sein kann, wenn Sie das Hugging Face Team um Hilfe bitten möchten. +Face Team um Hilfe bitten. Wenn Sie mit Jupyter-Notizbüchern vertraut sind, empfehlen wir Ihnen dringend, mit ihnen zu arbeiten. + +Der offensichtliche Nachteil von Jupyter-Notizbüchern ist, dass Sie, wenn Sie nicht daran gewöhnt sind, mit ihnen zu arbeiten, einige Zeit damit verbringen müssen +einige Zeit damit verbringen müssen, sich an die neue Programmierumgebung zu gewöhnen, und dass Sie möglicherweise Ihre bekannten Debugging-Tools nicht mehr verwenden können +wie z.B. `ipdb` nicht mehr verwenden können. + +Für jede Codebasis ist es immer ein guter erster Schritt, einen **kleinen** vortrainierten Checkpoint zu laden und in der Lage zu sein, einen +einzelnen Vorwärtsdurchlauf mit einem Dummy-Integer-Vektor von Eingabe-IDs als Eingabe zu reproduzieren. Ein solches Skript könnte wie folgt aussehen (in +Pseudocode): + +```python +model = BrandNewBertModel.load_pretrained_checkpoint("/path/to/checkpoint/") +input_ids = [0, 4, 5, 2, 3, 7, 9] # vector of input ids +original_output = model.predict(input_ids) +``` + +Was die Debugging-Strategie anbelangt, so können Sie im Allgemeinen aus mehreren Strategien wählen: + +- Zerlegen Sie das ursprüngliche Modell in viele kleine testbare Komponenten und führen Sie für jede dieser Komponenten einen Vorwärtsdurchlauf zur + Überprüfung +- Zerlegen Sie das ursprüngliche Modell nur in den ursprünglichen *Tokenizer* und das ursprüngliche *Modell*, führen Sie einen Vorwärtsdurchlauf für diese Komponenten durch + und verwenden Sie dazwischenliegende Druckanweisungen oder Haltepunkte zur Überprüfung. + +Auch hier bleibt es Ihnen überlassen, welche Strategie Sie wählen. Oft ist die eine oder die andere Strategie vorteilhaft, je nach der ursprünglichen Codebasis +Basis. + +Wenn die ursprüngliche Codebasis es Ihnen erlaubt, das Modell in kleinere Teilkomponenten zu zerlegen, *z.B.* wenn die ursprüngliche +Code-Basis problemlos im Eager-Modus ausgeführt werden kann, lohnt es sich in der Regel, dies zu tun. Es gibt einige wichtige Vorteile +am Anfang den schwierigeren Weg zu gehen: + +- Wenn Sie später das ursprüngliche Modell mit der Hugging Face-Implementierung vergleichen, können Sie automatisch überprüfen, ob + für jede Komponente einzeln überprüfen, ob die entsprechende Komponente der 🤗 Transformers-Implementierung übereinstimmt, anstatt sich auf + anstatt sich auf den visuellen Vergleich über Druckanweisungen zu verlassen +- können Sie das große Problem der Portierung eines Modells in kleinere Probleme der Portierung einzelner Komponenten zerlegen + einzelnen Komponenten zu zerlegen und so Ihre Arbeit besser zu strukturieren +- Die Aufteilung des Modells in logisch sinnvolle Komponenten hilft Ihnen, einen besseren Überblick über das Design des Modells zu bekommen + und somit das Modell besser zu verstehen +- In einem späteren Stadium helfen Ihnen diese komponentenweisen Tests dabei, sicherzustellen, dass keine Regressionen auftreten, während Sie fortfahren + Ihren Code ändern + +[Lysandre's](https://gist.github.com/LysandreJik/db4c948f6b4483960de5cbac598ad4ed) Integrationstests für ELECTRA +gibt ein schönes Beispiel dafür, wie dies geschehen kann. + +Wenn die ursprüngliche Codebasis jedoch sehr komplex ist oder nur die Ausführung von Zwischenkomponenten in einem kompilierten Modus erlaubt, +könnte es zu zeitaufwändig oder sogar unmöglich sein, das Modell in kleinere testbare Teilkomponenten zu zerlegen. Ein gutes +Beispiel ist die [T5's MeshTensorFlow](https://github.com/tensorflow/mesh/tree/master/mesh_tensorflow) Bibliothek, die sehr komplex ist +sehr komplex ist und keine einfache Möglichkeit bietet, das Modell in seine Unterkomponenten zu zerlegen. Bei solchen Bibliotheken ist man +oft auf die Überprüfung von Druckanweisungen angewiesen. + +Unabhängig davon, welche Strategie Sie wählen, ist die empfohlene Vorgehensweise oft die gleiche, nämlich dass Sie mit der Fehlersuche in den +die Anfangsebenen zuerst und die Endebenen zuletzt debuggen. + +Es wird empfohlen, dass Sie die Ausgaben der folgenden Ebenen abrufen, entweder durch Druckanweisungen oder Unterkomponentenfunktionen +Schichten in der folgenden Reihenfolge abrufen: + +1. Rufen Sie die Eingabe-IDs ab, die an das Modell übergeben wurden +2. Rufen Sie die Worteinbettungen ab +3. Rufen Sie die Eingabe der ersten Transformer-Schicht ab +4. Rufen Sie die Ausgabe der ersten Transformer-Schicht ab +5. Rufen Sie die Ausgabe der folgenden n - 1 Transformer-Schichten ab +6. Rufen Sie die Ausgabe des gesamten BrandNewBert Modells ab + +Die Eingabe-IDs sollten dabei aus einem Array von Ganzzahlen bestehen, *z.B.* `input_ids = [0, 4, 4, 3, 2, 4, 1, 7, 19]` + +Die Ausgaben der folgenden Schichten bestehen oft aus mehrdimensionalen Float-Arrays und können wie folgt aussehen: + +``` +[[ + [-0.1465, -0.6501, 0.1993, ..., 0.1451, 0.3430, 0.6024], + [-0.4417, -0.5920, 0.3450, ..., -0.3062, 0.6182, 0.7132], + [-0.5009, -0.7122, 0.4548, ..., -0.3662, 0.6091, 0.7648], + ..., + [-0.5613, -0.6332, 0.4324, ..., -0.3792, 0.7372, 0.9288], + [-0.5416, -0.6345, 0.4180, ..., -0.3564, 0.6992, 0.9191], + [-0.5334, -0.6403, 0.4271, ..., -0.3339, 0.6533, 0.8694]]], +``` + +Wir erwarten, dass jedes zu 🤗 Transformers hinzugefügte Modell eine Reihe von Integrationstests besteht, was bedeutet, dass das ursprüngliche +Modell und die neu implementierte Version in 🤗 Transformers exakt dieselbe Ausgabe liefern müssen, und zwar mit einer Genauigkeit von 0,001! +Da es normal ist, dass das exakt gleiche Modell, das in verschiedenen Bibliotheken geschrieben wurde, je nach Bibliotheksrahmen eine leicht unterschiedliche Ausgabe liefern kann +eine leicht unterschiedliche Ausgabe liefern kann, akzeptieren wir eine Fehlertoleranz von 1e-3 (0,001). Es reicht nicht aus, wenn das Modell +fast das gleiche Ergebnis liefert, sie müssen fast identisch sein. Daher werden Sie sicherlich die Zwischenergebnisse +Zwischenergebnisse der 🤗 Transformers-Version mehrfach mit den Zwischenergebnissen der ursprünglichen Implementierung von +*brand_new_bert* vergleichen. In diesem Fall ist eine **effiziente** Debugging-Umgebung des ursprünglichen Repositorys absolut +wichtig ist. Hier sind einige Ratschläge, um Ihre Debugging-Umgebung so effizient wie möglich zu gestalten. + +- Finden Sie den besten Weg, um Zwischenergebnisse zu debuggen. Ist das ursprüngliche Repository in PyTorch geschrieben? Dann sollten Sie + dann sollten Sie sich wahrscheinlich die Zeit nehmen, ein längeres Skript zu schreiben, das das ursprüngliche Modell in kleinere Unterkomponenten zerlegt, um + Zwischenwerte abzurufen. Ist das ursprüngliche Repository in Tensorflow 1 geschrieben? Dann müssen Sie sich möglicherweise auf die + TensorFlow Druckoperationen wie [tf.print](https://www.tensorflow.org/api_docs/python/tf/print) verlassen, um die + Zwischenwerte auszugeben. Ist das ursprüngliche Repository in Jax geschrieben? Dann stellen Sie sicher, dass das Modell **nicht jitted** ist, wenn + wenn Sie den Vorwärtsdurchlauf ausführen, *z.B.* schauen Sie sich [dieser Link](https://github.com/google/jax/issues/196) an. +- Verwenden Sie den kleinsten vortrainierten Prüfpunkt, den Sie finden können. Je kleiner der Prüfpunkt ist, desto schneller wird Ihr Debugging-Zyklus + wird. Es ist nicht effizient, wenn Ihr vorab trainiertes Modell so groß ist, dass Ihr Vorwärtsdurchlauf mehr als 10 Sekunden dauert. + Falls nur sehr große Checkpoints verfügbar sind, kann es sinnvoller sein, ein Dummy-Modell in der neuen + Umgebung mit zufällig initialisierten Gewichten zu erstellen und diese Gewichte zum Vergleich mit der 🤗 Transformers-Version + Ihres Modells +- Vergewissern Sie sich, dass Sie den einfachsten Weg wählen, um einen Forward Pass im ursprünglichen Repository aufzurufen. Idealerweise sollten Sie + die Funktion im originalen Repository finden, die **nur** einen einzigen Vorwärtspass aufruft, *d.h.* die oft aufgerufen wird + Vorhersagen", "Auswerten", "Vorwärts" oder "Aufruf" genannt wird. Sie wollen keine Funktion debuggen, die `forward` aufruft + mehrfach aufruft, *z.B.* um Text zu erzeugen, wie `autoregressive_sample`, `generate`. +- Versuchen Sie, die Tokenisierung vom *Forward*-Pass des Modells zu trennen. Wenn das Original-Repository Beispiele zeigt, bei denen + Sie eine Zeichenkette eingeben müssen, dann versuchen Sie herauszufinden, an welcher Stelle im Vorwärtsaufruf die Zeichenketteneingabe in Eingabe-IDs geändert wird + geändert wird und beginnen Sie an dieser Stelle. Das könnte bedeuten, dass Sie möglicherweise selbst ein kleines Skript schreiben oder den + Originalcode so ändern müssen, dass Sie die ids direkt eingeben können, anstatt eine Zeichenkette einzugeben. +- Vergewissern Sie sich, dass sich das Modell in Ihrem Debugging-Setup **nicht** im Trainingsmodus befindet, der oft dazu führt, dass das Modell + Dies führt häufig zu zufälligen Ergebnissen, da das Modell mehrere Dropout-Schichten enthält. Stellen Sie sicher, dass der Vorwärtsdurchlauf in Ihrer Debugging + Umgebung **deterministisch** ist, damit die Dropout-Schichten nicht verwendet werden. Oder verwenden Sie *transformers.utils.set_seed*. + wenn sich die alte und die neue Implementierung im selben Framework befinden. + +Im folgenden Abschnitt finden Sie genauere Details/Tipps, wie Sie dies für *brand_new_bert* tun können. + +### 5.-14. Portierung von BrandNewBert auf 🤗 Transformatoren + +Als nächstes können Sie endlich damit beginnen, neuen Code zu 🤗 Transformers hinzuzufügen. Gehen Sie in den Klon Ihres 🤗 Transformers Forks: + +```bash +cd transformers +``` + +In dem speziellen Fall, dass Sie ein Modell hinzufügen, dessen Architektur genau mit der Modellarchitektur eines +Modells übereinstimmt, müssen Sie nur ein Konvertierungsskript hinzufügen, wie in [diesem Abschnitt](#write-a-conversion-script) beschrieben. +In diesem Fall können Sie einfach die gesamte Modellarchitektur des bereits vorhandenen Modells wiederverwenden. + +Andernfalls beginnen wir mit der Erstellung eines neuen Modells. Wir empfehlen die Verwendung des folgenden Skripts, um ein Modell hinzuzufügen +ein bestehendes Modell: + +```bash +transformers add-new-model-like +``` + +Sie werden mit einem Fragebogen aufgefordert, die grundlegenden Informationen Ihres Modells einzugeben. + +**Eröffnen Sie einen Pull Request auf dem Haupt-Repositorium huggingface/transformers** + +Bevor Sie mit der Anpassung des automatisch generierten Codes beginnen, ist es nun an der Zeit, einen "Work in progress (WIP)" Pull +Anfrage, *z.B.* "[WIP] Add *brand_new_bert*", in 🤗 Transformers zu öffnen, damit Sie und das Hugging Face Team +Seite an Seite an der Integration des Modells in 🤗 Transformers arbeiten können. + +Sie sollten Folgendes tun: + +1. Erstellen Sie eine Verzweigung mit einem beschreibenden Namen von Ihrer Hauptverzweigung + +```bash +git checkout -b add_brand_new_bert +``` + +2. Bestätigen Sie den automatisch generierten Code: + +```bash +git add . +git commit +``` + +3. Abrufen und zurücksetzen auf die aktuelle Haupt + +```bash +git fetch upstream +git rebase upstream/main +``` + +4. Übertragen Sie die Änderungen auf Ihr Konto mit: + +```bash +git push -u origin a-descriptive-name-for-my-changes +``` + +5. Wenn Sie zufrieden sind, gehen Sie auf die Webseite Ihrer Abspaltung auf GitHub. Klicken Sie auf "Pull request". Stellen Sie sicher, dass Sie das + GitHub-Handle einiger Mitglieder des Hugging Face-Teams als Reviewer hinzuzufügen, damit das Hugging Face-Team über zukünftige Änderungen informiert wird. + zukünftige Änderungen benachrichtigt wird. + +6. Ändern Sie den PR in einen Entwurf, indem Sie auf der rechten Seite der GitHub-Pull-Request-Webseite auf "In Entwurf umwandeln" klicken. + +Vergessen Sie im Folgenden nicht, wenn Sie Fortschritte gemacht haben, Ihre Arbeit zu committen und in Ihr Konto zu pushen, damit sie in der Pull-Anfrage erscheint. +damit sie in der Pull-Anfrage angezeigt wird. Außerdem sollten Sie darauf achten, dass Sie Ihre Arbeit von Zeit zu Zeit mit dem aktuellen main +von Zeit zu Zeit zu aktualisieren, indem Sie dies tun: + +```bash +git fetch upstream +git merge upstream/main +``` + +Generell sollten Sie alle Fragen, die Sie in Bezug auf das Modell oder Ihre Implementierung haben, in Ihrem PR stellen und +in der PR diskutiert/gelöst werden. Auf diese Weise wird das Hugging Face Team immer benachrichtigt, wenn Sie neuen Code einreichen oder +wenn Sie eine Frage haben. Es ist oft sehr hilfreich, das Hugging Face-Team auf Ihren hinzugefügten Code hinzuweisen, damit das Hugging Face-Team Ihr Problem oder Ihre Frage besser verstehen kann. +Face-Team Ihr Problem oder Ihre Frage besser verstehen kann. + +Gehen Sie dazu auf die Registerkarte "Geänderte Dateien", auf der Sie alle Ihre Änderungen sehen, gehen Sie zu einer Zeile, zu der Sie eine Frage stellen möchten +eine Frage stellen möchten, und klicken Sie auf das "+"-Symbol, um einen Kommentar hinzuzufügen. Wenn eine Frage oder ein Problem gelöst wurde, +können Sie auf die Schaltfläche "Lösen" des erstellten Kommentars klicken. + +Auf dieselbe Weise wird das Hugging Face-Team Kommentare öffnen, wenn es Ihren Code überprüft. Wir empfehlen, die meisten Fragen +auf GitHub in Ihrem PR zu stellen. Für einige sehr allgemeine Fragen, die für die Öffentlichkeit nicht sehr nützlich sind, können Sie das +Hugging Face Team per Slack oder E-Mail zu stellen. + +**5. Passen Sie den Code der generierten Modelle für brand_new_bert** an. + +Zunächst werden wir uns nur auf das Modell selbst konzentrieren und uns nicht um den Tokenizer kümmern. Den gesamten relevanten Code sollten Sie +finden Sie in den generierten Dateien `src/transformers/models/brand_new_bert/modeling_brand_new_bert.py` und +`src/transformers/models/brand_new_bert/configuration_brand_new_bert.py`. + +Jetzt können Sie endlich mit dem Programmieren beginnen :). Der generierte Code in +`src/transformers/models/brand_new_bert/modeling_brand_new_bert.py` wird entweder die gleiche Architektur wie BERT haben, wenn +wenn es sich um ein reines Encoder-Modell handelt oder BART, wenn es sich um ein Encoder-Decoder-Modell handelt. An diesem Punkt sollten Sie sich daran erinnern, was +was Sie am Anfang über die theoretischen Aspekte des Modells gelernt haben: *Wie unterscheidet sich das Modell von BERT oder +BART?*". Implementieren Sie diese Änderungen, was oft bedeutet, dass Sie die *Selbstaufmerksamkeitsschicht*, die Reihenfolge der Normalisierungsschicht usw. ändern müssen. +Schicht usw... Auch hier ist es oft nützlich, sich die ähnliche Architektur bereits bestehender Modelle in Transformers anzusehen, um ein besseres Gefühl dafür zu bekommen +ein besseres Gefühl dafür zu bekommen, wie Ihr Modell implementiert werden sollte. + +**Beachten Sie**, dass Sie an diesem Punkt nicht sehr sicher sein müssen, dass Ihr Code völlig korrekt oder sauber ist. Vielmehr ist es +Sie sollten vielmehr eine erste *unbereinigte*, kopierte Version des ursprünglichen Codes in +src/transformers/models/brand_new_bert/modeling_brand_new_bert.py" hinzuzufügen, bis Sie das Gefühl haben, dass der gesamte notwendige Code +hinzugefügt wurde. Unserer Erfahrung nach ist es viel effizienter, schnell eine erste Version des erforderlichen Codes hinzuzufügen und +den Code iterativ mit dem Konvertierungsskript zu verbessern/korrigieren, wie im nächsten Abschnitt beschrieben. Das einzige, was +zu diesem Zeitpunkt funktionieren muss, ist, dass Sie die 🤗 Transformers-Implementierung von *brand_new_bert* instanziieren können, *d.h.* der +folgende Befehl sollte funktionieren: + +```python +from transformers import BrandNewBertModel, BrandNewBertConfig + +model = BrandNewBertModel(BrandNewBertConfig()) +``` + +Der obige Befehl erstellt ein Modell gemäß den Standardparametern, die in `BrandNewBertConfig()` definiert sind, mit +zufälligen Gewichten und stellt damit sicher, dass die `init()` Methoden aller Komponenten funktionieren. + +Beachten Sie, dass alle zufälligen Initialisierungen in der Methode `_init_weights` Ihres `BrandnewBertPreTrainedModel` stattfinden sollten. +Klasse erfolgen sollte. Sie sollte alle Blattmodule in Abhängigkeit von den Variablen der Konfiguration initialisieren. Hier ist ein Beispiel mit der +BERT `_init_weights` Methode: + +```py +def _init_weights(self, module): + """Initialize the weights""" + if isinstance(module, nn.Linear): + module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) + if module.bias is not None: + module.bias.data.zero_() + elif isinstance(module, nn.Embedding): + module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) + if module.padding_idx is not None: + module.weight.data[module.padding_idx].zero_() + elif isinstance(module, nn.LayerNorm): + module.bias.data.zero_() + module.weight.data.fill_(1.0) +``` + +Sie können weitere benutzerdefinierte Schemata verwenden, wenn Sie eine spezielle Initialisierung für einige Module benötigen. Zum Beispiel in +`Wav2Vec2ForPreTraining` müssen die letzten beiden linearen Schichten die Initialisierung des regulären PyTorch `nn.Linear` haben. +aber alle anderen sollten eine Initialisierung wie oben verwenden. Dies ist wie folgt kodiert: + +```py +def _init_weights(self, module): + """Initialize the weights""" + if isinstance(module, Wav2Vec2ForPreTraining): + module.project_hid.reset_parameters() + module.project_q.reset_parameters() + module.project_hid._is_hf_initialized = True + module.project_q._is_hf_initialized = True + elif isinstance(module, nn.Linear): + module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) + if module.bias is not None: + module.bias.data.zero_() +``` + +Das Flag `_is_hf_initialized` wird intern verwendet, um sicherzustellen, dass wir ein Submodul nur einmal initialisieren. Wenn Sie es auf +`True` für `module.project_q` und `module.project_hid` setzen, stellen wir sicher, dass die benutzerdefinierte Initialisierung, die wir vorgenommen haben, später nicht überschrieben wird, +die Funktion `_init_weights` nicht auf sie angewendet wird. + +**6. Schreiben Sie ein Konvertierungsskript** + +Als nächstes sollten Sie ein Konvertierungsskript schreiben, mit dem Sie den Checkpoint, den Sie zum Debuggen von *brand_new_bert* im +im ursprünglichen Repository in einen Prüfpunkt konvertieren, der mit Ihrer gerade erstellten 🤗 Transformers-Implementierung von +*brand_new_bert*. Es ist nicht ratsam, das Konvertierungsskript von Grund auf neu zu schreiben, sondern die bereits +bestehenden Konvertierungsskripten in 🤗 Transformers nach einem Skript zu suchen, das für die Konvertierung eines ähnlichen Modells verwendet wurde, das im +demselben Framework wie *brand_new_bert* geschrieben wurde. Normalerweise reicht es aus, ein bereits vorhandenes Konvertierungsskript zu kopieren und +es für Ihren Anwendungsfall leicht anzupassen. Zögern Sie nicht, das Hugging Face Team zu bitten, Sie auf ein ähnliches, bereits vorhandenes +Konvertierungsskript für Ihr Modell zu finden. + +- Wenn Sie ein Modell von TensorFlow nach PyTorch portieren, ist ein guter Ausgangspunkt das Konvertierungsskript von BERT [hier](https://github.com/huggingface/transformers/blob/7acfa95afb8194f8f9c1f4d2c6028224dbed35a2/src/transformers/models/bert/modeling_bert.py#L91) +- Wenn Sie ein Modell von PyTorch nach PyTorch portieren, ist ein guter Ausgangspunkt das Konvertierungsskript von BART [hier](https://github.com/huggingface/transformers/blob/main/src/transformers/models/bart/convert_bart_original_pytorch_checkpoint_to_pytorch.py) + +Im Folgenden werden wir kurz erklären, wie PyTorch-Modelle Ebenengewichte speichern und Ebenennamen definieren. In PyTorch wird der +Name einer Ebene durch den Namen des Klassenattributs definiert, das Sie der Ebene geben. Lassen Sie uns ein Dummy-Modell in +PyTorch, das wir `SimpleModel` nennen, wie folgt: + +```python +from torch import nn + + +class SimpleModel(nn.Module): + def __init__(self): + super().__init__() + self.dense = nn.Linear(10, 10) + self.intermediate = nn.Linear(10, 10) + self.layer_norm = nn.LayerNorm(10) +``` + +Jetzt können wir eine Instanz dieser Modelldefinition erstellen, die alle Gewichte ausfüllt: `dense`, `intermediate`, +`layer_norm` mit zufälligen Gewichten. Wir können das Modell ausdrucken, um seine Architektur zu sehen + +```python +model = SimpleModel() + +print(model) +``` + +Dies gibt folgendes aus: + +``` +SimpleModel( + (dense): Linear(in_features=10, out_features=10, bias=True) + (intermediate): Linear(in_features=10, out_features=10, bias=True) + (layer_norm): LayerNorm((10,), eps=1e-05, elementwise_affine=True) +) +``` + +Wir können sehen, dass die Ebenennamen durch den Namen des Klassenattributs in PyTorch definiert sind. Sie können die Gewichtswerte +Werte einer bestimmten Ebene anzeigen lassen: + +```python +print(model.dense.weight.data) +``` + +um zu sehen, dass die Gewichte zufällig initialisiert wurden + +``` +tensor([[-0.0818, 0.2207, -0.0749, -0.0030, 0.0045, -0.1569, -0.1598, 0.0212, + -0.2077, 0.2157], + [ 0.1044, 0.0201, 0.0990, 0.2482, 0.3116, 0.2509, 0.2866, -0.2190, + 0.2166, -0.0212], + [-0.2000, 0.1107, -0.1999, -0.3119, 0.1559, 0.0993, 0.1776, -0.1950, + -0.1023, -0.0447], + [-0.0888, -0.1092, 0.2281, 0.0336, 0.1817, -0.0115, 0.2096, 0.1415, + -0.1876, -0.2467], + [ 0.2208, -0.2352, -0.1426, -0.2636, -0.2889, -0.2061, -0.2849, -0.0465, + 0.2577, 0.0402], + [ 0.1502, 0.2465, 0.2566, 0.0693, 0.2352, -0.0530, 0.1859, -0.0604, + 0.2132, 0.1680], + [ 0.1733, -0.2407, -0.1721, 0.1484, 0.0358, -0.0633, -0.0721, -0.0090, + 0.2707, -0.2509], + [-0.1173, 0.1561, 0.2945, 0.0595, -0.1996, 0.2988, -0.0802, 0.0407, + 0.1829, -0.1568], + [-0.1164, -0.2228, -0.0403, 0.0428, 0.1339, 0.0047, 0.1967, 0.2923, + 0.0333, -0.0536], + [-0.1492, -0.1616, 0.1057, 0.1950, -0.2807, -0.2710, -0.1586, 0.0739, + 0.2220, 0.2358]]). +``` + +Im Konvertierungsskript sollten Sie diese zufällig initialisierten Gewichte mit den genauen Gewichten der +entsprechenden Ebene im Kontrollpunkt. *Z.B.* + +```python +# retrieve matching layer weights, e.g. by +# recursive algorithm +layer_name = "dense" +pretrained_weight = array_of_dense_layer + +model_pointer = getattr(model, "dense") + +model_pointer.weight.data = torch.from_numpy(pretrained_weight) +``` + +Dabei müssen Sie sicherstellen, dass jedes zufällig initialisierte Gewicht Ihres PyTorch-Modells und sein entsprechendes +Checkpoint-Gewicht in **Form und Name** genau übereinstimmen. Zu diesem Zweck ist es **notwendig**, assert +Anweisungen für die Form hinzuzufügen und die Namen der Checkpoint-Gewichte auszugeben. Sie sollten z.B. Anweisungen hinzufügen wie: + +```python +assert ( + model_pointer.weight.shape == pretrained_weight.shape +), f"Pointer shape of random weight {model_pointer.shape} and array shape of checkpoint weight {pretrained_weight.shape} mismatched" +``` + +Außerdem sollten Sie die Namen der beiden Gewichte ausdrucken, um sicherzustellen, dass sie übereinstimmen, *z.B.*. + +```python +logger.info(f"Initialize PyTorch weight {layer_name} from {pretrained_weight.name}") +``` + +Wenn entweder die Form oder der Name nicht übereinstimmt, haben Sie wahrscheinlich das falsche Kontrollpunktgewicht einer zufällig +Ebene der 🤗 Transformers-Implementierung zugewiesen. + +Eine falsche Form ist höchstwahrscheinlich auf eine falsche Einstellung der Konfigurationsparameter in `BrandNewBertConfig()` zurückzuführen, die +nicht genau mit denen übereinstimmen, die für den zu konvertierenden Prüfpunkt verwendet wurden. Es könnte aber auch sein, dass +die PyTorch-Implementierung eines Layers erfordert, dass das Gewicht vorher transponiert wird. + +Schließlich sollten Sie auch überprüfen, ob **alle** erforderlichen Gewichte initialisiert sind und alle Checkpoint-Gewichte ausgeben, die +die nicht zur Initialisierung verwendet wurden, um sicherzustellen, dass das Modell korrekt konvertiert wurde. Es ist völlig normal, dass die +Konvertierungsversuche entweder mit einer falschen Shape-Anweisung oder einer falschen Namenszuweisung fehlschlagen. Das liegt höchstwahrscheinlich daran, dass entweder +Sie haben falsche Parameter in `BrandNewBertConfig()` verwendet, haben eine falsche Architektur in der 🤗 Transformers +Implementierung, Sie haben einen Fehler in den `init()` Funktionen einer der Komponenten der 🤗 Transformers +Implementierung oder Sie müssen eine der Kontrollpunktgewichte transponieren. + +Dieser Schritt sollte mit dem vorherigen Schritt wiederholt werden, bis alle Gewichte des Kontrollpunkts korrekt in das +Transformers-Modell geladen sind. Nachdem Sie den Prüfpunkt korrekt in die 🤗 Transformers-Implementierung geladen haben, können Sie das Modell +das Modell unter einem Ordner Ihrer Wahl `/path/to/converted/checkpoint/folder` speichern, der dann sowohl ein +Datei `pytorch_model.bin` und eine Datei `config.json` enthalten sollte: + +```python +model.save_pretrained("/path/to/converted/checkpoint/folder") +``` + +**7. Implementieren Sie den Vorwärtspass** + +Nachdem es Ihnen gelungen ist, die trainierten Gewichte korrekt in die 🤗 Transformers-Implementierung zu laden, sollten Sie nun dafür sorgen +sicherstellen, dass der Forward Pass korrekt implementiert ist. In [Machen Sie sich mit dem ursprünglichen Repository vertraut](#3-4-führen-sie-einen-pre-training-checkpoint-mit-dem-original-repository-durch) haben Sie bereits ein Skript erstellt, das einen Forward Pass +Durchlauf des Modells unter Verwendung des Original-Repositorys durchführt. Jetzt sollten Sie ein analoges Skript schreiben, das die 🤗 Transformers +Implementierung anstelle der Originalimplementierung verwenden. Es sollte wie folgt aussehen: + +```python +model = BrandNewBertModel.from_pretrained("/path/to/converted/checkpoint/folder") +input_ids = [0, 4, 4, 3, 2, 4, 1, 7, 19] +output = model(input_ids).last_hidden_states +``` + +Es ist sehr wahrscheinlich, dass die 🤗 Transformers-Implementierung und die ursprüngliche Modell-Implementierung nicht genau die gleiche Ausgabe liefern. +beim ersten Mal nicht die gleiche Ausgabe liefern oder dass der Vorwärtsdurchlauf einen Fehler auslöst. Seien Sie nicht enttäuscht - das ist zu erwarten! Erstens, +sollten Sie sicherstellen, dass der Vorwärtsdurchlauf keine Fehler auslöst. Es passiert oft, dass die falschen Dimensionen verwendet werden +verwendet werden, was zu einem *Dimensionality mismatch* Fehler führt oder dass der falsche Datentyp verwendet wird, *z.B.* `torch.long` +anstelle von `torch.float32`. Zögern Sie nicht, das Hugging Face Team um Hilfe zu bitten, wenn Sie bestimmte Fehler nicht lösen können. +bestimmte Fehler nicht lösen können. + +Um sicherzustellen, dass die Implementierung von 🤗 Transformers korrekt funktioniert, müssen Sie sicherstellen, dass die Ausgaben +einer Genauigkeit von `1e-3` entsprechen. Zunächst sollten Sie sicherstellen, dass die Ausgabeformen identisch sind, *d.h.*. +Die Ausgabeform *outputs.shape* sollte für das Skript der 🤗 Transformers-Implementierung und die ursprüngliche +Implementierung ergeben. Als nächstes sollten Sie sicherstellen, dass auch die Ausgabewerte identisch sind. Dies ist einer der schwierigsten +Teile des Hinzufügens eines neuen Modells. Häufige Fehler, warum die Ausgaben nicht identisch sind, sind: + +- Einige Ebenen wurden nicht hinzugefügt, *d.h.* eine *Aktivierungsebene* wurde nicht hinzugefügt, oder die Restverbindung wurde vergessen +- Die Worteinbettungsmatrix wurde nicht gebunden +- Es werden die falschen Positionseinbettungen verwendet, da die ursprüngliche Implementierung einen Offset verwendet +- Dropout wird während des Vorwärtsdurchlaufs angewendet. Um dies zu beheben, stellen Sie sicher, dass *model.training auf False* steht und dass keine Dropout + Schicht während des Vorwärtsdurchlaufs fälschlicherweise aktiviert wird, *d.h.* übergeben Sie *self.training* an [PyTorch's functional dropout](https://pytorch.org/docs/stable/nn.functional.html?highlight=dropout#torch.nn.functional.dropout) + +Der beste Weg, das Problem zu beheben, besteht normalerweise darin, sich den Vorwärtsdurchlauf der ursprünglichen Implementierung und die 🤗 +Transformers-Implementierung nebeneinander zu sehen und zu prüfen, ob es Unterschiede gibt. Idealerweise sollten Sie die +Zwischenergebnisse beider Implementierungen des Vorwärtsdurchlaufs debuggen/ausdrucken, um die genaue Position im Netzwerk zu finden, an der die 🤗 +Transformers-Implementierung eine andere Ausgabe zeigt als die ursprüngliche Implementierung. Stellen Sie zunächst sicher, dass die +hartcodierten `input_ids` in beiden Skripten identisch sind. Überprüfen Sie dann, ob die Ausgaben der ersten Transformation von +der `input_ids` (normalerweise die Worteinbettungen) identisch sind. Und dann arbeiten Sie sich bis zur allerletzten Schicht des +Netzwerks. Irgendwann werden Sie einen Unterschied zwischen den beiden Implementierungen feststellen, der Sie auf den Fehler +in der Implementierung von 🤗 Transformers hinweist. Unserer Erfahrung nach ist ein einfacher und effizienter Weg, viele Druckanweisungen hinzuzufügen +sowohl in der Original-Implementierung als auch in der 🤗 Transformers-Implementierung an den gleichen Stellen im Netzwerk +hinzuzufügen und nacheinander Druckanweisungen zu entfernen, die dieselben Werte für Zwischenpräsentationen anzeigen. + +Wenn Sie sicher sind, dass beide Implementierungen die gleiche Ausgabe liefern, überprüfen Sie die Ausgaben mit +`torch.allclose(original_output, output, atol=1e-3)` überprüfen, haben Sie den schwierigsten Teil hinter sich! Herzlichen Glückwunsch - die +Arbeit, die noch zu erledigen ist, sollte ein Kinderspiel sein 😊. + +**8. Hinzufügen aller notwendigen Modelltests** + +An diesem Punkt haben Sie erfolgreich ein neues Modell hinzugefügt. Es ist jedoch sehr gut möglich, dass das Modell noch nicht +noch nicht vollständig mit dem erforderlichen Design übereinstimmt. Um sicherzustellen, dass die Implementierung vollständig kompatibel mit 🤗 Transformers ist, sollten alle +gemeinsamen Tests bestehen. Der Cookiecutter sollte automatisch eine Testdatei für Ihr Modell hinzugefügt haben, wahrscheinlich unter +demselben `tests/models/brand_new_bert/test_modeling_brand_new_bert.py`. Führen Sie diese Testdatei aus, um zu überprüfen, ob alle gängigen +Tests bestehen: + +```bash +pytest tests/models/brand_new_bert/test_modeling_brand_new_bert.py +``` + +Nachdem Sie alle allgemeinen Tests festgelegt haben, müssen Sie nun sicherstellen, dass all die schöne Arbeit, die Sie geleistet haben, gut getestet ist, damit + +- a) die Community Ihre Arbeit leicht nachvollziehen kann, indem sie sich spezifische Tests von *brand_new_bert* ansieht +- b) zukünftige Änderungen an Ihrem Modell keine wichtigen Funktionen des Modells zerstören. + +Als erstes sollten Sie Integrationstests hinzufügen. Diese Integrationstests tun im Wesentlichen dasselbe wie die Debugging-Skripte +die Sie zuvor zur Implementierung des Modells in 🤗 Transformers verwendet haben. Eine Vorlage für diese Modelltests wurde bereits von dem +Cookiecutter hinzugefügt, die `BrandNewBertModelIntegrationTests` heißt und nur noch von Ihnen ausgefüllt werden muss. Um sicherzustellen, dass diese +Tests erfolgreich sind, führen Sie + +```bash +RUN_SLOW=1 pytest -sv tests/models/brand_new_bert/test_modeling_brand_new_bert.py::BrandNewBertModelIntegrationTests +``` + + + +Falls Sie Windows verwenden, sollten Sie `RUN_SLOW=1` durch `SET RUN_SLOW=1` ersetzen. + + + +Zweitens sollten alle Funktionen, die speziell für *brand_new_bert* sind, zusätzlich in einem separaten Test getestet werden unter +`BrandNewBertModelTester`/`BrandNewBertModelTest`. Dieser Teil wird oft vergessen, ist aber in zweierlei Hinsicht äußerst nützlich +Weise: + +- Er hilft dabei, das Wissen, das Sie während der Modellerweiterung erworben haben, an die Community weiterzugeben, indem er zeigt, wie die + speziellen Funktionen von *brand_new_bert* funktionieren sollten. +- Künftige Mitwirkende können Änderungen am Modell schnell testen, indem sie diese speziellen Tests ausführen. + + +**9. Implementieren Sie den Tokenizer** + +Als nächstes sollten wir den Tokenizer von *brand_new_bert* hinzufügen. Normalerweise ist der Tokenizer äquivalent oder sehr ähnlich zu einem +bereits vorhandenen Tokenizer von 🤗 Transformers. + +Es ist sehr wichtig, die ursprüngliche Tokenizer-Datei zu finden/extrahieren und es zu schaffen, diese Datei in die 🤗 +Transformers Implementierung des Tokenizers zu laden. + +Um sicherzustellen, dass der Tokenizer korrekt funktioniert, empfiehlt es sich, zunächst ein Skript im ursprünglichen Repository zu erstellen +zu erstellen, das eine Zeichenkette eingibt und die `input_ids` zurückgibt. Es könnte etwa so aussehen (in Pseudocode): + +```python +input_str = "This is a long example input string containing special characters .$?-, numbers 2872 234 12 and words." +model = BrandNewBertModel.load_pretrained_checkpoint("/path/to/checkpoint/") +input_ids = model.tokenize(input_str) +``` + +Möglicherweise müssen Sie noch einmal einen Blick in das ursprüngliche Repository werfen, um die richtige Tokenizer-Funktion zu finden, oder Sie müssen +Sie müssen vielleicht sogar Änderungen an Ihrem Klon des Original-Repositorys vornehmen, um nur die `input_ids` auszugeben. Nach dem Schreiben +ein funktionierendes Tokenisierungsskript geschrieben, das das ursprüngliche Repository verwendet, sollten Sie ein analoges Skript für 🤗 Transformers +erstellt werden. Es sollte ähnlich wie dieses aussehen: + +```python +from transformers import BrandNewBertTokenizer + +input_str = "This is a long example input string containing special characters .$?-, numbers 2872 234 12 and words." + +tokenizer = BrandNewBertTokenizer.from_pretrained("/path/to/tokenizer/folder/") + +input_ids = tokenizer(input_str).input_ids +``` + +Wenn beide `input_ids` die gleichen Werte ergeben, sollte als letzter Schritt auch eine Tokenizer-Testdatei hinzugefügt werden. + +Analog zu den Modellierungstestdateien von *brand_new_bert* sollten auch die Tokenisierungs-Testdateien von *brand_new_bert* +eine Reihe von fest kodierten Integrationstests enthalten. + +**10. Führen Sie End-to-End-Integrationstests aus** + +Nachdem Sie den Tokenizer hinzugefügt haben, sollten Sie auch ein paar End-to-End-Integrationstests, die sowohl das Modell als auch den +Tokenizer zu `tests/models/brand_new_bert/test_modeling_brand_new_bert.py` in 🤗 Transformers. +Ein solcher Test sollte bei einem aussagekräftigen +Text-zu-Text-Beispiel zeigen, dass die Implementierung von 🤗 Transformers wie erwartet funktioniert. Ein aussagekräftiges Text-zu-Text-Beispiel kann +z.B. *ein Quell-zu-Ziel-Übersetzungspaar, ein Artikel-zu-Zusammenfassung-Paar, ein Frage-zu-Antwort-Paar, usw... Wenn keiner der +der portierten Prüfpunkte in einer nachgelagerten Aufgabe feinabgestimmt wurde, genügt es, sich einfach auf die Modelltests zu verlassen. In einem +letzten Schritt, um sicherzustellen, dass das Modell voll funktionsfähig ist, sollten Sie alle Tests auch auf der GPU durchführen. Es kann +Es kann vorkommen, dass Sie vergessen haben, einige `.to(self.device)` Anweisungen zu internen Tensoren des Modells hinzuzufügen, was in einem solchen +Test zu einem Fehler führen würde. Falls Sie keinen Zugang zu einem Grafikprozessor haben, kann das Hugging Face Team diese Tests für Sie durchführen. +Tests für Sie übernehmen. + +**11. Docstring hinzufügen** + +Nun sind alle notwendigen Funktionen für *brand_new_bert* hinzugefügt - Sie sind fast fertig! Das Einzige, was Sie noch hinzufügen müssen, ist +ein schöner Docstring und eine Doku-Seite. Der Cookiecutter sollte eine Vorlagendatei namens +`docs/source/model_doc/brand_new_bert.md` hinzugefügt haben, die Sie ausfüllen sollten. Die Benutzer Ihres Modells werden in der Regel zuerst einen Blick auf +diese Seite ansehen, bevor sie Ihr Modell verwenden. Daher muss die Dokumentation verständlich und prägnant sein. Es ist sehr nützlich für +die Gemeinschaft, einige *Tipps* hinzuzufügen, um zu zeigen, wie das Modell verwendet werden sollte. Zögern Sie nicht, das Hugging Face-Team anzupingen +bezüglich der Docstrings. + +Stellen Sie als nächstes sicher, dass der zu `src/transformers/models/brand_new_bert/modeling_brand_new_bert.py` hinzugefügte docstring +korrekt ist und alle erforderlichen Eingaben und Ausgaben enthält. Wir haben eine ausführliche Anleitung zum Schreiben von Dokumentationen und unserem Docstring-Format [hier](writing-documentation). Es ist immer gut, sich daran zu erinnern, dass die Dokumentation +mindestens so sorgfältig behandelt werden sollte wie der Code in 🤗 Transformers, denn die Dokumentation ist in der Regel der erste Kontaktpunkt der +Berührungspunkt der Community mit dem Modell ist. + +**Code refactor** + +Großartig, jetzt haben Sie den gesamten erforderlichen Code für *brand_new_bert* hinzugefügt. An diesem Punkt sollten Sie einige mögliche +falschen Codestil korrigieren, indem Sie ausführen: + +```bash +make style +``` + +und überprüfen Sie, ob Ihr Kodierungsstil die Qualitätsprüfung besteht: + +```bash +make quality +``` + +Es gibt noch ein paar andere sehr strenge Designtests in 🤗 Transformers, die möglicherweise noch fehlschlagen, was sich in den +den Tests Ihres Pull Requests. Dies liegt oft an fehlenden Informationen im Docstring oder an einer falschen +Benennung. Das Hugging Face Team wird Ihnen sicherlich helfen, wenn Sie hier nicht weiterkommen. + +Und schließlich ist es immer eine gute Idee, den eigenen Code zu refaktorisieren, nachdem man sichergestellt hat, dass er korrekt funktioniert. Wenn alle +Tests bestanden haben, ist es nun an der Zeit, den hinzugefügten Code noch einmal durchzugehen und einige Überarbeitungen vorzunehmen. + +Sie haben nun den Codierungsteil abgeschlossen, herzlichen Glückwunsch! 🎉 Sie sind großartig! 😎 + +**12. Laden Sie die Modelle in den Model Hub hoch** + +In diesem letzten Teil sollten Sie alle Checkpoints konvertieren und in den Modell-Hub hochladen und eine Modellkarte für jeden +hochgeladenen Modell-Kontrollpunkt. Sie können sich mit den Hub-Funktionen vertraut machen, indem Sie unsere [Model sharing and uploading Page](model_sharing) lesen. Hier sollten Sie mit dem Hugging Face-Team zusammenarbeiten, um einen passenden Namen für jeden +Checkpoint festzulegen und die erforderlichen Zugriffsrechte zu erhalten, um das Modell unter der Organisation des Autors *brand_new_bert* hochladen zu können. +*brand_new_bert*. Die Methode `push_to_hub`, die in allen Modellen in `transformers` vorhanden ist, ist ein schneller und effizienter Weg, Ihren Checkpoint in den Hub zu pushen. Ein kleines Snippet ist unten eingefügt: + +```python +brand_new_bert.push_to_hub("brand_new_bert") +# Uncomment the following line to push to an organization. +# brand_new_bert.push_to_hub("/brand_new_bert") +``` + +Es lohnt sich, etwas Zeit darauf zu verwenden, für jeden Kontrollpunkt passende Musterkarten zu erstellen. Die Modellkarten sollten die +spezifischen Merkmale dieses bestimmten Prüfpunkts hervorheben, * z.B.* auf welchem Datensatz wurde der Prüfpunkt +vortrainiert/abgestimmt? Für welche nachgelagerte Aufgabe sollte das Modell verwendet werden? Und fügen Sie auch etwas Code bei, wie Sie +wie das Modell korrekt verwendet wird. + +**13. (Optional) Notizbuch hinzufügen** + +Es ist sehr hilfreich, ein Notizbuch hinzuzufügen, in dem im Detail gezeigt wird, wie *brand_new_bert* für Schlussfolgerungen verwendet werden kann und/oder +bei einer nachgelagerten Aufgabe feinabgestimmt wird. Dies ist nicht zwingend erforderlich, um Ihren PR zusammenzuführen, aber sehr nützlich für die Gemeinschaft. + +**14. Reichen Sie Ihren fertigen PR ein** + +Sie sind jetzt mit der Programmierung fertig und können zum letzten Schritt übergehen, nämlich der Zusammenführung Ihres PR mit main. Normalerweise hat das +Hugging Face Team Ihnen an diesem Punkt bereits geholfen haben, aber es lohnt sich, sich etwas Zeit zu nehmen, um Ihrem fertigen +PR eine schöne Beschreibung zu geben und eventuell Kommentare zu Ihrem Code hinzuzufügen, wenn Sie Ihren Gutachter auf bestimmte Designentscheidungen hinweisen wollen. +Gutachter hinweisen wollen. + +### Teilen Sie Ihre Arbeit!! + +Jetzt ist es an der Zeit, von der Community Anerkennung für Ihre Arbeit zu bekommen! Die Fertigstellung einer Modellergänzung ist ein wichtiger +Beitrag zu Transformers und der gesamten NLP-Gemeinschaft. Ihr Code und die portierten vortrainierten Modelle werden sicherlich +von Hunderten und vielleicht sogar Tausenden von Entwicklern und Forschern genutzt werden. Sie sollten stolz auf Ihre Arbeit sein und Ihre +Ihre Leistung mit der Gemeinschaft teilen. + +**Sie haben ein weiteres Modell erstellt, das für jeden in der Community super einfach zugänglich ist! 🤯** diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/add_new_pipeline.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/add_new_pipeline.md new file mode 100644 index 0000000000000000000000000000000000000000..47d93e90ac14948b1d0429214efd281790701c01 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/add_new_pipeline.md @@ -0,0 +1,254 @@ + + +# Wie erstellt man eine benutzerdefinierte Pipeline? + +In dieser Anleitung sehen wir uns an, wie Sie eine benutzerdefinierte Pipeline erstellen und sie auf dem [Hub](https://hf.co/models) freigeben oder sie der +🤗 Transformers-Bibliothek hinzufügen. + +Zuallererst müssen Sie entscheiden, welche Roheingaben die Pipeline verarbeiten kann. Es kann sich um Strings, rohe Bytes, +Dictionaries oder was auch immer die wahrscheinlichste gewünschte Eingabe ist. Versuchen Sie, diese Eingaben so rein wie möglich in Python zu halten +denn das macht die Kompatibilität einfacher (auch mit anderen Sprachen über JSON). Dies werden die Eingaben der +Pipeline (`Vorverarbeitung`). + +Definieren Sie dann die `Outputs`. Dieselbe Richtlinie wie für die Eingänge. Je einfacher, desto besser. Dies werden die Ausgaben der +Methode `Postprocess`. + +Beginnen Sie damit, die Basisklasse `Pipeline` mit den 4 Methoden zu erben, die für die Implementierung von `preprocess` benötigt werden, +Weiterleiten", "Nachbearbeitung" und "Parameter säubern". + + +```python +from transformers import Pipeline + + +class MyPipeline(Pipeline): + def _sanitize_parameters(self, **kwargs): + preprocess_kwargs = {} + if "maybe_arg" in kwargs: + preprocess_kwargs["maybe_arg"] = kwargs["maybe_arg"] + return preprocess_kwargs, {}, {} + + def preprocess(self, inputs, maybe_arg=2): + model_input = Tensor(inputs["input_ids"]) + return {"model_input": model_input} + + def _forward(self, model_inputs): + # model_inputs == {"model_input": model_input} + outputs = self.model(**model_inputs) + # Maybe {"logits": Tensor(...)} + return outputs + + def postprocess(self, model_outputs): + best_class = model_outputs["logits"].softmax(-1) + return best_class +``` + +Die Struktur dieser Aufteilung soll eine relativ nahtlose Unterstützung für CPU/GPU ermöglichen und gleichzeitig die Durchführung von +Vor-/Nachbearbeitung auf der CPU in verschiedenen Threads + +Preprocess" nimmt die ursprünglich definierten Eingaben und wandelt sie in etwas um, das in das Modell eingespeist werden kann. Es kann +mehr Informationen enthalten und ist normalerweise ein `Dict`. + +`_forward` ist das Implementierungsdetail und ist nicht dafür gedacht, direkt aufgerufen zu werden. Weiterleiten" ist die bevorzugte +aufgerufene Methode, da sie Sicherheitsvorkehrungen enthält, die sicherstellen, dass alles auf dem erwarteten Gerät funktioniert. Wenn etwas +mit einem realen Modell verknüpft ist, gehört es in die Methode `_forward`, alles andere gehört in die Methoden preprocess/postprocess. + +Die Methode `Postprocess` nimmt die Ausgabe von `_forward` und verwandelt sie in die endgültige Ausgabe, die zuvor festgelegt wurde. +zuvor entschieden wurde. + +Die Methode `_sanitize_parameters` ermöglicht es dem Benutzer, beliebige Parameter zu übergeben, wann immer er möchte, sei es bei der Initialisierung +Zeit `pipeline(...., maybe_arg=4)` oder zur Aufrufzeit `pipe = pipeline(...); output = pipe(...., maybe_arg=4)`. + +Die Rückgabe von `_sanitize_parameters` sind die 3 Dicts von kwargs, die direkt an `preprocess` übergeben werden, +`_forward` und `postprocess` übergeben werden. Füllen Sie nichts aus, wenn der Aufrufer keinen zusätzlichen Parameter angegeben hat. Das +erlaubt es, die Standardargumente in der Funktionsdefinition beizubehalten, was immer "natürlicher" ist. + +Ein klassisches Beispiel wäre das Argument `top_k` in der Nachbearbeitung bei Klassifizierungsaufgaben. + +```python +>>> pipe = pipeline("my-new-task") +>>> pipe("This is a test") +[{"label": "1-star", "score": 0.8}, {"label": "2-star", "score": 0.1}, {"label": "3-star", "score": 0.05} +{"label": "4-star", "score": 0.025}, {"label": "5-star", "score": 0.025}] + +>>> pipe("This is a test", top_k=2) +[{"label": "1-star", "score": 0.8}, {"label": "2-star", "score": 0.1}] +``` + +In order to achieve that, we'll update our `postprocess` method with a default parameter to `5`. and edit +`_sanitize_parameters` to allow this new parameter. + + +```python +def postprocess(self, model_outputs, top_k=5): + best_class = model_outputs["logits"].softmax(-1) + # Add logic to handle top_k + return best_class + + +def _sanitize_parameters(self, **kwargs): + preprocess_kwargs = {} + if "maybe_arg" in kwargs: + preprocess_kwargs["maybe_arg"] = kwargs["maybe_arg"] + + postprocess_kwargs = {} + if "top_k" in kwargs: + postprocess_kwargs["top_k"] = kwargs["top_k"] + return preprocess_kwargs, {}, postprocess_kwargs +``` + +Versuchen Sie, die Eingaben/Ausgaben sehr einfach und idealerweise JSON-serialisierbar zu halten, da dies die Verwendung der Pipeline sehr einfach macht +ohne dass die Benutzer neue Arten von Objekten verstehen müssen. Es ist auch relativ üblich, viele verschiedene Arten von Argumenten zu unterstützen +von Argumenten zu unterstützen (Audiodateien, die Dateinamen, URLs oder reine Bytes sein können). + + + +## Hinzufügen zur Liste der unterstützten Aufgaben + +Um Ihre `neue Aufgabe` in die Liste der unterstützten Aufgaben aufzunehmen, müssen Sie sie zur `PIPELINE_REGISTRY` hinzufügen: + +```python +from transformers.pipelines import PIPELINE_REGISTRY + +PIPELINE_REGISTRY.register_pipeline( + "new-task", + pipeline_class=MyPipeline, + pt_model=AutoModelForSequenceClassification, +) +``` + +Wenn Sie möchten, können Sie ein Standardmodell angeben. In diesem Fall sollte es mit einer bestimmten Revision (die der Name einer Verzweigung oder ein Commit-Hash sein kann, hier haben wir `"abcdef"` genommen) sowie mit dem Typ versehen sein: + +```python +PIPELINE_REGISTRY.register_pipeline( + "new-task", + pipeline_class=MyPipeline, + pt_model=AutoModelForSequenceClassification, + default={"pt": ("user/awesome_model", "abcdef")}, + type="text", # current support type: text, audio, image, multimodal +) +``` + +## Teilen Sie Ihre Pipeline auf dem Hub + +Um Ihre benutzerdefinierte Pipeline auf dem Hub freizugeben, müssen Sie lediglich den benutzerdefinierten Code Ihrer `Pipeline`-Unterklasse in einer +Python-Datei speichern. Nehmen wir zum Beispiel an, Sie möchten eine benutzerdefinierte Pipeline für die Klassifizierung von Satzpaaren wie folgt verwenden: + +```py +import numpy as np + +from transformers import Pipeline + + +def softmax(outputs): + maxes = np.max(outputs, axis=-1, keepdims=True) + shifted_exp = np.exp(outputs - maxes) + return shifted_exp / shifted_exp.sum(axis=-1, keepdims=True) + + +class PairClassificationPipeline(Pipeline): + def _sanitize_parameters(self, **kwargs): + preprocess_kwargs = {} + if "second_text" in kwargs: + preprocess_kwargs["second_text"] = kwargs["second_text"] + return preprocess_kwargs, {}, {} + + def preprocess(self, text, second_text=None): + return self.tokenizer(text, text_pair=second_text, return_tensors=self.framework) + + def _forward(self, model_inputs): + return self.model(**model_inputs) + + def postprocess(self, model_outputs): + logits = model_outputs.logits[0].numpy() + probabilities = softmax(logits) + + best_class = np.argmax(probabilities) + label = self.model.config.id2label[best_class] + score = probabilities[best_class].item() + logits = logits.tolist() + return {"label": label, "score": score, "logits": logits} +``` + +Die Implementierung ist Framework-unabhängig und funktioniert für PyTorch- und TensorFlow-Modelle. Wenn wir dies in einer Datei +einer Datei namens `pair_classification.py` gespeichert haben, können wir sie importieren und wie folgt registrieren: + +```py +from pair_classification import PairClassificationPipeline +from transformers.pipelines import PIPELINE_REGISTRY +from transformers import AutoModelForSequenceClassification, TFAutoModelForSequenceClassification + +PIPELINE_REGISTRY.register_pipeline( + "pair-classification", + pipeline_class=PairClassificationPipeline, + pt_model=AutoModelForSequenceClassification, + tf_model=TFAutoModelForSequenceClassification, +) +``` + +Sobald dies geschehen ist, können wir es mit einem vortrainierten Modell verwenden. Zum Beispiel wurde `sgugger/finetuned-bert-mrpc` auf den +auf den MRPC-Datensatz abgestimmt, der Satzpaare als Paraphrasen oder nicht klassifiziert. + +```py +from transformers import pipeline + +classifier = pipeline("pair-classification", model="sgugger/finetuned-bert-mrpc") +``` + +Dann können wir sie auf dem Hub mit der Methode `push_to_hub` freigeben: + +```py +classifier.push_to_hub("test-dynamic-pipeline") +``` + +Dadurch wird die Datei, in der Sie `PairClassificationPipeline` definiert haben, in den Ordner `"test-dynamic-pipeline"` kopiert, +und speichert das Modell und den Tokenizer der Pipeline, bevor Sie alles in das Repository verschieben +`{Ihr_Benutzername}/test-dynamic-pipeline`. Danach kann jeder die Pipeline verwenden, solange er die Option +`trust_remote_code=True` angeben: + +```py +from transformers import pipeline + +classifier = pipeline(model="{your_username}/test-dynamic-pipeline", trust_remote_code=True) +``` + +## Hinzufügen der Pipeline zu 🤗 Transformers + +Wenn Sie Ihre Pipeline zu 🤗 Transformers beitragen möchten, müssen Sie ein neues Modul im Untermodul `pipelines` hinzufügen +mit dem Code Ihrer Pipeline hinzufügen. Fügen Sie es dann der Liste der in `pipelines/__init__.py` definierten Aufgaben hinzu. + +Dann müssen Sie noch Tests hinzufügen. Erstellen Sie eine neue Datei `tests/test_pipelines_MY_PIPELINE.py` mit Beispielen für die anderen Tests. + +Die Funktion `run_pipeline_test` ist sehr allgemein gehalten und läuft auf kleinen Zufallsmodellen auf jeder möglichen +Architektur, wie durch `model_mapping` und `tf_model_mapping` definiert. + +Dies ist sehr wichtig, um die zukünftige Kompatibilität zu testen, d.h. wenn jemand ein neues Modell für +`XXXForQuestionAnswering` hinzufügt, wird der Pipeline-Test versuchen, mit diesem Modell zu arbeiten. Da die Modelle zufällig sind, ist es +ist es unmöglich, die tatsächlichen Werte zu überprüfen. Deshalb gibt es eine Hilfsfunktion `ANY`, die einfach versucht, die +Ausgabe der Pipeline TYPE. + +Außerdem *müssen* Sie 2 (idealerweise 4) Tests implementieren. + +- `test_small_model_pt` : Definieren Sie 1 kleines Modell für diese Pipeline (es spielt keine Rolle, ob die Ergebnisse keinen Sinn ergeben) + und testen Sie die Ausgaben der Pipeline. Die Ergebnisse sollten die gleichen sein wie bei `test_small_model_tf`. +- `test_small_model_tf` : Definieren Sie 1 kleines Modell für diese Pipeline (es spielt keine Rolle, ob die Ergebnisse keinen Sinn ergeben) + und testen Sie die Ausgaben der Pipeline. Die Ergebnisse sollten die gleichen sein wie bei `test_small_model_pt`. +- `test_large_model_pt` (`optional`): Testet die Pipeline an einer echten Pipeline, bei der die Ergebnisse + Sinn machen. Diese Tests sind langsam und sollten als solche gekennzeichnet werden. Hier geht es darum, die Pipeline zu präsentieren und sicherzustellen + sicherzustellen, dass es in zukünftigen Versionen keine Abweichungen gibt. +- `test_large_model_tf` (`optional`): Testet die Pipeline an einer echten Pipeline, bei der die Ergebnisse + Sinn machen. Diese Tests sind langsam und sollten als solche gekennzeichnet werden. Hier geht es darum, die Pipeline zu präsentieren und sicherzustellen + sicherzustellen, dass es in zukünftigen Versionen keine Abweichungen gibt. diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/autoclass_tutorial.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/autoclass_tutorial.md new file mode 100644 index 0000000000000000000000000000000000000000..5dea87ca552c1af2ee6953bcf424b12f7bc56217 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/autoclass_tutorial.md @@ -0,0 +1,131 @@ + + +# Vortrainierte Instanzen mit einer AutoClass laden + +Bei so vielen verschiedenen Transformator-Architekturen kann es eine Herausforderung sein, eine für Ihren Checkpoint zu erstellen. Als Teil der 🤗 Transformers Kernphilosophie, die Bibliothek leicht, einfach und flexibel nutzbar zu machen, leitet eine `AutoClass` automatisch die richtige Architektur aus einem gegebenen Checkpoint ab und lädt sie. Mit der Methode `from_pretrained()` kann man schnell ein vortrainiertes Modell für eine beliebige Architektur laden, so dass man keine Zeit und Ressourcen aufwenden muss, um ein Modell von Grund auf zu trainieren. Die Erstellung dieser Art von Checkpoint-agnostischem Code bedeutet, dass Ihr Code, wenn er für einen Checkpoint funktioniert, auch mit einem anderen Checkpoint funktionieren wird - solange er für eine ähnliche Aufgabe trainiert wurde - selbst wenn die Architektur unterschiedlich ist. + + + +Denken Sie daran, dass sich die Architektur auf das Skelett des Modells bezieht und die Checkpoints die Gewichte für eine bestimmte Architektur sind. Zum Beispiel ist [BERT](https://huggingface.co/google-bert/bert-base-uncased) eine Architektur, während `google-bert/bert-base-uncased` ein Checkpoint ist. Modell ist ein allgemeiner Begriff, der entweder Architektur oder Prüfpunkt bedeuten kann. + + + +In dieser Anleitung lernen Sie, wie man: + +* Einen vortrainierten Tokenizer lädt. +* Einen vortrainierten Merkmalsextraktor lädt. +* Einen vortrainierten Prozessor lädt. +* Ein vortrainiertes Modell lädt. + +## AutoTokenizer + +Nahezu jede NLP-Aufgabe beginnt mit einem Tokenizer. Ein Tokenizer wandelt Ihre Eingabe in ein Format um, das vom Modell verarbeitet werden kann. + +Laden Sie einen Tokenizer mit [`AutoTokenizer.from_pretrained`]: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased") +``` + +Dann tokenisieren Sie Ihre Eingabe wie unten gezeigt: + +```py +>>> sequence = "In a hole in the ground there lived a hobbit." +>>> print(tokenizer(sequence)) +{'input_ids': [101, 1999, 1037, 4920, 1999, 1996, 2598, 2045, 2973, 1037, 7570, 10322, 4183, 1012, 102], + 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]} +``` + +## AutoFeatureExtractor + +Für Audio- und Bildverarbeitungsaufgaben verarbeitet ein Merkmalsextraktor das Audiosignal oder Bild in das richtige Eingabeformat. + +Laden Sie einen Merkmalsextraktor mit [`AutoFeatureExtractor.from_pretrained`]: + +```py +>>> from transformers import AutoFeatureExtractor + +>>> feature_extractor = AutoFeatureExtractor.from_pretrained( +... "ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition" +... ) +``` + +## AutoProcessor + +Multimodale Aufgaben erfordern einen Prozessor, der zwei Arten von Vorverarbeitungswerkzeugen kombiniert. Das Modell [LayoutLMV2](model_doc/layoutlmv2) beispielsweise benötigt einen Feature-Extraktor für Bilder und einen Tokenizer für Text; ein Prozessor kombiniert beide. + +Laden Sie einen Prozessor mit [`AutoProcessor.from_pretrained`]: + +```py +>>> from transformers import AutoProcessor + +>>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv2-base-uncased") +``` + +## AutoModel + + + +Mit den `AutoModelFor`-Klassen können Sie schließlich ein vortrainiertes Modell für eine bestimmte Aufgabe laden (siehe [hier](model_doc/auto) für eine vollständige Liste der verfügbaren Aufgaben). Laden Sie zum Beispiel ein Modell für die Sequenzklassifikation mit [`AutoModelForSequenceClassification.from_pretrained`]: + +```py +>>> from transformers import AutoModelForSequenceClassification + +>>> model = AutoModelForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased") +``` + +Sie können denselben Prüfpunkt problemlos wiederverwenden, um eine Architektur für eine andere Aufgabe zu laden: + +```py +>>> from transformers import AutoModelForTokenClassification + +>>> model = AutoModelForTokenClassification.from_pretrained("distilbert/distilbert-base-uncased") +``` + + + +Für PyTorch-Modelle verwendet die Methode `from_pretrained()` `torch.load()`, die intern `pickle` verwendet und als unsicher bekannt ist. Generell sollte man niemals ein Modell laden, das aus einer nicht vertrauenswürdigen Quelle stammen könnte, oder das manipuliert worden sein könnte. Dieses Sicherheitsrisiko wird für öffentliche Modelle, die auf dem Hugging Face Hub gehostet werden, teilweise gemildert, da diese bei jeder Übertragung [auf Malware](https://huggingface.co/docs/hub/security-malware) gescannt werden. Siehe die [Hub-Dokumentation](https://huggingface.co/docs/hub/security) für Best Practices wie [signierte Commit-Verifizierung](https://huggingface.co/docs/hub/security-gpg#signing-commits-with-gpg) mit GPG. + +TensorFlow- und Flax-Checkpoints sind nicht betroffen und können in PyTorch-Architekturen mit den Kwargs `from_tf` und `from_flax` für die Methode `from_pretrained` geladen werden, um dieses Problem zu umgehen. + + + +Im Allgemeinen empfehlen wir die Verwendung der Klasse "AutoTokenizer" und der Klasse "AutoModelFor", um trainierte Instanzen von Modellen zu laden. Dadurch wird sichergestellt, dass Sie jedes Mal die richtige Architektur laden. Im nächsten [Tutorial] (Vorverarbeitung) erfahren Sie, wie Sie Ihren neu geladenen Tokenizer, Feature Extractor und Prozessor verwenden, um einen Datensatz für die Feinabstimmung vorzuverarbeiten. + + +Mit den Klassen `TFAutoModelFor` schließlich können Sie ein vortrainiertes Modell für eine bestimmte Aufgabe laden (siehe [hier](model_doc/auto) für eine vollständige Liste der verfügbaren Aufgaben). Laden Sie zum Beispiel ein Modell für die Sequenzklassifikation mit [`TFAutoModelForSequenceClassification.from_pretrained`]: + +```py +>>> from transformers import TFAutoModelForSequenceClassification + +>>> model = TFAutoModelForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased") +``` + +Sie können denselben Prüfpunkt problemlos wiederverwenden, um eine Architektur für eine andere Aufgabe zu laden: + +```py +>>> from transformers import TFAutoModelForTokenClassification + +>>> model = TFAutoModelForTokenClassification.from_pretrained("distilbert/distilbert-base-uncased") +``` + +Im Allgemeinen empfehlen wir, die Klasse "AutoTokenizer" und die Klasse "TFAutoModelFor" zu verwenden, um vortrainierte Instanzen von Modellen zu laden. Dadurch wird sichergestellt, dass Sie jedes Mal die richtige Architektur laden. Im nächsten [Tutorial] (Vorverarbeitung) erfahren Sie, wie Sie Ihren neu geladenen Tokenizer, Feature Extractor und Prozessor verwenden, um einen Datensatz für die Feinabstimmung vorzuverarbeiten. + + diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/contributing.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/contributing.md new file mode 100644 index 0000000000000000000000000000000000000000..f7fc3d1359c3d25460952849ce61b46eac9b1857 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/contributing.md @@ -0,0 +1,332 @@ + + +# Zu 🤗 Transformers beitragen + +Jeder ist willkommen, einen Beitrag zu leisten, und wir schätzen den Beitrag jedes Einzelnen. Codebeiträge sind nicht der einzige Weg, der Community zu helfen. Fragen zu beantworten, anderen zu helfen und die Dokumentation zu verbessern, sind ebenfalls äußerst wertvoll. + +Es hilft uns auch, wenn Sie das Projekt weiterempfehlen! Erwähnen Sie die Bibliothek in Blogposts über die großartigen Projekte, die sie ermöglicht hat, tweeten Sie, wenn sie Ihnen geholfen hat, oder hinterlassen Sie dem Repository ein ⭐️, um Danke zu sagen. + +Wie auch immer Sie sich entscheiden beizutragen, seien Sie achtsam und respektieren Sie unseren [Verhaltenskodex](https://github.com/huggingface/transformers/blob/main/CODE_OF_CONDUCT.md). + +**Dieser Leitfaden wurde stark durch den fantastischen [scikit-learn-Leitfaden für Beiträge](https://github.com/scikit-learn/scikit-learn/blob/main/CONTRIBUTING.md) inspiriert.** + +## Beitragsmöglichkeiten + +Es gibt mehrere Wege, wie Sie zu 🤗 Transformers beitragen können: + +* Beheben Sie bestehende Probleme im vorhandenen Code. +* Erstellen Sie Issues im Zusammenhang mit Fehlern oder gewünschten neuen Funktionen. +* Implementieren Sie neue Modelle. +* Tragen Sie zu den Beispielen oder zur Dokumentation bei. + +Wenn Sie nicht wissen, wo Sie anfangen sollen, gibt es eine spezielle Liste von [Good First Issues](https://github.com/huggingface/transformers/contribute). Sie bietet Ihnen eine Liste offener und anfängerfreundlicher Probleme und hilft Ihnen, einen ersten Beitrag zu Open-Source zu leisten. Idealerweise erstellen Sie eine Pull-Anfrage und verlinken sie mit dem Issue, an dem Sie arbeiten möchten. Wir versuchen, erstellte PRs bevorzugt zu behandeln, da wir so den Fortschritt leicht verfolgen können, und die Option besteht, dass jemand anderes den PR übernehmen kann, falls der Beitragende keine Zeit mehr hat. + +Für etwas mehr Herausforderung, können Sie auch einen Blick auf die Liste der [Good Second Issues](https://github.com/huggingface/transformers/labels/Good%20Second%20Issue) werfen. Generell gilt: Legen Sie los, wenn Sie sich den Anforderungen gewachsen sehen und wir helfen Ihnen dabei! 🚀 + +> Alle Beiträge sind für die Community gleichermaßen wertvoll. 🥰 + +## Bestehende Probleme beheben + +Wenn Ihnen ein Problem im vorhandenen Code auffällt und Sie eine Lösung im Sinn haben, können Sie gerne einen Beitrag leisten und [eine Pull-Anfrage erstellen](#eine-pull-anfrage-erstellen)! + +## Ein fehlerspezifisches Issue oder eine Feature-Anfrage erstellen + +Tun Sie Ihr Bestes, diesen Richtlinien zu folgen, wenn Sie ein fehlerspezifisches Issue erstellen oder eine Feature-Anfrage einreichen. Das macht es uns leichter, Ihnen schnell und mit gutem Feedback zu antworten. + +### Haben Sie einen Fehler gefunden? + +Die 🤗 Transformers-Bibliothek verdankt ihre Robustheit und Zuverlässigkeit aller Nutzer, die frisch entdeckte Probleme melden. + +Wir würden es wirklich schätzen, wenn Sie **sicherstellen könnten, dass der Fehler noch nicht gemeldet wurde** (verwenden Sie die Suchleiste auf GitHub unter Issues), bevor Sie ein Issue erstellen. Ihr Problem sollte sich auch auf Fehler in der Bibliothek selbst und nicht auf Ihren eigenen Code beziehen. Wenn Sie sich nicht sicher sind, ob der Fehler in Ihrem eigenen Code oder der Bibliothek liegt, fragen Sie bitte zuerst im [Forum](https://discuss.huggingface.co/) nach. Das hilft uns, schneller auf Probleme im Zusammenhang mit der Bibliothek zu reagieren, anstatt auf allgemeine Fragen. + +Wenn Sie sich vergewissert haben, dass der Fehler noch nicht gemeldet wurde, geben Sie bitte die folgenden Informationen in Ihrem Issue an, damit wir es schnell beheben können: + +* Ihr **Betriebssystem und Version** sowie die Versionen von **Python**, **PyTorch** und **TensorFlow**, falls zutreffend. +* Ein kurzes und unabhängiges Code-Snippet, das es uns ermöglicht, den Fehler in weniger als 30 Sekunden nachzustellen. +* Den *vollständigen* Traceback, wenn eine Ausnahme geworfen wird. +* Fügen Sie weitere hilfreiche Informationen, wie z. B. Screenshots, an. + +Um das Betriebssystem und die Softwareversionen automatisch auszugeben, führen Sie den folgenden Befehl aus: + +```bash +transformers env +``` + +Sie können denselben Befehl auch im Hauptverzeichnis des Repositorys ausführen: + +```bash +python src/transformers/commands/transformers_cli.py env +``` + +### Möchten Sie eine neue Funktion? + +Wenn Sie eine bestimmte neue Funktion in 🤗 Transformers sehen möchten, erstellen Sie bitte ein Issue und fügen Sie eine Beschreibung hinzu: + +1. Was ist die *Motivation* hinter dieser Funktion? Steht sie in Zusammenhang mit einem Problem oder einer Frustration mit der Bibliothek? Ist es eine Funktion, die Sie für ein Projekt benötigen? Ist es etwas, an dem Sie gearbeitet haben und denken, dass es der Community nutzen könnte? + + Was auch immer es ist, wir würden uns freuen, davon zu hören! + +1. Beschreiben Sie Ihre gewünschte Funktion so detailliert wie möglich. Je mehr Sie uns darüber erzählen können, desto besser können wir Ihnen helfen. +1. Stellen Sie einen *Code-Schnipsel* bereit, der die Funktionsweise demonstriert. +1. Falls die Funktion auf einem Paper beruht, verlinken Sie dieses bitte. + +Wenn Ihr Issue gut geschrieben ist, sind wir zum Zeitpunkt seiner Erstellung bereits zu 80 % fertig. + +Wir haben [Vorlagen](https://github.com/huggingface/transformers/tree/main/templates) hinzugefügt, um Ihnen den Start Ihres Issues zu erleichtern. + +## Möchten Sie ein neues Modell implementieren? + +Es werden ständig neue Modelle veröffentlicht. Wenn Sie ein neues Modell implementieren möchten, geben Sie bitte folgende Informationen an: + +* Eine kurze Beschreibung des Modells und einen Link zum Paper. +* Link zur Implementierung, falls sie Open-Source ist. +* Link zu den Modellgewichten, falls verfügbar. + +Lassen Sie es uns wissen, wenn Sie bereit sind, das Modell selbst beizutragen. Dann können wir Ihnen helfen, es zu 🤗 Transformers hinzuzufügen! + +Wir haben auch einen technischen Leitfaden dazu, [wie man ein Modell zu 🤗 Transformers hinzufügt](https://huggingface.co/docs/transformers/add_new_model). + +## Möchten Sie die Dokumentation erweitern? + +Wir sind immer auf der Suche nach Verbesserungen, die die Dokumentation klarer und präziser machen. Bitte teilen Sie uns Verbesserungsvorschläge mit, wie z. B. Tippfehler und fehlende, unklare oder ungenaue Inhalte. Wir übernehmen gerne die Änderungen oder helfen Ihnen, einen Beitrag zu leisten, wenn Sie daran interessiert sind! + +Für weitere Einzelheiten darüber, wie man die Dokumentation generiert, erstellt und schreibt, werfen Sie einen Blick auf das [README](https://github.com/huggingface/transformers/tree/main/docs) der Dokumentation. + +## Eine Pull-Anfrage erstellen + +Bevor Sie irgendwelchen Code schreiben, empfehlen wir Ihnen dringend, die bestehenden PRs oder Issues zu durchsuchen, um sicherzustellen, dass niemand bereits an diesem Thema arbeitet. Wenn Sie sich unsicher sind, ist es immer eine gute Idee, nach Feedback in einem neuen Issue zu fragen. + +Sie benötigen grundlegende `git`-Kenntnisse, um zu 🤗 Transformers beizutragen. Obwohl `git` nicht das einfachste Werkzeug ist, hat es ein sehr gutes Handbuch. Geben Sie `git --help` in eine Shell ein und genießen Sie es! Wenn Sie Bücher bevorzugen, ist [Pro Git](https://git-scm.com/book/en/v2) eine gute Anlaufstelle. + +Sie benötigen **[Python 3.9](https://github.com/huggingface/transformers/blob/main/setup.py#L426)** oder höher, um zu 🤗 Transformers beizutragen. Folgen Sie den nachstehenden Schritten, um mit dem Beitrag zu beginnen: + +1. Forken Sie das [Repository](https://github.com/huggingface/transformers), indem Sie auf den **[Fork](https://github.com/huggingface/transformers/fork)**-Button auf der Seite des Repositorys klicken. Dadurch wird eine Kopie des Codes auf Ihrem GitHub-Account erstellt. + +1. Klonen Sie Ihren Fork auf Ihre lokale Festplatte und fügen Sie das ursprüngliche Repository als Remote hinzu: + + ```bash + git clone git@github.com:/transformers.git + cd transformers + git remote add upstream https://github.com/huggingface/transformers.git + ``` + +1. Erstellen Sie einen neuen Branch, um Ihre Änderungen zu speichern: + + ```bash + git checkout -b a-descriptive-name-for-my-changes + ``` + + 🚨 Arbeiten Sie **nicht** auf dem `main` Branch! + +1. Richten Sie eine Entwicklungsumgebung ein, indem Sie den folgenden Befehl in einer virtuellen Umgebung ausführen: + + ```bash + pip install -e ".[dev]" + ``` + + Wenn 🤗 Transformers bereits in der virtuellen Umgebung installiert war, entfernen Sie es mit `pip uninstall transformers`, bevor Sie es im bearbeitbaren Modus mit dem `-e` Flag neu installieren. + + Abhängig von Ihrem Betriebssystem und durch die wachsende Anzahl der optionalen Abhängigkeiten von Transformers könnten Sie mit diesem Befehl einen Fehler verursachen. Wenn das der Fall ist, stellen Sie sicher, dass Sie ihr bevorzugtes Deep-Learning-Framework (PyTorch, TensorFlow und/oder Flax) installieren und anschließend den folgenden Befehl ausführen: + + ```bash + pip install -e ".[quality]" + ``` + + Dies sollte für die meisten Anwendungsfälle ausreichend sein. + +1. Entwickeln Sie die Funktionen in Ihrem Branch. + + Während Sie an Ihrem Code arbeiten, sollten Sie sicherstellen, dass die Test-Suite erfolgreich durchläuft. Führen Sie die von Ihren Änderungen betroffenen Tests wie folgt aus: + + ```bash + pytest tests/.py + ``` + + Weitere Informationen über Tests finden Sie in der Anleitung zum Thema [Testen](https://huggingface.co/docs/transformers/testing). + + 🤗 Transformers stützt sich auf `black` und `ruff`, um seinen Quellcode konsistent zu formatieren. Nachdem Sie Änderungen vorgenommen haben, wenden Sie automatische Stilkorrekturen und Codeprüfungen, die nicht automatisiert werden können, in einem Schritt an: + + ```bash + make fixup + ``` + + Dieser Task ist optimiert, nur mit Dateien zu arbeiten, die von Ihrer PR modifiziert wurden. + + Wenn Sie die Prüfungen nacheinander ausführen möchten, wendet der folgende Befehl die Stilkorrekturen an: + + ```bash + make style + ``` + + 🤗 Transformers verwendet auch `ruff` und einige benutzerdefinierte Skripte, um auf Programmierfehler zu prüfen. Qualitätskontrollen werden von der CI durchgeführt, aber Sie können die gleichen Überprüfungen auch selbst ausführen: + + ```bash + make quality + ``` + + Abschließend haben wir viele Skripte, die sicherstellen, dass wir alle betroffenen Dateien aktualisieren, wenn wir ein neues Modell hinzufügen. Sie können diese wie folgt ausführen: + + ```bash + make repo-consistency + ``` + + Um mehr über diese Prüfungen zu erfahren und wie man mit ihnen Probleme behebt, lesen Sie den Leitfaden zu [Überprüfungen bei einer Pull-Anfrage](https://huggingface.co/docs/transformers/pr_checks). + + Wenn Sie Dokumente im Verzeichnis `docs/source` ändern, stellen Sie sicher, dass die Dokumentation noch generiert werden kann. Diese Prüfung wird auch im CI laufen, wenn Sie eine Pull-Anfrage erstellen. Um eine lokale Prüfung durchzuführen, müssen Sie den Dukumentation-Builder installieren: + + ```bash + pip install ".[docs]" + ``` + + Führen Sie den folgenden Befehl im Hauptverzeichnis des Repositorys aus: + + ```bash + doc-builder build transformers docs/source/en --build_dir ~/tmp/test-build + ``` + + Dadurch wird die Dokumentation im Ordner `~/tmp/test-build` erstellt, wo Sie die erzeugten Markdown-Dateien mit Ihrem bevorzugten Editor überprüfen können. Sie können auch eine Vorschau der Dokumentation auf GitHub sehen, wenn Sie eine Pull-Anfrage öffnen. + + Wenn Sie mit Ihren Änderungen zufrieden sind, fügen Sie die geänderten Dateien mit `git add` hinzu und speichern Sie Ihre Änderungen lokal mit `git commit`: + + ```bash + git add modified_file.py + git commit + ``` + + Bitte achten Sie darauf, [gute Commit-Nachrichten](https://chris.beams.io/posts/git-commit/) zu schreiben, um die von Ihnen vorgenommenen Änderungen klar zu kommunizieren! + + Um Ihre Kopie des Codes auf dem aktuellen Stand des ursprünglichen Repositorys zu halten, rebasen Sie Ihren Branch auf `upstream/branch` *bevor* Sie eine Pull-Anfrage öffnen oder falls Sie von einem Maintainer dazu aufgefordert werden: + + ```bash + git fetch upstream + git rebase upstream/main + ``` + + Pushen Sie Ihre Änderungen in Ihrem Branch: + + ```bash + git push -u origin a-descriptive-name-for-my-changes + ``` + + Wenn Sie bereits eine Pull-Anfrage erstellt haben, müssen Sie den Push mit dem `--force` Flag erzwingen. Andernfalls, wenn die Pull-Anfrage noch nicht erstellt wurde, können Sie Ihre Änderungen normal pushen. + +1. Jetzt können Sie zu Ihrem Fork des Repositorys auf GitHub gehen und auf **Pull-Anfrage** klicken, um eine Pull-Anfrage zu erstellen. Stellen Sie sicher, dass Sie alle Punkte auf unserer [Checkliste](#checkliste-für-pull-anfragen) unten abhaken. Wenn Sie fertig sind, können Sie Ihre Änderungen zur Überprüfung an die Projektverantwortlichen senden. + +1. Es ist kein Problem, wenn die Maintainer Änderungen beantragen, das geschieht auch bei unseren Kernmitarbeitern! Damit jeder die Änderungen in der Pull-Anfrage sehen kann, arbeiten Sie in Ihrem lokalen Branch und pushen die Änderungen zu Ihrem Fork. Sie werden automatisch in der Pull-Anfrage erscheinen. + +### Checkliste für Pull-Anfragen + +☐ Der Titel der Pull-Anfrage sollte Ihren Beitrag zusammenfassen.
+☐ Wenn Ihre Pull-Anfrage ein bestimmtes Issue bearbeitet, erwähnen Sie bitte die zugehörige Nummer in der Beschreibung der Pull-Anfrage, sodass diese verlinkt sind (und Personen, die das Issue lesen, wissen, dass Sie daran arbeiten).
+☐ Um eine fortlaufende Bearbeitung anzuzeigen, versehen Sie bitte den Titel mit einem `[WIP]` Präfix. Diese sind nützlich, um doppelte Arbeit zu verhindern und sie von PRs abzuheben, die bereit zum Zusammenführen sind.
+☐ Stellen Sie sicher, dass existierende Tests bestanden werden.
+☐ Wenn Sie eine neue Funktion hinzufügen, erstellen Sie auch Tests dafür.
+ +* Wenn Sie ein neues Modell hinzufügen, stellen Sie sicher, dass Sie `ModelTester.all_model_classes = (MyModel, MyModelWithLMHead,...)` verwenden, um die gemeinsamen Tests auszulösen. +* Wenn Sie neue `@slow` Tests hinzufügen, stellen Sie mit `RUN_SLOW=1 python -m pytest tests/models/my_new_model/test_my_new_model.py` sicher, dass diese erfolgreich durchlaufen. +* Wenn Sie einen neuen Tokenizer hinzufügen, schreiben Sie Tests und stellen Sie mit `RUN_SLOW=1 python -m pytest tests/models/{your_model_name}/test_tokenization_{your_model_name}.py` sicher, dass diese erfolgreich durchlaufen. +* CircleCI führt die langsamen Tests nicht aus, aber GitHub Actions tut dies jede Nacht!
+ +☐ Alle public Methoden müssen informative Docstrings haben (siehe [`modeling_bert.py`](https://github.com/huggingface/transformers/blob/main/src/transformers/models/bert/modeling_bert.py) als Beispiel).
+☐ Aufgrund des schnell wachsenden Repositorys fügen Sie bitte keine Bilder, Videos oder andere Nicht-Textdateien hinzu, die das Repository erheblich belasten würden. Verwenden Sie stattdessen ein Hub-Repository wie [`hf-internal-testing`](https://huggingface.co/hf-internal-testing), um diese Dateien zu hosten und sie per URL zu verlinken. Wir empfehlen Bilder, die zur Dokumentation gehören, im folgenden Repository abzulegen: [huggingface/documentation-images](https://huggingface.co/datasets/huggingface/documentation-images). Sie können eine PR in diesem Datasets-Repository erstellen und ein Hugging-Face-Mitglied bitten, sie zu mergen. + +Um mehr über die Prüfungen zu erfahren, die bei einer Pull-Anfrage ausgelöst werden, lesen Sie unseren Leitfaden zu [Überprüfungen bei einer Pull-Anfrage](https://huggingface.co/docs/transformers/pr_checks). + +### Tests + +Eine umfangreiche Test-Suite ist enthalten, um das Verhalten der Bibliothek und mehrerer Beispiele zu testen. Tests für die Bibliothek und Beispiele finden Sie jeweils im [tests](https://github.com/huggingface/transformers/tree/main/tests) und im [examples](https://github.com/huggingface/transformers/tree/main/examples) Ordner. + +Wir bevorzugen `pytest` und `pytest-xdist`, weil es schneller ist. Geben Sie einen *Pfad zu einem Unterordner oder einer Testdatei* vom Hauptverzeichnis des Repositorys aus an, um den Test auszuführen: + +```bash +python -m pytest -n auto --dist=loadfile -s -v ./tests/models/my_new_model +``` + +Analog für den `examples` Ordner, geben Sie einen *Pfad zu einem Unterordner oder einer Testdatei* an, um den Test auszuführen. Z. B. führt der folgende Befehl den Test des Unterordners für Textklassifizierung im PyTorch `examples` Ordner durch: + +```bash +pip install -r examples/xxx/requirements.txt # nur beim ersten Mal erforderlich +python -m pytest -n auto --dist=loadfile -s -v ./examples/pytorch/text-classification +``` + +Tatsächlich ist dies genau, wie unsere `make test` und `make test-examples` Befehle implementiert sind (abgesehen von `pip install`)! + +Sie können auch eine kleinere Anzahl an Tests angeben, um nur die Funktion, an der Sie arbeiten, zu testen. + +Standardmäßig werden langsame Tests übersprungen, aber Sie können die Umgebungsvariable `RUN_SLOW` auf `yes` setzen, um sie auszuführen. Dies wird den Download vieler Gigabyte an Modellen starten - stellen Sie also sicher, dass Sie sowohl genügend Festplattenspeicher als auch eine gute Internetverbindung oder die nötige Geduld haben! + + + +Vergessen Sie nicht, einen *Pfad zu einem Unterordner oder einer Testdatei* anzugeben, um den Test auszuführen. Sonst führen Sie alle Tests im `tests` oder `examples` Ordner aus, was sehr lange dauern wird! + + + +```bash +RUN_SLOW=yes python -m pytest -n auto --dist=loadfile -s -v ./tests/models/my_new_model +RUN_SLOW=yes python -m pytest -n auto --dist=loadfile -s -v ./examples/pytorch/text-classification +``` + +Wie bei den langsamen Tests gibt es auch andere Umgebungsvariablen, die standardmäßig beim Testen nicht gesetzt sind: + +* `RUN_CUSTOM_TOKENIZERS`: Aktiviert Tests für benutzerdefinierte Tokenizer. + +Weitere Umgebungsvariablen und zusätzliche Informationen finden Sie in der [testing_utils.py](src/transformers/testing_utils.py). + +🤗 Transformers verwendet `pytest` nur als Test-Runner. Es verwendet keine `pytest`-spezifischen Funktionen in der Test-Suite selbst. + +Das bedeutet, `unittest` wird vollständig unterstützt. Folgend wird beschrieben, wie man Tests mit `unittest` ausführt: + +```bash +python -m unittest discover -s tests -t . -v +python -m unittest discover -s examples -t examples -v +``` + +### Stil-Leitfaden + +Für Docstrings befolgt 🤗 Transformers den [Google Python Style Guide](https://google.github.io/styleguide/pyguide.html). +Lesen Sie unseren [Leitfaden zum Schreiben von Dokumentationen](https://github.com/huggingface/transformers/tree/main/docs#writing-documentation---specification) für weitere Informationen. + +### Entwickeln unter Windows + +Unter Windows (falls Sie nicht im [Windows-Subsystem für Linux](https://learn.microsoft.com/en-us/windows/wsl/) oder WSL arbeiten) müssen Sie git so konfigurieren, dass Windows `CRLF` in Linux `LF` Zeilenenden umgewandelt werden: + +```bash +git config core.autocrlf input +``` + +Eine Möglichkeit, den `make`-Befehl unter Windows auszuführen, ist mit MSYS2: + +1. Laden Sie [MSYS2](https://www.msys2.org/) herunter und installieren Sie es nach `C:\msys64`. +1. Öffnen Sie die Kommandozeile `C:\msys64\msys2.exe` (sie sollte vom **Start**-Menü aus verfügbar sein). +1. Führen Sie den Befehl in der Shell aus: `pacman -Syu` und installieren Sie `make` mit `pacman -S make`. +1. Fügen Sie `C:\msys64\usr\bin` an Ihrer PATH-Umgebungsvariable an. + +Sie können nun `make` aus jedem Terminal heraus verwenden (PowerShell, cmd.exe usw.)! 🎉 + +### Ein geforktes Repository mit dem Haupt-Repository von Hugging Face synchronisieren + +Beim Aktualisieren des main-Branches eines geforkten Repositories beachten Sie bitte die folgenden Schritte, um das Anpingen des Haupt-Repositorys zu vermeiden, was unnötige Verweise in abhängigen PRs vermerkt und beteiligte Entwickler benachrichtigt: + +1. Wenn möglich, vermeiden Sie die Synchronisation mit dem Haupt-Repository über einen Branch und PR im geforkten Repository. Mergen Sie stattdessen direkt in den main-Branch des Forks. +1. Wenn ein PR unbedingt notwendig ist, verwenden Sie die folgenden Schritte, nachdem Sie Ihren Branch ausgecheckt haben: + + ```bash + git checkout -b your-branch-for-syncing + git pull --squash --no-commit upstream main + git commit -m '' + git push --set-upstream origin your-branch-for-syncing + ``` diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/index.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/index.md new file mode 100644 index 0000000000000000000000000000000000000000..1c4d4e767520431e7241a6d489f044f28a6f1cbe --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/index.md @@ -0,0 +1,334 @@ + + +# 🤗 Transformers + +Maschinelles Lernen auf dem neuesten Stand der Technik für PyTorch, TensorFlow und JAX. + +🤗 Transformers bietet APIs zum einfachen Herunterladen und Trainieren von vortrainierten Modellen auf dem neuesten Stand der Technik. Die Verwendung von vortrainierten Modellen kann Rechenkosten sparen und den CO2-Fußabdruck reduzieren und Zeit sparen, die für das Training eines Modells von Grund auf benötigt wird. Die Modelle können für verschiedene Modalitäten verwendet werden, wie z. B.: + +* 📝 Text: Textklassifizierung, Informationsextrahierung, Beantwortung von Fragen, Zusammenfassung, Übersetzung und Texterstellung in über 100 Sprachen. +* 🖼️ Bilder: Bildklassifizierung, Objekterkennung und Segmentierung. +* 🗣️ Audio: Spracherkennung und Audioklassifizierung. +* 🐙 Multimodal: Beantwortung von Tabellenfragen, optische Zeichenerkennung, Informationsextraktion aus gescannten Dokumenten, Videoklassifizierung und Beantwortung visueller Fragen. + +Unsere Bibliothek unterstützt die nahtlose Integration von drei der beliebtesten Deep-Learning-Bibliotheken: [PyTorch](https://pytorch.org/), [TensorFlow](https://www.tensorflow.org/) und [JAX](https://jax.readthedocs.io/en/latest/). Trainieren Sie Ihr Modell in drei Codezeilen in einem Framework und laden Sie es zur Inferenz mit einem anderen. + +Jede 🤗 Transformers-Architektur ist in einem eigenständigen Python-Modul definiert, so dass sie leicht für Forschung und Experimente angepasst werden kann. + +## Wenn Sie auf der Suche nach individueller Unterstützung durch das Hugging Face-Team sind + + + HuggingFace Expert Acceleration Program + + +## Inhalt + +Die Dokumentation ist in fünf Teile gegliedert: + +- **GET STARTED** enthält eine kurze Tour und Installationsanweisungen, um mit 🤗 Transformers loszulegen. +- **TUTORIALS** sind ein hervorragender Ausgangspunkt, wenn Sie neu in unserer Bibliothek sind. Dieser Abschnitt hilft Ihnen, die grundlegenden Fähigkeiten zu erlangen, die Sie benötigen, um mit 🤗 Transformers zu arbeiten. +- **HOW-TO GUIDES** zeigen Ihnen, wie Sie ein bestimmtes Ziel erreichen können, z. B. die Feinabstimmung eines vortrainierten Modells für die Sprachmodellierung oder die Erstellung eines benutzerdefinierten Modellkopfs. +- **KONZEPTUELLE ANLEITUNGEN** bietet weitere Diskussionen und Erklärungen zu den zugrunde liegenden Konzepten und Ideen hinter Modellen, Aufgaben und der Designphilosophie von 🤗 Transformers. +- **API** beschreibt jede Klasse und Funktion, gruppiert in: + + - **MAIN CLASSES** für die Hauptklassen, die die wichtigsten APIs der Bibliothek darstellen. + - MODELLE** für die Klassen und Funktionen, die zu jedem in der Bibliothek implementierten Modell gehören. + - **INTERNAL HELPERS** für die Klassen und Funktionen, die wir intern verwenden. + +Die Bibliothek enthält derzeit JAX-, PyTorch- und TensorFlow-Implementierungen, vortrainierte Modellgewichte, Nutzungsskripte und Konvertierungsprogramme für die folgenden Modelle. + +### Unterstütze Modelle + + + +1. **[ALBERT](model_doc/albert)** (from Google Research and the Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for Self-supervised Learning of Language Representations](https://huggingface.co/papers/1909.11942), by Zhenzhong Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut. +1. **[ALIGN](model_doc/align)** (from Google Research) released with the paper [Scaling Up Visual and Vision-Language Representation Learning With Noisy Text Supervision](https://huggingface.co/papers/2102.05918) by Chao Jia, Yinfei Yang, Ye Xia, Yi-Ting Chen, Zarana Parekh, Hieu Pham, Quoc V. Le, Yunhsuan Sung, Zhen Li, Tom Duerig. +1. **[BART](model_doc/bart)** (from Facebook) released with the paper [BART: Denoising Sequence-to-Sequence Pre-training for Natural Language Generation, Translation, and Comprehension](https://huggingface.co/papers/1910.13461) by Mike Lewis, Yinhan Liu, Naman Goyal, Marjan Ghazvininejad, Abdelrahman Mohamed, Omer Levy, Ves Stoyanov and Luke Zettlemoyer. +1. **[BARThez](model_doc/barthez)** (from École polytechnique) released with the paper [BARThez: a Skilled Pretrained French Sequence-to-Sequence Model](https://huggingface.co/papers/2010.12321) by Moussa Kamal Eddine, Antoine J.-P. Tixier, Michalis Vazirgiannis. +1. **[BARTpho](model_doc/bartpho)** (from VinAI Research) released with the paper [BARTpho: Pre-trained Sequence-to-Sequence Models for Vietnamese](https://huggingface.co/papers/2109.09701) by Nguyen Luong Tran, Duong Minh Le and Dat Quoc Nguyen. +1. **[BEiT](model_doc/beit)** (from Microsoft) released with the paper [BEiT: BERT Pre-Training of Image Transformers](https://huggingface.co/papers/2106.08254) by Hangbo Bao, Li Dong, Furu Wei. +1. **[BERT](model_doc/bert)** (from Google) released with the paper [BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://huggingface.co/papers/1810.04805) by Jacob Devlin, Ming-Wei Chang, Kenton Lee and Kristina Toutanova. +1. **[BERT For Sequence Generation](model_doc/bert-generation)** (from Google) released with the paper [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://huggingface.co/papers/1907.12461) by Sascha Rothe, Shashi Narayan, Aliaksei Severyn. +1. **[BERTweet](model_doc/bertweet)** (from VinAI Research) released with the paper [BERTweet: A pre-trained language model for English Tweets](https://aclanthology.org/2020.emnlp-demos.2/) by Dat Quoc Nguyen, Thanh Vu and Anh Tuan Nguyen. +1. **[BigBird-Pegasus](model_doc/bigbird_pegasus)** (from Google Research) released with the paper [Big Bird: Transformers for Longer Sequences](https://huggingface.co/papers/2007.14062) by Manzil Zaheer, Guru Guruganesh, Avinava Dubey, Joshua Ainslie, Chris Alberti, Santiago Ontanon, Philip Pham, Anirudh Ravula, Qifan Wang, Li Yang, Amr Ahmed. +1. **[BigBird-RoBERTa](model_doc/big_bird)** (from Google Research) released with the paper [Big Bird: Transformers for Longer Sequences](https://huggingface.co/papers/2007.14062) by Manzil Zaheer, Guru Guruganesh, Avinava Dubey, Joshua Ainslie, Chris Alberti, Santiago Ontanon, Philip Pham, Anirudh Ravula, Qifan Wang, Li Yang, Amr Ahmed. +1. **[Blenderbot](model_doc/blenderbot)** (from Facebook) released with the paper [Recipes for building an open-domain chatbot](https://huggingface.co/papers/2004.13637) by Stephen Roller, Emily Dinan, Naman Goyal, Da Ju, Mary Williamson, Yinhan Liu, Jing Xu, Myle Ott, Kurt Shuster, Eric M. Smith, Y-Lan Boureau, Jason Weston. +1. **[BlenderbotSmall](model_doc/blenderbot-small)** (from Facebook) released with the paper [Recipes for building an open-domain chatbot](https://huggingface.co/papers/2004.13637) by Stephen Roller, Emily Dinan, Naman Goyal, Da Ju, Mary Williamson, Yinhan Liu, Jing Xu, Myle Ott, Kurt Shuster, Eric M. Smith, Y-Lan Boureau, Jason Weston. +1. **[BLOOM](model_doc/bloom)** (from BigScience workshop) released by the [BigScience Workshop](https://bigscience.huggingface.co/). +1. **[BORT](model_doc/bort)** (from Alexa) released with the paper [Optimal Subarchitecture Extraction For BERT](https://huggingface.co/papers/2010.10499) by Adrian de Wynter and Daniel J. Perry. +1. **[ByT5](model_doc/byt5)** (from Google Research) released with the paper [ByT5: Towards a token-free future with pre-trained byte-to-byte models](https://huggingface.co/papers/2105.13626) by Linting Xue, Aditya Barua, Noah Constant, Rami Al-Rfou, Sharan Narang, Mihir Kale, Adam Roberts, Colin Raffel. +1. **[CamemBERT](model_doc/camembert)** (from Inria/Facebook/Sorbonne) released with the paper [CamemBERT: a Tasty French Language Model](https://huggingface.co/papers/1911.03894) by Louis Martin*, Benjamin Muller*, Pedro Javier Ortiz Suárez*, Yoann Dupont, Laurent Romary, Éric Villemonte de la Clergerie, Djamé Seddah and Benoît Sagot. +1. **[CANINE](model_doc/canine)** (from Google Research) released with the paper [CANINE: Pre-training an Efficient Tokenization-Free Encoder for Language Representation](https://huggingface.co/papers/2103.06874) by Jonathan H. Clark, Dan Garrette, Iulia Turc, John Wieting. +1. **[CLIP](model_doc/clip)** (from OpenAI) released with the paper [Learning Transferable Visual Models From Natural Language Supervision](https://huggingface.co/papers/2103.00020) by Alec Radford, Jong Wook Kim, Chris Hallacy, Aditya Ramesh, Gabriel Goh, Sandhini Agarwal, Girish Sastry, Amanda Askell, Pamela Mishkin, Jack Clark, Gretchen Krueger, Ilya Sutskever. +1. **[CodeGen](model_doc/codegen)** (from Salesforce) released with the paper [A Conversational Paradigm for Program Synthesis](https://huggingface.co/papers/2203.13474) by Erik Nijkamp, Bo Pang, Hiroaki Hayashi, Lifu Tu, Huan Wang, Yingbo Zhou, Silvio Savarese, Caiming Xiong. +1. **[ConvBERT](model_doc/convbert)** (from YituTech) released with the paper [ConvBERT: Improving BERT with Span-based Dynamic Convolution](https://huggingface.co/papers/2008.02496) by Zihang Jiang, Weihao Yu, Daquan Zhou, Yunpeng Chen, Jiashi Feng, Shuicheng Yan. +1. **[ConvNeXT](model_doc/convnext)** (from Facebook AI) released with the paper [A ConvNet for the 2020s](https://huggingface.co/papers/2201.03545) by Zhuang Liu, Hanzi Mao, Chao-Yuan Wu, Christoph Feichtenhofer, Trevor Darrell, Saining Xie. +1. **[ConvNeXTV2](model_doc/convnextv2)** (from Facebook AI) released with the paper [ConvNeXt V2: Co-designing and Scaling ConvNets with Masked Autoencoders](https://huggingface.co/papers/2301.00808) by Sanghyun Woo, Shoubhik Debnath, Ronghang Hu, Xinlei Chen, Zhuang Liu, In So Kweon, Saining Xie. +1. **[CPM](model_doc/cpm)** (from Tsinghua University) released with the paper [CPM: A Large-scale Generative Chinese Pre-trained Language Model](https://huggingface.co/papers/2012.00413) by Zhengyan Zhang, Xu Han, Hao Zhou, Pei Ke, Yuxian Gu, Deming Ye, Yujia Qin, Yusheng Su, Haozhe Ji, Jian Guan, Fanchao Qi, Xiaozhi Wang, Yanan Zheng, Guoyang Zeng, Huanqi Cao, Shengqi Chen, Daixuan Li, Zhenbo Sun, Zhiyuan Liu, Minlie Huang, Wentao Han, Jie Tang, Juanzi Li, Xiaoyan Zhu, Maosong Sun. +1. **[CTRL](model_doc/ctrl)** (from Salesforce) released with the paper [CTRL: A Conditional Transformer Language Model for Controllable Generation](https://huggingface.co/papers/1909.05858) by Nitish Shirish Keskar*, Bryan McCann*, Lav R. Varshney, Caiming Xiong and Richard Socher. +1. **[CvT](model_doc/cvt)** (from Microsoft) released with the paper [CvT: Introducing Convolutions to Vision Transformers](https://huggingface.co/papers/2103.15808) by Haiping Wu, Bin Xiao, Noel Codella, Mengchen Liu, Xiyang Dai, Lu Yuan, Lei Zhang. +1. **[Data2Vec](model_doc/data2vec)** (from Facebook) released with the paper [Data2Vec: A General Framework for Self-supervised Learning in Speech, Vision and Language](https://huggingface.co/papers/2202.03555) by Alexei Baevski, Wei-Ning Hsu, Qiantong Xu, Arun Babu, Jiatao Gu, Michael Auli. +1. **[DeBERTa](model_doc/deberta)** (from Microsoft) released with the paper [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://huggingface.co/papers/2006.03654) by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen. +1. **[DeBERTa-v2](model_doc/deberta-v2)** (from Microsoft) released with the paper [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://huggingface.co/papers/2006.03654) by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen. +1. **[Decision Transformer](model_doc/decision_transformer)** (from Berkeley/Facebook/Google) released with the paper [Decision Transformer: Reinforcement Learning via Sequence Modeling](https://huggingface.co/papers/2106.01345) by Lili Chen, Kevin Lu, Aravind Rajeswaran, Kimin Lee, Aditya Grover, Michael Laskin, Pieter Abbeel, Aravind Srinivas, Igor Mordatch. +1. **[DeiT](model_doc/deit)** (from Facebook) released with the paper [Training data-efficient image transformers & distillation through attention](https://huggingface.co/papers/2012.12877) by Hugo Touvron, Matthieu Cord, Matthijs Douze, Francisco Massa, Alexandre Sablayrolles, Hervé Jégou. +1. **[DETR](model_doc/detr)** (from Facebook) released with the paper [End-to-End Object Detection with Transformers](https://huggingface.co/papers/2005.12872) by Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, Sergey Zagoruyko. +1. **[DialoGPT](model_doc/dialogpt)** (from Microsoft Research) released with the paper [DialoGPT: Large-Scale Generative Pre-training for Conversational Response Generation](https://huggingface.co/papers/1911.00536) by Yizhe Zhang, Siqi Sun, Michel Galley, Yen-Chun Chen, Chris Brockett, Xiang Gao, Jianfeng Gao, Jingjing Liu, Bill Dolan. +1. **[DistilBERT](model_doc/distilbert)** (from HuggingFace), released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter](https://huggingface.co/papers/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same method has been applied to compress GPT2 into [DistilGPT2](https://github.com/huggingface/transformers-research-projects/tree/main/distillation), RoBERTa into [DistilRoBERTa](https://github.com/huggingface/transformers-research-projects/tree/main/distillation), Multilingual BERT into [DistilmBERT](https://github.com/huggingface/transformers-research-projects/tree/main/distillation) and a German version of DistilBERT. +1. **[DiT](model_doc/dit)** (from Microsoft Research) released with the paper [DiT: Self-supervised Pre-training for Document Image Transformer](https://huggingface.co/papers/2203.02378) by Junlong Li, Yiheng Xu, Tengchao Lv, Lei Cui, Cha Zhang, Furu Wei. +1. **[DPR](model_doc/dpr)** (from Facebook) released with the paper [Dense Passage Retrieval for Open-Domain Question Answering](https://huggingface.co/papers/2004.04906) by Vladimir Karpukhin, Barlas Oğuz, Sewon Min, Patrick Lewis, Ledell Wu, Sergey Edunov, Danqi Chen, and Wen-tau Yih. +1. **[DPT](master/model_doc/dpt)** (from Intel Labs) released with the paper [Vision Transformers for Dense Prediction](https://huggingface.co/papers/2103.13413) by René Ranftl, Alexey Bochkovskiy, Vladlen Koltun. +1. **[EfficientNet](model_doc/efficientnet)** (from Google Research) released with the paper [EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks](https://huggingface.co/papers/1905.11946) by Mingxing Tan and Quoc V. Le. +1. **[ELECTRA](model_doc/electra)** (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders as discriminators rather than generators](https://huggingface.co/papers/2003.10555) by Kevin Clark, Minh-Thang Luong, Quoc V. Le, Christopher D. Manning. +1. **[EncoderDecoder](model_doc/encoder-decoder)** (from Google Research) released with the paper [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://huggingface.co/papers/1907.12461) by Sascha Rothe, Shashi Narayan, Aliaksei Severyn. +1. **[FlauBERT](model_doc/flaubert)** (from CNRS) released with the paper [FlauBERT: Unsupervised Language Model Pre-training for French](https://huggingface.co/papers/1912.05372) by Hang Le, Loïc Vial, Jibril Frej, Vincent Segonne, Maximin Coavoux, Benjamin Lecouteux, Alexandre Allauzen, Benoît Crabbé, Laurent Besacier, Didier Schwab. +1. **[FLAVA](model_doc/flava)** (from Facebook AI) released with the paper [FLAVA: A Foundational Language And Vision Alignment Model](https://huggingface.co/papers/2112.04482) by Amanpreet Singh, Ronghang Hu, Vedanuj Goswami, Guillaume Couairon, Wojciech Galuba, Marcus Rohrbach, and Douwe Kiela. +1. **[FNet](model_doc/fnet)** (from Google Research) released with the paper [FNet: Mixing Tokens with Fourier Transforms](https://huggingface.co/papers/2105.03824) by James Lee-Thorp, Joshua Ainslie, Ilya Eckstein, Santiago Ontanon. +1. **[Funnel Transformer](model_doc/funnel)** (from CMU/Google Brain) released with the paper [Funnel-Transformer: Filtering out Sequential Redundancy for Efficient Language Processing](https://huggingface.co/papers/2006.03236) by Zihang Dai, Guokun Lai, Yiming Yang, Quoc V. Le. +1. **[GLPN](model_doc/glpn)** (from KAIST) released with the paper [Global-Local Path Networks for Monocular Depth Estimation with Vertical CutDepth](https://huggingface.co/papers/2201.07436) by Doyeon Kim, Woonghyun Ga, Pyungwhan Ahn, Donggyu Joo, Sehwan Chun, Junmo Kim. +1. **[GPT](model_doc/openai-gpt)** (from OpenAI) released with the paper [Improving Language Understanding by Generative Pre-Training](https://openai.com/research/language-unsupervised/) by Alec Radford, Karthik Narasimhan, Tim Salimans and Ilya Sutskever. +1. **[GPT Neo](model_doc/gpt_neo)** (from EleutherAI) released in the repository [EleutherAI/gpt-neo](https://github.com/EleutherAI/gpt-neo) by Sid Black, Stella Biderman, Leo Gao, Phil Wang and Connor Leahy. +1. **[GPT NeoX](model_doc/gpt_neox)** (from EleutherAI) released with the paper [GPT-NeoX-20B: An Open-Source Autoregressive Language Model](https://huggingface.co/papers/2204.06745) by Sid Black, Stella Biderman, Eric Hallahan, Quentin Anthony, Leo Gao, Laurence Golding, Horace He, Connor Leahy, Kyle McDonell, Jason Phang, Michael Pieler, USVSN Sai Prashanth, Shivanshu Purohit, Laria Reynolds, Jonathan Tow, Ben Wang, Samuel Weinbach +1. **[GPT-2](model_doc/gpt2)** (from OpenAI) released with the paper [Language Models are Unsupervised Multitask Learners](https://openai.com/research/better-language-models/) by Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei and Ilya Sutskever. +1. **[GPT-J](model_doc/gptj)** (from EleutherAI) released in the repository [kingoflolz/mesh-transformer-jax](https://github.com/kingoflolz/mesh-transformer-jax/) by Ben Wang and Aran Komatsuzaki. +1. **[GPTSAN-japanese](model_doc/gptsan-japanese)** released in the repository [tanreinama/GPTSAN](https://github.com/tanreinama/GPTSAN/blob/main/report/model.md) by Toshiyuki Sakamoto(tanreinama). +1. **[GroupViT](model_doc/groupvit)** (from UCSD, NVIDIA) released with the paper [GroupViT: Semantic Segmentation Emerges from Text Supervision](https://huggingface.co/papers/2202.11094) by Jiarui Xu, Shalini De Mello, Sifei Liu, Wonmin Byeon, Thomas Breuel, Jan Kautz, Xiaolong Wang. +1. **[Hubert](model_doc/hubert)** (from Facebook) released with the paper [HuBERT: Self-Supervised Speech Representation Learning by Masked Prediction of Hidden Units](https://huggingface.co/papers/2106.07447) by Wei-Ning Hsu, Benjamin Bolte, Yao-Hung Hubert Tsai, Kushal Lakhotia, Ruslan Salakhutdinov, Abdelrahman Mohamed. +1. **[I-BERT](model_doc/ibert)** (from Berkeley) released with the paper [I-BERT: Integer-only BERT Quantization](https://huggingface.co/papers/2101.01321) by Sehoon Kim, Amir Gholami, Zhewei Yao, Michael W. Mahoney, Kurt Keutzer. +1. **[ImageGPT](model_doc/imagegpt)** (from OpenAI) released with the paper [Generative Pretraining from Pixels](https://openai.com/blog/image-gpt/) by Mark Chen, Alec Radford, Rewon Child, Jeffrey Wu, Heewoo Jun, David Luan, Ilya Sutskever. +1. **[LayoutLM](model_doc/layoutlm)** (from Microsoft Research Asia) released with the paper [LayoutLM: Pre-training of Text and Layout for Document Image Understanding](https://huggingface.co/papers/1912.13318) by Yiheng Xu, Minghao Li, Lei Cui, Shaohan Huang, Furu Wei, Ming Zhou. +1. **[LayoutLMv2](model_doc/layoutlmv2)** (from Microsoft Research Asia) released with the paper [LayoutLMv2: Multi-modal Pre-training for Visually-Rich Document Understanding](https://huggingface.co/papers/2012.14740) by Yang Xu, Yiheng Xu, Tengchao Lv, Lei Cui, Furu Wei, Guoxin Wang, Yijuan Lu, Dinei Florencio, Cha Zhang, Wanxiang Che, Min Zhang, Lidong Zhou. +1. **[LayoutLMv3](model_doc/layoutlmv3)** (from Microsoft Research Asia) released with the paper [LayoutLMv3: Pre-training for Document AI with Unified Text and Image Masking](https://huggingface.co/papers/2204.08387) by Yupan Huang, Tengchao Lv, Lei Cui, Yutong Lu, Furu Wei. +1. **[LayoutXLM](model_doc/layoutxlm)** (from Microsoft Research Asia) released with the paper [LayoutXLM: Multimodal Pre-training for Multilingual Visually-rich Document Understanding](https://huggingface.co/papers/2104.08836) by Yiheng Xu, Tengchao Lv, Lei Cui, Guoxin Wang, Yijuan Lu, Dinei Florencio, Cha Zhang, Furu Wei. +1. **[LED](model_doc/led)** (from AllenAI) released with the paper [Longformer: The Long-Document Transformer](https://huggingface.co/papers/2004.05150) by Iz Beltagy, Matthew E. Peters, Arman Cohan. +1. **[LeViT](model_doc/levit)** (from Meta AI) released with the paper [LeViT: A Vision Transformer in ConvNet's Clothing for Faster Inference](https://huggingface.co/papers/2104.01136) by Ben Graham, Alaaeldin El-Nouby, Hugo Touvron, Pierre Stock, Armand Joulin, Hervé Jégou, Matthijs Douze. +1. **[Longformer](model_doc/longformer)** (from AllenAI) released with the paper [Longformer: The Long-Document Transformer](https://huggingface.co/papers/2004.05150) by Iz Beltagy, Matthew E. Peters, Arman Cohan. +1. **[LongT5](model_doc/longt5)** (from Google AI) released with the paper [LongT5: Efficient Text-To-Text Transformer for Long Sequences](https://huggingface.co/papers/2112.07916) by Mandy Guo, Joshua Ainslie, David Uthus, Santiago Ontanon, Jianmo Ni, Yun-Hsuan Sung, Yinfei Yang. +1. **[LUKE](model_doc/luke)** (from Studio Ousia) released with the paper [LUKE: Deep Contextualized Entity Representations with Entity-aware Self-attention](https://huggingface.co/papers/2010.01057) by Ikuya Yamada, Akari Asai, Hiroyuki Shindo, Hideaki Takeda, Yuji Matsumoto. +1. **[LXMERT](model_doc/lxmert)** (from UNC Chapel Hill) released with the paper [LXMERT: Learning Cross-Modality Encoder Representations from Transformers for Open-Domain Question Answering](https://huggingface.co/papers/1908.07490) by Hao Tan and Mohit Bansal. +1. **[M-CTC-T](model_doc/mctct)** (from Facebook) released with the paper [Pseudo-Labeling For Massively Multilingual Speech Recognition](https://huggingface.co/papers/2111.00161) by Loren Lugosch, Tatiana Likhomanenko, Gabriel Synnaeve, and Ronan Collobert. +1. **[M2M100](model_doc/m2m_100)** (from Facebook) released with the paper [Beyond English-Centric Multilingual Machine Translation](https://huggingface.co/papers/2010.11125) by Angela Fan, Shruti Bhosale, Holger Schwenk, Zhiyi Ma, Ahmed El-Kishky, Siddharth Goyal, Mandeep Baines, Onur Celebi, Guillaume Wenzek, Vishrav Chaudhary, Naman Goyal, Tom Birch, Vitaliy Liptchinsky, Sergey Edunov, Edouard Grave, Michael Auli, Armand Joulin. +1. **[MarianMT](model_doc/marian)** Machine translation models trained using [OPUS](http://opus.nlpl.eu/) data by Jörg Tiedemann. The [Marian Framework](https://marian-nmt.github.io/) is being developed by the Microsoft Translator Team. +1. **[Mask2Former](model_doc/mask2former)** (from FAIR and UIUC) released with the paper [Masked-attention Mask Transformer for Universal Image Segmentation](https://huggingface.co/papers/2112.01527) by Bowen Cheng, Ishan Misra, Alexander G. Schwing, Alexander Kirillov, Rohit Girdhar. +1. **[MaskFormer](model_doc/maskformer)** (from Meta and UIUC) released with the paper [Per-Pixel Classification is Not All You Need for Semantic Segmentation](https://huggingface.co/papers/2107.06278) by Bowen Cheng, Alexander G. Schwing, Alexander Kirillov. +1. **[mBART](model_doc/mbart)** (from Facebook) released with the paper [Multilingual Denoising Pre-training for Neural Machine Translation](https://huggingface.co/papers/2001.08210) by Yinhan Liu, Jiatao Gu, Naman Goyal, Xian Li, Sergey Edunov, Marjan Ghazvininejad, Mike Lewis, Luke Zettlemoyer. +1. **[mBART-50](model_doc/mbart)** (from Facebook) released with the paper [Multilingual Translation with Extensible Multilingual Pretraining and Finetuning](https://huggingface.co/papers/2008.00401) by Yuqing Tang, Chau Tran, Xian Li, Peng-Jen Chen, Naman Goyal, Vishrav Chaudhary, Jiatao Gu, Angela Fan. +1. **[Megatron-BERT](model_doc/megatron-bert)** (from NVIDIA) released with the paper [Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://huggingface.co/papers/1909.08053) by Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper and Bryan Catanzaro. +1. **[Megatron-GPT2](model_doc/megatron_gpt2)** (from NVIDIA) released with the paper [Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://huggingface.co/papers/1909.08053) by Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper and Bryan Catanzaro. +1. **[mLUKE](model_doc/mluke)** (from Studio Ousia) released with the paper [mLUKE: The Power of Entity Representations in Multilingual Pretrained Language Models](https://huggingface.co/papers/2110.08151) by Ryokan Ri, Ikuya Yamada, and Yoshimasa Tsuruoka. +1. **[MobileBERT](model_doc/mobilebert)** (from CMU/Google Brain) released with the paper [MobileBERT: a Compact Task-Agnostic BERT for Resource-Limited Devices](https://huggingface.co/papers/2004.02984) by Zhiqing Sun, Hongkun Yu, Xiaodan Song, Renjie Liu, Yiming Yang, and Denny Zhou. +1. **[MobileViT](model_doc/mobilevit)** (from Apple) released with the paper [MobileViT: Light-weight, General-purpose, and Mobile-friendly Vision Transformer](https://huggingface.co/papers/2110.02178) by Sachin Mehta and Mohammad Rastegari. +1. **[MPNet](model_doc/mpnet)** (from Microsoft Research) released with the paper [MPNet: Masked and Permuted Pre-training for Language Understanding](https://huggingface.co/papers/2004.09297) by Kaitao Song, Xu Tan, Tao Qin, Jianfeng Lu, Tie-Yan Liu. +1. **[MT5](model_doc/mt5)** (from Google AI) released with the paper [mT5: A massively multilingual pre-trained text-to-text transformer](https://huggingface.co/papers/2010.11934) by Linting Xue, Noah Constant, Adam Roberts, Mihir Kale, Rami Al-Rfou, Aditya Siddhant, Aditya Barua, Colin Raffel. +1. **[MVP](model_doc/mvp)** (from RUC AI Box) released with the paper [MVP: Multi-task Supervised Pre-training for Natural Language Generation](https://huggingface.co/papers/2206.12131) by Tianyi Tang, Junyi Li, Wayne Xin Zhao and Ji-Rong Wen. +1. **[Nezha](model_doc/nezha)** (from Huawei Noah’s Ark Lab) released with the paper [NEZHA: Neural Contextualized Representation for Chinese Language Understanding](https://huggingface.co/papers/1909.00204) by Junqiu Wei, Xiaozhe Ren, Xiaoguang Li, Wenyong Huang, Yi Liao, Yasheng Wang, Jiashu Lin, Xin Jiang, Xiao Chen and Qun Liu. +1. **[NLLB](model_doc/nllb)** (from Meta) released with the paper [No Language Left Behind: Scaling Human-Centered Machine Translation](https://huggingface.co/papers/2207.04672) by the NLLB team. +1. **[Nyströmformer](model_doc/nystromformer)** (from the University of Wisconsin - Madison) released with the paper [Nyströmformer: A Nyström-Based Algorithm for Approximating Self-Attention](https://huggingface.co/papers/2102.03902) by Yunyang Xiong, Zhanpeng Zeng, Rudrasis Chakraborty, Mingxing Tan, Glenn Fung, Yin Li, Vikas Singh. +1. **[OneFormer](model_doc/oneformer)** (from SHI Labs) released with the paper [OneFormer: One Transformer to Rule Universal Image Segmentation](https://huggingface.co/papers/2211.06220) by Jitesh Jain, Jiachen Li, MangTik Chiu, Ali Hassani, Nikita Orlov, Humphrey Shi. +1. **[OPT](master/model_doc/opt)** (from Meta AI) released with the paper [OPT: Open Pre-trained Transformer Language Models](https://huggingface.co/papers/2205.01068) by Susan Zhang, Stephen Roller, Naman Goyal, Mikel Artetxe, Moya Chen, Shuohui Chen et al. +1. **[OWL-ViT](model_doc/owlvit)** (from Google AI) released with the paper [Simple Open-Vocabulary Object Detection with Vision Transformers](https://huggingface.co/papers/2205.06230) by Matthias Minderer, Alexey Gritsenko, Austin Stone, Maxim Neumann, Dirk Weissenborn, Alexey Dosovitskiy, Aravindh Mahendran, Anurag Arnab, Mostafa Dehghani, Zhuoran Shen, Xiao Wang, Xiaohua Zhai, Thomas Kipf, and Neil Houlsby. +1. **[Pegasus](model_doc/pegasus)** (from Google) released with the paper [PEGASUS: Pre-training with Extracted Gap-sentences for Abstractive Summarization](https://huggingface.co/papers/1912.08777) by Jingqing Zhang, Yao Zhao, Mohammad Saleh and Peter J. Liu. +1. **[Perceiver IO](model_doc/perceiver)** (from Deepmind) released with the paper [Perceiver IO: A General Architecture for Structured Inputs & Outputs](https://huggingface.co/papers/2107.14795) by Andrew Jaegle, Sebastian Borgeaud, Jean-Baptiste Alayrac, Carl Doersch, Catalin Ionescu, David Ding, Skanda Koppula, Daniel Zoran, Andrew Brock, Evan Shelhamer, Olivier Hénaff, Matthew M. Botvinick, Andrew Zisserman, Oriol Vinyals, João Carreira. +1. **[PhoBERT](model_doc/phobert)** (from VinAI Research) released with the paper [PhoBERT: Pre-trained language models for Vietnamese](https://www.aclweb.org/anthology/2020.findings-emnlp.92/) by Dat Quoc Nguyen and Anh Tuan Nguyen. +1. **[PLBart](model_doc/plbart)** (from UCLA NLP) released with the paper [Unified Pre-training for Program Understanding and Generation](https://huggingface.co/papers/2103.06333) by Wasi Uddin Ahmad, Saikat Chakraborty, Baishakhi Ray, Kai-Wei Chang. +1. **[PoolFormer](model_doc/poolformer)** (from Sea AI Labs) released with the paper [MetaFormer is Actually What You Need for Vision](https://huggingface.co/papers/2111.11418) by Yu, Weihao and Luo, Mi and Zhou, Pan and Si, Chenyang and Zhou, Yichen and Wang, Xinchao and Feng, Jiashi and Yan, Shuicheng. +1. **[ProphetNet](model_doc/prophetnet)** (from Microsoft Research) released with the paper [ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training](https://huggingface.co/papers/2001.04063) by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou. +1. **[QDQBert](model_doc/qdqbert)** (from NVIDIA) released with the paper [Integer Quantization for Deep Learning Inference: Principles and Empirical Evaluation](https://huggingface.co/papers/2004.09602) by Hao Wu, Patrick Judd, Xiaojie Zhang, Mikhail Isaev and Paulius Micikevicius. +1. **[RAG](model_doc/rag)** (from Facebook) released with the paper [Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks](https://huggingface.co/papers/2005.11401) by Patrick Lewis, Ethan Perez, Aleksandara Piktus, Fabio Petroni, Vladimir Karpukhin, Naman Goyal, Heinrich Küttler, Mike Lewis, Wen-tau Yih, Tim Rocktäschel, Sebastian Riedel, Douwe Kiela. +1. **[REALM](model_doc/realm.html)** (from Google Research) released with the paper [REALM: Retrieval-Augmented Language Model Pre-Training](https://huggingface.co/papers/2002.08909) by Kelvin Guu, Kenton Lee, Zora Tung, Panupong Pasupat and Ming-Wei Chang. +1. **[Reformer](model_doc/reformer)** (from Google Research) released with the paper [Reformer: The Efficient Transformer](https://huggingface.co/papers/2001.04451) by Nikita Kitaev, Łukasz Kaiser, Anselm Levskaya. +1. **[RegNet](model_doc/regnet)** (from META Platforms) released with the paper [Designing Network Design Space](https://huggingface.co/papers/2003.13678) by Ilija Radosavovic, Raj Prateek Kosaraju, Ross Girshick, Kaiming He, Piotr Dollár. +1. **[RemBERT](model_doc/rembert)** (from Google Research) released with the paper [Rethinking embedding coupling in pre-trained language models](https://huggingface.co/papers/2010.12821) by Hyung Won Chung, Thibault Févry, Henry Tsai, M. Johnson, Sebastian Ruder. +1. **[ResNet](model_doc/resnet)** (from Microsoft Research) released with the paper [Deep Residual Learning for Image Recognition](https://huggingface.co/papers/1512.03385) by Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun. +1. **[RoBERTa](model_doc/roberta)** (from Facebook), released together with the paper [RoBERTa: A Robustly Optimized BERT Pretraining Approach](https://huggingface.co/papers/1907.11692) by Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, Veselin Stoyanov. +1. **[RoFormer](model_doc/roformer)** (from ZhuiyiTechnology), released together with the paper [RoFormer: Enhanced Transformer with Rotary Position Embedding](https://huggingface.co/papers/2104.09864) by Jianlin Su and Yu Lu and Shengfeng Pan and Bo Wen and Yunfeng Liu. +1. **[SegFormer](model_doc/segformer)** (from NVIDIA) released with the paper [SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers](https://huggingface.co/papers/2105.15203) by Enze Xie, Wenhai Wang, Zhiding Yu, Anima Anandkumar, Jose M. Alvarez, Ping Luo. +1. **[SEW](model_doc/sew)** (from ASAPP) released with the paper [Performance-Efficiency Trade-offs in Unsupervised Pre-training for Speech Recognition](https://huggingface.co/papers/2109.06870) by Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi. +1. **[SEW-D](model_doc/sew_d)** (from ASAPP) released with the paper [Performance-Efficiency Trade-offs in Unsupervised Pre-training for Speech Recognition](https://huggingface.co/papers/2109.06870) by Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi. +1. **[SpeechToTextTransformer](model_doc/speech_to_text)** (from Facebook), released together with the paper [fairseq S2T: Fast Speech-to-Text Modeling with fairseq](https://huggingface.co/papers/2010.05171) by Changhan Wang, Yun Tang, Xutai Ma, Anne Wu, Dmytro Okhonko, Juan Pino. +1. **[SpeechToTextTransformer2](model_doc/speech_to_text_2)** (from Facebook), released together with the paper [Large-Scale Self- and Semi-Supervised Learning for Speech Translation](https://huggingface.co/papers/2104.06678) by Changhan Wang, Anne Wu, Juan Pino, Alexei Baevski, Michael Auli, Alexis Conneau. +1. **[Splinter](model_doc/splinter)** (from Tel Aviv University), released together with the paper [Few-Shot Question Answering by Pretraining Span Selection](https://huggingface.co/papers/2101.00438) by Ori Ram, Yuval Kirstain, Jonathan Berant, Amir Globerson, Omer Levy. +1. **[SqueezeBERT](model_doc/squeezebert)** (from Berkeley) released with the paper [SqueezeBERT: What can computer vision teach NLP about efficient neural networks?](https://huggingface.co/papers/2006.11316) by Forrest N. Iandola, Albert E. Shaw, Ravi Krishna, and Kurt W. Keutzer. +1. **[Swin Transformer](model_doc/swin)** (from Microsoft) released with the paper [Swin Transformer: Hierarchical Vision Transformer using Shifted Windows](https://huggingface.co/papers/2103.14030) by Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin, Baining Guo. +1. **[Swin Transformer V2](model_doc/swinv2)** (from Microsoft) released with the paper [Swin Transformer V2: Scaling Up Capacity and Resolution](https://huggingface.co/papers/2111.09883) by Ze Liu, Han Hu, Yutong Lin, Zhuliang Yao, Zhenda Xie, Yixuan Wei, Jia Ning, Yue Cao, Zheng Zhang, Li Dong, Furu Wei, Baining Guo. +1. **[T5](model_doc/t5)** (from Google AI) released with the paper [Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer](https://huggingface.co/papers/1910.10683) by Colin Raffel and Noam Shazeer and Adam Roberts and Katherine Lee and Sharan Narang and Michael Matena and Yanqi Zhou and Wei Li and Peter J. Liu. +1. **[T5v1.1](model_doc/t5v1.1)** (from Google AI) released in the repository [google-research/text-to-text-transfer-transformer](https://github.com/google-research/text-to-text-transfer-transformer/blob/main/released_checkpoints.md#t511) by Colin Raffel and Noam Shazeer and Adam Roberts and Katherine Lee and Sharan Narang and Michael Matena and Yanqi Zhou and Wei Li and Peter J. Liu. +1. **[TAPAS](model_doc/tapas)** (from Google AI) released with the paper [TAPAS: Weakly Supervised Table Parsing via Pre-training](https://huggingface.co/papers/2004.02349) by Jonathan Herzig, Paweł Krzysztof Nowak, Thomas Müller, Francesco Piccinno and Julian Martin Eisenschlos. +1. **[TAPEX](model_doc/tapex)** (from Microsoft Research) released with the paper [TAPEX: Table Pre-training via Learning a Neural SQL Executor](https://huggingface.co/papers/2107.07653) by Qian Liu, Bei Chen, Jiaqi Guo, Morteza Ziyadi, Zeqi Lin, Weizhu Chen, Jian-Guang Lou. +1. **[Trajectory Transformer](model_doc/trajectory_transformers)** (from the University of California at Berkeley) released with the paper [Offline Reinforcement Learning as One Big Sequence Modeling Problem](https://huggingface.co/papers/2106.02039) by Michael Janner, Qiyang Li, Sergey Levine +1. **[Transformer-XL](model_doc/transfo-xl)** (from Google/CMU) released with the paper [Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context](https://huggingface.co/papers/1901.02860) by Zihang Dai*, Zhilin Yang*, Yiming Yang, Jaime Carbonell, Quoc V. Le, Ruslan Salakhutdinov. +1. **[TrOCR](model_doc/trocr)** (from Microsoft), released together with the paper [TrOCR: Transformer-based Optical Character Recognition with Pre-trained Models](https://huggingface.co/papers/2109.10282) by Minghao Li, Tengchao Lv, Lei Cui, Yijuan Lu, Dinei Florencio, Cha Zhang, Zhoujun Li, Furu Wei. +1. **[UL2](model_doc/ul2)** (from Google Research) released with the paper [Unifying Language Learning Paradigms](https://huggingface.co/papers/2205.05131v1) by Yi Tay, Mostafa Dehghani, Vinh Q. Tran, Xavier Garcia, Dara Bahri, Tal Schuster, Huaixiu Steven Zheng, Neil Houlsby, Donald Metzler +1. **[UMT5](model_doc/umt5)** (from Google Research) released with the paper [UniMax: Fairer and More Effective Language Sampling for Large-Scale Multilingual Pretraining](https://openreview.net/forum?id=kXwdL1cWOAi) by Hyung Won Chung, Xavier Garcia, Adam Roberts, Yi Tay, Orhan Firat, Sharan Narang, Noah Constant. +1. **[UniSpeech](model_doc/unispeech)** (from Microsoft Research) released with the paper [UniSpeech: Unified Speech Representation Learning with Labeled and Unlabeled Data](https://huggingface.co/papers/2101.07597) by Chengyi Wang, Yu Wu, Yao Qian, Kenichi Kumatani, Shujie Liu, Furu Wei, Michael Zeng, Xuedong Huang. +1. **[UniSpeechSat](model_doc/unispeech-sat)** (from Microsoft Research) released with the paper [UNISPEECH-SAT: UNIVERSAL SPEECH REPRESENTATION LEARNING WITH SPEAKER AWARE PRE-TRAINING](https://huggingface.co/papers/2110.05752) by Sanyuan Chen, Yu Wu, Chengyi Wang, Zhengyang Chen, Zhuo Chen, Shujie Liu, Jian Wu, Yao Qian, Furu Wei, Jinyu Li, Xiangzhan Yu. +1. **[VAN](model_doc/van)** (from Tsinghua University and Nankai University) released with the paper [Visual Attention Network](https://huggingface.co/papers/2202.09741) by Meng-Hao Guo, Cheng-Ze Lu, Zheng-Ning Liu, Ming-Ming Cheng, Shi-Min Hu. +1. **[VideoMAE](model_doc/videomae)** (from Multimedia Computing Group, Nanjing University) released with the paper [VideoMAE: Masked Autoencoders are Data-Efficient Learners for Self-Supervised Video Pre-Training](https://huggingface.co/papers/2203.12602) by Zhan Tong, Yibing Song, Jue Wang, Limin Wang. +1. **[ViLT](model_doc/vilt)** (from NAVER AI Lab/Kakao Enterprise/Kakao Brain) released with the paper [ViLT: Vision-and-Language Transformer Without Convolution or Region Supervision](https://huggingface.co/papers/2102.03334) by Wonjae Kim, Bokyung Son, Ildoo Kim. +1. **[Vision Transformer (ViT)](model_doc/vit)** (from Google AI) released with the paper [An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale](https://huggingface.co/papers/2010.11929) by Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob Uszkoreit, Neil Houlsby. +1. **[VisualBERT](model_doc/visual_bert)** (from UCLA NLP) released with the paper [VisualBERT: A Simple and Performant Baseline for Vision and Language](https://huggingface.co/papers/1908.03557) by Liunian Harold Li, Mark Yatskar, Da Yin, Cho-Jui Hsieh, Kai-Wei Chang. +1. **[ViTMAE](model_doc/vit_mae)** (from Meta AI) released with the paper [Masked Autoencoders Are Scalable Vision Learners](https://huggingface.co/papers/2111.06377) by Kaiming He, Xinlei Chen, Saining Xie, Yanghao Li, Piotr Dollár, Ross Girshick. +1. **[Wav2Vec2](model_doc/wav2vec2)** (from Facebook AI) released with the paper [wav2vec 2.0: A Framework for Self-Supervised Learning of Speech Representations](https://huggingface.co/papers/2006.11477) by Alexei Baevski, Henry Zhou, Abdelrahman Mohamed, Michael Auli. +1. **[Wav2Vec2-Conformer](model_doc/wav2vec2-conformer)** (from Facebook AI) released with the paper [FAIRSEQ S2T: Fast Speech-to-Text Modeling with FAIRSEQ](https://huggingface.co/papers/2010.05171) by Changhan Wang, Yun Tang, Xutai Ma, Anne Wu, Sravya Popuri, Dmytro Okhonko, Juan Pino. +1. **[Wav2Vec2Phoneme](model_doc/wav2vec2_phoneme)** (from Facebook AI) released with the paper [Simple and Effective Zero-shot Cross-lingual Phoneme Recognition](https://huggingface.co/papers/2109.11680) by Qiantong Xu, Alexei Baevski, Michael Auli. +1. **[WavLM](model_doc/wavlm)** (from Microsoft Research) released with the paper [WavLM: Large-Scale Self-Supervised Pre-Training for Full Stack Speech Processing](https://huggingface.co/papers/2110.13900) by Sanyuan Chen, Chengyi Wang, Zhengyang Chen, Yu Wu, Shujie Liu, Zhuo Chen, Jinyu Li, Naoyuki Kanda, Takuya Yoshioka, Xiong Xiao, Jian Wu, Long Zhou, Shuo Ren, Yanmin Qian, Yao Qian, Jian Wu, Michael Zeng, Furu Wei. +1. **[XGLM](model_doc/xglm)** (From Facebook AI) released with the paper [Few-shot Learning with Multilingual Language Models](https://huggingface.co/papers/2112.10668) by Xi Victoria Lin, Todor Mihaylov, Mikel Artetxe, Tianlu Wang, Shuohui Chen, Daniel Simig, Myle Ott, Naman Goyal, Shruti Bhosale, Jingfei Du, Ramakanth Pasunuru, Sam Shleifer, Punit Singh Koura, Vishrav Chaudhary, Brian O'Horo, Jeff Wang, Luke Zettlemoyer, Zornitsa Kozareva, Mona Diab, Veselin Stoyanov, Xian Li. +1. **[XLM](model_doc/xlm)** (from Facebook) released together with the paper [Cross-lingual Language Model Pretraining](https://huggingface.co/papers/1901.07291) by Guillaume Lample and Alexis Conneau. +1. **[XLM-ProphetNet](model_doc/xlm-prophetnet)** (from Microsoft Research) released with the paper [ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training](https://huggingface.co/papers/2001.04063) by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou. +1. **[XLM-RoBERTa](model_doc/xlm-roberta)** (from Facebook AI), released together with the paper [Unsupervised Cross-lingual Representation Learning at Scale](https://huggingface.co/papers/1911.02116) by Alexis Conneau*, Kartikay Khandelwal*, Naman Goyal, Vishrav Chaudhary, Guillaume Wenzek, Francisco Guzmán, Edouard Grave, Myle Ott, Luke Zettlemoyer and Veselin Stoyanov. +1. **[XLM-RoBERTa-XL](model_doc/xlm-roberta-xl)** (from Facebook AI), released together with the paper [Larger-Scale Transformers for Multilingual Masked Language Modeling](https://huggingface.co/papers/2105.00572) by Naman Goyal, Jingfei Du, Myle Ott, Giri Anantharaman, Alexis Conneau. +1. **[XLM-V](model_doc/xlm-v)** (from Meta AI) released with the paper [XLM-V: Overcoming the Vocabulary Bottleneck in Multilingual Masked Language Models](https://huggingface.co/papers/2301.10472) by Davis Liang, Hila Gonen, Yuning Mao, Rui Hou, Naman Goyal, Marjan Ghazvininejad, Luke Zettlemoyer, Madian Khabsa. +1. **[XLNet](model_doc/xlnet)** (from Google/CMU) released with the paper [​XLNet: Generalized Autoregressive Pretraining for Language Understanding](https://huggingface.co/papers/1906.08237) by Zhilin Yang*, Zihang Dai*, Yiming Yang, Jaime Carbonell, Ruslan Salakhutdinov, Quoc V. Le. +1. **[XLS-R](model_doc/xls_r)** (from Facebook AI) released with the paper [XLS-R: Self-supervised Cross-lingual Speech Representation Learning at Scale](https://huggingface.co/papers/2111.09296) by Arun Babu, Changhan Wang, Andros Tjandra, Kushal Lakhotia, Qiantong Xu, Naman Goyal, Kritika Singh, Patrick von Platen, Yatharth Saraf, Juan Pino, Alexei Baevski, Alexis Conneau, Michael Auli. +1. **[XLSR-Wav2Vec2](model_doc/xlsr_wav2vec2)** (from Facebook AI) released with the paper [Unsupervised Cross-Lingual Representation Learning For Speech Recognition](https://huggingface.co/papers/2006.13979) by Alexis Conneau, Alexei Baevski, Ronan Collobert, Abdelrahman Mohamed, Michael Auli. +1. **[YOLOS](model_doc/yolos)** (from Huazhong University of Science & Technology) released with the paper [You Only Look at One Sequence: Rethinking Transformer in Vision through Object Detection](https://huggingface.co/papers/2106.00666) by Yuxin Fang, Bencheng Liao, Xinggang Wang, Jiemin Fang, Jiyang Qi, Rui Wu, Jianwei Niu, Wenyu Liu. +1. **[YOSO](model_doc/yoso)** (from the University of Wisconsin - Madison) released with the paper [You Only Sample (Almost) Once: Linear Cost Self-Attention Via Bernoulli Sampling](https://huggingface.co/papers/2111.09714) by Zhanpeng Zeng, Yunyang Xiong, Sathya N. Ravi, Shailesh Acharya, Glenn Fung, Vikas Singh. + + +### Unterstützte Frameworks + +Die folgende Tabelle zeigt die derzeitige Unterstützung in der Bibliothek für jedes dieser Modelle, unabhängig davon, ob sie einen Python +Tokenizer haben (als "langsam" bezeichnet), ein "schneller" Tokenizer, der von der 🤗 Tokenizers Bibliothek unterstützt wird, ob sie Unterstützung in Jax (via +Flax), PyTorch, und/oder TensorFlow haben. + + + +| Model | Tokenizer slow | Tokenizer fast | PyTorch support | TensorFlow support | Flax Support | +|:---------------------------:|:--------------:|:--------------:|:---------------:|:------------------:|:------------:| +| ALBERT | ✅ | ✅ | ✅ | ✅ | ✅ | +| BART | ✅ | ✅ | ✅ | ✅ | ✅ | +| BEiT | ❌ | ❌ | ✅ | ❌ | ✅ | +| BERT | ✅ | ✅ | ✅ | ✅ | ✅ | +| Bert Generation | ✅ | ❌ | ✅ | ❌ | ❌ | +| BigBird | ✅ | ✅ | ✅ | ❌ | ✅ | +| BigBird-Pegasus | ❌ | ❌ | ✅ | ❌ | ❌ | +| Blenderbot | ✅ | ✅ | ✅ | ✅ | ✅ | +| BlenderbotSmall | ✅ | ✅ | ✅ | ✅ | ✅ | +| BLOOM | ❌ | ✅ | ✅ | ❌ | ✅ | +| CamemBERT | ✅ | ✅ | ✅ | ✅ | ❌ | +| CANINE | ✅ | ❌ | ✅ | ❌ | ❌ | +| CLIP | ✅ | ✅ | ✅ | ✅ | ✅ | +| CodeGen | ✅ | ✅ | ✅ | ❌ | ❌ | +| ConvBERT | ✅ | ✅ | ✅ | ✅ | ❌ | +| ConvNeXT | ❌ | ❌ | ✅ | ✅ | ❌ | +| CTRL | ✅ | ❌ | ✅ | ✅ | ❌ | +| CvT | ❌ | ❌ | ✅ | ❌ | ❌ | +| Data2VecAudio | ❌ | ❌ | ✅ | ❌ | ❌ | +| Data2VecText | ❌ | ❌ | ✅ | ❌ | ❌ | +| Data2VecVision | ❌ | ❌ | ✅ | ✅ | ❌ | +| DeBERTa | ✅ | ✅ | ✅ | ✅ | ❌ | +| DeBERTa-v2 | ✅ | ✅ | ✅ | ✅ | ❌ | +| Decision Transformer | ❌ | ❌ | ✅ | ❌ | ❌ | +| DeiT | ❌ | ❌ | ✅ | ✅ | ❌ | +| DETR | ❌ | ❌ | ✅ | ❌ | ❌ | +| DistilBERT | ✅ | ✅ | ✅ | ✅ | ✅ | +| DPR | ✅ | ✅ | ✅ | ✅ | ❌ | +| DPT | ❌ | ❌ | ✅ | ❌ | ❌ | +| ELECTRA | ✅ | ✅ | ✅ | ✅ | ✅ | +| Encoder decoder | ❌ | ❌ | ✅ | ✅ | ✅ | +| FairSeq Machine-Translation | ✅ | ❌ | ✅ | ❌ | ❌ | +| FlauBERT | ✅ | ❌ | ✅ | ✅ | ❌ | +| FLAVA | ❌ | ❌ | ✅ | ❌ | ❌ | +| FNet | ✅ | ✅ | ✅ | ❌ | ❌ | +| Funnel Transformer | ✅ | ✅ | ✅ | ✅ | ❌ | +| GLPN | ❌ | ❌ | ✅ | ❌ | ❌ | +| GPT Neo | ❌ | ❌ | ✅ | ❌ | ✅ | +| GPT NeoX | ❌ | ✅ | ✅ | ❌ | ❌ | +| GPT-J | ❌ | ❌ | ✅ | ✅ | ✅ | +| GroupViT | ❌ | ❌ | ✅ | ❌ | ❌ | +| Hubert | ❌ | ❌ | ✅ | ✅ | ❌ | +| I-BERT | ❌ | ❌ | ✅ | ❌ | ❌ | +| ImageGPT | ❌ | ❌ | ✅ | ❌ | ❌ | +| LayoutLM | ✅ | ✅ | ✅ | ✅ | ❌ | +| LayoutLMv2 | ✅ | ✅ | ✅ | ❌ | ❌ | +| LayoutLMv3 | ✅ | ✅ | ✅ | ❌ | ❌ | +| LED | ✅ | ✅ | ✅ | ✅ | ❌ | +| LeViT | ❌ | ❌ | ✅ | ❌ | ❌ | +| Longformer | ✅ | ✅ | ✅ | ✅ | ❌ | +| LongT5 | ❌ | ❌ | ✅ | ❌ | ✅ | +| LUKE | ✅ | ❌ | ✅ | ❌ | ❌ | +| LXMERT | ✅ | ✅ | ✅ | ✅ | ❌ | +| M-CTC-T | ❌ | ❌ | ✅ | ❌ | ❌ | +| M2M100 | ✅ | ❌ | ✅ | ❌ | ❌ | +| Marian | ✅ | ❌ | ✅ | ✅ | ✅ | +| MaskFormer | ❌ | ❌ | ✅ | ❌ | ❌ | +| mBART | ✅ | ✅ | ✅ | ✅ | ✅ | +| Megatron-BERT | ❌ | ❌ | ✅ | ❌ | ❌ | +| MobileBERT | ✅ | ✅ | ✅ | ✅ | ❌ | +| MobileViT | ❌ | ❌ | ✅ | ❌ | ❌ | +| MPNet | ✅ | ✅ | ✅ | ✅ | ❌ | +| MT5 | ✅ | ✅ | ✅ | ✅ | ✅ | +| MVP | ✅ | ✅ | ✅ | ❌ | ❌ | +| Nezha | ❌ | ❌ | ✅ | ❌ | ❌ | +| Nyströmformer | ❌ | ❌ | ✅ | ❌ | ❌ | +| OpenAI GPT | ✅ | ✅ | ✅ | ✅ | ❌ | +| OpenAI GPT-2 | ✅ | ✅ | ✅ | ✅ | ✅ | +| OPT | ❌ | ❌ | ✅ | ✅ | ✅ | +| OWL-ViT | ❌ | ❌ | ✅ | ❌ | ❌ | +| Pegasus | ✅ | ✅ | ✅ | ✅ | ✅ | +| Perceiver | ✅ | ❌ | ✅ | ❌ | ❌ | +| PLBart | ✅ | ❌ | ✅ | ❌ | ❌ | +| PoolFormer | ❌ | ❌ | ✅ | ❌ | ❌ | +| ProphetNet | ✅ | ❌ | ✅ | ❌ | ❌ | +| QDQBert | ❌ | ❌ | ✅ | ❌ | ❌ | +| RAG | ✅ | ❌ | ✅ | ✅ | ❌ | +| REALM | ✅ | ✅ | ✅ | ❌ | ❌ | +| Reformer | ✅ | ✅ | ✅ | ❌ | ❌ | +| RegNet | ❌ | ❌ | ✅ | ✅ | ✅ | +| RemBERT | ✅ | ✅ | ✅ | ✅ | ❌ | +| ResNet | ❌ | ❌ | ✅ | ✅ | ✅ | +| RetriBERT | ✅ | ✅ | ✅ | ❌ | ❌ | +| RoBERTa | ✅ | ✅ | ✅ | ✅ | ✅ | +| RoFormer | ✅ | ✅ | ✅ | ✅ | ✅ | +| SegFormer | ❌ | ❌ | ✅ | ✅ | ❌ | +| SEW | ❌ | ❌ | ✅ | ❌ | ❌ | +| SEW-D | ❌ | ❌ | ✅ | ❌ | ❌ | +| Speech Encoder decoder | ❌ | ❌ | ✅ | ❌ | ✅ | +| Speech2Text | ✅ | ❌ | ✅ | ✅ | ❌ | +| Speech2Text2 | ✅ | ❌ | ❌ | ❌ | ❌ | +| Splinter | ✅ | ✅ | ✅ | ❌ | ❌ | +| SqueezeBERT | ✅ | ✅ | ✅ | ❌ | ❌ | +| Swin Transformer | ❌ | ❌ | ✅ | ✅ | ❌ | +| Swin Transformer V2 | ❌ | ❌ | ✅ | ❌ | ❌ | +| T5 | ✅ | ✅ | ✅ | ✅ | ✅ | +| TAPAS | ✅ | ❌ | ✅ | ✅ | ❌ | +| Trajectory Transformer | ❌ | ❌ | ✅ | ❌ | ❌ | +| Transformer-XL | ✅ | ❌ | ✅ | ✅ | ❌ | +| TrOCR | ❌ | ❌ | ✅ | ❌ | ❌ | +| UniSpeech | ❌ | ❌ | ✅ | ❌ | ❌ | +| UniSpeechSat | ❌ | ❌ | ✅ | ❌ | ❌ | +| VAN | ❌ | ❌ | ✅ | ❌ | ❌ | +| VideoMAE | ❌ | ❌ | ✅ | ❌ | ❌ | +| ViLT | ❌ | ❌ | ✅ | ❌ | ❌ | +| Vision Encoder decoder | ❌ | ❌ | ✅ | ✅ | ✅ | +| VisionTextDualEncoder | ❌ | ❌ | ✅ | ❌ | ✅ | +| VisualBERT | ❌ | ❌ | ✅ | ❌ | ❌ | +| ViT | ❌ | ❌ | ✅ | ✅ | ✅ | +| ViTMAE | ❌ | ❌ | ✅ | ✅ | ❌ | +| Wav2Vec2 | ✅ | ❌ | ✅ | ✅ | ✅ | +| Wav2Vec2-Conformer | ❌ | ❌ | ✅ | ❌ | ❌ | +| WavLM | ❌ | ❌ | ✅ | ❌ | ❌ | +| XGLM | ✅ | ✅ | ✅ | ❌ | ✅ | +| XLM | ✅ | ❌ | ✅ | ✅ | ❌ | +| XLM-ProphetNet | ✅ | ❌ | ✅ | ❌ | ❌ | +| XLM-RoBERTa | ✅ | ✅ | ✅ | ✅ | ✅ | +| XLM-RoBERTa-XL | ❌ | ❌ | ✅ | ❌ | ❌ | +| XLNet | ✅ | ✅ | ✅ | ✅ | ❌ | +| YOLOS | ❌ | ❌ | ✅ | ❌ | ❌ | +| YOSO | ❌ | ❌ | ✅ | ❌ | ❌ | + + diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/installation.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/installation.md new file mode 100644 index 0000000000000000000000000000000000000000..44b6f1ed981e1ef3531a344877088290c3e7bdb8 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/installation.md @@ -0,0 +1,250 @@ + + +# Installation + +Installieren Sie 🤗 Transformers für die Deep-Learning-Bibliothek, mit der Sie arbeiten, richten Sie Ihren Cache ein und konfigurieren Sie 🤗 Transformers optional für den Offline-Betrieb. + +🤗 Transformers wurde unter Python 3.6+, PyTorch 1.1.0+, TensorFlow 2.0+, und Flax getestet. Folgen Sie den Installationsanweisungen unten für die von Ihnen verwendete Deep-Learning-Bibliothek: + +* [PyTorch](https://pytorch.org/get-started/locally/) installation instructions. +* [TensorFlow 2.0](https://www.tensorflow.org/install/pip) installation instructions. +* [Flax](https://flax.readthedocs.io/en/latest/) installation instructions. + +## Installation mit pip + +Sie sollten 🤗 Transformers in einer [virtuellen Umgebung](https://docs.python.org/3/library/venv.html) installieren. Wenn Sie mit virtuellen Python-Umgebungen nicht vertraut sind, werfen Sie einen Blick auf diese [Anleitung](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/). Eine virtuelle Umgebung macht es einfacher, verschiedene Projekte zu verwalten und Kompatibilitätsprobleme zwischen Abhängigkeiten zu vermeiden. + +Beginnen wir mit der Erstellung einer virtuellen Umgebung in Ihrem Projektverzeichnis: + + +```bash +python -m venv .env +``` + +Aktivieren wir die virtuelle Umgebung. Unter Linux und MacOs: + +```bash +source .env/bin/activate +``` +Aktivieren wir die virtuelle Umgebung unter Windows + +```bash +.env/Scripts/activate +``` + +Jetzt können wir die 🤗 Transformers mit dem folgenden Befehl installieren: + +```bash +pip install transformers +``` + +Bei reiner CPU-Unterstützung können wir 🤗 Transformers und eine Deep-Learning-Bibliothek bequem in einer Zeile installieren. Installieren wir zum Beispiel 🤗 Transformers und PyTorch mit: + +```bash +pip install transformers[torch] +``` + +🤗 Transformers und TensorFlow 2.0: + +```bash +pip install transformers[tf-cpu] +``` + +🤗 Transformers und Flax: + +```bash +pip install transformers[flax] +``` + +Überprüfen wir abschließend, ob 🤗 Transformers ordnungsgemäß installiert wurde, indem wir den folgenden Befehl ausführen. Es wird ein vortrainiertes Modell heruntergeladen: + +```bash +python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('we love you'))" +``` + +Dann wird die Kategorie und die Wahrscheinlichkeit ausgegeben: + +```bash +[{'label': 'POSITIVE', 'score': 0.9998704791069031}] +``` + +## Installation aus dem Code + +Installieren wir 🤗 Transformers aus dem Quellcode mit dem folgenden Befehl: + +```bash +pip install git+https://github.com/huggingface/transformers +``` + +Dieser Befehl installiert die aktuelle `main` Version und nicht die neueste `stable` Version. Die `main`-Version ist nützlich, um mit den neuesten Entwicklungen Schritt zu halten. Zum Beispiel, wenn ein Fehler seit der letzten offiziellen Version behoben wurde, aber eine neue Version noch nicht veröffentlicht wurde. Das bedeutet jedoch, dass die "Hauptversion" nicht immer stabil ist. Wir bemühen uns, die Hauptversion einsatzbereit zu halten, und die meisten Probleme werden normalerweise innerhalb weniger Stunden oder eines Tages behoben. Wenn Sie auf ein Problem stoßen, öffnen Sie bitte ein [Issue](https://github.com/huggingface/transformers/issues), damit wir es noch schneller beheben können! + +Überprüfen wir, ob 🤗 Transformers richtig installiert wurde, indem Sie den folgenden Befehl ausführen: + + +```bash +python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('I love you'))" +``` + +## Editierbare Installation + +Sie benötigen eine bearbeitbare Installation, wenn Sie: + +* die "Haupt"-Version des Quellcodes verwenden möchten. +* Zu 🤗 Transformers beitragen und Änderungen am Code testen wollen. + +Klonen Sie das Repository und installieren 🤗 Transformers mit den folgenden Befehlen: + +```bash +git clone https://github.com/huggingface/transformers.git +cd transformers +pip install -e . +``` + +Diese Befehle verknüpfen den Ordner, in den Sie das Repository geklont haben, mit den Pfaden Ihrer Python-Bibliotheken. Python wird nun in dem Ordner suchen, in den Sie geklont haben, zusätzlich zu den normalen Bibliothekspfaden. Wenn zum Beispiel Ihre Python-Pakete normalerweise in `~/anaconda3/envs/main/lib/python3.7/site-packages/` installiert sind, wird Python auch den Ordner durchsuchen, in den Sie geklont haben: `~/transformers/`. + + + + +Sie müssen den Ordner `transformers` behalten, wenn Sie die Bibliothek weiter verwenden wollen. + + + +Jetzt können Sie Ihren Klon mit dem folgenden Befehl ganz einfach auf die neueste Version von 🤗 Transformers aktualisieren: + + +```bash +cd ~/transformers/ +git pull +``` + +Ihre Python-Umgebung wird beim nächsten Ausführen die `main`-Version von 🤗 Transformers finden. + +## Installation mit conda + +Installation von dem conda Kanal `conda-forge`: + +```bash +conda install conda-forge::transformers +``` + +## Cache Einrichtung + +Vorgefertigte Modelle werden heruntergeladen und lokal zwischengespeichert unter: `~/.cache/huggingface/hub`. Dies ist das Standardverzeichnis, das durch die Shell-Umgebungsvariable "TRANSFORMERS_CACHE" vorgegeben ist. Unter Windows wird das Standardverzeichnis durch `C:\Benutzer\Benutzername\.cache\huggingface\hub` angegeben. Sie können die unten aufgeführten Shell-Umgebungsvariablen - in der Reihenfolge ihrer Priorität - ändern, um ein anderes Cache-Verzeichnis anzugeben: + +1. Shell-Umgebungsvariable (Standard): `HF_HUB_CACHE` oder `TRANSFORMERS_CACHE`. +2. Shell-Umgebungsvariable: `HF_HOME`. +3. Shell-Umgebungsvariable: `XDG_CACHE_HOME` + `/huggingface`. + + + + +Transformers verwendet die Shell-Umgebungsvariablen `PYTORCH_TRANSFORMERS_CACHE` oder `PYTORCH_PRETRAINED_BERT_CACHE`, wenn Sie von einer früheren Iteration dieser Bibliothek kommen und diese Umgebungsvariablen gesetzt haben, sofern Sie nicht die Shell-Umgebungsvariable `TRANSFORMERS_CACHE` angeben. + + + +## Offline Modus + +Transformers ist in der Lage, in einer Firewall- oder Offline-Umgebung zu laufen, indem es nur lokale Dateien verwendet. Setzen Sie die Umgebungsvariable `HF_HUB_OFFLINE=1`, um dieses Verhalten zu aktivieren. + + + +Fügen sie [🤗 Datasets](https://huggingface.co/docs/datasets/) zu Ihrem Offline-Trainingsworkflow hinzufügen, indem Sie die Umgebungsvariable `HF_DATASETS_OFFLINE=1` setzen. + + + +So würden Sie beispielsweise ein Programm in einem normalen Netzwerk mit einer Firewall für externe Instanzen mit dem folgenden Befehl ausführen: + +```bash +python examples/pytorch/translation/run_translation.py --model_name_or_path google-t5/t5-small --dataset_name wmt16 --dataset_config ro-en ... +``` + +Führen Sie das gleiche Programm in einer Offline-Instanz mit aus: + +```bash +HF_DATASETS_OFFLINE=1 HF_HUB_OFFLINE=1 \ +python examples/pytorch/translation/run_translation.py --model_name_or_path google-t5/t5-small --dataset_name wmt16 --dataset_config ro-en ... +``` + +Das Skript sollte nun laufen, ohne sich aufzuhängen oder eine Zeitüberschreitung abzuwarten, da es weiß, dass es nur nach lokalen Dateien suchen soll. + + +### Abrufen von Modellen und Tokenizern zur Offline-Verwendung + +Eine andere Möglichkeit, 🤗 Transformers offline zu verwenden, besteht darin, die Dateien im Voraus herunterzuladen und dann auf ihren lokalen Pfad zu verweisen, wenn Sie sie offline verwenden müssen. Es gibt drei Möglichkeiten, dies zu tun: + +* Laden Sie eine Datei über die Benutzeroberfläche des [Model Hub](https://huggingface.co/models) herunter, indem Sie auf das ↓-Symbol klicken. + + ![download-icon](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/download-icon.png) + +* Verwenden Sie den [PreTrainedModel.from_pretrained] und [PreTrainedModel.save_pretrained] Workflow: + + 1. Laden Sie Ihre Dateien im Voraus mit [`PreTrainedModel.from_pretrained`] herunter: + + ```py + >>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM + + >>> tokenizer = AutoTokenizer.from_pretrained("bigscience/T0_3B") + >>> model = AutoModelForSeq2SeqLM.from_pretrained("bigscience/T0_3B") + ``` + + 2. Speichern Sie Ihre Dateien in einem bestimmten Verzeichnis mit [`PreTrainedModel.save_pretrained`]: + + ```py + >>> tokenizer.save_pretrained("./your/path/bigscience_t0") + >>> model.save_pretrained("./your/path/bigscience_t0") + ``` + + 3. Wenn Sie nun offline sind, laden Sie Ihre Dateien mit [`PreTrainedModel.from_pretrained`] aus dem bestimmten Verzeichnis: + + ```py + >>> tokenizer = AutoTokenizer.from_pretrained("./your/path/bigscience_t0") + >>> model = AutoModel.from_pretrained("./your/path/bigscience_t0") + ``` + +* Programmatisches Herunterladen von Dateien mit der [huggingface_hub](https://github.com/huggingface/huggingface_hub/tree/main/src/huggingface_hub) Bibliothek: + + 1. Installieren Sie die "huggingface_hub"-Bibliothek in Ihrer virtuellen Umgebung: + + ```bash + python -m pip install huggingface_hub + ``` + + 2. Verwenden Sie die Funktion [`hf_hub_download`](https://huggingface.co/docs/hub/adding-a-library#download-files-from-the-hub), um eine Datei in einen bestimmten Pfad herunterzuladen. Der folgende Befehl lädt zum Beispiel die Datei "config.json" aus dem Modell [T0](https://huggingface.co/bigscience/T0_3B) in den gewünschten Pfad herunter: + + ```py + >>> from huggingface_hub import hf_hub_download + + >>> hf_hub_download(repo_id="bigscience/T0_3B", filename="config.json", cache_dir="./your/path/bigscience_t0") + ``` + +Sobald Ihre Datei heruntergeladen und lokal zwischengespeichert ist, geben Sie den lokalen Pfad an, um sie zu laden und zu verwenden: + +```py +>>> from transformers import AutoConfig + +>>> config = AutoConfig.from_pretrained("./your/path/bigscience_t0/config.json") +``` + + + +Weitere Informationen zum Herunterladen von Dateien, die auf dem Hub gespeichert sind, finden Sie im Abschnitt [Wie man Dateien vom Hub herunterlädt](https://huggingface.co/docs/hub/how-to-downstream). + + diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/llm_tutorial.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/llm_tutorial.md new file mode 100644 index 0000000000000000000000000000000000000000..ea4a96632cb1de97864c88a9107b262325c5618c --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/llm_tutorial.md @@ -0,0 +1,221 @@ + + + +# Generation with LLMs + +[[open-in-colab]] + +LLMs (Large Language Models) sind die Schlüsselkomponente bei der Texterstellung. Kurz gesagt, bestehen sie aus großen, vortrainierten Transformationsmodellen, die darauf trainiert sind, das nächste Wort (oder genauer gesagt Token) aus einem Eingabetext vorherzusagen. Da sie jeweils ein Token vorhersagen, müssen Sie etwas Aufwändigeres tun, um neue Sätze zu generieren, als nur das Modell aufzurufen - Sie müssen eine autoregressive Generierung durchführen. + +Die autoregressive Generierung ist ein Verfahren zur Inferenzzeit, bei dem ein Modell mit seinen eigenen generierten Ausgaben iterativ aufgerufen wird, wenn einige anfängliche Eingaben vorliegen. In 🤗 Transformers wird dies von der Methode [`~generation.GenerationMixin.generate`] übernommen, die allen Modellen mit generativen Fähigkeiten zur Verfügung steht. + +Dieses Tutorial zeigt Ihnen, wie Sie: + +* Text mit einem LLM generieren +* Vermeiden Sie häufige Fallstricke +* Nächste Schritte, damit Sie das Beste aus Ihrem LLM herausholen können + +Bevor Sie beginnen, stellen Sie sicher, dass Sie alle erforderlichen Bibliotheken installiert haben: + +```bash +pip install transformers bitsandbytes>=0.39.0 -q +``` + + +## Text generieren + +Ein Sprachmodell, das für [causal language modeling](tasks/language_modeling) trainiert wurde, nimmt eine Folge von Text-Token als Eingabe und gibt die Wahrscheinlichkeitsverteilung für das nächste Token zurück. + + +
+ +
"Forward pass of an LLM"
+
+ +Ein wichtiger Aspekt der autoregressiven Generierung mit LLMs ist die Auswahl des nächsten Tokens aus dieser Wahrscheinlichkeitsverteilung. In diesem Schritt ist alles möglich, solange Sie am Ende ein Token für die nächste Iteration haben. Das heißt, es kann so einfach sein wie die Auswahl des wahrscheinlichsten Tokens aus der Wahrscheinlichkeitsverteilung oder so komplex wie die Anwendung von einem Dutzend Transformationen vor der Stichprobenziehung aus der resultierenden Verteilung. + + +
+ +
"Die autoregressive Generierung wählt iterativ das nächste Token aus einer Wahrscheinlichkeitsverteilung aus, um Text zu erzeugen"
+
+ +Der oben dargestellte Prozess wird iterativ wiederholt, bis eine bestimmte Abbruchbedingung erreicht ist. Im Idealfall wird die Abbruchbedingung vom Modell vorgegeben, das lernen sollte, wann es ein Ende-der-Sequenz-Token (EOS) ausgeben muss. Ist dies nicht der Fall, stoppt die Generierung, wenn eine vordefinierte Maximallänge erreicht ist. + +Damit sich Ihr Modell so verhält, wie Sie es für Ihre Aufgabe erwarten, müssen Sie den Schritt der Token-Auswahl und die Abbruchbedingung richtig einstellen. Aus diesem Grund haben wir zu jedem Modell eine [`~generation.GenerationConfig`]-Datei, die eine gute generative Standardparametrisierung enthält und zusammen mit Ihrem Modell geladen wird. + +Lassen Sie uns über Code sprechen! + + + +Wenn Sie an der grundlegenden Verwendung von LLMs interessiert sind, ist unsere High-Level-Schnittstelle [`Pipeline`](pipeline_tutorial) ein guter Ausgangspunkt. LLMs erfordern jedoch oft fortgeschrittene Funktionen wie Quantisierung und Feinsteuerung des Token-Auswahlschritts, was am besten über [`~generation.GenerationMixin.generate`] erfolgt. Die autoregressive Generierung mit LLMs ist ebenfalls ressourcenintensiv und sollte für einen angemessenen Durchsatz auf einer GPU ausgeführt werden. + + + + +Zunächst müssen Sie das Modell laden. + +```py +>>> from transformers import AutoModelForCausalLM + +>>> model = AutoModelForCausalLM.from_pretrained( +... "openlm-research/open_llama_7b", device_map="auto", load_in_4bit=True +... ) +``` + +Sie werden zwei Flags in dem Aufruf `from_pretrained` bemerken: + + - `device_map` stellt sicher, dass das Modell auf Ihre GPU(s) übertragen wird + - `load_in_4bit` wendet [dynamische 4-Bit-Quantisierung](main_classes/quantization) an, um die Ressourcenanforderungen massiv zu reduzieren + +Es gibt noch andere Möglichkeiten, ein Modell zu initialisieren, aber dies ist eine gute Grundlage, um mit einem LLM zu beginnen. + +Als nächstes müssen Sie Ihre Texteingabe mit einem [tokenizer](tokenizer_summary) vorverarbeiten. + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("openlm-research/open_llama_7b") +>>> model_inputs = tokenizer(["A list of colors: red, blue"], return_tensors="pt").to("cuda") +``` + +Die Variable `model_inputs` enthält die tokenisierte Texteingabe sowie die Aufmerksamkeitsmaske. Obwohl [`~generation.GenerationMixin.generate`] sein Bestes tut, um die Aufmerksamkeitsmaske abzuleiten, wenn sie nicht übergeben wird, empfehlen wir, sie für optimale Ergebnisse wann immer möglich zu übergeben. + +Rufen Sie schließlich die Methode [`~generation.GenerationMixin.generate`] auf, um die generierten Token zurückzugeben, die vor dem Drucken in Text umgewandelt werden sollten. + +```py +>>> generated_ids = model.generate(**model_inputs) +>>> tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'A list of colors: red, blue, green, yellow, black, white, and brown' +``` + +Und das war's! Mit ein paar Zeilen Code können Sie sich die Macht eines LLM zunutze machen. + + +## Häufige Fallstricke + +Es gibt viele [Generierungsstrategien](generation_strategies), und manchmal sind die Standardwerte für Ihren Anwendungsfall vielleicht nicht geeignet. Wenn Ihre Ausgaben nicht mit dem übereinstimmen, was Sie erwarten, haben wir eine Liste der häufigsten Fallstricke erstellt und wie Sie diese vermeiden können. + +```py +>>> from transformers import AutoModelForCausalLM, AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("openlm-research/open_llama_7b") +>>> tokenizer.pad_token = tokenizer.eos_token # Llama has no pad token by default +>>> model = AutoModelForCausalLM.from_pretrained( +... "openlm-research/open_llama_7b", device_map="auto", load_in_4bit=True +... ) +``` + +### Generierte Ausgabe ist zu kurz/lang + +Wenn in der Datei [`~generation.GenerationConfig`] nichts angegeben ist, gibt `generate` standardmäßig bis zu 20 Token zurück. Wir empfehlen dringend, `max_new_tokens` in Ihrem `generate`-Aufruf manuell zu setzen, um die maximale Anzahl neuer Token zu kontrollieren, die zurückgegeben werden können. Beachten Sie, dass LLMs (genauer gesagt, [decoder-only models](https://huggingface.co/learn/nlp-course/chapter1/6?fw=pt)) auch die Eingabeaufforderung als Teil der Ausgabe zurückgeben. + + +```py +>>> model_inputs = tokenizer(["A sequence of numbers: 1, 2"], return_tensors="pt").to("cuda") + +>>> # By default, the output will contain up to 20 tokens +>>> generated_ids = model.generate(**model_inputs) +>>> tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'A sequence of numbers: 1, 2, 3, 4, 5' + +>>> # Setting `max_new_tokens` allows you to control the maximum length +>>> generated_ids = model.generate(**model_inputs, max_new_tokens=50) +>>> tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'A sequence of numbers: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,' +``` + +### Falscher Generierungsmodus + +Standardmäßig und sofern nicht in der Datei [`~generation.GenerationConfig`] angegeben, wählt `generate` bei jeder Iteration das wahrscheinlichste Token aus (gierige Dekodierung). Je nach Aufgabe kann dies unerwünscht sein; kreative Aufgaben wie Chatbots oder das Schreiben eines Aufsatzes profitieren vom Sampling. Andererseits profitieren Aufgaben, bei denen es auf die Eingabe ankommt, wie z.B. Audiotranskription oder Übersetzung, von der gierigen Dekodierung. Aktivieren Sie das Sampling mit `do_sample=True`. Mehr zu diesem Thema erfahren Sie in diesem [Blogbeitrag](https://huggingface.co/blog/how-to-generate). + +```py +>>> # Set seed or reproducibility -- you don't need this unless you want full reproducibility +>>> from transformers import set_seed +>>> set_seed(0) + +>>> model_inputs = tokenizer(["I am a cat."], return_tensors="pt").to("cuda") + +>>> # LLM + greedy decoding = repetitive, boring output +>>> generated_ids = model.generate(**model_inputs) +>>> tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'I am a cat. I am a cat. I am a cat. I am a cat' + +>>> # With sampling, the output becomes more creative! +>>> generated_ids = model.generate(**model_inputs, do_sample=True) +>>> tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'I am a cat.\nI just need to be. I am always.\nEvery time' +``` + +### Falsche Auffüllseite + +LLMs sind [decoder-only](https://huggingface.co/learn/nlp-course/chapter1/6?fw=pt)-Architekturen, d.h. sie iterieren weiter über Ihre Eingabeaufforderung. Wenn Ihre Eingaben nicht die gleiche Länge haben, müssen sie aufgefüllt werden. Da LLMs nicht darauf trainiert sind, mit aufgefüllten Token fortzufahren, muss Ihre Eingabe links aufgefüllt werden. Vergessen Sie auch nicht, die Aufmerksamkeitsmaske an generate zu übergeben! + +```py +>>> # The tokenizer initialized above has right-padding active by default: the 1st sequence, +>>> # which is shorter, has padding on the right side. Generation fails. +>>> model_inputs = tokenizer( +... ["1, 2, 3", "A, B, C, D, E"], padding=True, return_tensors="pt" +... ).to("cuda") +>>> generated_ids = model.generate(**model_inputs) +>>> tokenizer.batch_decode(generated_ids[0], skip_special_tokens=True)[0] +'' + +>>> # With left-padding, it works as expected! +>>> tokenizer = AutoTokenizer.from_pretrained("openlm-research/open_llama_7b", padding_side="left") +>>> tokenizer.pad_token = tokenizer.eos_token # Llama has no pad token by default +>>> model_inputs = tokenizer( +... ["1, 2, 3", "A, B, C, D, E"], padding=True, return_tensors="pt" +... ).to("cuda") +>>> generated_ids = model.generate(**model_inputs) +>>> tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'1, 2, 3, 4, 5, 6,' +``` + + + +## Weitere Ressourcen + +Während der Prozess der autoregressiven Generierung relativ einfach ist, kann die optimale Nutzung Ihres LLM ein schwieriges Unterfangen sein, da es viele bewegliche Teile gibt. Für Ihre nächsten Schritte, die Ihnen helfen, tiefer in die LLM-Nutzung und das Verständnis einzutauchen: + + +### Fortgeschrittene Nutzung generieren + +1. [Leitfaden](generation_strategies) zur Steuerung verschiedener Generierungsmethoden, zur Einrichtung der Generierungskonfigurationsdatei und zum Streaming der Ausgabe; +2. API-Referenz zu [`~generation.GenerationConfig`], [`~generation.GenerationMixin.generate`] und [generate-bezogene Klassen](internal/generation_utils). + +### LLM-Ranglisten + +1. [Open LLM Leaderboard](https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard), das sich auf die Qualität der Open-Source-Modelle konzentriert; +2. [Open LLM-Perf Leaderboard](https://huggingface.co/spaces/optimum/llm-perf-leaderboard), das sich auf den LLM-Durchsatz konzentriert. + +### Latenz und Durchsatz + +1. [Leitfaden](main_classes/quantization) zur dynamischen Quantisierung, der Ihnen zeigt, wie Sie Ihren Speicherbedarf drastisch reduzieren können. + +### Verwandte Bibliotheken + +1. [text-generation-inference](https://github.com/huggingface/text-generation-inference), ein produktionsreifer Server für LLMs; +2. [`optimum`](https://github.com/huggingface/optimum), eine Erweiterung von 🤗 Transformers, die für bestimmte Hardware-Geräte optimiert. diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/model_sharing.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/model_sharing.md new file mode 100644 index 0000000000000000000000000000000000000000..3b6e55eb4bf9a804717afd45274fe31f4d75740b --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/model_sharing.md @@ -0,0 +1,232 @@ + + +# Ein Modell teilen + +Die letzten beiden Tutorials haben gezeigt, wie man ein Modell mit PyTorch, Keras und 🤗 Accelerate für verteilte Setups feinabstimmen kann. Der nächste Schritt besteht darin, Ihr Modell mit der Community zu teilen! Bei Hugging Face glauben wir an den offenen Austausch von Wissen und Ressourcen, um künstliche Intelligenz für alle zu demokratisieren. Wir ermutigen Sie, Ihr Modell mit der Community zu teilen, um anderen zu helfen, Zeit und Ressourcen zu sparen. + +In diesem Tutorial lernen Sie zwei Methoden kennen, wie Sie ein trainiertes oder verfeinertes Modell auf dem [Model Hub](https://huggingface.co/models) teilen können: + +- Programmgesteuertes Übertragen Ihrer Dateien auf den Hub. +- Ziehen Sie Ihre Dateien per Drag-and-Drop über die Weboberfläche in den Hub. + + + + + +Um ein Modell mit der Öffentlichkeit zu teilen, benötigen Sie ein Konto auf [huggingface.co](https://huggingface.co/join). Sie können auch einer bestehenden Organisation beitreten oder eine neue Organisation gründen. + + + +## Repository-Funktionen + +Jedes Repository im Model Hub verhält sich wie ein typisches GitHub-Repository. Unsere Repositorys bieten Versionierung, Commit-Historie und die Möglichkeit, Unterschiede zu visualisieren. + +Die integrierte Versionierung des Model Hub basiert auf Git und [git-lfs](https://git-lfs.github.com/). Mit anderen Worten: Sie können ein Modell als ein Repository behandeln, was eine bessere Zugriffskontrolle und Skalierbarkeit ermöglicht. Die Versionskontrolle ermöglicht *Revisionen*, eine Methode zum Anheften einer bestimmten Version eines Modells mit einem Commit-Hash, Tag oder Branch. + +Folglich können Sie eine bestimmte Modellversion mit dem Parameter "Revision" laden: + +```py +>>> model = AutoModel.from_pretrained( +... "julien-c/EsperBERTo-small", revision="4c77982" # tag name, or branch name, or commit hash +... ) +``` + +Dateien lassen sich auch in einem Repository leicht bearbeiten, und Sie können die Commit-Historie sowie die Unterschiede einsehen: + +![vis_diff](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/vis_diff.png) + +## Einrichtung + +Bevor Sie ein Modell für den Hub freigeben, benötigen Sie Ihre Hugging Face-Anmeldedaten. Wenn Sie Zugang zu einem Terminal haben, führen Sie den folgenden Befehl in der virtuellen Umgebung aus, in der 🤗 Transformers installiert ist. Dadurch werden Ihre Zugangsdaten in Ihrem Hugging Face-Cache-Ordner (standardmäßig `~/.cache/`) gespeichert: + +```bash +hf auth login +``` + +Wenn Sie ein Notebook wie Jupyter oder Colaboratory verwenden, stellen Sie sicher, dass Sie die [`huggingface_hub`](https://huggingface.co/docs/hub/adding-a-library) Bibliothek installiert haben. Diese Bibliothek ermöglicht Ihnen die programmatische Interaktion mit dem Hub. + +```bash +pip install huggingface_hub +``` + +Verwenden Sie dann `notebook_login`, um sich beim Hub anzumelden, und folgen Sie dem Link [hier](https://huggingface.co/settings/token), um ein Token für die Anmeldung zu generieren: + +```py +>>> from huggingface_hub import notebook_login + +>>> notebook_login() +``` + +## Ein Modell für alle Frameworks konvertieren + +Um sicherzustellen, dass Ihr Modell von jemandem verwendet werden kann, der mit einem anderen Framework arbeitet, empfehlen wir Ihnen, Ihr Modell sowohl mit PyTorch- als auch mit TensorFlow-Checkpoints zu konvertieren und hochzuladen. Während Benutzer immer noch in der Lage sind, Ihr Modell von einem anderen Framework zu laden, wenn Sie diesen Schritt überspringen, wird es langsamer sein, weil 🤗 Transformers den Checkpoint on-the-fly konvertieren müssen. + +Die Konvertierung eines Checkpoints für ein anderes Framework ist einfach. Stellen Sie sicher, dass Sie PyTorch und TensorFlow installiert haben (siehe [hier](installation) für Installationsanweisungen), und finden Sie dann das spezifische Modell für Ihre Aufgabe in dem anderen Framework. + + + +Geben Sie `from_tf=True` an, um einen Prüfpunkt von TensorFlow nach PyTorch zu konvertieren: + +```py +>>> pt_model = DistilBertForSequenceClassification.from_pretrained("path/to/awesome-name-you-picked", from_tf=True) +>>> pt_model.save_pretrained("path/to/awesome-name-you-picked") +``` + + +Geben Sie `from_pt=True` an, um einen Prüfpunkt von PyTorch nach TensorFlow zu konvertieren: + +```py +>>> tf_model = TFDistilBertForSequenceClassification.from_pretrained("path/to/awesome-name-you-picked", from_pt=True) +``` + +Dann können Sie Ihr neues TensorFlow-Modell mit seinem neuen Checkpoint speichern: + +```py +>>> tf_model.save_pretrained("path/to/awesome-name-you-picked") +``` + + +Wenn ein Modell in Flax verfügbar ist, können Sie auch einen Kontrollpunkt von PyTorch nach Flax konvertieren: + +```py +>>> flax_model = FlaxDistilBertForSequenceClassification.from_pretrained( +... "path/to/awesome-name-you-picked", from_pt=True +... ) +``` + + + +## Ein Modell während des Trainings hochladen + + + + + +Die Weitergabe eines Modells an den Hub ist so einfach wie das Hinzufügen eines zusätzlichen Parameters oder Rückrufs. Erinnern Sie sich an das [Feinabstimmungs-Tutorial](training), in der Klasse [`TrainingArguments`] geben Sie Hyperparameter und zusätzliche Trainingsoptionen an. Eine dieser Trainingsoptionen beinhaltet die Möglichkeit, ein Modell direkt an den Hub zu pushen. Setzen Sie `push_to_hub=True` in Ihrer [`TrainingArguments`]: + +```py +>>> training_args = TrainingArguments(output_dir="my-awesome-model", push_to_hub=True) +``` + +Übergeben Sie Ihre Trainingsargumente wie gewohnt an [`Trainer`]: + +```py +>>> trainer = Trainer( +... model=model, +... args=training_args, +... train_dataset=small_train_dataset, +... eval_dataset=small_eval_dataset, +... compute_metrics=compute_metrics, +... ) +``` + +Nach der Feinabstimmung Ihres Modells rufen Sie [`~transformers.Trainer.push_to_hub`] auf [`Trainer`] auf, um das trainierte Modell an den Hub zu übertragen. Transformers fügt sogar automatisch Trainings-Hyperparameter, Trainingsergebnisse und Framework-Versionen zu Ihrer Modellkarte hinzu! + +```py +>>> trainer.push_to_hub() +``` + + +Geben Sie ein Modell mit [`PushToHubCallback`] an den Hub weiter. In der [`PushToHubCallback`] Funktion, fügen Sie hinzu: + +- Ein Ausgabeverzeichnis für Ihr Modell. +- Einen Tokenizer. +- Die `hub_model_id`, die Ihr Hub-Benutzername und Modellname ist. + +```py +>>> from transformers import PushToHubCallback + +>>> push_to_hub_callback = PushToHubCallback( +... output_dir="./your_model_save_path", tokenizer=tokenizer, hub_model_id="your-username/my-awesome-model" +... ) +``` + +Fügen Sie den Callback zu [`fit`](https://keras.io/api/models/model_training_apis/) hinzu, und 🤗 Transformers wird das trainierte Modell an den Hub weiterleiten: + +```py +>>> model.fit(tf_train_dataset, validation_data=tf_validation_dataset, epochs=3, callbacks=push_to_hub_callback) +``` + + + +## Verwenden Sie die Funktion `push_to_hub`. + +Sie können `push_to_hub` auch direkt für Ihr Modell aufrufen, um es in den Hub hochzuladen. + +Geben Sie den Namen Ihres Modells in "push_to_hub" an: + +```py +>>> pt_model.push_to_hub("my-awesome-model") +``` + +Dadurch wird ein Repository unter Ihrem Benutzernamen mit dem Modellnamen `my-awesome-model` erstellt. Benutzer können nun Ihr Modell mit der Funktion `from_pretrained` laden: + +```py +>>> from transformers import AutoModel + +>>> model = AutoModel.from_pretrained("your_username/my-awesome-model") +``` + +Wenn Sie zu einer Organisation gehören und Ihr Modell stattdessen unter dem Namen der Organisation pushen wollen, fügen Sie diesen einfach zur `repo_id` hinzu: + +```py +>>> pt_model.push_to_hub("my-awesome-org/my-awesome-model") +``` + +Die Funktion "push_to_hub" kann auch verwendet werden, um andere Dateien zu einem Modell-Repository hinzuzufügen. Zum Beispiel kann man einen Tokenizer zu einem Modell-Repository hinzufügen: + +```py +>>> tokenizer.push_to_hub("my-awesome-model") +``` + +Oder vielleicht möchten Sie die TensorFlow-Version Ihres fein abgestimmten PyTorch-Modells hinzufügen: + +```py +>>> tf_model.push_to_hub("my-awesome-model") +``` + +Wenn Sie nun zu Ihrem Hugging Face-Profil navigieren, sollten Sie Ihr neu erstelltes Modell-Repository sehen. Wenn Sie auf die Registerkarte **Dateien** klicken, werden alle Dateien angezeigt, die Sie in das Repository hochgeladen haben. + +Weitere Einzelheiten zum Erstellen und Hochladen von Dateien in ein Repository finden Sie in der Hub-Dokumentation [hier](https://huggingface.co/docs/hub/how-to-upstream). + +## Hochladen mit der Weboberfläche + +Benutzer, die einen no-code Ansatz bevorzugen, können ein Modell über das Webinterface des Hubs hochladen. Besuchen Sie [huggingface.co/new](https://huggingface.co/new) um ein neues Repository zu erstellen: + +![new_model_repo](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/new_model_repo.png) + +Fügen Sie von hier aus einige Informationen über Ihr Modell hinzu: + +- Wählen Sie den **Besitzer** des Repositorys. Dies können Sie selbst oder eine der Organisationen sein, denen Sie angehören. +- Wählen Sie einen Namen für Ihr Modell, der auch der Name des Repositorys sein wird. +- Wählen Sie, ob Ihr Modell öffentlich oder privat ist. +- Geben Sie die Lizenzverwendung für Ihr Modell an. + +Klicken Sie nun auf die Registerkarte **Dateien** und klicken Sie auf die Schaltfläche **Datei hinzufügen**, um eine neue Datei in Ihr Repository hochzuladen. Ziehen Sie dann eine Datei per Drag-and-Drop hoch und fügen Sie eine Übergabemeldung hinzu. + +![upload_file](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/upload_file.png) + +## Hinzufügen einer Modellkarte + +Um sicherzustellen, dass die Benutzer die Fähigkeiten, Grenzen, möglichen Verzerrungen und ethischen Aspekte Ihres Modells verstehen, fügen Sie bitte eine Modellkarte zu Ihrem Repository hinzu. Die Modellkarte wird in der Datei `README.md` definiert. Sie können eine Modellkarte hinzufügen, indem Sie: + +* Manuelles Erstellen und Hochladen einer "README.md"-Datei. +* Klicken Sie auf die Schaltfläche **Modellkarte bearbeiten** in Ihrem Modell-Repository. + +Werfen Sie einen Blick auf die DistilBert [model card](https://huggingface.co/distilbert/distilbert-base-uncased) als gutes Beispiel für die Art von Informationen, die eine Modellkarte enthalten sollte. Weitere Details über andere Optionen, die Sie in der Datei "README.md" einstellen können, wie z.B. den Kohlenstoff-Fußabdruck eines Modells oder Beispiele für Widgets, finden Sie in der Dokumentation [hier](https://huggingface.co/docs/hub/models-cards). \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/peft.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/peft.md new file mode 100644 index 0000000000000000000000000000000000000000..f43d227a9a6e54d08d15e6dd5ec7cb156978d88a --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/peft.md @@ -0,0 +1,216 @@ + + +# Adapter mit 🤗 PEFT laden + +[[open-in-colab]] + +Die [Parameter-Efficient Fine Tuning (PEFT)](https://huggingface.co/blog/peft) Methoden frieren die vorab trainierten Modellparameter während der Feinabstimmung ein und fügen eine kleine Anzahl trainierbarer Parameter (die Adapter) hinzu. Die Adapter werden trainiert, um aufgabenspezifische Informationen zu lernen. Es hat sich gezeigt, dass dieser Ansatz sehr speichereffizient ist und weniger Rechenleistung beansprucht, während die Ergebnisse mit denen eines vollständig feinabgestimmten Modells vergleichbar sind. + +Adapter, die mit PEFT trainiert wurden, sind in der Regel um eine Größenordnung kleiner als das vollständige Modell, so dass sie bequem gemeinsam genutzt, gespeichert und geladen werden können. + +
+ +
Die Adaptergewichte für ein OPTForCausalLM-Modell, die auf dem Hub gespeichert sind, sind nur ~6MB groß, verglichen mit der vollen Größe der Modellgewichte, die ~700MB betragen können.
+
+ +Wenn Sie mehr über die 🤗 PEFT-Bibliothek erfahren möchten, sehen Sie sich die [Dokumentation](https://huggingface.co/docs/peft/index) an. + +## Setup + +Starten Sie mit der Installation von 🤗 PEFT: + +```bash +pip install peft +``` + +Wenn Sie die brandneuen Funktionen ausprobieren möchten, sollten Sie die Bibliothek aus dem Quellcode installieren: + +```bash +pip install git+https://github.com/huggingface/peft.git +``` + +## Unterstützte PEFT-Modelle + +Transformers unterstützt nativ einige PEFT-Methoden, d.h. Sie können lokal oder auf dem Hub gespeicherte Adaptergewichte laden und sie mit wenigen Zeilen Code einfach ausführen oder trainieren. Die folgenden Methoden werden unterstützt: + +- [Low Rank Adapters](https://huggingface.co/docs/peft/conceptual_guides/lora) +- [IA3](https://huggingface.co/docs/peft/conceptual_guides/ia3) +- [AdaLoRA](https://huggingface.co/papers/2303.10512) + +Wenn Sie andere PEFT-Methoden, wie z.B. Prompt Learning oder Prompt Tuning, verwenden möchten, oder über die 🤗 PEFT-Bibliothek im Allgemeinen, lesen Sie bitte die [Dokumentation](https://huggingface.co/docs/peft/index). + + +## Laden Sie einen PEFT-Adapter + +Um ein PEFT-Adaptermodell von 🤗 Transformers zu laden und zu verwenden, stellen Sie sicher, dass das Hub-Repository oder das lokale Verzeichnis eine `adapter_config.json`-Datei und die Adaptergewichte enthält, wie im obigen Beispielbild gezeigt. Dann können Sie das PEFT-Adaptermodell mit der Klasse `AutoModelFor` laden. Um zum Beispiel ein PEFT-Adaptermodell für die kausale Sprachmodellierung zu laden: + +1. Geben Sie die PEFT-Modell-ID an. +2. übergeben Sie es an die Klasse [`AutoModelForCausalLM`]. + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer + +peft_model_id = "ybelkada/opt-350m-lora" +model = AutoModelForCausalLM.from_pretrained(peft_model_id) +``` + + + +Sie können einen PEFT-Adapter entweder mit einer `AutoModelFor`-Klasse oder der Basismodellklasse wie `OPTForCausalLM` oder `LlamaForCausalLM` laden. + + + +Sie können einen PEFT-Adapter auch laden, indem Sie die Methode `load_adapter` aufrufen: + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer + +model_id = "facebook/opt-350m" +peft_model_id = "ybelkada/opt-350m-lora" + +model = AutoModelForCausalLM.from_pretrained(model_id) +model.load_adapter(peft_model_id) +``` + +## Laden in 8bit oder 4bit + +Die `bitsandbytes`-Integration unterstützt Datentypen mit 8bit und 4bit Genauigkeit, was für das Laden großer Modelle nützlich ist, weil es Speicher spart (lesen Sie den `bitsandbytes`-Integrations [guide](./quantization#bitsandbytes-integration), um mehr zu erfahren). Fügen Sie die Parameter `load_in_8bit` oder `load_in_4bit` zu [`~PreTrainedModel.from_pretrained`] hinzu und setzen Sie `device_map="auto"`, um das Modell effektiv auf Ihre Hardware zu verteilen: + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig + +peft_model_id = "ybelkada/opt-350m-lora" +model = AutoModelForCausalLM.from_pretrained(peft_model_id, quantization_config=BitsAndBytesConfig(load_in_8bit=True)) +``` + +## Einen neuen Adapter hinzufügen + +Sie können [`~peft.PeftModel.add_adapter`] verwenden, um einen neuen Adapter zu einem Modell mit einem bestehenden Adapter hinzuzufügen, solange der neue Adapter vom gleichen Typ ist wie der aktuelle Adapter. Wenn Sie zum Beispiel einen bestehenden LoRA-Adapter an ein Modell angehängt haben: + +```py +from transformers import AutoModelForCausalLM, OPTForCausalLM, AutoTokenizer +from peft import PeftConfig + +model_id = "facebook/opt-350m" +model = AutoModelForCausalLM.from_pretrained(model_id) + +lora_config = LoraConfig( + target_modules=["q_proj", "k_proj"], + init_lora_weights=False +) + +model.add_adapter(lora_config, adapter_name="adapter_1") +``` + +Um einen neuen Adapter hinzuzufügen: + +```py +# attach new adapter with same config +model.add_adapter(lora_config, adapter_name="adapter_2") +``` + +Jetzt können Sie mit [`~peft.PeftModel.set_adapter`] festlegen, welcher Adapter verwendet werden soll: + +```py +# use adapter_1 +model.set_adapter("adapter_1") +output = model.generate(**inputs) +print(tokenizer.decode(output_disabled[0], skip_special_tokens=True)) + +# use adapter_2 +model.set_adapter("adapter_2") +output_enabled = model.generate(**inputs) +print(tokenizer.decode(output_enabled[0], skip_special_tokens=True)) +``` + +## Aktivieren und Deaktivieren von Adaptern + +Sobald Sie einen Adapter zu einem Modell hinzugefügt haben, können Sie das Adaptermodul aktivieren oder deaktivieren. So aktivieren Sie das Adaptermodul: + +```py +from transformers import AutoModelForCausalLM, OPTForCausalLM, AutoTokenizer +from peft import PeftConfig + +model_id = "facebook/opt-350m" +adapter_model_id = "ybelkada/opt-350m-lora" +tokenizer = AutoTokenizer.from_pretrained(model_id) +text = "Hello" +inputs = tokenizer(text, return_tensors="pt") + +model = AutoModelForCausalLM.from_pretrained(model_id) +peft_config = PeftConfig.from_pretrained(adapter_model_id) + +# to initiate with random weights +peft_config.init_lora_weights = False + +model.add_adapter(peft_config) +model.enable_adapters() +output = model.generate(**inputs) +``` + +So deaktivieren Sie das Adaptermodul: + +```py +model.disable_adapters() +output = model.generate(**inputs) +``` + +## PEFT-Adapter trainieren + +PEFT-Adapter werden von der Klasse [`Trainer`] unterstützt, so dass Sie einen Adapter für Ihren speziellen Anwendungsfall trainieren können. Dazu müssen Sie nur ein paar weitere Codezeilen hinzufügen. Zum Beispiel, um einen LoRA-Adapter zu trainieren: + + + +Wenn Sie mit der Feinabstimmung eines Modells mit [`Trainer`] noch nicht vertraut sind, werfen Sie einen Blick auf das Tutorial [Feinabstimmung eines vortrainierten Modells](Training). + + + +1. Definieren Sie Ihre Adapterkonfiguration mit dem Aufgabentyp und den Hyperparametern (siehe [`~peft.LoraConfig`] für weitere Details darüber, was die Hyperparameter tun). + +```py +from peft import LoraConfig + +peft_config = LoraConfig( + lora_alpha=16, + lora_dropout=0.1, + r=64, + bias="none", + task_type="CAUSAL_LM", +) +``` + +2. Fügen Sie dem Modell einen Adapter hinzu. + +```py +model.add_adapter(peft_config) +``` + +3. Jetzt können Sie das Modell an [`Trainer`] übergeben! + +```py +trainer = Trainer(model=model, ...) +trainer.train() +``` + +So speichern Sie Ihren trainierten Adapter und laden ihn wieder: + +```py +model.save_pretrained(save_dir) +model = AutoModelForCausalLM.from_pretrained(save_dir) +``` + + diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/pipeline_tutorial.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/pipeline_tutorial.md new file mode 100644 index 0000000000000000000000000000000000000000..5106af9b2fafc76564f8e895c53d3b8146e45aeb --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/pipeline_tutorial.md @@ -0,0 +1,175 @@ + + +# Pipelines für Inferenzen + +Die [`pipeline`] macht es einfach, jedes beliebige Modell aus dem [Hub](https://huggingface.co/models) für die Inferenz auf jede Sprache, Computer Vision, Sprache und multimodale Aufgaben zu verwenden. Selbst wenn Sie keine Erfahrung mit einer bestimmten Modalität haben oder nicht mit dem zugrundeliegenden Code hinter den Modellen vertraut sind, können Sie sie mit der [`pipeline`] für Inferenzen verwenden! In diesem Beispiel lernen Sie, wie: + +* Eine [`pipeline`] für Inferenz zu verwenden. +* Einen bestimmten Tokenizer oder ein bestimmtes Modell zu verwenden. +* Eine [`pipeline`] für Audio-, Vision- und multimodale Aufgaben zu verwenden. + + + +Eine vollständige Liste der unterstützten Aufgaben und verfügbaren Parameter finden Sie in der [`pipeline`]-Dokumentation. + + + +## Verwendung von Pipelines + +Obwohl jede Aufgabe eine zugehörige [`pipeline`] hat, ist es einfacher, die allgemeine [`pipeline`]-Abstraktion zu verwenden, die alle aufgabenspezifischen Pipelines enthält. Die [`pipeline`] lädt automatisch ein Standardmodell und eine Vorverarbeitungsklasse, die für Ihre Aufgabe inferenzfähig ist. + +1. Beginnen Sie mit der Erstellung einer [`pipeline`] und geben Sie eine Inferenzaufgabe an: + +```py +>>> from transformers import pipeline + +>>> generator = pipeline(task="text-generation") +``` + +2. Übergeben Sie Ihren Eingabetext an die [`pipeline`]: + +```py +>>> generator( +... "Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone" +... ) # doctest: +SKIP +[{'generated_text': 'Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone, Seven for the Iron-priests at the door to the east, and thirteen for the Lord Kings at the end of the mountain'}] +``` + +Wenn Sie mehr als eine Eingabe haben, übergeben Sie die Eingabe als Liste: + +```py +>>> generator( +... [ +... "Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone", +... "Nine for Mortal Men, doomed to die, One for the Dark Lord on his dark throne", +... ] +... ) # doctest: +SKIP +``` + +Alle zusätzlichen Parameter für Ihre Aufgabe können auch in die [`pipeline`] aufgenommen werden. Die Aufgabe `Text-Generierung` hat eine [`~generation.GenerationMixin.generate`]-Methode mit mehreren Parametern zur Steuerung der Ausgabe. Wenn Sie zum Beispiel mehr als eine Ausgabe erzeugen wollen, setzen Sie den Parameter `num_return_sequences`: + +```py +>>> generator( +... "Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone", +... num_return_sequences=2, +... ) # doctest: +SKIP +``` + +### Wählen Sie ein Modell und einen Tokenizer + +Die [`pipeline`] akzeptiert jedes Modell aus dem [Hub](https://huggingface.co/models). Auf dem Hub gibt es Tags, mit denen Sie nach einem Modell filtern können, das Sie für Ihre Aufgabe verwenden möchten. Sobald Sie ein passendes Modell ausgewählt haben, laden Sie es mit der entsprechenden `AutoModelFor` und [`AutoTokenizer`] Klasse. Laden Sie zum Beispiel die Klasse [`AutoModelForCausalLM`] für eine kausale Sprachmodellierungsaufgabe: + +```py +>>> from transformers import AutoTokenizer, AutoModelForCausalLM + +>>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2") +>>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2") +``` + +Erstellen Sie eine [`pipeline`] für Ihre Aufgabe, und geben Sie das Modell und den Tokenizer an, die Sie geladen haben: + +```py +>>> from transformers import pipeline + +>>> generator = pipeline(task="text-generation", model=model, tokenizer=tokenizer) +``` + +Übergeben Sie Ihren Eingabetext an die [`pipeline`] , um einen Text zu erzeugen: + +```py +>>> generator( +... "Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone" +... ) # doctest: +SKIP +[{'generated_text': 'Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone, Seven for the Dragon-lords (for them to rule in a world ruled by their rulers, and all who live within the realm'}] +``` + +## Audio-Pipeline + +Die [`pipeline`] unterstützt auch Audioaufgaben wie Audioklassifizierung und automatische Spracherkennung. + +Lassen Sie uns zum Beispiel die Emotion in diesem Audioclip klassifizieren: + +```py +>>> from datasets import load_dataset +>>> import torch + +>>> torch.manual_seed(42) # doctest: +IGNORE_RESULT +>>> ds = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation") +>>> audio_file = ds[0]["audio"]["path"] +``` + +Finden Sie ein [Audioklassifikation](https://huggingface.co/models?pipeline_tag=audio-classification) Modell auf dem Model Hub für Emotionserkennung und laden Sie es in die [`pipeline`]: + +```py +>>> from transformers import pipeline + +>>> audio_classifier = pipeline( +... task="audio-classification", model="ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition" +... ) +``` + +Übergeben Sie die Audiodatei an die [`pipeline`]: + +```py +>>> preds = audio_classifier(audio_file) +>>> preds = [{"score": round(pred["score"], 4), "label": pred["label"]} for pred in preds] +>>> preds +[{'score': 0.1315, 'label': 'calm'}, {'score': 0.1307, 'label': 'neutral'}, {'score': 0.1274, 'label': 'sad'}, {'score': 0.1261, 'label': 'fearful'}, {'score': 0.1242, 'label': 'happy'}] +``` + +## Bildverarbeitungs-Pipeline + +Die Verwendung einer [`pipeline`] für Bildverarbeitungsaufgaben ist praktisch identisch. + +Geben Sie Ihre Aufgabe an und übergeben Sie Ihr Bild an den Klassifikator. Das Bild kann ein Link oder ein lokaler Pfad zu dem Bild sein. Zum Beispiel: Welche Katzenart ist unten abgebildet? + +![pipeline-cat-chonk](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg) + +```py +>>> from transformers import pipeline + +>>> vision_classifier = pipeline(task="image-classification") +>>> preds = vision_classifier( +... images="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg" +... ) +>>> preds = [{"score": round(pred["score"], 4), "label": pred["label"]} for pred in preds] +>>> preds +[{'score': 0.4335, 'label': 'lynx, catamount'}, {'score': 0.0348, 'label': 'cougar, puma, catamount, mountain lion, painter, panther, Felis concolor'}, {'score': 0.0324, 'label': 'snow leopard, ounce, Panthera uncia'}, {'score': 0.0239, 'label': 'Egyptian cat'}, {'score': 0.0229, 'label': 'tiger cat'}] +``` + +## Multimodale Pipeline + +Die [`pipeline`] unterstützt mehr als eine Modalität. Eine Aufgabe zur Beantwortung visueller Fragen (VQA) kombiniert zum Beispiel Text und Bild. Verwenden Sie einen beliebigen Bildlink und eine Frage, die Sie zu dem Bild stellen möchten. Das Bild kann eine URL oder ein lokaler Pfad zu dem Bild sein. + +Wenn Sie zum Beispiel das gleiche Bild wie in der obigen Vision-Pipeline verwenden: + +```py +>>> image = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg" +>>> question = "Where is the cat?" +``` + +Erstellen Sie eine Pipeline für "vqa" und übergeben Sie ihr das Bild und die Frage: + +```py +>>> from transformers import pipeline + +>>> vqa = pipeline(task="vqa") +>>> preds = vqa(image=image, question=question) +>>> preds = [{"score": round(pred["score"], 4), "answer": pred["answer"]} for pred in preds] +>>> preds +[{'score': 0.9112, 'answer': 'snow'}, {'score': 0.8796, 'answer': 'in snow'}, {'score': 0.6717, 'answer': 'outside'}, {'score': 0.0291, 'answer': 'on ground'}, {'score': 0.027, 'answer': 'ground'}] +``` diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/pr_checks.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/pr_checks.md new file mode 100644 index 0000000000000000000000000000000000000000..ee2bbf489b8e7535f277e6f95ab7062c2e52020c --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/pr_checks.md @@ -0,0 +1,199 @@ + + +# Überprüfungen bei einer Pull-Anfrage + +Wenn Sie eine Pull-Anfrage für 🤗 Transformers öffnen, wird eine ganze Reihe von Prüfungen durchgeführt, um sicherzustellen, dass der Patch, den Sie hinzufügen, nichts Bestehendes zerstört. Es gibt vier Arten von Prüfungen: +- reguläre Tests +- Erstellung der Dokumentation +- Stil von Code und Dokumentation +- allgemeine Konsistenz des Repository + +In diesem Dokument werden wir versuchen zu erklären, worum es sich bei diesen verschiedenen Prüfungen handelt und wie Sie sie lokal debuggen können, wenn eine der Prüfungen in Ihrer PR fehlschlägt. + +Beachten Sie, dass Sie im Idealfall eine Dev-Installation benötigen: + +```bash +pip install transformers[dev] +``` + +oder für eine bearbeitbare Installation: + +```bash +pip install -e .[dev] +``` + +innerhalb des Transformers Repo. Da die Anzahl der optionalen Abhängigkeiten von Transformers stark zugenommen hat, ist es möglich, dass Sie nicht alle davon bekommen können. Wenn die Dev-Installation fehlschlägt, stellen Sie sicher, dass Sie das Deep Learning-Framework, mit dem Sie arbeiten, installieren (PyTorch, TensorFlow und/oder Flax). + +```bash +pip install transformers[quality] +``` + +oder für eine bearbeitbare Installation: + +```bash +pip install -e .[quality] +``` + + +## Tests + +Alle Jobs, die mit `ci/circleci: run_tests_` beginnen, führen Teile der Transformers-Testsuite aus. Jeder dieser Jobs konzentriert sich auf einen Teil der Bibliothek in einer bestimmten Umgebung: `ci/circleci: run_tests_pipelines_tf` zum Beispiel führt den Pipelines-Test in einer Umgebung aus, in der nur TensorFlow installiert ist. + +Beachten Sie, dass nur ein Teil der Testsuite jedes Mal ausgeführt wird, um zu vermeiden, dass Tests ausgeführt werden, wenn es keine wirkliche Änderung in den Modulen gibt, die sie testen: ein Dienstprogramm wird ausgeführt, um die Unterschiede in der Bibliothek zwischen vor und nach dem PR zu ermitteln (was GitHub Ihnen auf der Registerkarte "Files changes" anzeigt) und die Tests auszuwählen, die von diesem Unterschied betroffen sind. Dieses Dienstprogramm kann lokal mit ausgeführt werden: + +```bash +python utils/tests_fetcher.py +``` + +aus dem Stammverzeichnis des Transformers-Repositoriums. Es wird: + +1. Überprüfen Sie für jede Datei im Diff, ob die Änderungen im Code oder nur in Kommentaren oder Docstrings enthalten sind. Nur die Dateien mit echten Codeänderungen werden beibehalten. +2. Erstellen Sie eine interne Map, die für jede Datei des Quellcodes der Bibliothek alle Dateien angibt, auf die sie rekursiv Einfluss nimmt. Von Modul A wird gesagt, dass es sich auf Modul B auswirkt, wenn Modul B Modul A importiert. Für die rekursive Auswirkung benötigen wir eine Kette von Modulen, die von Modul A zu Modul B führt und in der jedes Modul das vorherige importiert. +3. Wenden Sie diese Zuordnung auf die in Schritt 1 gesammelten Dateien an. So erhalten wir die Liste der Modelldateien, die von der PR betroffen sind. +4. Ordnen Sie jede dieser Dateien der/den entsprechenden Testdatei(en) zu und erhalten Sie die Liste der auszuführenden Tests. + +Wenn Sie das Skript lokal ausführen, sollten Sie die Ergebnisse von Schritt 1, 3 und 4 ausgegeben bekommen und somit wissen, welche Tests ausgeführt werden. Das Skript erstellt außerdem eine Datei namens `test_list.txt`, die die Liste der auszuführenden Tests enthält, die Sie mit dem folgenden Befehl lokal ausführen können: + +```bash +python -m pytest -n 8 --dist=loadfile -rA -s $(cat test_list.txt) +``` + +Für den Fall, dass Ihnen etwas entgangen ist, wird die komplette Testreihe ebenfalls täglich ausgeführt. + +## Dokumentation erstellen + +Der Job `build_pr_documentation` erstellt und generiert eine Vorschau der Dokumentation, um sicherzustellen, dass alles in Ordnung ist, wenn Ihr PR zusammengeführt wird. Ein Bot fügt einen Link zur Vorschau der Dokumentation zu Ihrem PR hinzu. Alle Änderungen, die Sie an dem PR vornehmen, werden automatisch in der Vorschau aktualisiert. Wenn die Dokumentation nicht erstellt werden kann, klicken Sie auf **Details** neben dem fehlgeschlagenen Auftrag, um zu sehen, wo der Fehler liegt. Oft ist der Fehler so einfach wie eine fehlende Datei im `toctree`. + +Wenn Sie daran interessiert sind, die Dokumentation lokal zu erstellen oder in der Vorschau anzusehen, werfen Sie einen Blick in die [`README.md`](https://github.com/huggingface/transformers/tree/main/docs) im Ordner docs. + +## Code und Dokumentationsstil + +Die Formatierung des Codes erfolgt für alle Quelldateien, die Beispiele und die Tests mit `black` und `ruff`. Wir haben auch ein benutzerdefiniertes Tool, das sich um die Formatierung von docstrings und `rst`-Dateien kümmert (`utils/style_doc.py`), sowie um die Reihenfolge der Lazy-Importe, die in den Transformers `__init__.py`-Dateien durchgeführt werden (`utils/custom_init_isort.py`). All dies können Sie starten, indem Sie Folgendes ausführen + +```bash +make style +``` + +Das CI prüft, ob diese innerhalb der Prüfung `ci/circleci: check_code_quality` angewendet wurden. Es führt auch `ruff` aus, das einen grundlegenden Blick auf Ihren Code wirft und sich beschwert, wenn es eine undefinierte Variable findet oder eine, die nicht verwendet wird. Um diese Prüfung lokal auszuführen, verwenden Sie + +```bash +make quality +``` + +Dies kann sehr viel Zeit in Anspruch nehmen. Um dasselbe nur für die Dateien zu tun, die Sie im aktuellen Zweig geändert haben, führen Sie + +```bash +make fixup +``` + +Dieser letzte Befehl führt auch alle zusätzlichen Prüfungen für die Konsistenz des Repositorys durch. Schauen wir uns diese an. + +## Repository-Konsistenz + +Dies fasst alle Tests zusammen, die sicherstellen, dass Ihr PR das Repository in einem guten Zustand verlässt. Sie können diese Prüfung lokal durchführen, indem Sie Folgendes ausführen: + +```bash +make repo-consistency +``` + +Dies überprüft, ob: + +- Alle zum Init hinzugefügten Objekte sind dokumentiert (ausgeführt von `utils/check_repo.py`) +- Alle `__init__.py`-Dateien haben in ihren beiden Abschnitten den gleichen Inhalt (ausgeführt von `utils/check_inits.py`) +- Der gesamte Code, der als Kopie eines anderen Moduls identifiziert wurde, stimmt mit dem Original überein (ausgeführt von `utils/check_copies.py`) +- Alle Konfigurationsklassen haben mindestens einen gültigen Prüfpunkt, der in ihren Dokumentationen erwähnt wird (ausgeführt von `utils/check_config_docstrings.py`) +- Alle Konfigurationsklassen enthalten nur Attribute, die in den entsprechenden Modellierungsdateien verwendet werden (ausgeführt von `utils/check_config_attributes.py`) +- Die Übersetzungen der READMEs und der Index des Dokuments haben die gleiche Modellliste wie die Haupt-README (durchgeführt von `utils/check_copies.py`) +- Die automatisch generierten Tabellen in der Dokumentation sind auf dem neuesten Stand (ausgeführt von `utils/check_table.py`) +- Die Bibliothek verfügt über alle Objekte, auch wenn nicht alle optionalen Abhängigkeiten installiert sind (ausgeführt von `utils/check_dummies.py`) + +Sollte diese Prüfung fehlschlagen, müssen die ersten beiden Punkte manuell korrigiert werden, die letzten vier können automatisch für Sie korrigiert werden, indem Sie den Befehl + +```bash +make fix-copies +``` + +Zusätzliche Prüfungen betreffen PRs, die neue Modelle hinzufügen, vor allem, dass: + +- Alle hinzugefügten Modelle befinden sich in einer Auto-Zuordnung (durchgeführt von `utils/check_repo.py`) + +- Alle Modelle werden ordnungsgemäß getestet (ausgeführt von `utils/check_repo.py`) + + + +### Kopien prüfen + +Da die Transformers-Bibliothek in Bezug auf den Modellcode sehr eigenwillig ist und jedes Modell vollständig in einer einzigen Datei implementiert sein sollte, ohne sich auf andere Modelle zu stützen, haben wir einen Mechanismus hinzugefügt, der überprüft, ob eine Kopie des Codes einer Ebene eines bestimmten Modells mit dem Original übereinstimmt. Auf diese Weise können wir bei einer Fehlerbehebung alle anderen betroffenen Modelle sehen und entscheiden, ob wir die Änderung weitergeben oder die Kopie zerstören. + + + +Wenn eine Datei eine vollständige Kopie einer anderen Datei ist, sollten Sie sie in der Konstante `FULL_COPIES` von `utils/check_copies.py` registrieren. + + + +Dieser Mechanismus stützt sich auf Kommentare der Form `# Kopiert von xxx`. Das `xxx` sollte den gesamten Pfad zu der Klasse der Funktion enthalten, die darunter kopiert wird. Zum Beispiel ist `RobertaSelfOutput` eine direkte Kopie der Klasse `BertSelfOutput`. Sie können also [hier](https://github.com/huggingface/transformers/blob/2bd7a27a671fd1d98059124024f580f8f5c0f3b5/src/transformers/models/roberta/modeling_roberta.py#L289) sehen, dass sie einen Kommentar hat: + +```py +# Copied from transformers.models.bert.modeling_bert.BertSelfOutput +``` + +Beachten Sie, dass Sie dies nicht auf eine ganze Klasse anwenden, sondern auf die entsprechenden Methoden, von denen kopiert wird. Zum Beispiel [hier](https://github.com/huggingface/transformers/blob/2bd7a27a671fd1d98059124024f580f8f5c0f3b5/src/transformers/models/roberta/modeling_roberta.py#L598) können Sie sehen, wie `RobertaPreTrainedModel._init_weights` von der gleichen Methode in `BertPreTrainedModel` mit dem Kommentar kopiert wird: + +```py +# Copied from transformers.models.bert.modeling_bert.BertPreTrainedModel._init_weights +``` + +Manchmal ist die Kopie bis auf die Namen genau gleich: zum Beispiel verwenden wir in `RobertaAttention` `RobertaSelfAttention` anstelle von `BertSelfAttention`, aber ansonsten ist der Code genau derselbe. Aus diesem Grund unterstützt `#Copied from` einfache String-Ersetzungen mit der folgenden Syntax: `Kopiert von xxx mit foo->bar`. Das bedeutet, dass der Code kopiert wird, wobei alle Instanzen von "foo" durch "bar" ersetzt werden. Sie können sehen, wie es [hier](https://github.com/huggingface/transformers/blob/2bd7a27a671fd1d98059124024f580f8f5c0f3b5/src/transformers/models/roberta/modeling_roberta.py#L304C1-L304C86) in `RobertaAttention` mit dem Kommentar verwendet wird: + +```py +# Copied from transformers.models.bert.modeling_bert.BertAttention with Bert->Roberta +``` + +Beachten Sie, dass um den Pfeil herum keine Leerzeichen stehen sollten (es sei denn, das Leerzeichen ist Teil des zu ersetzenden Musters, natürlich). + +Sie können mehrere Muster durch ein Komma getrennt hinzufügen. Zum Beispiel ist hier `CamemberForMaskedLM` eine direkte Kopie von `RobertaForMaskedLM` mit zwei Ersetzungen: `Roberta` zu `Camembert` und `ROBERTA` zu `CAMEMBERT`. Sie können [hier](https://github.com/huggingface/transformers/blob/15082a9dc6950ecae63a0d3e5060b2fc7f15050a/src/transformers/models/camembert/modeling_camembert.py#L929) sehen, wie dies mit dem Kommentar gemacht wird: + +```py +# Copied from transformers.models.roberta.modeling_roberta.RobertaForMaskedLM with Roberta->Camembert, ROBERTA->CAMEMBERT +``` + +Wenn die Reihenfolge eine Rolle spielt (weil eine der Ersetzungen mit einer vorherigen in Konflikt geraten könnte), werden die Ersetzungen von links nach rechts ausgeführt. + + + +Wenn die Ersetzungen die Formatierung ändern (wenn Sie z.B. einen kurzen Namen durch einen sehr langen Namen ersetzen), wird die Kopie nach Anwendung des automatischen Formats überprüft. + + + +Eine andere Möglichkeit, wenn es sich bei den Mustern nur um verschiedene Umschreibungen derselben Ersetzung handelt (mit einer groß- und einer kleingeschriebenen Variante), besteht darin, die Option `all-casing` hinzuzufügen. [Hier](https://github.com/huggingface/transformers/blob/15082a9dc6950ecae63a0d3e5060b2fc7f15050a/src/transformers/models/mobilebert/modeling_mobilebert.py#L1237) ist ein Beispiel in `MobileBertForSequenceClassification` mit dem Kommentar: + +```py +# Copied from transformers.models.bert.modeling_bert.BertForSequenceClassification with Bert->MobileBert all-casing +``` + +In diesem Fall wird der Code von `BertForSequenceClassification` kopiert, indem er ersetzt wird: +- `Bert` durch `MobileBert` (zum Beispiel bei der Verwendung von `MobileBertModel` in der Init) +- `bert` durch `mobilebert` (zum Beispiel bei der Definition von `self.mobilebert`) +- `BERT` durch `MOBILEBERT` (in der Konstante `MOBILEBERT_INPUTS_DOCSTRING`) diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/preprocessing.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/preprocessing.md new file mode 100644 index 0000000000000000000000000000000000000000..b56a5c0ae4ca1cf64137d6331d10d20cae698769 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/preprocessing.md @@ -0,0 +1,506 @@ + + +# Vorverarbeiten + +[[open-in-colab]] + +Bevor Sie Ihre Daten in einem Modell verwenden können, müssen die Daten in ein für das Modell akzeptables Format gebracht werden. Ein Modell versteht keine Rohtexte, Bilder oder Audiodaten. Diese Eingaben müssen in Zahlen umgewandelt und zu Tensoren zusammengesetzt werden. In dieser Anleitung werden Sie: + +* Textdaten mit einem Tokenizer vorverarbeiten. +* Bild- oder Audiodaten mit einem Feature Extractor vorverarbeiten. +* Daten für eine multimodale Aufgabe mit einem Prozessor vorverarbeiten. + +## NLP + + + +Das wichtigste Werkzeug zur Verarbeitung von Textdaten ist ein [Tokenizer](main_classes/tokenizer). Ein Tokenizer zerlegt Text zunächst nach einer Reihe von Regeln in *Token*. Die Token werden in Zahlen umgewandelt, die zum Aufbau von Tensoren als Eingabe für ein Modell verwendet werden. Alle zusätzlichen Eingaben, die ein Modell benötigt, werden ebenfalls vom Tokenizer hinzugefügt. + + + +Wenn Sie ein vortrainiertes Modell verwenden möchten, ist es wichtig, den zugehörigen vortrainierten Tokenizer zu verwenden. Dadurch wird sichergestellt, dass der Text auf die gleiche Weise aufgeteilt wird wie das Pretraining-Korpus und die gleichen entsprechenden Token-zu-Index (in der Regel als *vocab* bezeichnet) während des Pretrainings verwendet werden. + + + +Laden Sie einen vortrainierten Tokenizer mit der Klasse [AutoTokenizer], um schnell loszulegen. Damit wird das *vocab* heruntergeladen, das verwendet wird, wenn ein Modell vortrainiert wird. + +### Tokenize + +Laden Sie einen vortrainierten Tokenizer mit [`AutoTokenizer.from_pretrained`]: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased") +``` + +Dann übergeben Sie Ihren Satz an den Tokenizer: + +```py +>>> encoded_input = tokenizer("Do not meddle in the affairs of wizards, for they are subtle and quick to anger.") +>>> print(encoded_input) +{'input_ids': [101, 2079, 2025, 19960, 10362, 1999, 1996, 3821, 1997, 16657, 1010, 2005, 2027, 2024, 11259, 1998, 4248, 2000, 4963, 1012, 102], + 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]} +``` + +Der Tokenizer gibt ein Wörterbuch mit drei wichtigen Elementen zurück: + +* [input_ids](glossary#input-ids) sind die Indizes, die den einzelnen Token im Satz entsprechen. +* [attention_mask](glossary#attention-mask) gibt an, ob ein Token beachtet werden soll oder nicht. +* [token_type_ids](glossary#token-type-ids) gibt an, zu welcher Sequenz ein Token gehört, wenn es mehr als eine Sequenz gibt. + +Sie können die `input_ids` dekodieren, um die ursprüngliche Eingabe zurückzugeben: + +```py +>>> tokenizer.decode(encoded_input["input_ids"]) +'[CLS] Do not meddle in the affairs of wizards, for they are subtle and quick to anger. [SEP]' +``` + +Wie Sie sehen können, hat der Tokenisierer zwei spezielle Token - `CLS` und `SEP` (Klassifikator und Separator) - zum Satz hinzugefügt. Nicht alle Modelle benötigen +spezielle Token, aber wenn dies der Fall ist, fügt der Tokenisierer sie automatisch für Sie hinzu. + +Wenn Sie mehrere Sätze verarbeiten wollen, übergeben Sie die Sätze als Liste an den Tokenizer: + +```py +>>> batch_sentences = [ +... "But what about second breakfast?", +... "Don't think he knows about second breakfast, Pip.", +... "What about elevensies?", +... ] +>>> encoded_inputs = tokenizer(batch_sentences) +>>> print(encoded_inputs) +{'input_ids': [[101, 1252, 1184, 1164, 1248, 6462, 136, 102], + [101, 1790, 112, 189, 1341, 1119, 3520, 1164, 1248, 6462, 117, 21902, 1643, 119, 102], + [101, 1327, 1164, 5450, 23434, 136, 102]], + 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], + 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1]]} +``` + +### Pad + +Dies bringt uns zu einem wichtigen Thema. Wenn Sie einen Haufen von Sätzen verarbeiten, sind diese nicht immer gleich lang. Das ist ein Problem, weil Tensoren, die Eingabe für das Modell, eine einheitliche Form haben müssen. Padding ist eine Strategie, die sicherstellt, dass Tensoren rechteckig sind, indem ein spezielles *Padding-Token* zu Sätzen mit weniger Token hinzugefügt wird. + +Setzen Sie den Parameter "padding" auf "true", um die kürzeren Sequenzen im Stapel so aufzufüllen, dass sie der längsten Sequenz entsprechen: + +```py +>>> batch_sentences = [ +... "But what about second breakfast?", +... "Don't think he knows about second breakfast, Pip.", +... "What about elevensies?", +... ] +>>> encoded_input = tokenizer(batch_sentences, padding=True) +>>> print(encoded_input) +{'input_ids': [[101, 1252, 1184, 1164, 1248, 6462, 136, 102, 0, 0, 0, 0, 0, 0, 0], + [101, 1790, 112, 189, 1341, 1119, 3520, 1164, 1248, 6462, 117, 21902, 1643, 119, 102], + [101, 1327, 1164, 5450, 23434, 136, 102, 0, 0, 0, 0, 0, 0, 0, 0]], + 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], + 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]]} +``` + +Beachten Sie, dass der Tokenizer den ersten und den dritten Satz mit einer "0" aufgefüllt hat, weil sie kürzer sind! + +### Kürzung + +Auf der anderen Seite des Spektrums kann es vorkommen, dass eine Sequenz zu lang für ein Modell ist. In diesem Fall müssen Sie die Sequenz auf eine kürzere Länge kürzen. + +Setzen Sie den Parameter "truncation" auf "true", um eine Sequenz auf die vom Modell akzeptierte Höchstlänge zu kürzen: + +```py +>>> batch_sentences = [ +... "But what about second breakfast?", +... "Don't think he knows about second breakfast, Pip.", +... "What about elevensies?", +... ] +>>> encoded_input = tokenizer(batch_sentences, padding=True, truncation=True) +>>> print(encoded_input) +{'input_ids': [[101, 1252, 1184, 1164, 1248, 6462, 136, 102, 0, 0, 0, 0, 0, 0, 0], + [101, 1790, 112, 189, 1341, 1119, 3520, 1164, 1248, 6462, 117, 21902, 1643, 119, 102], + [101, 1327, 1164, 5450, 23434, 136, 102, 0, 0, 0, 0, 0, 0, 0, 0]], + 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], + 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]]} +``` + +### Tensoren erstellen + +Schließlich möchten Sie, dass der Tokenizer die tatsächlichen Tensoren zurückgibt, die dem Modell zugeführt werden. + +Setzen Sie den Parameter `return_tensors` entweder auf `pt` für PyTorch, oder `tf` für TensorFlow: + + + + +```py +>>> batch_sentences = [ +... "But what about second breakfast?", +... "Don't think he knows about second breakfast, Pip.", +... "What about elevensies?", +... ] +>>> encoded_input = tokenizer(batch_sentences, padding=True, truncation=True, return_tensors="pt") +>>> print(encoded_input) +{'input_ids': tensor([[101, 1252, 1184, 1164, 1248, 6462, 136, 102, 0, 0, 0, 0, 0, 0, 0], + [101, 1790, 112, 189, 1341, 1119, 3520, 1164, 1248, 6462, 117, 21902, 1643, 119, 102], + [101, 1327, 1164, 5450, 23434, 136, 102, 0, 0, 0, 0, 0, 0, 0, 0]]), + 'token_type_ids': tensor([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]), + 'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]])} +``` + + +```py +>>> batch_sentences = [ +... "But what about second breakfast?", +... "Don't think he knows about second breakfast, Pip.", +... "What about elevensies?", +... ] +>>> encoded_input = tokenizer(batch_sentences, padding=True, truncation=True, return_tensors="tf") +>>> print(encoded_input) +{'input_ids': , + 'token_type_ids': , + 'attention_mask': } +``` + + + +## Audio + +Audioeingaben werden anders vorverarbeitet als Texteingaben, aber das Endziel bleibt dasselbe: numerische Sequenzen zu erstellen, die das Modell verstehen kann. Ein [feature extractor](main_classes/feature_extractor) dient dem ausdrücklichen Zweck, Merkmale aus Rohbild- oder Audiodaten zu extrahieren und in Tensoren zu konvertieren. Bevor Sie beginnen, installieren Sie 🤗 Datasets, um einen Audio-Datensatz zu laden, mit dem Sie experimentieren können: + +```bash +pip install datasets +``` + +Laden Sie den [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) Datensatz (weitere Informationen zum Laden eines Datensatzes finden Sie im 🤗 [Datasets tutorial](https://huggingface.co/docs/datasets/load_hub)): + +```py +>>> from datasets import load_dataset, Audio + +>>> dataset = load_dataset("PolyAI/minds14", name="en-US", split="train") +``` + +Greifen Sie auf das erste Element der `audio`-Spalte zu, um einen Blick auf die Eingabe zu werfen. Durch den Aufruf der Spalte "audio" wird die Audiodatei automatisch geladen und neu gesampelt: + +```py +>>> dataset[0]["audio"] +{'array': array([ 0. , 0.00024414, -0.00024414, ..., -0.00024414, + 0. , 0. ], dtype=float32), + 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav', + 'sampling_rate': 8000} +``` + +Dies gibt drei Elemente zurück: + +* "array" ist das Sprachsignal, das als 1D-Array geladen - und möglicherweise neu gesampelt - wurde. +* Pfad" zeigt auf den Speicherort der Audiodatei. +* `sampling_rate` bezieht sich darauf, wie viele Datenpunkte im Sprachsignal pro Sekunde gemessen werden. + +### Resample + +Für dieses Tutorial werden Sie das Modell [Wav2Vec2](https://huggingface.co/facebook/wav2vec2-base) verwenden. Wie Sie aus der Modellkarte ersehen können, ist das Wav2Vec2-Modell auf 16kHz abgetastetes Sprachaudio vortrainiert. Es ist wichtig, dass die Abtastrate Ihrer Audiodaten mit der Abtastrate des Datensatzes übereinstimmt, der für das Pre-Training des Modells verwendet wurde. Wenn die Abtastrate Ihrer Daten nicht dieselbe ist, müssen Sie Ihre Audiodaten neu abtasten. + +Der Datensatz [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) hat zum Beispiel eine Abtastrate von 8000 kHz. Um das Wav2Vec2-Modell mit diesem Datensatz verwenden zu können, müssen Sie die Abtastrate auf 16 kHz erhöhen: + +```py +>>> dataset = load_dataset("PolyAI/minds14", name="en-US", split="train") +>>> dataset[0]["audio"] +{'array': array([ 0. , 0.00024414, -0.00024414, ..., -0.00024414, + 0. , 0. ], dtype=float32), + 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav', + 'sampling_rate': 8000} +``` + +1. Verwenden Sie die Methode [`~datasets.Dataset.cast_column`] von 🤗 Datasets, um die Abtastrate auf 16kHz zu erhöhen: + +```py +>>> dataset = dataset.cast_column("audio", Audio(sampling_rate=16_000)) +``` + +2. Laden Sie die Audiodatei: + +```py +>>> dataset[0]["audio"] +{'array': array([ 2.3443763e-05, 2.1729663e-04, 2.2145823e-04, ..., + 3.8356509e-05, -7.3497440e-06, -2.1754686e-05], dtype=float32), + 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav', + 'sampling_rate': 16000} +``` + +Wie Sie sehen können, ist die Abtastrate jetzt 16kHz! + +### Merkmalsextraktor + +Der nächste Schritt ist das Laden eines Merkmalsextraktors, um die Eingabe zu normalisieren und aufzufüllen. Beim Auffüllen von Textdaten wird für kürzere Sequenzen ein `0` hinzugefügt. Die gleiche Idee gilt für Audiodaten, und der Audio-Feature-Extraktor fügt eine `0` - interpretiert als Stille - zu `array` hinzu. + +Laden Sie den Merkmalsextraktor mit [`AutoFeatureExtractor.from_pretrained`]: + +```py +>>> from transformers import AutoFeatureExtractor + +>>> feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base") +``` + +Übergeben Sie das Audio-"Array" an den Feature-Extraktor. Wir empfehlen auch, das Argument `sampling_rate` im Feature Extractor hinzuzufügen, um eventuell auftretende stille Fehler besser zu beheben. + +```py +>>> audio_input = [dataset[0]["audio"]["array"]] +>>> feature_extractor(audio_input, sampling_rate=16000) +{'input_values': [array([ 3.8106556e-04, 2.7506407e-03, 2.8015103e-03, ..., + 5.6335266e-04, 4.6588284e-06, -1.7142107e-04], dtype=float32)]} +``` + +### Auffüllen und Kürzen + +Genau wie beim Tokenizer können Sie variable Sequenzen in einem Stapel durch Auffüllen oder Abschneiden behandeln. Werfen Sie einen Blick auf die Sequenzlänge dieser beiden Audiobeispiele: + +```py +>>> dataset[0]["audio"]["array"].shape +(173398,) + +>>> dataset[1]["audio"]["array"].shape +(106496,) +``` + +Wie Sie sehen können, hat das erste Beispiel eine längere Sequenz als das zweite Beispiel. Lassen Sie uns eine Funktion erstellen, die den Datensatz vorverarbeitet. Geben Sie eine maximale Länge der Probe an, und der Feature-Extraktor wird die Sequenzen entweder auffüllen oder abschneiden, damit sie dieser Länge entsprechen: + +```py +>>> def preprocess_function(examples): +... audio_arrays = [x["array"] for x in examples["audio"]] +... inputs = feature_extractor( +... audio_arrays, +... sampling_rate=16000, +... padding=True, +... max_length=100000, +... truncation=True, +... ) +... return inputs +``` + +Wenden Sie die Funktion auf die ersten paar Beispiele im Datensatz an: + +```py +>>> processed_dataset = preprocess_function(dataset[:5]) +``` + +Schauen Sie sich nun noch einmal die verarbeiteten Beispiel-Längen an: + +```py +>>> processed_dataset["input_values"][0].shape +(100000,) + +>>> processed_dataset["input_values"][1].shape +(100000,) +``` + +Die Länge der ersten beiden Beispiele entspricht nun der von Ihnen angegebenen Maximallänge. + +## Bildverarbeitung + +Ein Merkmalsextraktor wird auch verwendet, um Bilder für Bildverarbeitungsaufgaben zu verarbeiten. Auch hier besteht das Ziel darin, das Rohbild in eine Reihe von Tensoren als Eingabe zu konvertieren. + +Laden wir den [food101](https://huggingface.co/datasets/food101) Datensatz für dieses Tutorial. Verwenden Sie den Parameter 🤗 Datasets `split`, um nur eine kleine Stichprobe aus dem Trainingssplit zu laden, da der Datensatz recht groß ist: + +```py +>>> from datasets import load_dataset + +>>> dataset = load_dataset("food101", split="train[:100]") +``` + +Als Nächstes sehen Sie sich das Bild mit dem Merkmal 🤗 Datensätze [Bild](https://huggingface.co/docs/datasets/package_reference/main_classes?highlight=image#datasets.Image) an: + +```py +>>> dataset[0]["image"] +``` + +![vision-preprocess-tutorial.png](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/vision-preprocess-tutorial.png) + +### Merkmalsextraktor + +Laden Sie den Merkmalsextraktor mit [`AutoImageProcessor.from_pretrained`]: + +```py +>>> from transformers import AutoImageProcessor + +>>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224") +``` + +### Datenerweiterung + +Bei Bildverarbeitungsaufgaben ist es üblich, den Bildern als Teil der Vorverarbeitung eine Art von Datenerweiterung hinzuzufügen. Sie können Erweiterungen mit jeder beliebigen Bibliothek hinzufügen, aber in diesem Tutorial werden Sie das Modul [`transforms`](https://pytorch.org/vision/stable/transforms.html) von torchvision verwenden. + +1. Normalisieren Sie das Bild und verwenden Sie [`Compose`](https://pytorch.org/vision/master/generated/torchvision.transforms.Compose.html), um einige Transformationen - [`RandomResizedCrop`](https://pytorch.org/vision/main/generated/torchvision.transforms.RandomResizedCrop.html) und [`ColorJitter`](https://pytorch.org/vision/main/generated/torchvision.transforms.ColorJitter.html) - miteinander zu verknüpfen: + +```py +>>> from torchvision.transforms import Compose, Normalize, RandomResizedCrop, ColorJitter, ToTensor + +>>> normalize = Normalize(mean=image_processor.image_mean, std=image_processor.image_std) +>>> _transforms = Compose( +... [RandomResizedCrop(image_processor.size["height"]), ColorJitter(brightness=0.5, hue=0.5), ToTensor(), normalize] +... ) +``` + +2. Das Modell akzeptiert [`pixel_values`](model_doc/visionencoderdecoder#transformers.VisionEncoderDecoderModel.forward.pixel_values) als Eingabe. Dieser Wert wird vom Merkmalsextraktor erzeugt. Erstellen Sie eine Funktion, die `pixel_values` aus den Transformationen erzeugt: + +```py +>>> def transforms(examples): +... examples["pixel_values"] = [_transforms(image.convert("RGB")) for image in examples["image"]] +... return examples +``` + +3. Dann verwenden Sie 🤗 Datasets [`set_transform`](https://huggingface.co/docs/datasets/process#format-transform), um die Transformationen im laufenden Betrieb anzuwenden: + +```py +>>> dataset.set_transform(transforms) +``` + +4. Wenn Sie nun auf das Bild zugreifen, werden Sie feststellen, dass der Feature Extractor die Modelleingabe "pixel_values" hinzugefügt hat: + +```py +>>> dataset[0]["image"] +{'image': , + 'label': 6, + 'pixel_values': tensor([[[ 0.0353, 0.0745, 0.1216, ..., -0.9922, -0.9922, -0.9922], + [-0.0196, 0.0667, 0.1294, ..., -0.9765, -0.9843, -0.9922], + [ 0.0196, 0.0824, 0.1137, ..., -0.9765, -0.9686, -0.8667], + ..., + [ 0.0275, 0.0745, 0.0510, ..., -0.1137, -0.1216, -0.0824], + [ 0.0667, 0.0824, 0.0667, ..., -0.0588, -0.0745, -0.0980], + [ 0.0353, 0.0353, 0.0431, ..., -0.0039, -0.0039, -0.0588]], + + [[ 0.2078, 0.2471, 0.2863, ..., -0.9451, -0.9373, -0.9451], + [ 0.1608, 0.2471, 0.3098, ..., -0.9373, -0.9451, -0.9373], + [ 0.2078, 0.2706, 0.3020, ..., -0.9608, -0.9373, -0.8275], + ..., + [-0.0353, 0.0118, -0.0039, ..., -0.2392, -0.2471, -0.2078], + [ 0.0196, 0.0353, 0.0196, ..., -0.1843, -0.2000, -0.2235], + [-0.0118, -0.0039, -0.0039, ..., -0.0980, -0.0980, -0.1529]], + + [[ 0.3961, 0.4431, 0.4980, ..., -0.9216, -0.9137, -0.9216], + [ 0.3569, 0.4510, 0.5216, ..., -0.9059, -0.9137, -0.9137], + [ 0.4118, 0.4745, 0.5216, ..., -0.9137, -0.8902, -0.7804], + ..., + [-0.2314, -0.1922, -0.2078, ..., -0.4196, -0.4275, -0.3882], + [-0.1843, -0.1686, -0.2000, ..., -0.3647, -0.3804, -0.4039], + [-0.1922, -0.1922, -0.1922, ..., -0.2941, -0.2863, -0.3412]]])} +``` + +Hier sehen Sie, wie das Bild nach der Vorverarbeitung aussieht. Wie von den angewandten Transformationen zu erwarten, wurde das Bild willkürlich beschnitten und seine Farbeigenschaften sind anders. + +```py +>>> import numpy as np +>>> import matplotlib.pyplot as plt + +>>> img = dataset[0]["pixel_values"] +>>> plt.imshow(img.permute(1, 2, 0)) +``` + +![preprocessed_image](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/preprocessed_image.png) + +## Multimodal + +Für multimodale Aufgaben werden Sie eine Kombination aus allem, was Sie bisher gelernt haben, verwenden und Ihre Fähigkeiten auf eine Aufgabe der automatischen Spracherkennung (ASR) anwenden. Dies bedeutet, dass Sie einen: + +* Feature Extractor zur Vorverarbeitung der Audiodaten. +* Tokenizer, um den Text zu verarbeiten. + +Kehren wir zum [LJ Speech](https://huggingface.co/datasets/lj_speech) Datensatz zurück: + +```py +>>> from datasets import load_dataset + +>>> lj_speech = load_dataset("lj_speech", split="train") +``` + +Da Sie hauptsächlich an den Spalten "Audio" und "Text" interessiert sind, entfernen Sie die anderen Spalten: + +```py +>>> lj_speech = lj_speech.map(remove_columns=["file", "id", "normalized_text"]) +``` + +Schauen Sie sich nun die Spalten "Audio" und "Text" an: + +```py +>>> lj_speech[0]["audio"] +{'array': array([-7.3242188e-04, -7.6293945e-04, -6.4086914e-04, ..., + 7.3242188e-04, 2.1362305e-04, 6.1035156e-05], dtype=float32), + 'path': '/root/.cache/huggingface/datasets/downloads/extracted/917ece08c95cf0c4115e45294e3cd0dee724a1165b7fc11798369308a465bd26/LJSpeech-1.1/wavs/LJ001-0001.wav', + 'sampling_rate': 22050} + +>>> lj_speech[0]["text"] +'Printing, in the only sense with which we are at present concerned, differs from most if not from all the arts and crafts represented in the Exhibition' +``` + +Erinnern Sie sich an den früheren Abschnitt über die Verarbeitung von Audiodaten: Sie sollten immer die Abtastrate Ihrer Audiodaten [resample](preprocessing#audio), damit sie mit der Abtastrate des Datensatzes übereinstimmt, der für das Vortraining eines Modells verwendet wird: + +```py +>>> lj_speech = lj_speech.cast_column("audio", Audio(sampling_rate=16_000)) +``` + +### Prozessor + +Ein Processor kombiniert einen Feature-Extraktor und einen Tokenizer. Laden Sie einen Processor mit [`AutoProcessor.from_pretrained`]: + +```py +>>> from transformers import AutoProcessor + +>>> processor = AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h") +``` + +1. Erstellen Sie eine Funktion, die die Audiodaten zu `input_values` verarbeitet und den Text zu `labels` tokenisiert. Dies sind Ihre Eingaben für das Modell: + +```py +>>> def prepare_dataset(example): +... audio = example["audio"] + +... example.update(processor(audio=audio["array"], text=example["text"], sampling_rate=16000)) + +... return example +``` + +2. Wenden Sie die Funktion "prepare_dataset" auf ein Beispiel an: + +```py +>>> prepare_dataset(lj_speech[0]) +``` + +Beachten Sie, dass der Processor `input_values` und `labels` hinzugefügt hat. Auch die Abtastrate wurde korrekt auf 16kHz heruntergerechnet. + +Toll, Sie sollten jetzt in der Lage sein, Daten für jede Modalität vorzuverarbeiten und sogar verschiedene Modalitäten zu kombinieren! Im nächsten Kurs lernen Sie, wie Sie ein Modell mit Ihren neu aufbereiteten Daten feinabstimmen können. diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/quicktour.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/quicktour.md new file mode 100644 index 0000000000000000000000000000000000000000..856ba546b977693c261939ca8ac19296b764740c --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/quicktour.md @@ -0,0 +1,438 @@ + + +# Schnellstart + +[[open-in-colab]] + +Mit 🤗 Transformers können Sie sofort loslegen! Verwenden Sie die [`pipeline`] für schnelle Inferenz und laden Sie schnell ein vortrainiertes Modell und einen Tokenizer mit einer [AutoClass](./model_doc/auto), um Ihre Text-, Bild- oder Audioaufgabe zu lösen. + + + +Alle in der Dokumentation vorgestellten Codebeispiele haben oben links einen Umschalter für PyTorch und TensorFlow. Wenn +nicht, wird erwartet, dass der Code für beide Backends ohne Änderungen funktioniert. + + + +## Pipeline + +[`pipeline`] ist der einfachste Weg, ein vortrainiertes Modell für eine bestimmte Aufgabe zu verwenden. + + + +Die [`pipeline`] unterstützt viele gängige Aufgaben: + +**Text**: +* Stimmungsanalyse: Klassifizierung der Polarität eines gegebenen Textes. +* Textgenerierung (auf Englisch): Generierung von Text aus einer gegebenen Eingabe. +* Name-Entity-Recognition (NER): Kennzeichnung jedes Worts mit der Entität, die es repräsentiert (Person, Datum, Ort usw.). +* Beantwortung von Fragen: Extrahieren der Antwort aus dem Kontext, wenn ein gewisser Kontext und eine Frage gegeben sind. +* Fill-mask: Ausfüllen von Lücken in einem Text mit maskierten Wörtern. +* Zusammenfassung: Erstellung einer Zusammenfassung einer langen Text- oder Dokumentensequenz. +* Übersetzung: Übersetzen eines Textes in eine andere Sprache. +* Merkmalsextraktion: Erstellen einer Tensordarstellung des Textes. + +**Bild**: +* Bildklassifizierung: Klassifizierung eines Bildes. +* Bildsegmentierung: Klassifizierung jedes Pixels in einem Bild. +* Objekterkennung: Erkennen von Objekten innerhalb eines Bildes. + +**Audio**: +* Audioklassifizierung: Zuweisung eines Labels zu einem bestimmten Audiosegment. +* Automatische Spracherkennung (ASR): Transkription von Audiodaten in Text. + + + +Für mehr Details über die [`pipeline`] und assoziierte Aufgaben, schauen Sie in die Dokumentation [hier](./main_classes/pipelines). + + + +### Verwendung der Pipeline + +Im folgenden Beispiel werden Sie die [`pipeline`] für die Stimmungsanalyse verwenden. + +Installieren Sie die folgenden Abhängigkeiten, falls Sie dies nicht bereits getan haben: + + + + +```bash +pip install torch +``` + + + +```bash +pip install tensorflow +``` + + + +Importieren sie die [`pipeline`] und spezifizieren sie die Aufgabe, welche sie lösen möchten: + +```py +>>> from transformers import pipeline + +>>> classifier = pipeline("sentiment-analysis") +``` + +Die Pipeline lädt ein standardmäßiges [vortrainiertes Modell](https://huggingface.co/distilbert/distilbert-base-uncased-finetuned-sst-2-english) und einen Tokenizer für die Stimmungs-Analyse herunter und speichert sie. Jetzt können Sie den "Klassifikator" auf Ihren Zieltext anwenden: + +```py +>>> classifier("We are very happy to show you the 🤗 Transformers library.") +[{'label': 'POSITIVE', 'score': 0.9998}] +``` + +For more than one sentence, pass a list of sentences to the [`pipeline`] which returns a list of dictionaries: + +```py +>>> results = classifier(["We are very happy to show you the 🤗 Transformers library.", "We hope you don't hate it."]) +>>> for result in results: +... print(f"label: {result['label']}, with score: {round(result['score'], 4)}") +label: POSITIVE, with score: 0.9998 +label: NEGATIVE, with score: 0.5309 +``` + +Die [`pipeline`] kann auch über einen ganzen Datensatz iterieren. Starten wir mit der Installation der [🤗 Datasets](https://huggingface.co/docs/datasets/) Bibliothek: + +```bash +pip install datasets +``` + +Erstellen wir eine [`pipeline`] mit der Aufgabe die wir lösen und dem Modell welches wir nutzen möchten. + +```py +>>> import torch +>>> from transformers import pipeline + +>>> speech_recognizer = pipeline("automatic-speech-recognition", model="facebook/wav2vec2-base-960h") +``` + +Als nächstes laden wir den Datensatz (siehe 🤗 Datasets [Quick Start](https://huggingface.co/docs/datasets/quickstart) für mehr Details) welches wir nutzen möchten. Zum Beispiel laden wir den [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) Datensatz: + +```py +>>> from datasets import load_dataset, Audio + +>>> dataset = load_dataset("PolyAI/minds14", name="en-US", split="train") # doctest: +IGNORE_RESULT +``` + +Wir müssen sicherstellen, dass die Abtastrate des Datensatzes der Abtastrate entspricht, mit der `facebook/wav2vec2-base-960h` trainiert wurde. + +```py +>>> dataset = dataset.cast_column("audio", Audio(sampling_rate=speech_recognizer.feature_extractor.sampling_rate)) +``` + +Audiodateien werden automatisch geladen und neu abgetastet, wenn die Spalte "audio" aufgerufen wird. +Extrahieren wir die rohen Wellenform-Arrays der ersten 4 Beispiele und übergeben wir sie als Liste an die Pipeline: + +```py +>>> result = speech_recognizer(dataset[:4]["audio"]) +>>> print([d["text"] for d in result]) +['I WOULD LIKE TO SET UP A JOINT ACCOUNT WITH MY PARTNER HOW DO I PROCEED WITH DOING THAT', "FODING HOW I'D SET UP A JOIN TO HET WITH MY WIFE AND WHERE THE AP MIGHT BE", "I I'D LIKE TOY SET UP A JOINT ACCOUNT WITH MY PARTNER I'M NOT SEEING THE OPTION TO DO IT ON THE AP SO I CALLED IN TO GET SOME HELP CAN I JUST DO IT OVER THE PHONE WITH YOU AND GIVE YOU THE INFORMATION OR SHOULD I DO IT IN THE AP AND I'M MISSING SOMETHING UQUETTE HAD PREFERRED TO JUST DO IT OVER THE PHONE OF POSSIBLE THINGS", 'HOW DO I THURN A JOIN A COUNT'] +``` + +Bei einem größeren Datensatz mit vielen Eingaben (wie bei Sprache oder Bildverarbeitung) sollten Sie einen Generator anstelle einer Liste übergeben, der alle Eingaben in den Speicher lädt. Weitere Informationen finden Sie in der [Pipeline-Dokumentation](./main_classes/pipelines). + +### Ein anderes Modell und einen anderen Tokenizer in der Pipeline verwenden + +Die [`pipeline`] kann jedes Modell aus dem [Model Hub](https://huggingface.co/models) verwenden, wodurch es einfach ist, die [`pipeline`] für andere Anwendungsfälle anzupassen. Wenn Sie beispielsweise ein Modell wünschen, das französischen Text verarbeiten kann, verwenden Sie die Tags im Model Hub, um nach einem geeigneten Modell zu filtern. Das oberste gefilterte Ergebnis liefert ein mehrsprachiges [BERT-Modell](https://huggingface.co/nlptown/bert-base-multilingual-uncased-sentiment), das auf die Stimmungsanalyse abgestimmt ist. Großartig, verwenden wir dieses Modell! + +```py +>>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment" +``` + + + +Use the [`AutoModelForSequenceClassification`] and [`AutoTokenizer`] to load the pretrained model and its associated tokenizer (more on an `AutoClass` below): + +```py +>>> from transformers import AutoTokenizer, AutoModelForSequenceClassification + +>>> model = AutoModelForSequenceClassification.from_pretrained(model_name) +>>> tokenizer = AutoTokenizer.from_pretrained(model_name) +``` + + +Use the [`TFAutoModelForSequenceClassification`] and [`AutoTokenizer`] to load the pretrained model and its associated tokenizer (more on an `TFAutoClass` below): + +```py +>>> from transformers import AutoTokenizer, TFAutoModelForSequenceClassification + +>>> model = TFAutoModelForSequenceClassification.from_pretrained(model_name) +>>> tokenizer = AutoTokenizer.from_pretrained(model_name) +``` + + + +Dann können Sie das Modell und den Tokenizer in der [`pipeline`] angeben und den `Klassifikator` auf Ihren Zieltext anwenden: + +```py +>>> classifier = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer) +>>> classifier("Nous sommes très heureux de vous présenter la bibliothèque 🤗 Transformers.") +[{'label': '5 stars', 'score': 0.7273}] +``` + +Wenn Sie kein Modell für Ihren Anwendungsfall finden können, müssen Sie ein vortrainiertes Modell auf Ihren Daten feinabstimmen. Schauen Sie sich unser [Feinabstimmungs-Tutorial](./training) an, um zu erfahren, wie das geht. Und schließlich, nachdem Sie Ihr trainiertes Modell verfeinert haben, sollten Sie es mit der Community im Model Hub teilen (siehe Tutorial [hier](./model_sharing)), um NLP für alle zu demokratisieren! 🤗 + +## AutoClass + + + +Unter der Haube arbeiten die Klassen [`AutoModelForSequenceClassification`] und [`AutoTokenizer`] zusammen, um die [`pipeline`] zu betreiben. Eine [`AutoClass`](./model_doc/auto) ist eine Abkürzung, die automatisch die Architektur eines trainierten Modells aus dessen Namen oder Pfad abruft. Sie müssen nur die passende `AutoClass` für Ihre Aufgabe und den zugehörigen Tokenizer mit [`AutoTokenizer`] auswählen. + +Kehren wir zu unserem Beispiel zurück und sehen wir uns an, wie Sie die `AutoClass` verwenden können, um die Ergebnisse der [`pipeline`] zu replizieren. + +### AutoTokenizer + +Ein Tokenizer ist für die Vorverarbeitung von Text in ein für das Modell verständliches Format zuständig. Zunächst zerlegt der Tokenisierer den Text in Wörter, die *Token* genannt werden. Es gibt mehrere Regeln für den Tokenisierungsprozess, z. B. wie und auf welcher Ebene ein Wort aufgespalten wird (weitere Informationen über Tokenisierung [hier](./tokenizer_summary)). Das Wichtigste ist jedoch, dass Sie den Tokenizer mit demselben Modellnamen instanziieren müssen, um sicherzustellen, dass Sie dieselben Tokenisierungsregeln verwenden, mit denen ein Modell zuvor trainiert wurde. +Laden sie einen Tokenizer mit [`AutoTokenizer`]: + +```py +>>> from transformers import AutoTokenizer + +>>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment" +>>> tokenizer = AutoTokenizer.from_pretrained(model_name) +``` + +Anschließend wandelt der Tokenizer die Token in Zahlen um, um einen Tensor als Eingabe für das Modell zu konstruieren. Dieser wird als *Vokabular* des Modells bezeichnet. + +Übergeben Sie Ihren Text an den Tokenizer: + +```py +>>> encoding = tokenizer("We are very happy to show you the 🤗 Transformers library.") +>>> print(encoding) +{'input_ids': [101, 11312, 10320, 12495, 19308, 10114, 11391, 10855, 10103, 100, 58263, 13299, 119, 102], + 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]} +``` + +Der Tokenizer gibt ein Wörterbuch zurück, das Folgendes enthält: + +* [input_ids](./glossary#input-ids): numerische Repräsentationen Ihrer Token. +* [attention_mask](.glossary#attention-mask): gibt an, welche Token beachtet werden sollen. + +Genau wie die [`pipeline`] akzeptiert der Tokenizer eine Liste von Eingaben. Darüber hinaus kann der Tokenizer den Text auch auffüllen und kürzen, um einen Stapel mit einheitlicher Länge zurückzugeben: + + + + +```py +>>> pt_batch = tokenizer( +... ["We are very happy to show you the 🤗 Transformers library.", "We hope you don't hate it."], +... padding=True, +... truncation=True, +... max_length=512, +... return_tensors="pt", +... ) +``` + + + +```py +>>> tf_batch = tokenizer( +... ["We are very happy to show you the 🤗 Transformers library.", "We hope you don't hate it."], +... padding=True, +... truncation=True, +... max_length=512, +... return_tensors="tf", +... ) +``` + + + +Lesen Sie das Tutorial [preprocessing](./preprocessing) für weitere Details zur Tokenisierung. + +### AutoModel + + + +🤗 Transformers bietet eine einfache und einheitliche Möglichkeit, vortrainierte Instanzen zu laden. Das bedeutet, dass Sie ein [`AutoModel`] laden können, wie Sie einen [`AutoTokenizer`] laden würden. Der einzige Unterschied ist die Auswahl des richtigen [`AutoModel`] für die Aufgabe. Da Sie eine Text- oder Sequenzklassifizierung vornehmen, laden Sie [`AutoModelForSequenceClassification`]: + +```py +>>> from transformers import AutoModelForSequenceClassification + +>>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment" +>>> pt_model = AutoModelForSequenceClassification.from_pretrained(model_name) +``` + + + +In der [Aufgabenzusammenfassung](./task_summary) steht, welche [AutoModel]-Klasse für welche Aufgabe zu verwenden ist. + + + +Jetzt können Sie Ihren vorverarbeiteten Stapel von Eingaben direkt an das Modell übergeben. Sie müssen nur das Wörterbuch entpacken, indem Sie `**` hinzufügen: + +```py +>>> pt_outputs = pt_model(**pt_batch) +``` + +Das Modell gibt die endgültigen Aktivierungen in dem Attribut "logits" aus. Wenden Sie die Softmax-Funktion auf die "logits" an, um die Wahrscheinlichkeiten zu erhalten: + +```py +>>> from torch import nn + +>>> pt_predictions = nn.functional.softmax(pt_outputs.logits, dim=-1) +>>> print(pt_predictions) +tensor([[0.0021, 0.0018, 0.0115, 0.2121, 0.7725], + [0.2084, 0.1826, 0.1969, 0.1755, 0.2365]], grad_fn=) +``` + + +🤗 Transformers bietet eine einfache und einheitliche Methode zum Laden von vortrainierten Instanzen. Das bedeutet, dass Sie ein [`TFAutoModel`] genauso laden können, wie Sie einen [`AutoTokenizer`] laden würden. Der einzige Unterschied ist die Auswahl des richtigen [`TFAutoModel`] für die Aufgabe. Da Sie Text - oder Sequenz - Klassifizierung machen, laden Sie [`TFAutoModelForSequenceClassification`]: + +```py +>>> from transformers import TFAutoModelForSequenceClassification + +>>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment" +>>> tf_model = TFAutoModelForSequenceClassification.from_pretrained(model_name) +``` + + + +In der [Aufgabenzusammenfassung](./task_summary) steht, welche [AutoModel]-Klasse für welche Aufgabe zu verwenden ist. + + + +Jetzt können Sie Ihren vorverarbeiteten Stapel von Eingaben direkt an das Modell übergeben, indem Sie die Wörterbuchschlüssel direkt an die Tensoren übergeben: + +```py +>>> tf_outputs = tf_model(tf_batch) +``` + +Das Modell gibt die endgültigen Aktivierungen in dem Attribut "logits" aus. Wenden Sie die Softmax-Funktion auf die "logits" an, um die Wahrscheinlichkeiten zu erhalten: + +```py +>>> import tensorflow as tf + +>>> tf_predictions = tf.nn.softmax(tf_outputs.logits, axis=-1) +>>> tf_predictions # doctest: +IGNORE_RESULT +``` + + + + + +Alle 🤗 Transformers-Modelle (PyTorch oder TensorFlow) geben die Tensoren *vor* der endgültigen Aktivierungsfunktion +Funktion (wie Softmax) aus, da die endgültige Aktivierungsfunktion oft mit dem Verlusten verschmolzen ist. + + + +Modelle sind ein standardmäßiges [`torch.nn.Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) oder ein [`tf.keras.Model`](https://www.tensorflow.org/api_docs/python/tf/keras/Model), sodass Sie sie in Ihrer üblichen Trainingsschleife verwenden können. Um jedoch die Dinge einfacher zu machen, bietet 🤗 Transformers eine [`Trainer`]-Klasse für PyTorch, die Funktionalität für verteiltes Training, gemischte Präzision und mehr bietet. Für TensorFlow können Sie die Methode `fit` aus [Keras](https://keras.io/) verwenden. Siehe das [training tutorial](./training) für weitere Details. + + + +Transformers-Modellausgaben sind spezielle Datenklassen, so dass ihre Attribute in einer IDE automatisch vervollständigt werden. +Die Modellausgänge verhalten sich auch wie ein Tupel oder ein Wörterbuch (z.B. können Sie mit einem Integer, einem Slice oder einem String indexieren), wobei die Attribute, die "None" sind, ignoriert werden. + + + +### Modell speichern + + + +Sobald Ihr Modell feinabgestimmt ist, können Sie es mit seinem Tokenizer speichern, indem Sie [`PreTrainedModel.save_pretrained`] verwenden: + +```py +>>> pt_save_directory = "./pt_save_pretrained" +>>> tokenizer.save_pretrained(pt_save_directory) # doctest: +IGNORE_RESULT +>>> pt_model.save_pretrained(pt_save_directory) +``` + +Wenn Sie bereit sind, das Modell erneut zu verwenden, laden Sie es mit [`PreTrainedModel.from_pretrained`]: + +```py +>>> pt_model = AutoModelForSequenceClassification.from_pretrained("./pt_save_pretrained") +``` + + +Sobald Ihr Modell feinabgestimmt ist, können Sie es mit seinem Tokenizer unter Verwendung von [`TFPreTrainedModel.save_pretrained`] speichern: + +```py +>>> tf_save_directory = "./tf_save_pretrained" +>>> tokenizer.save_pretrained(tf_save_directory) # doctest: +IGNORE_RESULT +>>> tf_model.save_pretrained(tf_save_directory) +``` + +Wenn Sie bereit sind, das Modell wieder zu verwenden, laden Sie es mit [`TFPreTrainedModel.from_pretrained`]: + +```py +>>> tf_model = TFAutoModelForSequenceClassification.from_pretrained("./tf_save_pretrained") +``` + + + +Ein besonders cooles 🤗 Transformers-Feature ist die Möglichkeit, ein Modell zu speichern und es entweder als PyTorch- oder TensorFlow-Modell wieder zu laden. Der Parameter "from_pt" oder "from_tf" kann das Modell von einem Framework in das andere konvertieren: + + + + +```py +>>> from transformers import AutoModel + +>>> tokenizer = AutoTokenizer.from_pretrained(pt_save_directory) +>>> pt_model = AutoModelForSequenceClassification.from_pretrained(pt_save_directory, from_pt=True) +``` + + + +```py +>>> from transformers import TFAutoModel + +>>> tokenizer = AutoTokenizer.from_pretrained(tf_save_directory) +>>> tf_model = TFAutoModelForSequenceClassification.from_pretrained(tf_save_directory, from_tf=True) +``` + + + +## Custom model builds + +Sie können die Konfigurationsklasse des Modells ändern, um zu bestimmen, wie ein Modell aufgebaut ist. Die Konfiguration legt die Attribute eines Modells fest, z. B. die Anzahl der verborgenen Schichten oder der Aufmerksamkeitsköpfe. Wenn Sie ein Modell aus einer benutzerdefinierten Konfigurationsklasse initialisieren, beginnen Sie bei Null. Die Modellattribute werden zufällig initialisiert, und Sie müssen das Modell trainieren, bevor Sie es verwenden können, um aussagekräftige Ergebnisse zu erhalten. + +Beginnen Sie mit dem Import von [`AutoConfig`] und laden Sie dann das trainierte Modell, das Sie ändern möchten. Innerhalb von [`AutoConfig.from_pretrained`] können Sie das Attribut angeben, das Sie ändern möchten, z. B. die Anzahl der Aufmerksamkeitsköpfe: + +```py +>>> from transformers import AutoConfig + +>>> my_config = AutoConfig.from_pretrained("distilbert/distilbert-base-uncased", n_heads=12) +``` + + + +Create a model from your custom configuration with [`AutoModel.from_config`]: + +```py +>>> from transformers import AutoModel + +>>> my_model = AutoModel.from_config(my_config) +``` + + +Create a model from your custom configuration with [`TFAutoModel.from_config`]: + +```py +>>> from transformers import TFAutoModel + +>>> my_model = TFAutoModel.from_config(my_config) +``` + + + +Weitere Informationen zur Erstellung von benutzerdefinierten Konfigurationen finden Sie in der Anleitung [Erstellen einer benutzerdefinierten Architektur](./create_a_model). + +## Wie geht es weiter? + +Nachdem Sie nun die 🤗 Transformers-Kurztour abgeschlossen haben, schauen Sie sich unsere Anleitungen an und erfahren Sie, wie Sie spezifischere Dinge tun können, wie das Schreiben eines benutzerdefinierten Modells, die Feinabstimmung eines Modells für eine Aufgabe und wie man ein Modell mit einem Skript trainiert. Wenn Sie mehr über die Kernkonzepte von 🤗 Transformers erfahren möchten, nehmen Sie sich eine Tasse Kaffee und werfen Sie einen Blick auf unsere konzeptionellen Leitfäden! diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/run_scripts.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/run_scripts.md new file mode 100644 index 0000000000000000000000000000000000000000..069a0c3fd3de4537cd1967343c4075ae22ded803 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/run_scripts.md @@ -0,0 +1,351 @@ + + +# Trainieren mit einem Skript + +Neben den 🤗 Transformers [notebooks](./notebooks) gibt es auch Beispielskripte, die zeigen, wie man ein Modell für eine Aufgabe mit [PyTorch](https://github.com/huggingface/transformers/tree/main/examples/pytorch), [TensorFlow](https://github.com/huggingface/transformers/tree/main/examples/tensorflow) oder [JAX/Flax](https://github.com/huggingface/transformers/tree/main/examples/flax) trainiert. + +Sie werden auch Skripte finden, die wir in unseren [Forschungsprojekten](https://github.com/huggingface/transformers-research-projects/) und [Legacy-Beispielen](https://github.com/huggingface/transformers/tree/main/examples/legacy) verwendet haben und die größtenteils von der Community stammen. Diese Skripte werden nicht aktiv gepflegt und erfordern eine bestimmte Version von 🤗 Transformers, die höchstwahrscheinlich nicht mit der neuesten Version der Bibliothek kompatibel ist. + +Es wird nicht erwartet, dass die Beispielskripte bei jedem Problem sofort funktionieren. Möglicherweise müssen Sie das Skript an das Problem anpassen, das Sie zu lösen versuchen. Um Ihnen dabei zu helfen, legen die meisten Skripte vollständig offen, wie die Daten vorverarbeitet werden, so dass Sie sie nach Bedarf für Ihren Anwendungsfall bearbeiten können. + +Für jede Funktion, die Sie in einem Beispielskript implementieren möchten, diskutieren Sie bitte im [Forum](https://discuss.huggingface.co/) oder in einem [issue](https://github.com/huggingface/transformers/issues), bevor Sie einen Pull Request einreichen. Wir freuen uns zwar über Fehlerkorrekturen, aber es ist unwahrscheinlich, dass wir einen Pull Request zusammenführen, der mehr Funktionalität auf Kosten der Lesbarkeit hinzufügt. + +Diese Anleitung zeigt Ihnen, wie Sie ein Beispiel für ein Trainingsskript zur Zusammenfassung in [PyTorch](https://github.com/huggingface/transformers/tree/main/examples/pytorch/summarization) und [TensorFlow](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/summarization) ausführen können. Sofern nicht anders angegeben, sollten alle Beispiele mit beiden Frameworks funktionieren. + +## Einrichtung + +Um die neueste Version der Beispielskripte erfolgreich auszuführen, **müssen Sie 🤗 Transformers aus dem Quellcode** in einer neuen virtuellen Umgebung installieren: + +```bash +git clone https://github.com/huggingface/transformers +cd transformers +pip install . +``` + +Für ältere Versionen der Beispielskripte klicken Sie auf die Umschalttaste unten: + +
+ Beispiele für ältere Versionen von 🤗 Transformers + +
+ +Dann stellen Sie Ihren aktuellen Klon von 🤗 Transformers auf eine bestimmte Version um, z.B. v3.5.1: + +```bash +git checkout tags/v3.5.1 +``` + +Nachdem Sie die richtige Bibliotheksversion eingerichtet haben, navigieren Sie zu dem Beispielordner Ihrer Wahl und installieren die beispielspezifischen Anforderungen: + +```bash +pip install -r requirements.txt +``` + +## Ein Skript ausführen + + + +Das Beispielskript lädt einen Datensatz aus der 🤗 [Datasets](https://huggingface.co/docs/datasets/) Bibliothek herunter und verarbeitet ihn vor. Dann nimmt das Skript eine Feinabstimmung eines Datensatzes mit dem [Trainer](https://huggingface.co/docs/transformers/main_classes/trainer) auf einer Architektur vor, die eine Zusammenfassung unterstützt. Das folgende Beispiel zeigt, wie die Feinabstimmung von [T5-small](https://huggingface.co/google-t5/t5-small) auf dem Datensatz [CNN/DailyMail](https://huggingface.co/datasets/cnn_dailymail) durchgeführt wird. Das T5-Modell benötigt aufgrund der Art und Weise, wie es trainiert wurde, ein zusätzliches Argument `source_prefix`. Mit dieser Eingabeaufforderung weiß T5, dass es sich um eine Zusammenfassungsaufgabe handelt. + +```bash +python examples/pytorch/summarization/run_summarization.py \ + --model_name_or_path google-t5/t5-small \ + --do_train \ + --do_eval \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --overwrite_output_dir \ + --predict_with_generate +``` + + +Das Beispielskript lädt einen Datensatz aus der 🤗 [Datasets](https://huggingface.co/docs/datasets/) Bibliothek herunter und verarbeitet ihn vor. Anschließend nimmt das Skript die Feinabstimmung eines Datensatzes mit Keras auf einer Architektur vor, die die Zusammenfassung unterstützt. Das folgende Beispiel zeigt, wie die Feinabstimmung von [T5-small](https://huggingface.co/google-t5/t5-small) auf dem [CNN/DailyMail](https://huggingface.co/datasets/cnn_dailymail) Datensatz durchgeführt wird. Das T5-Modell benötigt aufgrund der Art und Weise, wie es trainiert wurde, ein zusätzliches Argument `source_prefix`. Mit dieser Eingabeaufforderung weiß T5, dass es sich um eine Zusammenfassungsaufgabe handelt. + +```bash +python examples/tensorflow/summarization/run_summarization.py \ + --model_name_or_path google-t5/t5-small \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size 8 \ + --per_device_eval_batch_size 16 \ + --num_train_epochs 3 \ + --do_train \ + --do_eval +``` + + + +## Verteiltes Training und gemischte Präzision + +Der [Trainer](https://huggingface.co/docs/transformers/main_classes/trainer) unterstützt verteiltes Training und gemischte Präzision, d.h. Sie können ihn auch in einem Skript verwenden. So aktivieren Sie diese beiden Funktionen: + +- Fügen Sie das Argument `fp16` hinzu, um gemischte Genauigkeit zu aktivieren. +- Legen Sie die Anzahl der zu verwendenden GPUs mit dem Argument `nproc_per_node` fest. + +```bash +torchrun \ + --nproc_per_node 8 pytorch/summarization/run_summarization.py \ + --fp16 \ + --model_name_or_path google-t5/t5-small \ + --do_train \ + --do_eval \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --overwrite_output_dir \ + --predict_with_generate +``` + +TensorFlow-Skripte verwenden eine [`MirroredStrategy`](https://www.tensorflow.org/guide/distributed_training#mirroredstrategy) für verteiltes Training, und Sie müssen dem Trainingsskript keine zusätzlichen Argumente hinzufügen. Das TensorFlow-Skript verwendet standardmäßig mehrere GPUs, wenn diese verfügbar sind. + +## Ein Skript auf einer TPU ausführen + + + +Tensor Processing Units (TPUs) sind speziell für die Beschleunigung der Leistung konzipiert. PyTorch unterstützt TPUs mit dem [XLA](https://www.tensorflow.org/xla) Deep Learning Compiler (siehe [hier](https://github.com/pytorch/xla/blob/master/README.md) für weitere Details). Um eine TPU zu verwenden, starten Sie das Skript `xla_spawn.py` und verwenden das Argument `num_cores`, um die Anzahl der TPU-Kerne festzulegen, die Sie verwenden möchten. + +```bash +python xla_spawn.py --num_cores 8 \ + summarization/run_summarization.py \ + --model_name_or_path google-t5/t5-small \ + --do_train \ + --do_eval \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --overwrite_output_dir \ + --predict_with_generate +``` + + +Tensor Processing Units (TPUs) sind speziell für die Beschleunigung der Leistung konzipiert. TensorFlow Skripte verwenden eine [`TPUStrategy`](https://www.tensorflow.org/guide/distributed_training#tpustrategy) für das Training auf TPUs. Um eine TPU zu verwenden, übergeben Sie den Namen der TPU-Ressource an das Argument `tpu`. + +```bash +python run_summarization.py \ + --tpu name_of_tpu_resource \ + --model_name_or_path google-t5/t5-small \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size 8 \ + --per_device_eval_batch_size 16 \ + --num_train_epochs 3 \ + --do_train \ + --do_eval +``` + + + +## Führen Sie ein Skript mit 🤗 Accelerate aus. + +🤗 [Accelerate](https://huggingface.co/docs/accelerate) ist eine reine PyTorch-Bibliothek, die eine einheitliche Methode für das Training eines Modells auf verschiedenen Arten von Setups (nur CPU, mehrere GPUs, TPUs) bietet und dabei die vollständige Transparenz der PyTorch-Trainingsschleife beibehält. Stellen Sie sicher, dass Sie 🤗 Accelerate installiert haben, wenn Sie es nicht bereits haben: + +> Hinweis: Da Accelerate schnell weiterentwickelt wird, muss die Git-Version von Accelerate installiert sein, um die Skripte auszuführen. +```bash +pip install git+https://github.com/huggingface/accelerate +``` + +Anstelle des Skripts `run_summarization.py` müssen Sie das Skript `run_summarization_no_trainer.py` verwenden. Die von Accelerate unterstützten Skripte haben eine Datei `task_no_trainer.py` im Ordner. Beginnen Sie mit dem folgenden Befehl, um eine Konfigurationsdatei zu erstellen und zu speichern: + +```bash +accelerate config +``` + +Testen Sie Ihre Einrichtung, um sicherzustellen, dass sie korrekt konfiguriert ist: + +```bash +accelerate test +``` + +Jetzt sind Sie bereit, das Training zu starten: + +```bash +accelerate launch run_summarization_no_trainer.py \ + --model_name_or_path google-t5/t5-small \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --output_dir ~/tmp/tst-summarization +``` + +## Verwenden Sie einen benutzerdefinierten Datensatz + +Das Verdichtungsskript unterstützt benutzerdefinierte Datensätze, solange es sich um eine CSV- oder JSON-Line-Datei handelt. Wenn Sie Ihren eigenen Datensatz verwenden, müssen Sie mehrere zusätzliche Argumente angeben: + +- `train_file` und `validation_file` geben den Pfad zu Ihren Trainings- und Validierungsdateien an. +- `text_column` ist der Eingabetext, der zusammengefasst werden soll. +- Summary_column" ist der auszugebende Zieltext. + +Ein Zusammenfassungsskript, das einen benutzerdefinierten Datensatz verwendet, würde wie folgt aussehen: + +```bash +python examples/pytorch/summarization/run_summarization.py \ + --model_name_or_path google-t5/t5-small \ + --do_train \ + --do_eval \ + --train_file path_to_csv_or_jsonlines_file \ + --validation_file path_to_csv_or_jsonlines_file \ + --text_column text_column_name \ + --summary_column summary_column_name \ + --source_prefix "summarize: " \ + --output_dir /tmp/tst-summarization \ + --overwrite_output_dir \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --predict_with_generate +``` + +## Testen Sie ein Skript + +Es ist oft eine gute Idee, Ihr Skript an einer kleineren Anzahl von Beispielen für Datensätze auszuführen, um sicherzustellen, dass alles wie erwartet funktioniert, bevor Sie sich auf einen ganzen Datensatz festlegen, dessen Fertigstellung Stunden dauern kann. Verwenden Sie die folgenden Argumente, um den Datensatz auf eine maximale Anzahl von Stichproben zu beschränken: + +- `max_train_samples` +- `max_eval_samples` +- `max_predict_samples` + +```bash +python examples/pytorch/summarization/run_summarization.py \ + --model_name_or_path google-t5/t5-small \ + --max_train_samples 50 \ + --max_eval_samples 50 \ + --max_predict_samples 50 \ + --do_train \ + --do_eval \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --overwrite_output_dir \ + --predict_with_generate +``` + +Nicht alle Beispielskripte unterstützen das Argument `max_predict_samples`. Wenn Sie sich nicht sicher sind, ob Ihr Skript dieses Argument unterstützt, fügen Sie das Argument `-h` hinzu, um dies zu überprüfen: + +```bash +examples/pytorch/summarization/run_summarization.py -h +``` + +## Training vom Kontrollpunkt fortsetzen + +Eine weitere hilfreiche Option, die Sie aktivieren können, ist die Wiederaufnahme des Trainings von einem früheren Kontrollpunkt aus. Auf diese Weise können Sie im Falle einer Unterbrechung Ihres Trainings dort weitermachen, wo Sie aufgehört haben, ohne von vorne beginnen zu müssen. Es gibt zwei Methoden, um das Training von einem Kontrollpunkt aus wieder aufzunehmen. + +Die erste Methode verwendet das Argument `output_dir previous_output_dir`, um das Training ab dem letzten in `output_dir` gespeicherten Kontrollpunkt wieder aufzunehmen. In diesem Fall sollten Sie `overwrite_output_dir` entfernen: + +```bash +python examples/pytorch/summarization/run_summarization.py + --model_name_or_path google-t5/t5-small \ + --do_train \ + --do_eval \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --output_dir previous_output_dir \ + --predict_with_generate +``` + +Die zweite Methode verwendet das Argument `Resume_from_checkpoint path_to_specific_checkpoint`, um das Training ab einem bestimmten Checkpoint-Ordner wieder aufzunehmen. + +```bash +python examples/pytorch/summarization/run_summarization.py + --model_name_or_path google-t5/t5-small \ + --do_train \ + --do_eval \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --overwrite_output_dir \ + --resume_from_checkpoint path_to_specific_checkpoint \ + --predict_with_generate +``` + +## Teilen Sie Ihr Modell + +Alle Skripte können Ihr endgültiges Modell in den [Model Hub](https://huggingface.co/models) hochladen. Stellen Sie sicher, dass Sie bei Hugging Face angemeldet sind, bevor Sie beginnen: + +```bash +hf auth login +``` + +Dann fügen Sie dem Skript das Argument `push_to_hub` hinzu. Mit diesem Argument wird ein Repository mit Ihrem Hugging Face-Benutzernamen und dem in `output_dir` angegebenen Ordnernamen erstellt. + +Wenn Sie Ihrem Repository einen bestimmten Namen geben möchten, fügen Sie ihn mit dem Argument `push_to_hub_model_id` hinzu. Das Repository wird automatisch unter Ihrem Namensraum aufgeführt. + +Das folgende Beispiel zeigt, wie Sie ein Modell mit einem bestimmten Repository-Namen hochladen können: + +```bash +python examples/pytorch/summarization/run_summarization.py + --model_name_or_path google-t5/t5-small \ + --do_train \ + --do_eval \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --push_to_hub \ + --push_to_hub_model_id finetuned-t5-cnn_dailymail \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --overwrite_output_dir \ + --predict_with_generate +``` \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/testing.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/testing.md new file mode 100644 index 0000000000000000000000000000000000000000..07be15f31ece9c085a8ec9eedb7fbf06bb708592 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/testing.md @@ -0,0 +1,1283 @@ + + +# Testen + + +Werfen wir einen Blick darauf, wie 🤗 Transformers-Modelle getestet werden und wie Sie neue Tests schreiben und die vorhandenen verbessern können. + +Es gibt 2 Testsuiten im Repository: + +1. `tests` -- Tests für die allgemeine API +2. `examples` -- Tests hauptsächlich für verschiedene Anwendungen, die nicht Teil der API sind + +## Wie Transformatoren getestet werden + +1. Sobald ein PR eingereicht wurde, wird er mit 9 CircleCi Jobs getestet. Jeder neue Commit zu diesem PR wird erneut getestet. Diese Aufträge + sind in dieser [Konfigurationsdatei](https://github.com/huggingface/transformers/tree/main/.circleci/config.yml) definiert, so dass Sie bei Bedarf die gleiche Umgebung auf Ihrem Rechner reproduzieren können. + Umgebung auf Ihrem Rechner reproduzieren können. + + Diese CI-Jobs führen keine `@slow`-Tests durch. + +2. Es gibt 3 Jobs, die von [github actions](https://github.com/huggingface/transformers/actions) ausgeführt werden: + + - [torch hub integration](https://github.com/huggingface/transformers/tree/main/.github/workflows/github-torch-hub.yml): prüft, ob die torch hub + Integration funktioniert. + + - [self-hosted (push)](https://github.com/huggingface/transformers/tree/main/.github/workflows/self-push.yml): führt schnelle Tests auf der GPU nur bei Commits auf + `main`. Es wird nur ausgeführt, wenn ein Commit auf `main` den Code in einem der folgenden Ordner aktualisiert hat: `src`, + `tests`, `.github` (um zu verhindern, dass er auf hinzugefügten Modellkarten, Notebooks usw. läuft) + + - [self-hosted runner](https://github.com/huggingface/transformers/tree/main/.github/workflows/self-scheduled.yml): führt normale und langsame Tests auf GPU in + `tests` und `examples`: + +```bash +RUN_SLOW=1 pytest tests/ +RUN_SLOW=1 pytest examples/ +``` + + Die Ergebnisse können Sie [hier](https://github.com/huggingface/transformers/actions) sehen. + + + +## Tests ausführen + + + + + +### Auswahl der auszuführenden Tests + +In diesem Dokument wird ausführlich erläutert, wie Tests ausgeführt werden können. Wenn Sie nach der Lektüre noch mehr Details benötigen +finden Sie diese [hier](https://docs.pytest.org/en/latest/usage.html). + +Hier sind einige der nützlichsten Möglichkeiten, Tests auszuführen. + +Alle ausführen: + +```console +pytest +``` + +oder: + +```bash +make test +``` + +Beachten Sie, dass Letzteres wie folgt definiert ist: + +```bash +python -m pytest -n auto --dist=loadfile -s -v ./tests/ +``` + +was pytest anweist: + +- so viele Testprozesse laufen zu lassen, wie es CPU-Kerne gibt (was zu viele sein könnten, wenn Sie nicht über eine Menge RAM verfügen!) +- sicherzustellen, dass alle Tests aus derselben Datei von demselben Testprozess ausgeführt werden +- Erfassen Sie keine Ausgaben +- im ausführlichen Modus laufen lassen + + + +### Abrufen der Liste aller Tests + +Alle Tests der Testsuite: + +```bash +pytest --collect-only -q +``` + +Alle Tests einer bestimmten Testdatei: + +```bash +pytest tests/test_optimization.py --collect-only -q +``` + +### Führen Sie ein bestimmtes Testmodul aus + +Um ein einzelnes Testmodul auszuführen: + +```bash +pytest tests/utils/test_logging.py +``` + +### Spezifische Tests ausführen + +Da unittest in den meisten Tests verwendet wird, müssen Sie, um bestimmte Untertests auszuführen, den Namen der unittest +Klasse, die diese Tests enthält. Er könnte zum Beispiel lauten: + +```bash +pytest tests/test_optimization.py::OptimizationTest::test_adam_w +``` + +Hier: + +- `tests/test_optimization.py` - die Datei mit den Tests +- `OptimizationTest` - der Name der Klasse +- `test_adam_w` - der Name der spezifischen Testfunktion + +Wenn die Datei mehrere Klassen enthält, können Sie auswählen, dass nur die Tests einer bestimmten Klasse ausgeführt werden sollen. Zum Beispiel: + +```bash +pytest tests/test_optimization.py::OptimizationTest +``` + +führt alle Tests innerhalb dieser Klasse aus. + +Wie bereits erwähnt, können Sie sehen, welche Tests in der Klasse `OptimizationTest` enthalten sind, indem Sie sie ausführen: + +```bash +pytest tests/test_optimization.py::OptimizationTest --collect-only -q +``` + +Sie können Tests mit Hilfe von Schlüsselwortausdrücken ausführen. + +Um nur Tests auszuführen, deren Name `adam` enthält: + +```bash +pytest -k adam tests/test_optimization.py +``` + +Die logischen `und` und `oder` können verwendet werden, um anzugeben, ob alle Schlüsselwörter übereinstimmen sollen oder nur eines. `nicht` kann verwendet werden, um +negieren. + +Um alle Tests auszuführen, außer denen, deren Name `adam` enthält: + +```bash +pytest -k "not adam" tests/test_optimization.py +``` + +Und Sie können die beiden Muster in einem kombinieren: + +```bash +pytest -k "ada and not adam" tests/test_optimization.py +``` + +Um zum Beispiel sowohl `test_adafactor` als auch `test_adam_w` auszuführen, können Sie verwenden: + +```bash +pytest -k "test_adam_w or test_adam_w" tests/test_optimization.py +``` + +Beachten Sie, dass wir hier `oder` verwenden, da wir wollen, dass eines der Schlüsselwörter übereinstimmt, um beide einzuschließen. + +Wenn Sie nur Tests einschließen möchten, die beide Muster enthalten, müssen Sie `und` verwenden: + +```bash +pytest -k "test and ada" tests/test_optimization.py +``` + +### Führen Sie `accelerate` Tests durch + +Manchmal müssen Sie `accelerate` Tests für Ihre Modelle ausführen. Dazu fügen Sie einfach `-m accelerate_tests` zu Ihrem Befehl hinzu, wenn Sie diese Tests bei einem `OPT`-Lauf ausführen möchten: +```bash +RUN_SLOW=1 pytest -m accelerate_tests tests/models/opt/test_modeling_opt.py +``` + + +### Dokumentationstests ausführen + +Um zu testen, ob die Dokumentationsbeispiele korrekt sind, sollten Sie überprüfen, ob die `doctests` erfolgreich sind. +Lassen Sie uns als Beispiel den docstring von [WhisperModel.forward](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/modeling_whisper.py#L1017-L1035) verwenden: + +```python +r""" +Returns: + +Example: + ```python + >>> import torch + >>> from transformers import WhisperModel, WhisperFeatureExtractor + >>> from datasets import load_dataset + + >>> model = WhisperModel.from_pretrained("openai/whisper-base") + >>> feature_extractor = WhisperFeatureExtractor.from_pretrained("openai/whisper-base") + >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + >>> inputs = feature_extractor(ds[0]["audio"]["array"], return_tensors="pt") + >>> input_features = inputs.input_features + >>> decoder_input_ids = torch.tensor([[1, 1]]) * model.config.decoder_start_token_id + >>> last_hidden_state = model(input_features, decoder_input_ids=decoder_input_ids).last_hidden_state + >>> list(last_hidden_state.shape) + [1, 2, 512] + ```""" + +``` + +Führen Sie einfach die folgende Zeile aus, um automatisch jedes docstring-Beispiel in der gewünschten Datei zu testen: +```bash +pytest --doctest-modules +``` +Wenn die Datei eine Markdown-Erweiterung hat, sollten Sie das Argument `--doctest-glob="*.md"` hinzufügen. + +### Nur geänderte Tests ausführen + +Mit [pytest-picked](https://github.com/anapaulagomes/pytest-picked) können Sie die Tests ausführen, die sich auf die unstaged Dateien oder den aktuellen Zweig (gemäß Git) beziehen. Auf diese Weise können Sie schnell testen, ob Ihre Änderungen nichts kaputt gemacht haben. +nichts kaputt gemacht haben, da die Tests für Dateien, die Sie nicht verändert haben, nicht ausgeführt werden. + +```bash +pip install pytest-picked +``` + +```bash +pytest --picked +``` + +Alle Tests werden von Dateien und Ordnern ausgeführt, die geändert, aber noch nicht übergeben wurden. + +### Fehlgeschlagene Tests bei Änderung der Quelle automatisch wiederholen + +[pytest-xdist](https://github.com/pytest-dev/pytest-xdist) bietet eine sehr nützliche Funktion zur Erkennung aller fehlgeschlagenen +Tests zu erkennen und dann darauf zu warten, dass Sie Dateien ändern, um die fehlgeschlagenen Tests so lange zu wiederholen, bis sie erfolgreich sind, während Sie die +sie reparieren. So müssen Sie pytest nicht erneut starten, nachdem Sie die Korrektur vorgenommen haben. Dies wird so lange wiederholt, bis alle Tests bestanden sind. +Danach wird erneut ein vollständiger Durchlauf durchgeführt. + +```bash +pip install pytest-xdist +``` + +So rufen Sie den Modus auf: `pytest -f` oder `pytest --looponfail` + +Datei-Änderungen werden erkannt, indem die Wurzelverzeichnisse von `looponfailroots` und alle ihre Inhalte (rekursiv) untersucht werden. +Wenn die Vorgabe für diesen Wert für Sie nicht funktioniert, können Sie ihn in Ihrem Projekt ändern, indem Sie eine Konfigurations +Option in der Datei `setup.cfg` ändern: + +```ini +[tool:pytest] +looponfailroots = transformers tests +``` + +oder die Dateien `pytest.ini`/`tox.ini``: + +```ini +[pytest] +looponfailroots = transformers tests +``` + +Dies würde dazu führen, dass nur nach Dateiänderungen in den jeweiligen Verzeichnissen gesucht wird, die relativ zum Verzeichnis der ini-Datei angegeben sind. +Verzeichnis. + +[pytest-watch](https://github.com/joeyespo/pytest-watch) ist eine alternative Implementierung dieser Funktionalität. + + +### Überspringen eines Testmoduls + +Wenn Sie alle Testmodule ausführen möchten, mit Ausnahme einiger weniger, können Sie diese ausschließen, indem Sie eine explizite Liste der auszuführenden Tests angeben. Für +Beispiel: Um alle Tests außer `test_modeling_*.py` auszuführen: + +```bash +pytest *ls -1 tests/*py | grep -v test_modeling* +``` + +### Status leeren + +CI-Builds und wenn Isolation wichtig ist (gegen Geschwindigkeit), sollte der Cache geleert werden: + +```bash +pytest --cache-clear tests +``` + +### Tests parallel ausführen + +Wie bereits erwähnt, führt `make test` über das Plugin `pytest-xdist` Tests parallel aus (Argument `-n X`, z.B. `-n 2` +um 2 Jobs parallel laufen zu lassen). + +Mit der Option `--dist=` von `pytest-xdist` können Sie steuern, wie die Tests gruppiert werden. Mit `--dist=loadfile` werden die +Tests, die sich in einer Datei befinden, in denselben Prozess. + +Da die Reihenfolge der ausgeführten Tests unterschiedlich und nicht vorhersehbar ist, kann die Ausführung der Testsuite mit `pytest-xdist` +zu Fehlern führt (was bedeutet, dass wir einige unentdeckte gekoppelte Tests haben), verwenden Sie [pytest-replay](https://github.com/ESSS/pytest-replay), um die Tests in der gleichen Reihenfolge abzuspielen, was dabei helfen sollte +diese fehlgeschlagene Sequenz auf ein Minimum zu reduzieren. + +### Testreihenfolge und Wiederholung + +Es ist gut, die Tests mehrmals zu wiederholen, nacheinander, zufällig oder in Gruppen, um mögliche +Abhängigkeiten und zustandsbezogene Fehler zu erkennen (Abriss). Und die einfache, mehrfache Wiederholung ist einfach gut, um +einige Probleme zu erkennen, die durch die Zufälligkeit von DL aufgedeckt werden. + + +#### Wiederholungstests + +- [pytest-flakefinder](https://github.com/dropbox/pytest-flakefinder): + +```bash +pip install pytest-flakefinder +``` + +Und führen Sie dann jeden Test mehrmals durch (standardmäßig 50): + +```bash +pytest --flake-finder --flake-runs=5 tests/test_failing_test.py +``` + + + +Dieses Plugin funktioniert nicht mit dem `-n` Flag von `pytest-xdist`. + + + + + +Es gibt noch ein anderes Plugin `pytest-repeat`, aber es funktioniert nicht mit `unittest`. + + + +#### Run tests in a random order + +```bash +pip install pytest-random-order +``` + +Wichtig: Das Vorhandensein von `pytest-random-order` sorgt für eine automatische Zufallsanordnung der Tests, es sind keine Konfigurationsänderungen oder +Befehlszeilenoptionen sind nicht erforderlich. + +Wie bereits erläutert, ermöglicht dies die Erkennung von gekoppelten Tests - bei denen der Zustand eines Tests den Zustand eines anderen beeinflusst. Wenn +`pytest-random-order` installiert ist, gibt es den Zufallswert aus, der für diese Sitzung verwendet wurde, z.B: + +```bash +pytest tests +[...] +Using --random-order-bucket=module +Using --random-order-seed=573663 +``` + +Wenn eine bestimmte Sequenz fehlschlägt, können Sie sie reproduzieren, indem Sie genau diesen Seed hinzufügen, z.B: + +```bash +pytest --random-order-seed=573663 +[...] +Using --random-order-bucket=module +Using --random-order-seed=573663 +``` + +Es wird nur dann die exakte Reihenfolge reproduzieren, wenn Sie genau dieselbe Liste von Tests (oder gar keine Liste) verwenden. Sobald Sie beginnen, die Liste +die Liste manuell einzugrenzen, können Sie sich nicht mehr auf den Seed verlassen, sondern müssen die Tests manuell in der genauen Reihenfolge auflisten +auflisten und pytest anweisen, sie nicht zu randomisieren, indem Sie `--random-order-bucket=none` verwenden, z.B.: + +```bash +pytest --random-order-bucket=none tests/test_a.py tests/test_c.py tests/test_b.py +``` + +So deaktivieren Sie das Shuffling für alle Tests: + +```bash +pytest --random-order-bucket=none +``` + +Standardmäßig ist `--random-order-bucket=module` impliziert, wodurch die Dateien auf den Modulebenen gemischt werden. Es kann auch +auf den Ebenen `class`, `package`, `global` und `none` mischen. Die vollständigen Details entnehmen Sie bitte der +[Dokumentation](https://github.com/jbasko/pytest-random-order). + +Eine weitere Alternative zur Randomisierung ist: [`pytest-random`](https://github.com/pytest-dev/pytest-randomly). Dieses +Modul hat eine sehr ähnliche Funktionalität/Schnittstelle, aber es hat nicht die Eimermodi, die in +`pytest-random-order` zur Verfügung. Es hat das gleiche Problem, dass es sich nach der Installation aufdrängt. + +### Variationen von Aussehen und Bedienung + +#### pytest-zucker + +[pytest-sugar](https://github.com/Frozenball/pytest-sugar) ist ein Plugin, das das Erscheinungsbild verbessert, eine +Fortschrittsbalken hinzufügt und Tests, die fehlschlagen, sowie die Bestätigung sofort anzeigt. Es wird bei der Installation automatisch aktiviert. + +```bash +pip install pytest-sugar +``` + +Um Tests ohne sie durchzuführen, führen Sie aus: + +```bash +pytest -p no:sugar +``` + +oder deinstallieren Sie es. + + + +#### Melden Sie den Namen jedes Subtests und seinen Fortschritt + +Für einen einzelnen oder eine Gruppe von Tests über `pytest` (nach `pip install pytest-pspec`): + +```bash +pytest --pspec tests/test_optimization.py +``` + +#### Zeigt fehlgeschlagene Tests sofort an + +[pytest-instafail](https://github.com/pytest-dev/pytest-instafail) zeigt Fehlschläge und Fehler sofort an, anstatt +bis zum Ende der Testsitzung zu warten. + +```bash +pip install pytest-instafail +``` + +```bash +pytest --instafail +``` + +### Zu GPU oder nicht zu GPU + +Bei einem GPU-aktivierten Setup fügen Sie zum Testen im reinen CPU-Modus `CUDA_VISIBLE_DEVICES=""` hinzu: + +```bash +CUDA_VISIBLE_DEVICES="" pytest tests/utils/test_logging.py +``` + +oder wenn Sie mehrere Grafikprozessoren haben, können Sie angeben, welcher von `pytest` verwendet werden soll. Wenn Sie zum Beispiel nur den +zweiten Grafikkarte zu verwenden, wenn Sie die Grafikkarten `0` und `1` haben, können Sie folgendes ausführen: + +```bash +CUDA_VISIBLE_DEVICES="1" pytest tests/utils/test_logging.py +``` + +Dies ist praktisch, wenn Sie verschiedene Aufgaben auf verschiedenen GPUs ausführen möchten. + +Einige Tests müssen nur auf der CPU ausgeführt werden, andere entweder auf der CPU, der GPU oder der TPU und wieder andere auf mehreren GPUs. Die folgenden skip +Dekorateure werden verwendet, um die Anforderungen von Tests in Bezug auf CPU/GPU/TPU festzulegen: + +- `require_torch` - dieser Test wird nur unter Torch ausgeführt +- `require_torch_gpu` - wie `require_torch` plus erfordert mindestens 1 GPU +- `require_torch_multi_gpu` - wie `require_torch` und zusätzlich mindestens 2 GPUs erforderlich +- `require_torch_non_multi_gpu` - wie `require_torch` plus benötigt 0 oder 1 GPUs +- `require_torch_up_to_2_gpus` - wie `require_torch` plus erfordert 0 oder 1 oder 2 GPUs +- `require_torch_xla` - wie `require_torch` plus erfordert mindestens 1 TPU + +Lassen Sie uns die GPU-Anforderungen in der folgenden Tabelle darstellen: + + +| n gpus | decorator | +|--------|--------------------------------| +| `>= 0` | `@require_torch` | +| `>= 1` | `@require_torch_gpu` | +| `>= 2` | `@require_torch_multi_gpu` | +| `< 2` | `@require_torch_non_multi_gpu` | +| `< 3` | `@require_torch_up_to_2_gpus` | + + +Hier ist zum Beispiel ein Test, der nur ausgeführt werden muss, wenn 2 oder mehr GPUs verfügbar sind und pytorch installiert ist: + +```python no-style +@require_torch_multi_gpu +def test_example_with_multi_gpu(): +``` + +Diese Dekors können gestapelt werden. Wenn zum Beispiel ein Test langsam ist und mindestens eine GPU unter pytorch benötigt, können Sie +wie Sie ihn einrichten können: + +```python no-style +@require_torch_gpu +@slow +def test_example_slow_on_gpu(): +``` + +Einige Dekoratoren wie `@parametrized` schreiben Testnamen um, daher müssen `@require_*`-Sprungdekoratoren als letztes aufgeführt werden. +zuletzt aufgeführt werden, damit sie korrekt funktionieren. Hier ist ein Beispiel für die korrekte Verwendung: + +```python no-style +@parameterized.expand(...) +@require_torch_multi_gpu +def test_integration_foo(): +``` + +Dieses Problem mit der Reihenfolge gibt es bei `@pytest.mark.parametrize` nicht, Sie können es an den Anfang oder an den Schluss setzen und es wird trotzdem funktionieren. +funktionieren. Aber es funktioniert nur bei Nicht-Unittests. + +Innerhalb von Tests: + +- Wie viele GPUs sind verfügbar: + +```python +from transformers.testing_utils import get_gpu_count + +n_gpu = get_gpu_count() # works with torch and tf +``` + +### Testen mit einem bestimmten PyTorch-Backend oder Gerät + +Um die Testsuite auf einem bestimmten Torch-Gerät auszuführen, fügen Sie `TRANSFORMERS_TEST_DEVICE="$Gerät"` hinzu, wobei `$Gerät` das Ziel-Backend ist. Zum Beispiel, um nur auf der CPU zu testen: +```bash +TRANSFORMERS_TEST_DEVICE="cpu" pytest tests/utils/test_logging.py +``` + +Diese Variable ist nützlich, um benutzerdefinierte oder weniger verbreitete PyTorch-Backends wie `mps` zu testen. Sie kann auch verwendet werden, um den gleichen Effekt wie `CUDA_VISIBLE_DEVICES` zu erzielen, indem Sie bestimmte GPUs anvisieren oder im reinen CPU-Modus testen. + +Bestimmte Geräte erfordern einen zusätzlichen Import, nachdem Sie `torch` zum ersten Mal importiert haben. Dies kann über die Umgebungsvariable `TRANSFORMERS_TEST_BACKEND` festgelegt werden: +```bash +TRANSFORMERS_TEST_BACKEND="torch_npu" pytest tests/utils/test_logging.py +``` + + +### Verteiltes Training + +`pytest` kann nicht direkt mit verteiltem Training umgehen. Wenn dies versucht wird, tun die Unterprozesse nicht das Richtige +und denken am Ende, sie seien `pytest` und beginnen, die Testsuite in Schleifen auszuführen. Es funktioniert jedoch, wenn man +einen normalen Prozess erzeugt, der dann mehrere Worker erzeugt und die IO-Pipes verwaltet. + +Hier sind einige Tests, die dies verwenden: + +- [test_trainer_distributed.py](https://github.com/huggingface/transformers/tree/main/tests/trainer/test_trainer_distributed.py) +- [test_deepspeed.py](https://github.com/huggingface/transformers/tree/main/tests/deepspeed/test_deepspeed.py) + +Um direkt mit der Ausführung zu beginnen, suchen Sie in diesen Tests nach dem Aufruf `execute_subprocess_async`. + +Sie benötigen mindestens 2 GPUs, um diese Tests in Aktion zu sehen: + +```bash +CUDA_VISIBLE_DEVICES=0,1 RUN_SLOW=1 pytest -sv tests/test_trainer_distributed.py +``` + +### Erfassung von Ausgaben + +Während der Testausführung werden alle Ausgaben, die an `stdout` und `stderr` gesendet werden, aufgezeichnet. Wenn ein Test oder eine Setup-Methode fehlschlägt, wird die +wird die entsprechende aufgezeichnete Ausgabe in der Regel zusammen mit dem Fehler-Traceback angezeigt. + +Um die Aufzeichnung von Ausgaben zu deaktivieren und `stdout` und `stderr` normal zu erhalten, verwenden Sie `-s` oder `--capture=no`: + +```bash +pytest -s tests/utils/test_logging.py +``` + +So senden Sie Testergebnisse an die JUnit-Formatausgabe: + +```bash +py.test tests --junitxml=result.xml +``` + +### Farbsteuerung + +Keine Farbe zu haben (z.B. gelb auf weißem Hintergrund ist nicht lesbar): + +```bash +pytest --color=no tests/utils/test_logging.py +``` + +### Testbericht an den Online-Dienst pastebin senden + +Erstellen Sie eine URL für jeden Testfehler: + +```bash +pytest --pastebin=failed tests/utils/test_logging.py +``` + +Dadurch werden Informationen über den Testlauf an einen entfernten Paste-Dienst übermittelt und eine URL für jeden Fehlschlag bereitgestellt. Sie können die +Tests wie gewohnt auswählen oder z.B. -x hinzufügen, wenn Sie nur einen bestimmten Fehler senden möchten. + +Erstellen einer URL für ein ganzes Testsitzungsprotokoll: + +```bash +pytest --pastebin=all tests/utils/test_logging.py +``` + +## Tests schreiben + +🤗 Die Tests von Transformers basieren auf `unittest`, werden aber von `pytest` ausgeführt, so dass die meiste Zeit Funktionen aus beiden Systemen +verwendet werden können. + +Sie können [hier](https://docs.pytest.org/en/stable/unittest.html) nachlesen, welche Funktionen unterstützt werden, aber das Wichtigste ist +Wichtig ist, dass die meisten `pytest`-Fixtures nicht funktionieren. Auch die Parametrisierung nicht, aber wir verwenden das Modul +`parametrisiert`, das auf ähnliche Weise funktioniert. + + +### Parametrisierung + +Oft besteht die Notwendigkeit, denselben Test mehrmals auszuführen, aber mit unterschiedlichen Argumenten. Das könnte innerhalb des Tests geschehen +des Tests gemacht werden, aber dann gibt es keine Möglichkeit, den Test mit nur einem Satz von Argumenten auszuführen. + +```python +# test_this1.py +import unittest +from parameterized import parameterized + + +class TestMathUnitTest(unittest.TestCase): + @parameterized.expand( + [ + ("negative", -1.5, -2.0), + ("integer", 1, 1.0), + ("large fraction", 1.6, 1), + ] + ) + def test_floor(self, name, input, expected): + assert_equal(math.floor(input), expected) +``` + +Nun wird dieser Test standardmäßig 3 Mal ausgeführt, wobei jedes Mal die letzten 3 Argumente von `test_floor` den entsprechenden Argumenten in der Parameterliste zugeordnet werden. +die entsprechenden Argumente in der Parameterliste. + +Sie können auch nur die Parameter `negativ` und `ganzzahlig` mit ausführen: + +```bash +pytest -k "negative and integer" tests/test_mytest.py +``` + +oder alle Untertests außer `negativ`, mit: + +```bash +pytest -k "not negative" tests/test_mytest.py +``` + +Neben der Verwendung des gerade erwähnten Filters `-k` können Sie auch den genauen Namen jedes Untertests herausfinden und jeden +oder alle unter Verwendung ihrer genauen Namen ausführen. + +```bash +pytest test_this1.py --collect-only -q +``` + +und es wird aufgelistet: + +```bash +test_this1.py::TestMathUnitTest::test_floor_0_negative +test_this1.py::TestMathUnitTest::test_floor_1_integer +test_this1.py::TestMathUnitTest::test_floor_2_large_fraction +``` + +Jetzt können Sie also nur 2 spezifische Untertests durchführen: + +```bash +pytest test_this1.py::TestMathUnitTest::test_floor_0_negative test_this1.py::TestMathUnitTest::test_floor_1_integer +``` + +Das Modul [parametrisiert](https://pypi.org/project/parameterized/), das sich bereits in den Entwickler-Abhängigkeiten befindet +von `transformers` befindet, funktioniert sowohl für `unittests` als auch für `pytest` Tests. + +Wenn es sich bei dem Test jedoch nicht um einen `Unittest` handelt, können Sie `pytest.mark.parametrize` verwenden (oder Sie können sehen, dass es in +einigen bestehenden Tests verwendet wird, meist unter `Beispiele`). + +Hier ist das gleiche Beispiel, diesmal unter Verwendung der `parametrize`-Markierung von `pytest`: + +```python +# test_this2.py +import pytest + + +@pytest.mark.parametrize( + "name, input, expected", + [ + ("negative", -1.5, -2.0), + ("integer", 1, 1.0), + ("large fraction", 1.6, 1), + ], +) +def test_floor(name, input, expected): + assert_equal(math.floor(input), expected) +``` + +Genau wie bei `parametrisiert` können Sie mit `pytest.mark.parametrize` genau steuern, welche Subtests ausgeführt werden +ausgeführt werden, wenn der Filter `-k` nicht ausreicht. Allerdings erzeugt diese Parametrisierungsfunktion einen etwas anderen Satz von +Namen für die Untertests. Sie sehen folgendermaßen aus: + +```bash +pytest test_this2.py --collect-only -q +``` + +und es wird aufgelistet: + +```bash +test_this2.py::test_floor[integer-1-1.0] +test_this2.py::test_floor[negative--1.5--2.0] +test_this2.py::test_floor[large fraction-1.6-1] +``` + +Jetzt können Sie also nur den spezifischen Test durchführen: + +```bash +pytest test_this2.py::test_floor[negative--1.5--2.0] test_this2.py::test_floor[integer-1-1.0] +``` + +wie im vorherigen Beispiel. + + + +### Dateien und Verzeichnisse + +In Tests müssen wir oft wissen, wo sich Dinge relativ zur aktuellen Testdatei befinden, und das ist nicht trivial, da der Test +von mehreren Verzeichnissen aus aufgerufen werden kann oder sich in Unterverzeichnissen mit unterschiedlicher Tiefe befinden kann. Eine Hilfsklasse +`transformers.test_utils.TestCasePlus` löst dieses Problem, indem sie alle grundlegenden Pfade sortiert und einfache +Zugriffsmöglichkeiten auf sie bietet: + +- `pathlib`-Objekte (alle vollständig aufgelöst): + + - `test_file_path` - der aktuelle Testdateipfad, d.h. `__file__` + - `test_file_dir` - das Verzeichnis, das die aktuelle Testdatei enthält + - `tests_dir` - das Verzeichnis der `tests` Testreihe + - `examples_dir` - das Verzeichnis der `examples` Test-Suite + - `repo_root_dir` - das Verzeichnis des Repositorys + - `src_dir` - das Verzeichnis von `src` (d.h. wo sich das Unterverzeichnis `transformers` befindet) + +- stringifizierte Pfade - wie oben, aber diese geben Pfade als Strings zurück, anstatt als `pathlib`-Objekte: + + - `test_file_path_str` + - `test_file_dir_str` + - `tests_dir_str` + - `examples_dir_str` + - `repo_root_dir_str` + - `src_dir_str` + +Um diese zu verwenden, müssen Sie lediglich sicherstellen, dass der Test in einer Unterklasse von +`transformers.test_utils.TestCasePlus` befindet. Zum Beispiel: + +```python +from transformers.testing_utils import TestCasePlus + + +class PathExampleTest(TestCasePlus): + def test_something_involving_local_locations(self): + data_dir = self.tests_dir / "fixtures/tests_samples/wmt_en_ro" +``` + +Wenn Sie Pfade nicht über `pathlib` manipulieren müssen oder nur einen Pfad als String benötigen, können Sie jederzeit +`str()` auf das `pathlib`-Objekt anwenden oder die Accessoren mit der Endung `_str` verwenden. Zum Beispiel: + +```python +from transformers.testing_utils import TestCasePlus + + +class PathExampleTest(TestCasePlus): + def test_something_involving_stringified_locations(self): + examples_dir = self.examples_dir_str +``` + +### Temporäre Dateien und Verzeichnisse + +Die Verwendung eindeutiger temporärer Dateien und Verzeichnisse ist für die parallele Durchführung von Tests unerlässlich, damit sich die Tests nicht gegenseitig überschreiben. +Daten gegenseitig überschreiben. Außerdem möchten wir, dass die temporären Dateien und Verzeichnisse am Ende jedes Tests, der sie erstellt hat, gelöscht werden. +erstellt hat. Daher ist die Verwendung von Paketen wie `tempfile`, die diese Anforderungen erfüllen, unerlässlich. + +Beim Debuggen von Tests müssen Sie jedoch sehen können, was in der temporären Datei oder dem temporären Verzeichnis gespeichert wird und Sie möchten +Sie müssen den genauen Pfad kennen und dürfen ihn nicht bei jedem neuen Testdurchlauf zufällig ändern. + +Für solche Zwecke ist die Hilfsklasse `transformers.test_utils.TestCasePlus` am besten geeignet. Sie ist eine Unterklasse von +Unittest.TestCase`, so dass wir in den Testmodulen einfach von ihr erben können. + +Hier ist ein Beispiel für die Verwendung dieser Klasse: + +```python +from transformers.testing_utils import TestCasePlus + + +class ExamplesTests(TestCasePlus): + def test_whatever(self): + tmp_dir = self.get_auto_remove_tmp_dir() +``` + +Dieser Code erstellt ein eindeutiges temporäres Verzeichnis und setzt `tmp_dir` auf dessen Speicherort. + +- Erstellen Sie ein eindeutiges temporäres Verzeichnis: + +```python +def test_whatever(self): + tmp_dir = self.get_auto_remove_tmp_dir() +``` + +tmp_dir" enthält den Pfad zu dem erstellten temporären Verzeichnis. Es wird am Ende des Tests automatisch entfernt. +Tests entfernt. + +- Erstellen Sie ein temporäres Verzeichnis meiner Wahl, stellen Sie sicher, dass es leer ist, bevor der Test beginnt, und leeren Sie es nach dem Test nicht. + +```python +def test_whatever(self): + tmp_dir = self.get_auto_remove_tmp_dir("./xxx") +``` + +Dies ist nützlich für die Fehlersuche, wenn Sie ein bestimmtes Verzeichnis überwachen und sicherstellen möchten, dass die vorherigen Tests keine Daten darin hinterlassen haben. +keine Daten dort hinterlassen haben. + +- Sie können das Standardverhalten außer Kraft setzen, indem Sie die Argumente `before` und `after` direkt überschreiben, was zu einem der folgenden Verhaltensweisen führt + folgenden Verhaltensweisen: + + - `before=True`: das temporäre Verzeichnis wird immer zu Beginn des Tests gelöscht. + - `before=False`: wenn das temporäre Verzeichnis bereits existiert, bleiben alle vorhandenen Dateien dort erhalten. + - `after=True`: das temporäre Verzeichnis wird immer am Ende des Tests gelöscht. + - `after=False`: das temporäre Verzeichnis wird am Ende des Tests immer beibehalten. + + + +Um das Äquivalent von `rm -r` sicher ausführen zu können, sind nur Unterverzeichnisse des Projektarchivs checkout erlaubt, wenn +ein explizites `tmp_dir` verwendet wird, so dass nicht versehentlich ein `/tmp` oder ein ähnlich wichtiger Teil des Dateisystems vernichtet wird. +d.h. geben Sie bitte immer Pfade an, die mit `./` beginnen. + + + + + +Jeder Test kann mehrere temporäre Verzeichnisse registrieren, die alle automatisch entfernt werden, sofern nicht anders gewünscht. +anders. + + + +### Temporäre Überschreibung von sys.path + +Wenn Sie `sys.path` vorübergehend überschreiben müssen, um z.B. von einem anderen Test zu importieren, können Sie den +Kontextmanager `ExtendSysPath` verwenden. Beispiel: + + +```python +import os +from transformers.testing_utils import ExtendSysPath + +bindir = os.path.abspath(os.path.dirname(__file__)) +with ExtendSysPath(f"{bindir}/.."): + from test_trainer import TrainerIntegrationCommon # noqa +``` + +### Überspringen von Tests + +Dies ist nützlich, wenn ein Fehler gefunden und ein neuer Test geschrieben wird, der Fehler aber noch nicht behoben ist. Damit wir ihn +in das Haupt-Repository zu übertragen, müssen wir sicherstellen, dass er bei `make test` übersprungen wird. + +Methoden: + +- Ein **Skip** bedeutet, dass Sie erwarten, dass Ihr Test nur dann erfolgreich ist, wenn einige Bedingungen erfüllt sind, andernfalls sollte pytest den Test überspringen. + die Ausführung des Tests ganz überspringen. Übliche Beispiele sind das Überspringen von Tests, die nur unter Windows laufen, auf Nicht-Windows-Plattformen oder das Überspringen von + Tests, die von einer externen Ressource abhängen, die im Moment nicht verfügbar ist (z.B. eine Datenbank). + +- Ein **xfail** bedeutet, dass Sie erwarten, dass ein Test aus irgendeinem Grund fehlschlägt. Ein gängiges Beispiel ist ein Test für eine Funktion, die noch nicht + noch nicht implementiert oder ein noch nicht behobener Fehler. Wenn ein Test trotz eines erwarteten Fehlschlags bestanden wird (markiert mit + pytest.mark.xfail), ist dies ein xpass und wird in der Testzusammenfassung gemeldet. + +Einer der wichtigsten Unterschiede zwischen den beiden ist, dass `skip` den Test nicht ausführt, während `xfail` dies tut. Wenn also der +Code, der fehlerhaft ist, einen schlechten Zustand verursacht, der sich auf andere Tests auswirkt, sollten Sie also nicht `xfail` verwenden. + +#### Implementierung + +- Hier sehen Sie, wie Sie einen ganzen Test bedingungslos überspringen können: + +```python no-style +@unittest.skip(reason="this bug needs to be fixed") +def test_feature_x(): +``` + +oder mit pytest: + +```python no-style +@pytest.mark.skip(reason="this bug needs to be fixed") +``` + +oder mit dem `xfail` Weg: + +```python no-style +@pytest.mark.xfail +def test_feature_x(): +``` + +- Hier erfahren Sie, wie Sie einen Test aufgrund einer internen Prüfung innerhalb des Tests auslassen können: + +```python +def test_feature_x(): + if not has_something(): + pytest.skip("unsupported configuration") +``` + +oder das ganze Modul: + +```python +import pytest + +if not pytest.config.getoption("--custom-flag"): + pytest.skip("--custom-flag is missing, skipping tests", allow_module_level=True) +``` + +oder mit dem `xfail` Weg: + +```python +def test_feature_x(): + pytest.xfail("expected to fail until bug XYZ is fixed") +``` + +- Hier erfahren Sie, wie Sie alle Tests in einem Modul überspringen können, wenn ein Import fehlt: + +```python +docutils = pytest.importorskip("docutils", minversion="0.3") +``` + +- Einen Test aufgrund einer Bedingung überspringen: + +```python no-style +@pytest.mark.skipif(sys.version_info < (3,6), reason="requires python3.6 or higher") +def test_feature_x(): +``` + +oder: + +```python no-style +@unittest.skipIf(torch_device == "cpu", "Can't do half precision") +def test_feature_x(): +``` + +oder überspringen Sie das ganze Modul: + +```python no-style +@pytest.mark.skipif(sys.platform == 'win32', reason="does not run on windows") +class TestClass(): + def test_feature_x(self): +``` + +Weitere Details, Beispiele und Möglichkeiten finden Sie [hier](https://docs.pytest.org/en/latest/skipping.html). + +### Langsame Tests + +Die Bibliothek der Tests wächst ständig, und einige der Tests brauchen Minuten, um ausgeführt zu werden, daher können wir es uns nicht leisten, eine Stunde zu warten, bis die +eine Stunde auf die Fertigstellung der Testsuite auf CI zu warten. Daher sollten langsame Tests, mit einigen Ausnahmen für wichtige Tests, wie im folgenden Beispiel +wie im folgenden Beispiel markiert werden: + +```python no-style +from transformers.testing_utils import slow +@slow +def test_integration_foo(): +``` + +Sobald ein Test als `@slow` markiert ist, setzen Sie die Umgebungsvariable `RUN_SLOW=1`, um solche Tests auszuführen, z.B: + +```bash +RUN_SLOW=1 pytest tests +``` + +Einige Dekoratoren wie `@parameterized` schreiben Testnamen um, daher müssen `@slow` und die übrigen Skip-Dekoratoren +`@require_*` müssen als letztes aufgeführt werden, damit sie korrekt funktionieren. Hier ist ein Beispiel für die korrekte Verwendung: + +```python no-style +@parameterized.expand(...) +@slow +def test_integration_foo(): +``` + +Wie zu Beginn dieses Dokuments erläutert, werden langsame Tests nach einem Zeitplan ausgeführt und nicht in PRs CI +Prüfungen. Es ist also möglich, dass einige Probleme bei der Einreichung eines PRs übersehen werden und zusammengeführt werden. Solche Probleme werden +werden beim nächsten geplanten CI-Job abgefangen. Das bedeutet aber auch, dass es wichtig ist, die langsamen Tests auf Ihrem +Rechner auszuführen, bevor Sie den PR einreichen. + +Hier ist ein grober Entscheidungsmechanismus für die Auswahl der Tests, die als langsam markiert werden sollen: + +Wenn der Test auf eine der internen Komponenten der Bibliothek ausgerichtet ist (z.B. Modellierungsdateien, Tokenisierungsdateien, +Pipelines), dann sollten wir diesen Test in der nicht langsamen Testsuite ausführen. Wenn er sich auf einen anderen Aspekt der Bibliothek bezieht, +wie z.B. die Dokumentation oder die Beispiele, dann sollten wir diese Tests in der langsamen Testsuite durchführen. Und dann, zur Verfeinerung +Ansatz zu verfeinern, sollten wir Ausnahmen einführen: + +- Alle Tests, die einen umfangreichen Satz von Gewichten oder einen Datensatz mit einer Größe von mehr als ~50MB herunterladen müssen (z.B. Modell- oder + Tokenizer-Integrationstests, Pipeline-Integrationstests) sollten auf langsam gesetzt werden. Wenn Sie ein neues Modell hinzufügen, sollten Sie + sollten Sie eine kleine Version des Modells (mit zufälligen Gewichtungen) für Integrationstests erstellen und in den Hub hochladen. Dies wird + wird in den folgenden Abschnitten erläutert. +- Alle Tests, die ein Training durchführen müssen, das nicht speziell auf Schnelligkeit optimiert ist, sollten auf langsam gesetzt werden. +- Wir können Ausnahmen einführen, wenn einige dieser Tests, die nicht langsam sein sollten, unerträglich langsam sind, und sie auf + `@slow`. Auto-Modellierungstests, die große Dateien auf der Festplatte speichern und laden, sind ein gutes Beispiel für Tests, die als + als `@slow` markiert sind. +- Wenn ein Test in weniger als 1 Sekunde auf CI abgeschlossen wird (einschließlich eventueller Downloads), sollte es sich trotzdem um einen normalen Test handeln. + +Insgesamt müssen alle nicht langsamen Tests die verschiedenen Interna abdecken und dabei schnell bleiben. Zum Beispiel, +kann eine signifikante Abdeckung erreicht werden, indem Sie mit speziell erstellten kleinen Modellen mit zufälligen Gewichten testen. Solche Modelle +haben eine sehr geringe Anzahl von Schichten (z.B. 2), Vokabeln (z.B. 1000), usw. Dann können die `@slow`-Tests große +langsame Modelle verwenden, um qualitative Tests durchzuführen. Um die Verwendung dieser Modelle zu sehen, suchen Sie einfach nach *winzigen* Modellen mit: + +```bash +grep tiny tests examples +``` + +Hier ist ein Beispiel für ein [Skript](https://github.com/huggingface/transformers/tree/main/scripts/fsmt/fsmt-make-tiny-model.py), das das winzige Modell erstellt hat +[stas/tiny-wmt19-en-de](https://huggingface.co/stas/tiny-wmt19-en-de). Sie können es ganz einfach an Ihre eigene +Architektur Ihres Modells anpassen. + +Es ist leicht, die Laufzeit falsch zu messen, wenn zum Beispiel ein großes Modell heruntergeladen wird, aber wenn +Sie es lokal testen, würden die heruntergeladenen Dateien zwischengespeichert und somit die Download-Zeit nicht gemessen werden. Prüfen Sie daher den +Ausführungsgeschwindigkeitsbericht in den CI-Protokollen (die Ausgabe von `pytest --durations=0 tests`). + +Dieser Bericht ist auch nützlich, um langsame Ausreißer zu finden, die nicht als solche gekennzeichnet sind oder die neu geschrieben werden müssen, um schnell zu sein. +Wenn Sie bemerken, dass die Testsuite beim CI langsam wird, zeigt die oberste Liste dieses Berichts die langsamsten +Tests. + + +### Testen der stdout/stderr-Ausgabe + +Um Funktionen zu testen, die in `stdout` und/oder `stderr` schreiben, kann der Test auf diese Ströme zugreifen, indem er die +[capsys system](https://docs.pytest.org/en/latest/capture.html) von `pytest` zugreifen. So wird dies bewerkstelligt: + +```python +import sys + + +def print_to_stdout(s): + print(s) + + +def print_to_stderr(s): + sys.stderr.write(s) + + +def test_result_and_stdout(capsys): + msg = "Hello" + print_to_stdout(msg) + print_to_stderr(msg) + out, err = capsys.readouterr() # consume the captured output streams + # optional: if you want to replay the consumed streams: + sys.stdout.write(out) + sys.stderr.write(err) + # test: + assert msg in out + assert msg in err +``` + +Und natürlich wird `stderr` in den meisten Fällen als Teil einer Ausnahme auftreten, so dass try/except in einem solchen Fall verwendet werden muss +Fall verwendet werden: + +```python +def raise_exception(msg): + raise ValueError(msg) + + +def test_something_exception(): + msg = "Not a good value" + error = "" + try: + raise_exception(msg) + except Exception as e: + error = str(e) + assert msg in error, f"{msg} is in the exception:\n{error}" +``` + +Ein anderer Ansatz zur Erfassung von stdout ist `contextlib.redirect_stdout`: + +```python +from io import StringIO +from contextlib import redirect_stdout + + +def print_to_stdout(s): + print(s) + + +def test_result_and_stdout(): + msg = "Hello" + buffer = StringIO() + with redirect_stdout(buffer): + print_to_stdout(msg) + out = buffer.getvalue() + # optional: if you want to replay the consumed streams: + sys.stdout.write(out) + # test: + assert msg in out +``` + +Ein wichtiges potenzielles Problem beim Erfassen von stdout ist, dass es `r` Zeichen enthalten kann, die bei normalem `print` +alles zurücksetzen, was bisher gedruckt wurde. Mit `pytest` gibt es kein Problem, aber mit `pytest -s` werden diese +werden diese Zeichen in den Puffer aufgenommen. Um den Test mit und ohne `-s` laufen zu lassen, müssen Sie also eine zusätzliche Bereinigung +zusätzliche Bereinigung der erfassten Ausgabe vornehmen, indem Sie `re.sub(r'~.*\r', '', buf, 0, re.M)` verwenden. + +Aber dann haben wir einen Hilfskontextmanager-Wrapper, der sich automatisch um alles kümmert, unabhängig davon, ob er +einige "*.*.*.*" enthält oder nicht: + +```python +from transformers.testing_utils import CaptureStdout + +with CaptureStdout() as cs: + function_that_writes_to_stdout() +print(cs.out) +``` + +Hier ist ein vollständiges Testbeispiel: + +```python +from transformers.testing_utils import CaptureStdout + +msg = "Secret message\r" +final = "Hello World" +with CaptureStdout() as cs: + print(msg + final) +assert cs.out == final + "\n", f"captured: {cs.out}, expecting {final}" +``` + +Wenn Sie `stderr` aufzeichnen möchten, verwenden Sie stattdessen die Klasse `CaptureStderr`: + +```python +from transformers.testing_utils import CaptureStderr + +with CaptureStderr() as cs: + function_that_writes_to_stderr() +print(cs.err) +``` + +Wenn Sie beide Streams auf einmal erfassen müssen, verwenden Sie die übergeordnete Klasse `CaptureStd`: + +```python +from transformers.testing_utils import CaptureStd + +with CaptureStd() as cs: + function_that_writes_to_stdout_and_stderr() +print(cs.err, cs.out) +``` + +Um das Debuggen von Testproblemen zu erleichtern, geben diese Kontextmanager standardmäßig die aufgezeichneten Streams beim Verlassen +aus dem Kontext wieder. + + +### Erfassen von Logger-Streams + +Wenn Sie die Ausgabe eines Loggers validieren müssen, können Sie `CaptureLogger` verwenden: + +```python +from transformers import logging +from transformers.testing_utils import CaptureLogger + +msg = "Testing 1, 2, 3" +logging.set_verbosity_info() +logger = logging.get_logger("transformers.models.bart.tokenization_bart") +with CaptureLogger(logger) as cl: + logger.info(msg) +assert cl.out, msg + "\n" +``` + +### Testen mit Umgebungsvariablen + +Wenn Sie die Auswirkungen von Umgebungsvariablen für einen bestimmten Test testen möchten, können Sie einen Hilfsdekorator verwenden +`transformers.testing_utils.mockenv` + +```python +from transformers.testing_utils import mockenv + + +class HfArgumentParserTest(unittest.TestCase): + @mockenv(TRANSFORMERS_VERBOSITY="error") + def test_env_override(self): + env_level_str = os.getenv("TRANSFORMERS_VERBOSITY", None) +``` + +Manchmal muss ein externes Programm aufgerufen werden, was die Einstellung von `PYTHONPATH` in `os.environ` erfordert, um mehrere lokale Pfade einzuschließen. +mehrere lokale Pfade. Eine Hilfsklasse `transformers.test_utils.TestCasePlus` hilft Ihnen dabei: + +```python +from transformers.testing_utils import TestCasePlus + + +class EnvExampleTest(TestCasePlus): + def test_external_prog(self): + env = self.get_env() + # now call the external program, passing `env` to it +``` + +Je nachdem, ob die Testdatei in der Testsuite `tests` oder in `examples` war, wird sie korrekt eingerichtet +`env[PYTHONPATH]` eines dieser beiden Verzeichnisse und auch das `src` Verzeichnis, um sicherzustellen, dass der Test gegen das aktuelle +um sicherzustellen, dass der Test mit dem aktuellen Projektarchiv durchgeführt wird, und schließlich mit dem, was in `env[PYTHONPATH]` bereits eingestellt war, bevor der Test aufgerufen wurde. +wenn überhaupt. + +Diese Hilfsmethode erstellt eine Kopie des Objekts `os.environ`, so dass das Original intakt bleibt. + + +### Reproduzierbare Ergebnisse erhalten + +In manchen Situationen möchten Sie vielleicht die Zufälligkeit Ihrer Tests beseitigen. Um identische, reproduzierbare Ergebnisse zu erhalten, müssen Sie +müssen Sie den Seed festlegen: + +```python +seed = 42 + +# python RNG +import random + +random.seed(seed) + +# pytorch RNGs +import torch + +torch.manual_seed(seed) +torch.backends.cudnn.deterministic = True +if torch.cuda.is_available(): + torch.cuda.manual_seed_all(seed) + +# numpy RNG +import numpy as np + +np.random.seed(seed) +``` + +### Tests debuggen + +Um einen Debugger an der Stelle zu starten, an der die Warnung auftritt, gehen Sie wie folgt vor: + +```bash +pytest tests/utils/test_logging.py -W error::UserWarning --pdb +``` + +## Arbeiten mit Github-Aktionen-Workflows + +Um einen CI-Job für einen Self-Push-Workflow auszulösen, müssen Sie: + +1. Erstellen Sie einen neuen Zweig auf `transformers` Ursprung (keine Gabelung!). +2. Der Name der Verzweigung muss entweder mit `ci_` oder `ci-` beginnen (`main` löst ihn auch aus, aber wir können keine PRs auf + `main`). Es wird auch nur für bestimmte Pfade ausgelöst - Sie können die aktuelle Definition finden, falls sie + falls sie sich seit der Erstellung dieses Dokuments geändert hat [hier](https://github.com/huggingface/transformers/blob/main/.github/workflows/self-push.yml) unter *push:* +3. Erstellen Sie einen PR von diesem Zweig. +4. Dann können Sie sehen, wie der Job erscheint [hier](https://github.com/huggingface/transformers/actions/workflows/self-push.yml). Er wird möglicherweise nicht sofort ausgeführt, wenn es + ein Backlog vorhanden ist. + + + + +## Testen experimenteller CI-Funktionen + +Das Testen von CI-Funktionen kann potenziell problematisch sein, da es die normale CI-Funktion beeinträchtigen kann. Wenn also eine +neue CI-Funktion hinzugefügt werden soll, sollte dies wie folgt geschehen. + +1. Erstellen Sie einen neuen Auftrag, der die zu testende Funktion testet. +2. Der neue Job muss immer erfolgreich sein, so dass er uns ein grünes ✓ gibt (Details unten). +3. Lassen Sie ihn einige Tage lang laufen, um zu sehen, dass eine Vielzahl verschiedener PR-Typen darauf laufen (Benutzer-Gabelzweige, + nicht geforkte Zweige, Zweige, die von github.com UI direct file edit stammen, verschiedene erzwungene Pushes, etc. - es gibt + es gibt so viele), während Sie die Protokolle des experimentellen Jobs überwachen (nicht den gesamten Job grün, da er absichtlich immer + grün) +4. Wenn klar ist, dass alles in Ordnung ist, fügen Sie die neuen Änderungen in die bestehenden Jobs ein. + +Auf diese Weise wird der normale Arbeitsablauf nicht durch Experimente mit der CI-Funktionalität selbst beeinträchtigt. + +Wie können wir nun dafür sorgen, dass der Auftrag immer erfolgreich ist, während die neue CI-Funktion entwickelt wird? + +Einige CIs, wie TravisCI, unterstützen ignore-step-failure und melden den gesamten Job als erfolgreich, aber CircleCI und +Github Actions unterstützen dies zum jetzigen Zeitpunkt nicht. + +Sie können also die folgende Abhilfe verwenden: + +1. Setzen Sie `set +euo pipefail` am Anfang des Ausführungsbefehls, um die meisten potenziellen Fehler im Bash-Skript zu unterdrücken. +2. Der letzte Befehl muss ein Erfolg sein: `echo "done"` oder einfach `true` reicht aus. + +Hier ist ein Beispiel: + +```yaml +- run: + name: run CI experiment + command: | + set +euo pipefail + echo "setting run-all-despite-any-errors-mode" + this_command_will_fail + echo "but bash continues to run" + # emulate another failure + false + # but the last command must be a success + echo "during experiment do not remove: reporting success to CI, even if there were failures" +``` + +Für einfache Befehle können Sie auch Folgendes tun: + +```bash +cmd_that_may_fail || true +``` + +Wenn Sie mit den Ergebnissen zufrieden sind, integrieren Sie den experimentellen Schritt oder Job natürlich in den Rest der normalen Jobs, +Entfernen Sie dabei `set +euo pipefail` oder andere Dinge, die Sie eventuell hinzugefügt haben, um sicherzustellen, dass der experimentelle Auftrag nicht +den normalen CI-Betrieb nicht beeinträchtigt. + +Dieser ganze Prozess wäre viel einfacher gewesen, wenn wir nur etwas wie `allow-failure` für den +experimentellen Schritt festlegen könnten und ihn scheitern lassen würden, ohne den Gesamtstatus der PRs zu beeinträchtigen. Aber wie bereits erwähnt, haben CircleCI und +Github Actions dies im Moment nicht unterstützen. + +Sie können in diesen CI-spezifischen Threads für diese Funktion stimmen und sehen, wo sie steht: + +- [Github Actions:](https://github.com/actions/toolkit/issues/399) +- [CircleCI:](https://ideas.circleci.com/ideas/CCI-I-344) diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/training.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/training.md new file mode 100644 index 0000000000000000000000000000000000000000..806a380b6cebc9e729581e70b5309ade5bf33159 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/de/training.md @@ -0,0 +1,433 @@ + + +# Optimierung eines vortrainierten Modells + +[[open-in-colab]] + +Die Verwendung eines vorab trainierten Modells hat erhebliche Vorteile. Es reduziert die Rechenkosten und den CO2-Fußabdruck und ermöglicht Ihnen die Verwendung von Modellen, die dem neuesten Stand der Technik entsprechen, ohne dass Sie ein Modell von Grund auf neu trainieren müssen. Transformers bietet Zugang zu Tausenden von vortrainierten Modellen für eine Vielzahl von Aufgaben. Wenn Sie ein vorab trainiertes Modell verwenden, trainieren Sie es auf einem für Ihre Aufgabe spezifischen Datensatz. Dies wird als Feinabstimmung bezeichnet und ist eine unglaublich leistungsfähige Trainingstechnik. In diesem Tutorial werden Sie ein vortrainiertes Modell mit einem Deep-Learning-Framework Ihrer Wahl feinabstimmen: + +* Feinabstimmung eines vorab trainierten Modells mit 🤗 Transformers [`Trainer`]. +* Feinabstimmung eines vorab trainierten Modells in TensorFlow mit Keras. +* Feinabstimmung eines vorab trainierten Modells in nativem PyTorch. + + + +## Vorbereitung eines Datensatzes + + + +Bevor Sie die Feinabstimmung eines vortrainierten Modells vornehmen können, müssen Sie einen Datensatz herunterladen und für das Training vorbereiten. Im vorangegangenen Leitfaden haben Sie gelernt, wie man Daten für das Training aufbereitet, und jetzt haben Sie die Gelegenheit, diese Fähigkeiten zu testen! + +Laden Sie zunächst den Datensatz [Yelp Reviews](https://huggingface.co/datasets/yelp_review_full): + +```py +>>> from datasets import load_dataset + +>>> dataset = load_dataset("yelp_review_full") +>>> dataset["train"][100] +{'label': 0, + 'text': 'My expectations for McDonalds are t rarely high. But for one to still fail so spectacularly...that takes something special!\\nThe cashier took my friends\'s order, then promptly ignored me. I had to force myself in front of a cashier who opened his register to wait on the person BEHIND me. I waited over five minutes for a gigantic order that included precisely one kid\'s meal. After watching two people who ordered after me be handed their food, I asked where mine was. The manager started yelling at the cashiers for \\"serving off their orders\\" when they didn\'t have their food. But neither cashier was anywhere near those controls, and the manager was the one serving food to customers and clearing the boards.\\nThe manager was rude when giving me my order. She didn\'t make sure that I had everything ON MY RECEIPT, and never even had the decency to apologize that I felt I was getting poor service.\\nI\'ve eaten at various McDonalds restaurants for over 30 years. I\'ve worked at more than one location. I expect bad days, bad moods, and the occasional mistake. But I have yet to have a decent experience at this store. It will remain a place I avoid unless someone in my party needs to avoid illness from low blood sugar. Perhaps I should go back to the racially biased service of Steak n Shake instead!'} +``` + +Wie Sie nun wissen, benötigen Sie einen Tokenizer, um den Text zu verarbeiten und eine Auffüll- und Abschneidungsstrategie einzubauen, um mit variablen Sequenzlängen umzugehen. Um Ihren Datensatz in einem Schritt zu verarbeiten, verwenden Sie die 🤗 Methode Datasets [`map`](https://huggingface.co/docs/datasets/process#map), um eine Vorverarbeitungsfunktion auf den gesamten Datensatz anzuwenden: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased") + + +>>> def tokenize_function(examples): +... return tokenizer(examples["text"], padding="max_length", truncation=True) + + +>>> tokenized_datasets = dataset.map(tokenize_function, batched=True) +``` + +Wenn Sie möchten, können Sie eine kleinere Teilmenge des gesamten Datensatzes für die Feinabstimmung erstellen, um den Zeitaufwand zu verringern: + +```py +>>> small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000)) +>>> small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000)) +``` + + + +## Training + +An dieser Stelle sollten Sie dem Abschnitt folgen, der dem Rahmen entspricht, den Sie verwenden möchten. Sie können über die Links +in der rechten Seitenleiste können Sie zu dem gewünschten Abschnitt springen - und wenn Sie den gesamten Inhalt eines bestimmten Frameworks ausblenden möchten, +klicken Sie einfach auf die Schaltfläche oben rechts im Block des jeweiligen Frameworks! + + + + + +## Trainieren mit PyTorch Trainer + +🤗 Transformers bietet eine [`Trainer`]-Klasse, die für das Training von 🤗 Transformers-Modellen optimiert ist und es einfacher macht, mit dem Training zu beginnen, ohne manuell eine eigene Trainingsschleife zu schreiben. Die [`Trainer`]-API unterstützt eine breite Palette von Trainingsoptionen und Funktionen wie Logging, Gradientenakkumulation und gemischte Präzision. + +Beginnen Sie mit dem Laden Ihres Modells und geben Sie die Anzahl der erwarteten Labels an. Aus dem Yelp Review [dataset card](https://huggingface.co/datasets/yelp_review_full#data-fields) wissen Sie, dass es fünf Labels gibt: + +```py +>>> from transformers import AutoModelForSequenceClassification + +>>> model = AutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-cased", num_labels=5) +``` + + + +Es wird eine Warnung angezeigt, dass einige der trainierten Parameter nicht verwendet werden und einige Parameter zufällig +initialisiert werden. Machen Sie sich keine Sorgen, das ist völlig normal! Der vorher trainierte Kopf des BERT-Modells wird verworfen und durch einen zufällig initialisierten Klassifikationskopf ersetzt. Sie werden diesen neuen Modellkopf in Ihrer Sequenzklassifizierungsaufgabe feinabstimmen, indem Sie das Wissen des vortrainierten Modells auf ihn übertragen. + + + +### Hyperparameter für das Training + +Als Nächstes erstellen Sie eine Klasse [`TrainingArguments`], die alle Hyperparameter enthält, die Sie einstellen können, sowie Flags zur Aktivierung verschiedener Trainingsoptionen. Für dieses Lernprogramm können Sie mit den Standard- [Hyperparametern](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments) beginnen, aber Sie können mit diesen experimentieren, um Ihre optimalen Einstellungen zu finden. + +Geben Sie an, wo die Kontrollpunkte Ihres Trainings gespeichert werden sollen: + +```py +>>> from transformers import TrainingArguments + +>>> training_args = TrainingArguments(output_dir="test_trainer") +``` + +### Auswerten + +Der [`Trainer`] wertet die Leistung des Modells während des Trainings nicht automatisch aus. Sie müssen [`Trainer`] eine Funktion übergeben, um Metriken zu berechnen und zu berichten. Die [🤗 Evaluate](https://huggingface.co/docs/evaluate/index) Bibliothek bietet eine einfache [`accuracy`](https://huggingface.co/spaces/evaluate-metric/accuracy) Funktion, die Sie mit der [`evaluate.load`] Funktion laden können (siehe diese [quicktour](https://huggingface.co/docs/evaluate/a_quick_tour) für weitere Informationen): + +```py +>>> import numpy as np +>>> import evaluate + +>>> metric = evaluate.load("accuracy") +``` + +Rufen Sie [`~evaluate.compute`] auf `metric` auf, um die Genauigkeit Ihrer Vorhersagen zu berechnen. Bevor Sie Ihre Vorhersagen an `compute` übergeben, müssen Sie die Vorhersagen in Logits umwandeln (denken Sie daran, dass alle 🤗 Transformers-Modelle Logits zurückgeben): + +```py +>>> def compute_metrics(eval_pred): +... logits, labels = eval_pred +... predictions = np.argmax(logits, axis=-1) +... return metric.compute(predictions=predictions, references=labels) +``` + +Wenn Sie Ihre Bewertungsmetriken während der Feinabstimmung überwachen möchten, geben Sie den Parameter `eval_strategy` in Ihren Trainingsargumenten an, um die Bewertungsmetrik am Ende jeder Epoche zu ermitteln: + +```py +>>> from transformers import TrainingArguments, Trainer + +>>> training_args = TrainingArguments(output_dir="test_trainer", eval_strategy="epoch") +``` + +### Trainer + +Erstellen Sie ein [`Trainer`]-Objekt mit Ihrem Modell, Trainingsargumenten, Trainings- und Testdatensätzen und einer Evaluierungsfunktion: + +```py +>>> trainer = Trainer( +... model=model, +... args=training_args, +... train_dataset=small_train_dataset, +... eval_dataset=small_eval_dataset, +... compute_metrics=compute_metrics, +... ) +``` + +Anschließend können Sie Ihr Modell durch den Aufruf von [`~transformers.Trainer.train`] optimieren: + +```py +>>> trainer.train() +``` + + + + + + +## Trainieren Sie ein TensorFlow-Modell mit Keras + +Sie können auch 🤗 Transformers Modelle in TensorFlow mit der Keras API trainieren! + +### Laden von Daten für Keras + +Wenn Sie ein 🤗 Transformers Modell mit der Keras API trainieren wollen, müssen Sie Ihren Datensatz in ein Format konvertieren, das +Keras versteht. Wenn Ihr Datensatz klein ist, können Sie das Ganze einfach in NumPy-Arrays konvertieren und an Keras übergeben. +Probieren wir das zuerst aus, bevor wir etwas Komplizierteres tun. + +Laden Sie zunächst ein Dataset. Wir werden den CoLA-Datensatz aus dem [GLUE-Benchmark](https://huggingface.co/datasets/glue) verwenden, +da es sich um eine einfache Aufgabe zur Klassifizierung von binärem Text handelt, und nehmen vorerst nur den Trainingssplit. + +```py +from datasets import load_dataset + +dataset = load_dataset("glue", "cola") +dataset = dataset["train"] # Just take the training split for now +``` + +Als nächstes laden Sie einen Tokenizer und tokenisieren die Daten als NumPy-Arrays. Beachten Sie, dass die Beschriftungen bereits eine Liste von 0 und 1en sind, +Wir können sie also ohne Tokenisierung direkt in ein NumPy-Array konvertieren! + +```py +from transformers import AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased") +tokenized_data = tokenizer(dataset["text"], return_tensors="np", padding=True) +# Tokenizer returns a BatchEncoding, but we convert that to a dict for Keras +tokenized_data = dict(tokenized_data) + +labels = np.array(dataset["label"]) # Label is already an array of 0 and 1 +``` + +Schließlich laden, [`compile`](https://keras.io/api/models/model_training_apis/#compile-method) und [`fit`](https://keras.io/api/models/model_training_apis/#fit-method) Sie das Modell: + +```py +from transformers import TFAutoModelForSequenceClassification +from tensorflow.keras.optimizers import Adam + +# Load and compile our model +model = TFAutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-cased") +# Lower learning rates are often better for fine-tuning transformers +model.compile(optimizer=Adam(3e-5)) + +model.fit(tokenized_data, labels) +``` + + + +Sie müssen Ihren Modellen kein Verlustargument übergeben, wenn Sie sie `compile()`! Hugging-Face-Modelle wählen automatisch +einen Loss, der für ihre Aufgabe und Modellarchitektur geeignet ist, wenn dieses Argument leer gelassen wird. Sie können jederzeit außer Kraft setzen, indem Sie selbst einen Loss angeben, wenn Sie das möchten! + + + +Dieser Ansatz eignet sich hervorragend für kleinere Datensätze, aber bei größeren Datensätzen kann er zu einem Problem werden. Warum? +Weil das tokenisierte Array und die Beschriftungen vollständig in den Speicher geladen werden müssten, und weil NumPy nicht mit +"gezackte" Arrays nicht verarbeiten kann, so dass jedes tokenisierte Sample auf die Länge des längsten Samples im gesamten Datensatz aufgefüllt werden müsste. +Datensatzes aufgefüllt werden. Dadurch wird das Array noch größer, und all die aufgefüllten Token verlangsamen auch das Training! + +### Laden von Daten als tf.data.Dataset + +Wenn Sie eine Verlangsamung des Trainings vermeiden wollen, können Sie Ihre Daten stattdessen als `tf.data.Dataset` laden. Sie können zwar Ihre eigene +tf.data"-Pipeline schreiben können, wenn Sie wollen, haben wir zwei bequeme Methoden, um dies zu tun: + +- [`~TFPreTrainedModel.prepare_tf_dataset`]: Dies ist die Methode, die wir in den meisten Fällen empfehlen. Da es sich um eine Methode +Ihres Modells ist, kann sie das Modell inspizieren, um automatisch herauszufinden, welche Spalten als Modelleingaben verwendet werden können, und +verwirft die anderen, um einen einfacheren, leistungsfähigeren Datensatz zu erstellen. +- [`~datasets.Dataset.to_tf_dataset`]: Diese Methode ist eher auf niedriger Ebene angesiedelt und ist nützlich, wenn Sie genau kontrollieren wollen, wie +Dataset erstellt wird, indem man genau angibt, welche `columns` und `label_cols` einbezogen werden sollen. + +Bevor Sie [`~TFPreTrainedModel.prepare_tf_dataset`] verwenden können, müssen Sie die Tokenizer-Ausgaben als Spalten zu Ihrem Datensatz hinzufügen, wie in +dem folgenden Codebeispiel: + +```py +def tokenize_dataset(data): + # Keys of the returned dictionary will be added to the dataset as columns + return tokenizer(data["text"]) + + +dataset = dataset.map(tokenize_dataset) +``` + +Denken Sie daran, dass Hugging Face-Datensätze standardmäßig auf der Festplatte gespeichert werden, so dass dies nicht zu einem erhöhten Arbeitsspeicherbedarf führen wird! Sobald die +Spalten hinzugefügt wurden, können Sie Batches aus dem Datensatz streamen und zu jedem Batch Auffüllungen hinzufügen, was die Anzahl der Auffüllungs-Token im Vergleich zum Auffüllen des gesamten Datensatzes reduziert. + + +```py +>>> tf_dataset = model.prepare_tf_dataset(dataset, batch_size=16, shuffle=True, tokenizer=tokenizer) +``` + +Beachten Sie, dass Sie im obigen Codebeispiel den Tokenizer an `prepare_tf_dataset` übergeben müssen, damit die Stapel beim Laden korrekt aufgefüllt werden können. +Wenn alle Stichproben in Ihrem Datensatz die gleiche Länge haben und kein Auffüllen erforderlich ist, können Sie dieses Argument weglassen. +Wenn Sie etwas Komplexeres als nur das Auffüllen von Stichproben benötigen (z. B. das Korrumpieren von Token für die maskierte Sprachmodellierung), können Sie das Argument +Modellierung), können Sie stattdessen das Argument `collate_fn` verwenden, um eine Funktion zu übergeben, die aufgerufen wird, um die +Liste von Stichproben in einen Stapel umwandelt und alle gewünschten Vorverarbeitungen vornimmt. Siehe unsere +[examples](https://github.com/huggingface/transformers/tree/main/examples) oder +[notebooks](https://huggingface.co/docs/transformers/notebooks), um diesen Ansatz in Aktion zu sehen. + +Sobald Sie einen `tf.data.Dataset` erstellt haben, können Sie das Modell wie zuvor kompilieren und anpassen: + +```py +model.compile(optimizer=Adam(3e-5)) + +model.fit(tf_dataset) +``` + + + + + + +## Trainieren in nativem PyTorch + + + + + +[`Trainer`] kümmert sich um die Trainingsschleife und ermöglicht die Feinabstimmung eines Modells in einer einzigen Codezeile. Für Benutzer, die es vorziehen, ihre eigene Trainingsschleife zu schreiben, können Sie auch eine Feinabstimmung eines 🤗 Transformers-Modells in nativem PyTorch vornehmen. + +An diesem Punkt müssen Sie möglicherweise Ihr Notebook neu starten oder den folgenden Code ausführen, um etwas Speicher freizugeben: + +```py +del model +del pytorch_model +del trainer +torch.cuda.empty_cache() +``` + +Als Nächstes müssen Sie den Datensatz `tokenized_dataset` manuell nachbearbeiten, um ihn für das Training vorzubereiten. + +1. Entfernen Sie die Spalte "Text", da das Modell keinen Rohtext als Eingabe akzeptiert: + + ```py + >>> tokenized_datasets = tokenized_datasets.remove_columns(["text"]) + ``` + +2. Benennen Sie die Spalte "Label" in "Labels" um, da das Modell erwartet, dass das Argument "Labels" genannt wird: + + ```py + >>> tokenized_datasets = tokenized_datasets.rename_column("label", "labels") + ``` + +3. Stellen Sie das Format des Datensatzes so ein, dass PyTorch-Tensoren anstelle von Listen zurückgegeben werden: + + ```py + >>> tokenized_datasets.set_format("torch") + ``` + +Erstellen Sie dann eine kleinere Teilmenge des Datensatzes, wie zuvor gezeigt, um die Feinabstimmung zu beschleunigen: + +```py +>>> small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000)) +>>> small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000)) +``` + +### DataLoader + +Erstellen Sie einen `DataLoader` für Ihre Trainings- und Testdatensätze, damit Sie über die Datenstapel iterieren können: + +```py +>>> from torch.utils.data import DataLoader + +>>> train_dataloader = DataLoader(small_train_dataset, shuffle=True, batch_size=8) +>>> eval_dataloader = DataLoader(small_eval_dataset, batch_size=8) +``` + +Laden Sie Ihr Modell mit der Anzahl der erwarteten Kennzeichnungen: + +```py +>>> from transformers import AutoModelForSequenceClassification + +>>> model = AutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-cased", num_labels=5) +``` + +### Optimierer und Lernratensteuerung + +Erstellen Sie einen Optimierer und einen Scheduler für die Lernrate, um das Modell fein abzustimmen. Wir verwenden den Optimierer [`AdamW`](https://pytorch.org/docs/stable/generated/torch.optim.AdamW.html) aus PyTorch: + +```py +>>> from torch.optim import AdamW + +>>> optimizer = AdamW(model.parameters(), lr=5e-5) +``` + +Erstellen Sie den Standard-Lernratenplaner aus [`Trainer`]: + +```py +>>> from transformers import get_scheduler + +>>> num_epochs = 3 +>>> num_training_steps = num_epochs * len(train_dataloader) +>>> lr_scheduler = get_scheduler( +... name="linear", optimizer=optimizer, num_warmup_steps=0, num_training_steps=num_training_steps +... ) +``` + +Geben Sie schließlich `device` an, um einen Grafikprozessor zu verwenden, wenn Sie Zugang zu einem solchen haben. Andernfalls kann das Training auf einer CPU mehrere Stunden statt ein paar Minuten dauern. + +```py +>>> import torch + +>>> device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") +>>> model.to(device) +``` + + + +Holen Sie sich mit einem gehosteten Notebook wie [Colaboratory](https://colab.research.google.com/) oder [SageMaker StudioLab](https://studiolab.sagemaker.aws/) kostenlosen Zugang zu einem Cloud-GPU, wenn Sie noch keinen haben. + + + +Großartig, Sie sind bereit für das Training! 🥳 + +### Trainingsschleife + +Um Ihren Trainingsfortschritt zu verfolgen, verwenden Sie die [tqdm](https://tqdm.github.io/) Bibliothek, um einen Fortschrittsbalken über die Anzahl der Trainingsschritte hinzuzufügen: + +```py +>>> from tqdm.auto import tqdm + +>>> progress_bar = tqdm(range(num_training_steps)) + +>>> model.train() +>>> for epoch in range(num_epochs): +... for batch in train_dataloader: +... batch = {k: v.to(device) for k, v in batch.items()} +... outputs = model(**batch) +... loss = outputs.loss +... loss.backward() + +... optimizer.step() +... lr_scheduler.step() +... optimizer.zero_grad() +... progress_bar.update(1) +``` + +### Auswertung + +Genauso wie Sie eine Bewertungsfunktion zu [`Trainer`] hinzugefügt haben, müssen Sie dasselbe tun, wenn Sie Ihre eigene Trainingsschleife schreiben. Aber anstatt die Metrik am Ende jeder Epoche zu berechnen und zu melden, werden Sie dieses Mal alle Stapel mit [`~evaluate.add_batch`] akkumulieren und die Metrik ganz am Ende berechnen. + +```py +>>> import evaluate + +>>> metric = evaluate.load("accuracy") +>>> model.eval() +>>> for batch in eval_dataloader: +... batch = {k: v.to(device) for k, v in batch.items()} +... with torch.no_grad(): +... outputs = model(**batch) + +... logits = outputs.logits +... predictions = torch.argmax(logits, dim=-1) +... metric.add_batch(predictions=predictions, references=batch["labels"]) + +>>> metric.compute() +``` + + + + + +## Zusätzliche Ressourcen + +Weitere Beispiele für die Feinabstimmung finden Sie unter: + +- [🤗 Transformers Examples](https://github.com/huggingface/transformers/tree/main/examples) enthält Skripte + um gängige NLP-Aufgaben in PyTorch und TensorFlow zu trainieren. + +- [🤗 Transformers Notebooks](notebooks) enthält verschiedene Notebooks zur Feinabstimmung eines Modells für bestimmte Aufgaben in PyTorch und TensorFlow. \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/_config.py b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/_config.py new file mode 100644 index 0000000000000000000000000000000000000000..f49e4e4731965a504b8da443c2cd979638cd22bb --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/_config.py @@ -0,0 +1,14 @@ +# docstyle-ignore +INSTALL_CONTENT = """ +# Transformers installation +! pip install transformers datasets evaluate accelerate +# To install from source instead of the last release, comment the command above and uncomment the following one. +# ! pip install git+https://github.com/huggingface/transformers.git +""" + +notebook_first_cells = [{"type": "code", "content": INSTALL_CONTENT}] +black_avoid_patterns = { + "{processor_class}": "FakeProcessorClass", + "{model_class}": "FakeModelClass", + "{object_class}": "FakeObjectClass", +} diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/_redirects.yml b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/_redirects.yml new file mode 100644 index 0000000000000000000000000000000000000000..ff70547c7228419daa3e1b048c7256ec8a5deae1 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/_redirects.yml @@ -0,0 +1,5 @@ +# Optimizing inference + +perf_infer_gpu_many: perf_infer_gpu_one +transformers_agents: agents +quantization: quantization/overview diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/accelerate.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/accelerate.md new file mode 100644 index 0000000000000000000000000000000000000000..a18436889e03814cfeff6f861bf9f05558dae08e --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/accelerate.md @@ -0,0 +1,165 @@ + + +# Accelerate + +[Accelerate](https://hf.co/docs/accelerate/index) is a library designed to simplify distributed training on any type of setup with PyTorch by uniting the most common frameworks ([Fully Sharded Data Parallel (FSDP)](https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/) and [DeepSpeed](https://www.deepspeed.ai/)) for it into a single interface. [`Trainer`] is powered by Accelerate under the hood, enabling loading big models and distributed training. + +This guide will show you two ways to use Accelerate with Transformers, using FSDP as the backend. The first method demonstrates distributed training with [`Trainer`], and the second method demonstrates adapting a PyTorch training loop. For more detailed information about Accelerate, please refer to the [documentation](https://hf.co/docs/accelerate/index). + +```bash +pip install accelerate +``` + +Start by running [accelerate config](https://hf.co/docs/accelerate/main/en/package_reference/cli#accelerate-config) in the command line to answer a series of prompts about your training system. This creates and saves a configuration file to help Accelerate correctly set up training based on your setup. + +```bash +accelerate config +``` + +Depending on your setup and the answers you provide, an example configuration file for distributing training with FSDP on one machine with two GPUs may look like the following. + +```yaml +compute_environment: LOCAL_MACHINE +debug: false +distributed_type: FSDP +downcast_bf16: 'no' +fsdp_config: + fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP + fsdp_backward_prefetch_policy: BACKWARD_PRE + fsdp_forward_prefetch: false + fsdp_cpu_ram_efficient_loading: true + fsdp_offload_params: false + fsdp_sharding_strategy: FULL_SHARD + fsdp_state_dict_type: SHARDED_STATE_DICT + fsdp_sync_module_states: true + fsdp_transformer_layer_cls_to_wrap: BertLayer + fsdp_use_orig_params: true +machine_rank: 0 +main_training_function: main +mixed_precision: bf16 +num_machines: 1 +num_processes: 2 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false +``` + +## Trainer + +Pass the path to the saved configuration file to [`TrainingArguments`], and from there, pass your [`TrainingArguments`] to [`Trainer`]. + +```py +from transformers import TrainingArguments, Trainer + +training_args = TrainingArguments( + output_dir="your-model", + learning_rate=2e-5, + per_device_train_batch_size=16, + per_device_eval_batch_size=16, + num_train_epochs=2, + fsdp_config="path/to/fsdp_config", + fsdp="full_shard", + weight_decay=0.01, + eval_strategy="epoch", + save_strategy="epoch", + load_best_model_at_end=True, + push_to_hub=True, +) + +trainer = Trainer( + model=model, + args=training_args, + train_dataset=dataset["train"], + eval_dataset=dataset["test"], + processing_class=tokenizer, + data_collator=data_collator, + compute_metrics=compute_metrics, +) + +trainer.train() +``` + +## Native PyTorch + +Accelerate can also be added to any PyTorch training loop to enable distributed training. The [`~accelerate.Accelerator`] is the main entry point for adapting your PyTorch code to work with Accelerate. It automatically detects your distributed training setup and initializes all the necessary components for training. You don't need to explicitly place your model on a device because [`~accelerate.Accelerator`] knows which device to move your model to. + +```py +from accelerate import Accelerator + +accelerator = Accelerator() +device = accelerator.device +``` + +All PyTorch objects (model, optimizer, scheduler, dataloaders) should be passed to the [`~accelerate.Accelerator.prepare`] method now. This method moves your model to the appropriate device or devices, adapts the optimizer and scheduler to use [`~accelerate.optimizer.AcceleratedOptimizer`] and [`~accelerate.scheduler.AcceleratedScheduler`], and creates a new shardable dataloader. + +```py +train_dataloader, eval_dataloader, model, optimizer = accelerator.prepare( + train_dataloader, eval_dataloader, model, optimizer +) +``` + +Replace `loss.backward` in your training loop with Accelerates [`~accelerate.Accelerator.backward`] method to scale the gradients and determine the appropriate `backward` method to use depending on your framework (for example, DeepSpeed or Megatron). + +```py +for epoch in range(num_epochs): + for batch in train_dataloader: + outputs = model(**batch) + loss = outputs.loss + accelerator.backward(loss) + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + progress_bar.update(1) +``` + +Combine everything into a function and make it callable as a script. + +```py +from accelerate import Accelerator + +def main(): + accelerator = Accelerator() + + model, optimizer, training_dataloader, scheduler = accelerator.prepare( + model, optimizer, training_dataloader, scheduler + ) + + for batch in training_dataloader: + optimizer.zero_grad() + inputs, targets = batch + outputs = model(inputs) + loss = loss_function(outputs, targets) + accelerator.backward(loss) + optimizer.step() + scheduler.step() + +if __name__ == "__main__": + main() +``` + +From the command line, call [accelerate launch](https://hf.co/docs/accelerate/main/en/package_reference/cli#accelerate-launch) to run your training script. Any additional arguments or parameters can be passed here as well. + +To launch your training script on two GPUs, add the `--num_processes` argument. + +```bash +accelerate launch --num_processes=2 your_script.py +``` + +Refer to the [Launching Accelerate scripts](https://hf.co/docs/accelerate/main/en/basic_tutorials/launch) for more details. diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/accelerator_selection.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/accelerator_selection.md new file mode 100644 index 0000000000000000000000000000000000000000..5d5bbc2675fa233a65f6fac1f13c4b92aa6ed5e9 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/accelerator_selection.md @@ -0,0 +1,126 @@ + + +# Accelerator selection + +During distributed training, you can specify the number and order of accelerators (CUDA, XPU, MPS, HPU, etc.) to use. This can be useful when you have accelerators with different computing power and you want to use the faster accelerator first. Or you could only use a subset of the available accelerators. The selection process works for both [DistributedDataParallel](https://pytorch.org/docs/stable/generated/torch.nn.parallel.DistributedDataParallel.html) and [DataParallel](https://pytorch.org/docs/stable/generated/torch.nn.DataParallel.html). You don't need Accelerate or [DeepSpeed integration](./main_classes/deepspeed). + +This guide will show you how to select the number of accelerators to use and the order to use them in. + +## Number of accelerators + +For example, if there are 4 accelerators and you only want to use the first 2, run the command below. + + + + +Use the `--nproc_per_node` to select how many accelerators to use. + +```bash +torchrun --nproc_per_node=2 trainer-program.py ... +``` + + + + +Use `--num_processes` to select how many accelerators to use. + +```bash +accelerate launch --num_processes 2 trainer-program.py ... +``` + + + + +Use `--num_gpus` to select how many GPUs to use. + +```bash +deepspeed --num_gpus 2 trainer-program.py ... +``` + + + + +## Order of accelerators +To select specific accelerators to use and their order, use the environment variable appropriate for your hardware. This is often set on the command line for each run, but can also be added to your `~/.bashrc` or other startup config file. + +For example, if there are 4 accelerators (0, 1, 2, 3) and you only want to run accelerators 0 and 2: + + + + +```bash +CUDA_VISIBLE_DEVICES=0,2 torchrun trainer-program.py ... +``` + +Only GPUs 0 and 2 are "visible" to PyTorch and are mapped to `cuda:0` and `cuda:1` respectively. +To reverse the order (use GPU 2 as `cuda:0` and GPU 0 as `cuda:1`): + + +```bash +CUDA_VISIBLE_DEVICES=2,0 torchrun trainer-program.py ... +``` + +To run without any GPUs: + +```bash +CUDA_VISIBLE_DEVICES= python trainer-program.py ... +``` + +You can also control the order of CUDA devices using `CUDA_DEVICE_ORDER`: + +- Order by PCIe bus ID (matches `nvidia-smi`): + + ```bash + export CUDA_DEVICE_ORDER=PCI_BUS_ID + ``` + +- Order by compute capability (fastest first): + + ```bash + export CUDA_DEVICE_ORDER=FASTEST_FIRST + ``` + + + + +```bash +ZE_AFFINITY_MASK=0,2 torchrun trainer-program.py ... +``` + +Only XPUs 0 and 2 are "visible" to PyTorch and are mapped to `xpu:0` and `xpu:1` respectively. +To reverse the order (use XPU 2 as `xpu:0` and XPU 0 as `xpu:1`): + +```bash +ZE_AFFINITY_MASK=2,0 torchrun trainer-program.py ... +``` + + +You can also control the order of Intel XPUs with: + +```bash +export ZE_ENABLE_PCI_ID_DEVICE_ORDER=1 +``` + +For more information about device enumeration and sorting on Intel XPU, please refer to the [Level Zero](https://github.com/oneapi-src/level-zero/blob/master/README.md?plain=1#L87) documentation. + + + + + + +> [!WARNING] +> Environment variables can be exported instead of being added to the command line. This is not recommended because it can be confusing if you forget how the environment variable was set up and you end up using the wrong accelerators. Instead, it is common practice to set the environment variable for a specific training run on the same command line. diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/add_new_model.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/add_new_model.md new file mode 100644 index 0000000000000000000000000000000000000000..c4695b2fe35a96916d144fa8dd2cd3b4c42555a1 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/add_new_model.md @@ -0,0 +1,665 @@ + + +# Legacy model contribution + +> [!TIP] +> Try adding new models with a more [modular](./modular_transformers) approach first. This makes it significantly easier to contribute a model to Transformers! + +Many of the models in Transformers are contributed by developers and researchers. As an open-source first project, we're invested in empowering the community to actively and independently add more models. + +When you add a model to Transformers, you'll learn: + +- more about open-source best practices +- about a models architecture +- about Transformers' design principles +- how to efficiently test large models +- how to use Python utilities like [Black](https://black.readthedocs.io/en/stable/) and [Ruff](https://docs.astral.sh/ruff/) to create clean and readable code + +It is a challenging but rewarding process. + +This guide will walk you through adding an example BrandNewLlama PyTorch model to Transformers. Before you begin, it is a good idea to familiarize yourself with the library. + +## Transformers overview + +Transformers is an opinionated library with its own unique philosophy and design choices. These choices help us sustainably scale and maintain Transformers. + +> [!TIP] +> Learn more about our design principles on the [Philosophy](./philosophy) doc. + +Some of these design choices are: + +- composition > over-abstraction +- duplicate code isn't always bad if it greatly improves readability and accessibility +- model files are self-contained and all the necessary model code is found in the `modeling_mymodel.py` file + +These design choices are important *for everyone* interacting with the model. It is easier to read, understand, and modify. + +This section describes how the model and configuration classes interact and the Transformers code style. + +### Model and configuration + +All Transformers' models inherit from a base [`PreTrainedModel`] and [`PretrainedConfig`] class. The configuration is the models blueprint. + +There is never more than two levels of abstraction for any model to keep the code readable. The example model here, BrandNewLlama, inherits from `BrandNewLlamaPreTrainedModel` and [`PreTrainedModel`]. It is important that a new model only depends on [`PreTrainedModel`] so that it can use the [`~PreTrainedModel.from_pretrained`] and [`~PreTrainedModel.save_pretrained`] methods. + +Other important functions like the forward method are defined in the `modeling.py` file. + +Specific model heads (for example, sequence classification or language modeling) should call the base model in the forward pass rather than inheriting from it to keep abstraction low. + +New models require a configuration, for example `BrandNewLlamaConfig`, that is stored as an attribute of [`PreTrainedModel`]. + +```py +model = BrandNewLlamaModel.from_pretrained("username/brand_new_llama") +model.config +``` + +[`PretrainedConfig`] provides the [`~PretrainedConfig.from_pretrained`] and [`~PretrainedConfig.save_pretrained`] methods. + +When you use [`PreTrainedModel.save_pretrained`], it automatically calls [`PretrainedConfig.save_pretrained`] so that both the model and configuration are saved together. + +A model is saved to a `model.safetensors` file and a configuration is saved to a `config.json` file. + +### Code style + +Transformers prefers a clean and readable code over a more abstracted code style. Some of the code style choices include: + +- The code should be accessible to non-English users. Pick descriptive variable names and avoid abbreviations. For example, "activation" is preferred over "act". One letter variables names are highly discouraged unless it's an index in a for loop. + +- Explicit code is preferred - even if it's longer - over shorter code. + +- Avoid subclassing [nn.Sequential](https://pytorch.org/docs/stable/generated/torch.nn.Sequential.html). Subclass [nn.Module](https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module) instead so the code can be quickly debugged with print statements or breakpoints. + +- Function signatures should be type-annotated. Otherwise, use good variable names so they're more understandable. + +## New model addition issue + +Open a [New model addition](https://github.com/huggingface/transformers/issues/new?assignees=&labels=New+model&template=new-model-addition.yml) issue to add a specific model. + +> [!TIP] +> Filter by the [New model](https://github.com/huggingface/transformers/labels/New%20model) label on GitHub to view and add any existing model requests. + +Now is a good time to get familiar with BrandNewLlama. It is helpful to read a models research paper to understand its technical design and implementation. You don't necessarily have to worry too much about the theoretical details. Instead, focus on the practical ones. Use the questions below to guide your reading. + +- What type of model is BrandNewLlama? Is it a encoder, decoder, or encoder-decoder model? +- What tasks can BrandNewLlama be used for? +- What makes BrandNewLlama different from other models? +- What models in Transformers are most similar to BrandNewLlama? +- What tokenizer does BrandNewLlama use? + +In addition to learning more about your model, use the tips below to help you add a model faster. + +> [!TIP] +> Each contributor has a unique style and workflow for adding models to Transformers. For an example, take a look at how [Gemma](https://github.com/huggingface/transformers/pull/29167) was added. + +- Don't reinvent the wheel! Take your time to explore existing models and tokenizers to see what you can copy and reuse. [Grep](https://www.gnu.org/software/grep/) and [ripgrep](https://github.com/BurntSushi/ripgrep) are great tools for this. +- This is more of an engineering than a science challenge. Focus on the more practical (setting up an efficient debugging environment for example) instead of the theorertical aspects of the model. +- Don't be shy to ask for help! We are here to support you. 🤗 + +## Dev environment + +Click on the **Fork** button on the [Transformers](https://github.com/huggingface/transformers) repository to create your own copy to work on. Clone the repository to your local disk and add the base repository as the remote. + +```bash +git clone https://github.com/[your Github handle]/transformers.git +cd transformers +git remote add upstream https://github.com/huggingface/transformers.git +``` + +Create a virtual environment and perform an [editable install](./installation#editable-install) of the library with the "dev" or development dependencies. + +```bash +python -m venv .env +source .env/bin/activate +pip install -e ".[dev]" +``` + +Due to the number of optional dependencies as Transformers grows, this command may fail. In this case, install the "quality" dependencies. Also make sure you have a deep learning framework installed. + +```bash +pip install -e ".[quality]" +``` + +Return to the parent directory and clone and install the original BrandNewLlama repository. + +```bash +git clone https://github.com/org_that_created_brand_new_llama_org/brand_new_llama.git +cd brand_new_bert +pip install -e . +``` + +Return to your clone of Transformers to begin porting BrandNewLlama. + +```bash +cd transformers +``` + +There are two possible debugging environments for running the original model, a notebook ([Google Colab](https://colab.research.google.com/notebooks/intro.ipynb) or [Jupyter](https://jupyter.org/)) or a local Python script. + +> [!WARNING] +> We don't recommend setting up a GPU environment to run the original model because it can be expensive. Instead, work in a CPU environment first to verify the model works in Transformers. Once it does, then you can verify it on a GPU. + +Notebooks are great for executing code cell-by-cell which can help split logical components from one another. It can also accelerate debugging cycles because intermediate results can be stored. You can also share notebooks when working with other contributors. + +The downside is that if you aren't used to them, it may take some time to get used to. + +> [!TIP] +> If the model architecture is identical to an existing model, skip ahead to add a [conversion script](#conversion-script), because you can reuse the architecture of the existing model. + +Run the command below to start and complete the questionnaire with some basic information about the new model. This command jumpstarts the process by automatically generating some model code that you'll need to adapt. + +```bash +transformers add-new-model-like +``` + +## Create a pull request + +Before you start adapting the code, create a pull request to track your progress and get feedback from the Transformers team. Title your pull request **[WIP] Add BrandNewLlama** so it's clear that this is a work in progress. + +Create a branch with a descriptive name from your main branch. + +```bash +git checkout -b add_brand_new_bert +``` + +Commit the code, and then fetch and rebase on the main branch. + +```bash +git add . +git commit +git fetch upstream +git rebase upstream/main +``` + +Push any changes to your branch and click on **Compare & pull request** to open a pull request on GitHub. Open the pull request as a *draft* to indicate it's a work in progress. + +```bash +git push -u origin a-descriptive-name-for-my-changes +``` + +Include relevant Hugging Face team members by adding their GitHub handles in the pull request for questions, feedback, comments, and reviews. Direct team members to specific parts of the code you want by clicking on the **Files changed** tab, and then clicking on **+** to the left of the line number to add a comment. When a question or problem is solved, click on **Resolve** to indicate the issue is resolved. This keeps the conversation organized and clean. + +Remember to periodically commit and push your work, and update your work with the current main branch. + +```bash +git fetch upstream +git merge upstream/main +``` + +## Original checkpoint + +Take some time to work on the original model implementation first to understand how it works. + +This can be difficult if the original model repository is lacking documentation or if the codebase is complex. But you should use this as your motivation to implement the model in Transformers. Your contribution makes it more accessible and user-friendly to everyone! + +Orient yourself with the original repository by doing the following. + +- Locate the pretrained weights. +- Figure out how to the load pretrained weights into the model. +- Figure out how to run the tokenizer independently of the model. +- Trace one forward pass to understand which classes and functions are required. These are probably the only classes and functions you'll have to implement. +- Locate all the important components (model class, model subclasses, self-attention layer, etc.) of the model. +- Figure out how to debug the model in the original repository. Add print statements, use interactive debuggers like [ipdb](https://github.com/gotcha/ipdb), or a efficient integrated development environment (IDE) like [PyCharm](https://www.jetbrains.com/pycharm/). + +The last point is especially important because you'll need a thorough understanding of what's happening inside the original model before you can reimplement it in Transformers. Feel free to open issues and pull requests in the original repository if you encounter any issues. + +A good first step is to load a *small* pretrained checkpoint and try to reproduce a single forward pass with an example integer vector of inputs. For example, in pseudocode, this could look like the following. + +```py +model = BrandNewLlamaModel.load_pretrained_checkpoint("/path/to/checkpoint/") +input_ids = [0, 4, 5, 2, 3, 7, 9] # vector of input ids +original_output = model.generate(input_ids) +``` + +### Debugging + +If you run into issues, you'll need to choose one of the following debugging strategies depending on the original models codebase. + + + + +This strategy relies on breaking the original model into smaller sub-components, such as when the code can be easily run in eager mode. While more difficult, there are some advantages to this approach. + +1. It is easier later to compare the original model to your implementation. You can automatically verify that each individual component matches its corresponding component in the Transformers' implementation. This is better than relying on a visual comparison based on print statements. +2. It is easier to port individual components instead of the entire model. +3. It is easier for understanding how a model works by breaking it up into smaller parts. +4. It is easier to prevent regressions at a later stage when you change your code thanks to component-by-component tests. + +> [!TIP] +> Refer to the ELECTRA [integration checks](https://gist.github.com/LysandreJik/db4c948f6b4483960de5cbac598ad4ed) for a good example of how to decompose a model into smaller components. + + + + +This strategy is viable when the original codebase is too complex, only allows intermediate components to be run in compiled mode, or if it's too time-consuming (maybe even impossible) to separate the model into smaller sub-components. + +For example, the MeshTensorFlow implementation of [T5](https://github.com/tensorflow/mesh/tree/master/mesh_tensorflow) is too complex and doesn't offer a simple way to decompose the model into its sub-components. In this situation, you'll have to rely on verifying print statements. + + + + +Whichever strategy you choose, it is recommended to debug the initial layers first and the final layers last. Retrieve the output, either with print statements or sub-component functions, of the following layers in this order. + +1. input ids passed to the model +2. word embeddings +3. input of the first Transformer layer +4. output of the first Transformer layer +5. output of the following n-1 Transformer layers +6. output of the whole model + +The input ids should just be an array of integers like `input_ids = [0, 4, 4, 3, 2, 4, 1, 7, 19]`. + +Layer outputs often consist of multi-dimensional float arrays. + +```py +[[ + [-0.1465, -0.6501, 0.1993, ..., 0.1451, 0.3430, 0.6024], + [-0.4417, -0.5920, 0.3450, ..., -0.3062, 0.6182, 0.7132], + [-0.5009, -0.7122, 0.4548, ..., -0.3662, 0.6091, 0.7648], + ..., + [-0.5613, -0.6332, 0.4324, ..., -0.3792, 0.7372, 0.9288], + [-0.5416, -0.6345, 0.4180, ..., -0.3564, 0.6992, 0.9191], + [-0.5334, -0.6403, 0.4271, ..., -0.3339, 0.6533, 0.8694]]], +``` + +Every Transformers model output should have a precision or error tolerance of *1e-3*. This accounts for any output differences that arise from using a different library framework. Compare the intermediate outputs of the original model with the Transformers implementation to ensure they're nearly identical. Having an *efficient* debugging environment is crucial for this step. + +Here are some tips for an efficient debugging environment. + +- To debug intermediate results, it depends on the machine learning framework the original model repository is using. For PyTorch, you should write a script to decompose the original model into smaller sub-components to retrieve the intermediate values. For TensorFlow, you may need to use [tf.print](https://www.tensorflow.org/api_docs/python/tf/print). For Flax, make sure the model is *not jitted* during the forward pass (refer to this GitHub [Issue](https://github.com/google/jax/issues/196) for more details). + +- It is faster to debug with a smaller pretrained checkpoint versus a larger checkpoint where the forward pass takes more than 10 seconds. If only large checkpoints are available, create a dummy model with randomly initialized weights and save those weights to compare against the Transformers implementation. + +- Find the easiest way to call the model's forward pass. Ideally, this function (may be called `predict`, `evaluate`, `forward`, or `__call__`) should only call the forward pass *once*. It is more difficult to debug a function that calls the forward pass multiple times. + +- Separate tokenization from the forward pass. Locate where a string input is changed to input ids in the forward pass and start here. You may need to create a small script or modify the original code to directly input the input ids instead of an input string. + +- Ensure the model is *not* in training mode. This can produce random outputs due to multiple dropout layers in a model. The forward pass in your debugging environment should be *deterministic* so that the dropout layers aren't used. + +Once you're able to run the original checkpoint, you're ready to start adapting the model code for Transformers. + +## Adapt the model code + +The `transformers add-new-model-like` command should have generated a model and configuration file. + +- `src/transformers/models/brand_new_llama/modeling_brand_new_llama.py` +- `src/transformers/models/brand_new_llama/configuration_brand_new_llama.py` + +The automatically generated code in the `modeling.py` file has the same architecture as Llama if you answered it's a decoder-only model or it will have the same architecture as BART if you answered it's an encoder-decoder model. The generated code is just a starting point. Based on your research on the new model, you'll need to implement those specific changes by adapting the generated code. This may involve changes to the self-attention layer, the order of the normalization layer, and so on. + +### Model initialization + +At this point, your code doesn't have to be clean or even fully correct, It is more efficient to quickly create a first draft and then iteratively improve on it. The most important thing is that your model can be instantiated from Transformers. The command below creates a model from the configuration with random weights, verifying that the `__init__` method works. + +```py +from transformers import BrandNewLlama, BrandNewLlamaConfig +model = BrandNewLlama(BrandNewLlamaConfig()) +``` + +Random initialization occurs in the `_init_weights` method of `BrandNewLlamaPreTrainedModel`. All leaf modules are initialized depending on the configuration's variables. + +```py +def _init_weights(self, module): + """Initialize the weights""" + if isinstance(module, nn.Linear): + module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) + if module.bias is not None: + module.bias.data.zero_() + elif isinstance(module, nn.Embedding): + module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) + if module.padding_idx is not None: + module.weight.data[module.padding_idx].zero_() + elif isinstance(module, nn.LayerNorm): + module.bias.data.zero_() + module.weight.data.fill_(1.0) +``` + +The initialization scheme can look different if you need to adapt it to your model. For example, [`Wav2Vec2ForPreTraining`] initializes [nn.Linear](https://pytorch.org/docs/stable/generated/torch.nn.Linear.html) in its last two linear layers. + +The `_is_hf_initialized` flag makes sure the submodule is only initialized once. Setting `module.project_q` and `module.project_hid` to `True` ensures the custom initialization is not overridden later. The `_init_weights` function won't be applied to these modules. + +```py +def _init_weights(self, module): + """Initialize the weights""" + if isinstance(module, Wav2Vec2ForPreTraining): + module.project_hid.reset_parameters() + module.project_q.reset_parameters() + module.project_hid._is_hf_initialized = True + module.project_q._is_hf_initialized = True + elif isinstance(module, nn.Linear): + module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) + if module.bias is not None: + module.bias.data.zero_() +``` + +### Convert checkpoints to Transformers + +The original checkpoint must be converted to a Transformers compatible checkpoint. + +> [!TIP] +> Try looking for an existing conversion script to copy, adapt, and reuse for your model! +> +> - If you're porting a model from TensorFlow to PyTorch, a good starting point may be the BERT [conversion script](https://github.com/huggingface/transformers/blob/7acfa95afb8194f8f9c1f4d2c6028224dbed35a2/src/transformers/models/bert/modeling_bert.py#L91). +> - If you're porting a model from PyTorch to PyTorch, a good starting point may be the BART [conversion script](https://github.com/huggingface/transformers/blob/main/src/transformers/models/bart/convert_bart_original_pytorch_checkpoint_to_pytorch.py). + +Make sure **all** required weights are initialized and print out all the checkpoint weights that weren't used for initialization to make sure the model has been converted correctly. + +You may encounter wrong shape statements or name assignments during the conversion. This is most likely because of incorrect parameters in `BrandNewLlamaConfig`, the wrong architecture, a bug in the `init` method of your implementation, or you need to transpose one of the checkpoint weights. + +Keep iterating on the [Adapt the model code](#adapt-the-model-code) section until all the checkpoint weights are correctly loaded. Once you can load a checkpoint in your model, save it to a folder. This should contain a `model.safetensors` file and a `config.json` file. + +```py +model.save_pretrained("/path/to/converted/checkpoint/folder") +``` + +To help with conversion, the next section briefly describes how PyTorch models stores and defines layer weights and names. + +#### PyTorch layer weights and names + +It is helpful to create a basic PyTorch model to understand how layer names are defined and weights are initialized. + +```py +from torch import nn + +class SimpleModel(nn.Module): + def __init__(self): + super().__init__() + self.dense = nn.Linear(10, 10) + self.intermediate = nn.Linear(10, 10) + self.layer_norm = nn.LayerNorm(10) +``` + +PyTorch layer names are defined by the class attribute name of the layer (`dense`, `intermediate`, `layer_norm`). Create a instance of `SimpleModel` to fill all the layers with random weights. + +```py +model = SimpleModel() +print(model) +SimpleModel( + (dense): Linear(in_features=10, out_features=10, bias=True) + (intermediate): Linear(in_features=10, out_features=10, bias=True) + (layer_norm): LayerNorm((10,), eps=1e-05, elementwise_affine=True) +) +``` + +The weight values of a specific layer are randomly initialized. + +```py +print(model.dense.weight.data) +tensor([[-0.0818, 0.2207, -0.0749, -0.0030, 0.0045, -0.1569, -0.1598, 0.0212, + -0.2077, 0.2157], + [ 0.1044, 0.0201, 0.0990, 0.2482, 0.3116, 0.2509, 0.2866, -0.2190, + 0.2166, -0.0212], + [-0.2000, 0.1107, -0.1999, -0.3119, 0.1559, 0.0993, 0.1776, -0.1950, + -0.1023, -0.0447], + [-0.0888, -0.1092, 0.2281, 0.0336, 0.1817, -0.0115, 0.2096, 0.1415, + -0.1876, -0.2467], + [ 0.2208, -0.2352, -0.1426, -0.2636, -0.2889, -0.2061, -0.2849, -0.0465, + 0.2577, 0.0402], + [ 0.1502, 0.2465, 0.2566, 0.0693, 0.2352, -0.0530, 0.1859, -0.0604, + 0.2132, 0.1680], + [ 0.1733, -0.2407, -0.1721, 0.1484, 0.0358, -0.0633, -0.0721, -0.0090, + 0.2707, -0.2509], + [-0.1173, 0.1561, 0.2945, 0.0595, -0.1996, 0.2988, -0.0802, 0.0407, + 0.1829, -0.1568], + [-0.1164, -0.2228, -0.0403, 0.0428, 0.1339, 0.0047, 0.1967, 0.2923, + 0.0333, -0.0536], + [-0.1492, -0.1616, 0.1057, 0.1950, -0.2807, -0.2710, -0.1586, 0.0739, + 0.2220, 0.2358]]). +``` + +In the conversion script, the random weights should be replaced with the exact weights from the corresponding layer in the original checkpoint. + +```py +# retrieve matching layer weights with recursive algorithm +layer_name = "dense" +pretrained_weight = array_of_dense_layer + +model_pointer = getattr(model, "dense") +model_pointer.weight.data = torch.from_numpy(pretrained_weight) +``` + +Verify the randomly initialized weights and their corresponding pretrained checkpoint weights have the identical **shape** and **name**. Add assert statements for the shape and print out the checkpoint weight names. + +```py +assert ( + model_pointer.weight.shape == pretrained_weight.shape +), f"Pointer shape of random weight {model_pointer.shape} and array shape of checkpoint weight {pretrained_weight.shape} mismatched" + +logger.info(f"Initialize PyTorch weight {layer_name} from {pretrained_weight.name}") +``` + +When the shape or name don't match, you may have assigned the incorrect checkpoint weight to a randomly initialized layer. An incorrect shape may be because the `BrandNewLlama` parameters don't exactly match the original models parameters. But it could also be that the PyTorch layer implementation requires the weights to be transposed first. + +### Implement the forward pass + +The forward pass should be implemented next if the model loads correctly. It takes some inputs and returns the model output. + +```py +model = BrandNewLlamaModel.from_pretrained("/path/to/converted/checkpoint/folder") +input_ids = [0, 4, 4, 3, 2, 4, 1, 7, 19] +output = model.generate(input_ids).last_hidden_states +``` + +Don't be discouraged if your forward pass isn't identical with the output from the original model or if it returns an error. Check that the forward pass doesn't throw any errors. This is often because the dimensions are wrong or because the wrong data type is used ([torch.long](https://pytorch.org/docs/stable/generated/torch.Tensor.long.html) instead of [torch.float32](https://pytorch.org/docs/stable/tensors.html)). + +Your output should have a precision of *1e-3*. Ensure the output shapes and output values are identical. Common reasons for why the outputs aren't identical include: + +- Some layers were not added (activation layer or a residual connection). +- The word embedding matrix is not tied. +- The wrong positional embeddings are used because the original implementation includes an offset. +- Dropout is applied during the forward pass. Fix this error by making sure `model.training` is `False` and passing `self.training` to [torch.nn.functional.dropout](https://pytorch.org/docs/stable/nn.functional.html?highlight=dropout#torch.nn.functional.dropout). + +Compare the forward pass of the original model and your implementation to check if there are any differences. Ideally, debug and print out the intermediate outputs of both implementations of the forward pass to pinpoint where the original implementation differs from yours. + +1. Make sure the hardcoded `input_ids` in both implementations are identical. +2. Verify the outputs of the first transformation of `input_ids` (usually the word embeddings) are identical, and work your way through to the last layer. + +Any difference between the two implementations should point to the bug in your implementation. + +One of the best strategies is to add many print statements to the same positions in both implementations, and then successively remove them when they output identical values for the intermediate outputs. + +When both implementations produce the same output, verify the outputs are within a precision of *1e-3*. + +```py +torch.allclose(original_output, output, atol=1e-3) +``` + +This is typically the most difficult part of the process. Congratulations if you've made it this far! + +And if you're stuck or struggling with this step, don't hesitate to ask for help on your pull request. + +### Add model tests + +While the model works, you still need to add tests to ensure it is compatible with Transformers. Tests are important because they help users understand your work by looking at specific tests, and because they prevent your model from breaking in the future if any changes are made. + +[Cookiecutter](https://cookiecutter.readthedocs.io/en/stable/) should have added a test file for your model. Run the test file below to make sure all common tests pass. + +```bash +pytest tests/models/brand_new_llama/test_modeling_brand_new_llama.py +``` + +The integration tests should be added first because they serve the same purpose as the debugging scripts you used earlier to implement the new model in Transformers. A template of those model tests, `BrandNewLlamaModelIntegrationTests`, was added by Cookiecutter and should be filled out. To ensure it passes, run the following command. + + + + +```bash +RUN_SLOW=1 pytest -sv tests/models/brand_new_llama/test_modeling_brand_new_llama.py::BrandNewLlamaModelIntegrationTests +``` + + + + +```bash +SET RUN_SLOW=1 pytest -sv tests/models/brand_new_llama/test_modeling_brand_new_llama.py::BrandNewLlamaModelIntegrationTests +``` + + + + +All features unique to BrandNewLlama should be tested in a separate test under `BrandNewLlamaModelTester/BrandNewLlamaModelTest`. This test is often overlooked, but it is extremely important because: + +- it helps transfer knowledge you acquired during the process to the community by showing how the models novel features work +- future contributors can quickly test changes to the model by running these special tests + +## Implement tokenizer + +> [!TIP] +> We recommend adding a fast tokenizer ([`PreTrainedTokenizerFast`]) to give users the best performance. Feel free to tag [@ArthurZucker](https://github.com/ArthurZucker) or [@itazap](https://github.com/itazap) in your PR for help on how to add [`PreTrainedTokenizerFast`]. + +With the model out of the way, time to focus on the tokenizer. The tokenizer should be identical or very similar to an existing tokenizer in Transformers. + +Find and load the original tokenizer file into your implementation. Create a script in the original repository that inputs a string and returns the `input_ids`. The pseudocode should look similar to the code below. + +```py +input_str = "This is a long example input string containing special characters .$?-, numbers 2872 234 12 and words." +model = BrandNewLlamaModel.load_pretrained_checkpoint("/path/to/checkpoint/") +input_ids = model.tokenize(input_str) +``` + +You may need to search the original repository to find the correct tokenizer function or modify the existing tokenizer in your clone of the original repository to only return the `input_ids`. The script for your tokenizer should look similar to the following. + +```py +from transformers import BrandNewLlamaTokenizer + +input_str = "This is a long example input string containing special characters .$?-, numbers 2872 234 12 and words." +tokenizer = BrandNewLlamaTokenizer.from_pretrained("/path/to/tokenizer/folder/") +input_ids = tokenizer(input_str).input_ids +``` + +When both implementations have the same `input_ids`, add a tokenizer test file. This file is analogous to the modeling test files. The tokenizer test files should contain a couple of hardcoded integration tests. + +## Implement image processor + +> [!TIP] +> Fast image processors use the [torchvision](https://pytorch.org/vision/stable/index.html) library and can perform image processing on the GPU, significantly improving processing speed. +> We recommend adding a fast image processor ([`BaseImageProcessorFast`]) in addition to the "slow" image processor ([`BaseImageProcessor`]) to provide users with the best performance. Feel free to tag [@yonigozlan](https://github.com/yonigozlan) for help adding a [`BaseImageProcessorFast`]. + +While this example doesn't include an image processor, you may need to implement one if your model requires image inputs. The image processor is responsible for converting images into a format suitable for your model. Before implementing a new one, check whether an existing image processor in the Transformers library can be reused, as many models share similar image processing techniques. Note that you can also use [modular](./modular_transformers) for image processors to reuse existing components. + +If you do need to implement a new image processor, refer to an existing image processor to understand the expected structure. Slow image processors ([`BaseImageProcessor`]) and fast image processors ([`BaseImageProcessorFast`]) are designed differently, so make sure you follow the correct structure based on the processor type you're implementing. + +Run the following command (only if you haven't already created the fast image processor with the `transformers add-new-model-like` command) to generate the necessary imports and to create a prefilled template for the fast image processor. Modify the template to fit your model. + +```bash +transformers add-fast-image-processor --model-name your_model_name +``` + +This command will generate the necessary imports and provide a pre-filled template for the fast image processor. You can then modify it to fit your model's needs. + +Add tests for the image processor in `tests/models/your_model_name/test_image_processing_your_model_name.py`. These tests should be similar to those for other image processors and should verify that the image processor correctly handles image inputs. If your image processor includes unique features or processing methods, ensure you add specific tests for those as well. + +## Implement processor + +If your model accepts multiple modalities, like text and images, you need to add a processor. The processor centralizes the preprocessing of different modalities before passing them to the model. + +The processor should call the appropriate modality-specific processors within its `__call__` function to handle each type of input correctly. Be sure to check existing processors in the library to understand their expected structure. Transformers uses the following convention in the `__call__` function signature. + +```python +def __call__( + self, + images: ImageInput = None, + text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None, + audio=None, + videos=None, + **kwargs: Unpack[YourModelProcessorKwargs], +) -> BatchFeature: + ... +``` + +`YourModelProcessorKwargs` is a `TypedDict` that includes all the typical processing arguments and any extra arguments a specific processor may require. + +Add tests for the processor in `tests/models/your_model_name/test_processor_your_model_name.py`. These tests should be similar to those for other processors and should verify that the processor correctly handles the different modalities. + +## Integration tests + +Now that you have a model and tokenizer, add end-to-end integration tests for the model and tokenizer to `tests/models/brand_new_llama/test_modeling_brand_new_llama.py`. + +The test should provide a meaningful text-to-text example to show the model works as expected. For example, you can include a source-to-target translation pair, an article-to-summary pair, or a question-to-answer pair. + +If the checkpoint hasn't been fine-tuned on a downstream task, then the model tests are sufficient. + +Finally, try to make sure your tests can run on a GPU by adding `.to(self.device)` statements to the models internal tensors. If you don't have access to a GPU, we can take care of that for you. + +## Add documentation + +Your model is only useful if users know how to use it. This is why it's important to add documentation and docstrings. Cookiecutter added a template file, `docs/source/model_doc/brand_new_llama.md`, that you can fill out with information about your model. + +This is generally a user's first interaction with a model, so the documentation should be clear and concise. It is often very useful to add examples of how the model should be used. + +Make sure docstrings are added to `src/transformers/models/brand_new_llama/modeling_brand_new_llama.py` and includes all necessary inputs and outputs. Review our [guide](https://github.com/huggingface/transformers/tree/main/docs#writing-documentation---specification) for writing documentation and docstrings. + +## Refactor + +Time to tidy things up and make sure the code style is consistent with the rest of the library. Run the following command to automatically fix incorrect styles. + +```bash +make style +``` + +To verify the code style passes quality checks, run the command below. + +```bash +make quality +``` + +There may be other failing tests or checks (missing docstring or incorrect naming) on your pull request due to Transformers strict design tests. We can help you with these issues if you're stuck. + +After ensuring the code runs correctly, you may want to refactor it to make it more readable or cleaner. + +## Upload to the Hub + +Convert and upload all checkpoints to the [Hub](https://hf.co/models). Add a model card to provide more transparency and context about the model. The model card should highlight specific characteristics of a checkpoint, how the model was trained, and code examples of how to use it. + +> [!TIP] +> In many cases, adding an interactive notebook users can run is a great way to showcase how to use the model for inference or fine-tune it on a downstream task. While not required, including a notebook can drive greater adoption of your model. + +You should also consult with the Transformers team to decide on an appropriate name for the model, and getting the required access rights to upload the model. + +Use the [`~PreTrainedModel.push_to_hub`] method to upload the model. + +```py +brand_new_bert.push_to_hub("brand_new_llama") +``` + +Refer to the [Sharing](./model_sharing) guide for more information about uploading models to the Hub. + +## Merge your model + +You're finally ready to merge your pull request and officially add the model to Transformers! Make sure all the tests are passing and all comments and feedback have been addressed. + +Congratulations on adding a new model to Transformers! 🥳 + +This is a very significant contribution. Your work makes Transformers more accessible to developers and researchers around the world. You should be proud of your contribution and share your accomplishment with the community! + +## Model addition timeline + +There are four timelines for model additions depending on the model contributor and community demand for an architecture. + +- **day-0 integration**: If you plan on having a Transformers-first release, this is a great option because we can ensure the documentation is clear and optimize your model as much as possible (quantization, FlashAttention, KV-cache, etc.). We can also help you add the model, provide early reviews and make sure it works as expected. + + Reach out to transformers@huggingface.co a few days (preferably weeks) in advance, especially if an architecture is particularly novel, to ensure model integration. We'll work together on a private fork of Transformers until your checkpoint and release is ready. + +- **same week integration**: Models with significant requests/demand are usually added the same week if the model author doesn't reach out. + + Use the [issue tracker](https://github.com/huggingface/transformers/issues/new?assignees=&labels=New+model&projects=&template=new-model-addition.yml) to request a specific model to add. The more activity on the issue, the faster and more likely we'll integrate it. + +- **post-release integration**: Models without popular requests/demand or if we don't have the bandwidth to integrate it are added post-release. + + This is a good opportunity if you're interested in contributing a model to Transformers. Take a look at open issues tagged with ["New model"](https://github.com/huggingface/transformers/issues?q=is%3Aopen+is%3Aissue+label%3A%22New+model%22). Feel free to give the most requested models a try first to multiply the impact of your contribution. We'll be there to help you each step of the way! + +- **Hub-first release**: Transformers [remote-code](./models#custom-models) feature allows Transformers-based projects to be shared directly on the Hub. This is a good option if you don't have the bandwidth to add a model directly to Transformers. + + If a model ends up being very popular, then it's very likely that we'll integrate it in Transformers ourselves to enable better support (documentation, maintenance, optimization, etc.) for it. A Hub-first release is the most frictionless way to add a model. diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/add_new_pipeline.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/add_new_pipeline.md new file mode 100644 index 0000000000000000000000000000000000000000..60ef43dab585032a01f6260dd2b748af732ee410 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/add_new_pipeline.md @@ -0,0 +1,229 @@ + + +# Adding a new pipeline + +Make [`Pipeline`] your own by subclassing it and implementing a few methods. Share the code with the community on the [Hub](https://hf.co) and register the pipeline with Transformers so that everyone can quickly and easily use it. + +This guide will walk you through the process of adding a new pipeline to Transformers. + +## Design choices + +At a minimum, you only need to provide [`Pipeline`] with an appropriate input for a task. This is also where you should begin when designing your pipeline. + +Decide what input types [`Pipeline`] can accept. It can be strings, raw bytes, dictionaries, and so on. Try to keep the inputs in pure Python where possible because it's more compatible. Next, decide on the output [`Pipeline`] should return. Again, keeping the output in Python is the simplest and best option because it's easier to work with. + +Keeping the inputs and outputs simple, and ideally JSON-serializable, makes it easier for users to run your [`Pipeline`] without needing to learn new object types. It's also common to support many different input types for even greater ease of use. For example, making an audio file acceptable from a filename, URL, or raw bytes gives the user more flexibility in how they provide the audio data. + +## Create a pipeline + +With an input and output decided, you can start implementing [`Pipeline`]. Your pipeline should inherit from the base [`Pipeline`] class and include 4 methods. + +```py +from transformers import Pipeline + +class MyPipeline(Pipeline): + def _sanitize_parameters(self, **kwargs): + + def preprocess(self, inputs, args=2): + + def _forward(self, model_inputs): + + def postprocess(self, model_outputs): +``` + +1. `preprocess` takes the inputs and transforms them into the appropriate input format for the model. + +```py +def preprocess(self, inputs, maybe_arg=2): + model_input = Tensor(inputs["input_ids"]) + return {"model_input": model_input} +``` + +2. `_forward` shouldn't be called directly. `forward` is the preferred method because it includes safeguards to make sure everything works correctly on the expected device. Anything linked to the model belongs in `_forward` and everything else belongs in either `preprocess` or `postprocess`. + +```py +def _forward(self, model_inputs): + outputs = self.model(**model_inputs) + return outputs +``` + +3. `postprocess` generates the final output from the models output in `_forward`. + +```py +def postprocess(self, model_outputs, top_k=5): + best_class = model_outputs["logits"].softmax(-1) + return best_class +``` + +4. `_sanitize_parameters` lets users pass additional parameters to [`Pipeline`]. This could be during initialization or when [`Pipeline`] is called. `_sanitize_parameters` returns 3 dicts of additional keyword arguments that are passed directly to `preprocess`, `_forward`, and `postprocess`. Don't add anything if a user didn't call the pipeline with extra parameters. This keeps the default arguments in the function definition which is always more natural. + +For example, add a `top_k` parameter in `postprocess` to return the top 5 most likely classes. Then in `_sanitize_parameters`, check if the user passed in `top_k` and add it to `postprocess_kwargs`. + +```py +def _sanitize_parameters(self, **kwargs): + preprocess_kwargs = {} + if "maybe_arg" in kwargs: + preprocess_kwargs["maybe_arg"] = kwargs["maybe_arg"] + + postprocess_kwargs = {} + if "top_k" in kwargs: + postprocess_kwargs["top_k"] = kwargs["top_k"] + return preprocess_kwargs, {}, postprocess_kwargs +``` + +Now the pipeline can return the top most likely labels if a user chooses to. + +```py +from transformers import pipeline + +pipeline = pipeline("my-task") +# returns 3 most likely labels +pipeline("This is the best meal I've ever had", top_k=3) +# returns 5 most likely labels by default +pipeline("This is the best meal I've ever had") +``` + +## Register a pipeline + +Register the new task your pipeline supports in the `PIPELINE_REGISTRY`. The registry defines: + +- the machine learning framework the pipeline supports with either `pt_model` or `tf_model` (add both to ensure it works with either frameworks) +- a default model which should come from a specific revision (branch, or commit hash) where the model works as expected with `default` +- the expected input with `type` + +```py +from transformers.pipelines import PIPELINE_REGISTRY +from transformers import AutoModelForSequenceClassification, TFAutoModelForSequenceClassification + +PIPELINE_REGISTRY.register_pipeline( + "new-task", + pipeline_class=MyPipeline, + pt_model=AutoModelForSequenceClassification, + tf_model=TFAutoModelForSequenceClassification, + default={"pt": ("user/awesome-model", "branch-name")}, + type="text", +) +``` + +## Share your pipeline + +Share your pipeline with the community on the [Hub](https://hf.co) or you can add it directly to Transformers. + +It's faster to upload your pipeline code to the Hub because it doesn't require a review from the Transformers team. Adding the pipeline to Transformers may be slower because it requires a review and you need to add tests to ensure your [`Pipeline`] works. + +### Upload to the Hub + +Add your pipeline code to the Hub in a Python file. + +For example, a custom pipeline for sentence pair classification might look like the following code below. The implementation works for PyTorch and TensorFlow models. + +```py +import numpy as np +from transformers import Pipeline + +def softmax(outputs): + maxes = np.max(outputs, axis=-1, keepdims=True) + shifted_exp = np.exp(outputs - maxes) + return shifted_exp / shifted_exp.sum(axis=-1, keepdims=True) + +class PairClassificationPipeline(Pipeline): + def _sanitize_parameters(self, **kwargs): + preprocess_kwargs = {} + if "second_text" in kwargs: + preprocess_kwargs["second_text"] = kwargs["second_text"] + return preprocess_kwargs, {}, {} + + def preprocess(self, text, second_text=None): + return self.tokenizer(text, text_pair=second_text, return_tensors=self.framework) + + def _forward(self, model_inputs): + return self.model(**model_inputs) + + def postprocess(self, model_outputs): + logits = model_outputs.logits[0].numpy() + probabilities = softmax(logits) + + best_class = np.argmax(probabilities) + label = self.model.config.id2label[best_class] + score = probabilities[best_class].item() + logits = logits.tolist() + return {"label": label, "score": score, "logits": logits} +``` + +Save the code in a file named `pair_classification.py`, and import and register it as shown below. + +```py +from pair_classification import PairClassificationPipeline +from transformers.pipelines import PIPELINE_REGISTRY +from transformers import AutoModelForSequenceClassification, TFAutoModelForSequenceClassification + +PIPELINE_REGISTRY.register_pipeline( + "pair-classification", + pipeline_class=PairClassificationPipeline, + pt_model=AutoModelForSequenceClassification, + tf_model=TFAutoModelForSequenceClassification, +) +``` + +The [register_pipeline](https://github.com/huggingface/transformers/blob/9feae5fb0164e89d4998e5776897c16f7330d3df/src/transformers/pipelines/base.py#L1387) function registers the pipeline details (task type, pipeline class, supported backends) to a models `config.json` file. + +```json + "custom_pipelines": { + "pair-classification": { + "impl": "pair_classification.PairClassificationPipeline", + "pt": [ + "AutoModelForSequenceClassification" + ], + "tf": [ + "TFAutoModelForSequenceClassification" + ], + } + }, +``` + +Call [`~Pipeline.push_to_hub`] to push the pipeline to the Hub. The Python file containing the code is copied to the Hub, and the pipelines model and tokenizer are also saved and pushed to the Hub. Your pipeline should now be available on the Hub under your namespace. + +```py +from transformers import pipeline + +pipeline = pipeline(task="pair-classification", model="sgugger/finetuned-bert-mrpc") +pipeline.push_to_hub("pair-classification-pipeline") +``` + +To use the pipeline, add `trust_remote_code=True` when loading the pipeline. + +```py +from transformers import pipeline + +pipeline = pipeline(task="pair-classification", trust_remote_code=True) +``` + +### Add to Transformers + +Adding a custom pipeline to Transformers requires adding tests to make sure everything works as expected, and requesting a review from the Transformers team. + +Add your pipeline code as a new module to the [pipelines](https://github.com/huggingface/transformers/tree/main/src/transformers/pipelines) submodule, and add it to the list of tasks defined in [pipelines/__init__.py](https://github.com/huggingface/transformers/blob/main/src/transformers/pipelines/__init__.py). + +Next, add a new test for the pipeline in [transformers/tests/pipelines](https://github.com/huggingface/transformers/tree/main/tests/pipelines). You can look at the other tests for examples of how to test your pipeline. + +The [run_pipeline_test](https://github.com/huggingface/transformers/blob/db70426854fe7850f2c5834d633aff637f14772e/tests/pipelines/test_pipelines_text_classification.py#L186) function should be very generic and run on the models defined in [model_mapping](https://github.com/huggingface/transformers/blob/db70426854fe7850f2c5834d633aff637f14772e/tests/pipelines/test_pipelines_text_classification.py#L48) and [tf_model_mapping](https://github.com/huggingface/transformers/blob/db70426854fe7850f2c5834d633aff637f14772e/tests/pipelines/test_pipelines_text_classification.py#L49). This is important for testing future compatibility with new models. + +You'll also notice `ANY` is used throughout the [run_pipeline_test](https://github.com/huggingface/transformers/blob/db70426854fe7850f2c5834d633aff637f14772e/tests/pipelines/test_pipelines_text_classification.py#L186) function. The models are random, so you can't check the actual values. Using `ANY` allows the test to match the output of the pipeline type instead. + +Finally, you should also implement the following 4 tests. + +1. [test_small_model_pt](https://github.com/huggingface/transformers/blob/db70426854fe7850f2c5834d633aff637f14772e/tests/pipelines/test_pipelines_text_classification.py#L59) and [test_small_model_tf](https://github.com/huggingface/transformers/blob/db70426854fe7850f2c5834d633aff637f14772e/tests/pipelines/test_pipelines_text_classification.py#L150), use a small model for these pipelines to make sure they return the correct outputs. The results don't have to make sense. Each pipeline should return the same result. +1. [test_large_model_pt](https://github.com/huggingface/transformers/blob/db70426854fe7850f2c5834d633aff637f14772e/tests/pipelines/test_pipelines_zero_shot_image_classification.py#L187) nad [test_large_model_tf](https://github.com/huggingface/transformers/blob/db70426854fe7850f2c5834d633aff637f14772e/tests/pipelines/test_pipelines_zero_shot_image_classification.py#L220), use a realistic model for these pipelines to make sure they return meaningful results. These tests are slow and should be marked as slow. diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/agents.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/agents.md new file mode 100644 index 0000000000000000000000000000000000000000..f8a60b5fc325b6251cdf99b7798d9d7cd8aba3a3 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/agents.md @@ -0,0 +1,22 @@ + + +# Agents + +(deprecated) + +> [!WARNING] +> Agents and tools were spun out into the standalone [smolagents](https://huggingface.co/docs/smolagents/index) library. They were removed from `transformers` in v4.52. diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/attention_interface.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/attention_interface.md new file mode 100644 index 0000000000000000000000000000000000000000..407a47a7d3538f597f31d1033fd6e2e84404f3fe --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/attention_interface.md @@ -0,0 +1,196 @@ + + +# Attention Interface + +This page describes how to use the `AttentionInterface` in order to register custom attention functions to use with +supported models. + +## Customizing attention function + +Most recent models can now switch from one attention function used in the Attention layer to the other, thanks to a simple mapping. +By default, we provide the implementation for [`sdpa`](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html), +[`flash_attention_2`](https://github.com/Dao-AILab/flash-attention) and [`flex_attention`](https://pytorch.org/docs/stable/nn.attention.flex_attention.html#module-torch.nn.attention.flex_attention) +as well as `eager`, which is a simple matrix multiplication without any optimization on top. +This is the setting you can usually choose when instantiating a model: + +```python +from transformers import AutoModelForCausalLM + +model_id = "meta-llama/Llama-3.2-1B" + +# Here, using flash attention as an example +model = AutoModelForCausalLM.from_pretrained(model_id, attn_implementation="flash_attention_2") +``` + +But what if you wanted to create your own attention function? Or simply play around with existing ones, adding +a few statements here and there? You can now do so with the `AttentionInterface`! Here is an example: + +```python +from transformers import AutoModelForCausalLM, AttentionInterface +from transformers.integrations.sdpa_attention import sdpa_attention_forward +import torch + +model_id = "meta-llama/Llama-3.2-1B" + +def my_new_sdpa(*args, **kwargs): + print("I just entered the attention computation") + return sdpa_attention_forward(*args, **kwargs) + +AttentionInterface.register("my_new_sdpa", my_new_sdpa) + +model = AutoModelForCausalLM.from_pretrained(model_id, attn_implementation="my_new_sdpa") +# Try running the forward with the new attention function +model(torch.ones(1, 5, dtype=int)) +``` + +You will see it prints "I just entered the attention computation" as many times as there are layers in the model (with this example, 16 times). + +## Dynamically switching attention function + +You could dynamically change the model's attention function as well: + +```python +# Back to use original sdpa implementation +model.set_attn_implementation("sdpa") + +model(torch.ones(1, 5, dtype=int)) +``` + +and it will stop printing the statements, as it now uses the `sdpa` attention. +This allows to quickly change an attention function, without needing to reload the model! + +## Different attention per backbone in multimodal models + +For multimodal models different attention functions may work better for each backbone module. For example, some vision backbones perform better in fp32, but are incompatible with FlashAttention. To continue using FlashAttention while keeping the vision encoder in fp32, create a dict and map each config to an attention implementation as shown below. + +```python +from transformers import AutoModelForImageTextToText + +model_id = "facebook/chameleon-7b" + +attention_implementation_per_backbone = {"vision_config": "sdpa", "text_config": "flash_attention_2"} +model = AutoModelForImageTextToText.from_pretrained(model_id, attn_implementation=attention_implementation_per_backbone) + +# NOTE: keys in the attention implementation have to be the same as the sub-config names +for key in attention_implementation_per_backbone: + assert key in model.config.sub_configs, f"Invalid key in `attention_implementation`" + +# You can omit certain backbones - the default attention function (SDPA) will be used +# This is equivalent to the previous example +model = AutoModelForImageTextToText.from_pretrained(model_id, attn_implementation={"text_config": "flash_attention_2"}) + + +# Set the same attention implementation for all backbones with single string, same as in non-multimodal models +model = AutoModelForImageTextToText.from_pretrained(model_id, attn_implementation="eager") + +# Alternatively use a dict with an empty key for global configuration +model = AutoModelForImageTextToText.from_pretrained(model_id, attn_implementation={"": "eager"}) +``` + +## What about new args needed in my custom attention function? + +But indeed, what if the new function requires a new arg to be properly used? It's no issue! Models supporting the +`AttentionInterface` propagate kwargs all the way to the Attention layers, and to the used attention function. That way, +you can simply pass the arg (as a kwargs, i.e. you need to qualify the name of the arg) in the model's forward, and it will be correctly used in the attention. However, custom attention functions have some limitations. In particular, it must follow the signature and return format of other attention functions, i.e. + +```python +from transformers import AutoModelForCausalLM, AttentionInterface +from transformers.integrations.sdpa_attention import sdpa_attention_forward +import torch + +def custom_attention( + module: torch.nn.Module, # required arg + query: torch.Tensor, # required arg + key: torch.Tensor, # required arg + value: torch.Tensor, # required arg + attention_mask: Optional[torch.Tensor], # required arg + a_new_kwargs = None, # You can now add as many kwargs as you need + another_new_kwargs = None, # You can now add as many kwargs as you need + **kwargs, # You need to accept **kwargs as models will pass other args +) -> tuple[torch.Tensor, Optional[torch.Tensor]] + ... # do your magic! + return attn_output, attn_weights # attn_weights are optional here + +AttentionInterface.register("custom", custom_attention) + +model = AutoModelForCausalLM.from_pretrained(model_id, attn_implementation="custom") +# Forward pass with the new kwargs +model(torch.ones(1, 5, dtype=int), a_new_kwargs=..., another_new_kwargs=...) +``` + +If in doubt about what args/kwargs a given model sends to the attention function, simply check that model's modeling code on [GitHub](https://github.com/huggingface/transformers/tree/main/src/transformers/models)! + +## Accessing current available implementations + +Most of the time, you will simply need to `register` a new function. If, however, you need to access an existing one, +and/or perform a few checks, the preferred way is to use the global `ALL_ATTENTION_FUNCTIONS`. It behaves the same way you +would expect from a usual Python dictionary: + +```python +>>> from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS + +>>> list(ALL_ATTENTION_FUNCTIONS.keys()) +>>> ['flash_attention_2', 'flex_attention', 'sdpa'] + +>>> ALL_ATTENTION_FUNCTIONS["sdpa"] +>>> + +>>> ALL_ATTENTION_FUNCTIONS.get("sdpa", None) +>>> + +# You can also globally `register` a new function directly on it +>>> ALL_ATTENTION_FUNCTIONS.register("new_func", new_func) +``` + +## Attention Mask Interface + +Having a new attention function may mean that you need a new format of attention mask to decide what key and value tokens +the query tokens should attend to. This is now possible with the `AttentionMaskInterface`! It works in the same way as +the `AttentionInterface`: + +```python +from transformers import AttentionMaskInterface +from transformers.masking_utils import sdpa_mask +import torch + +def my_new_sdpa_mask(*args, **kwargs): + print("I just entered the attention mask computation") + return sdpa_mask(*args, **kwargs) + +AttentionMaskInterface.register("my_new_sdpa_mask", my_new_sdpa_mask) +``` + +The reason you have to register it is because we need to automatically correct your mask format based on the attention implementation (for example, flex attention uses a BlockMask format, while sdpa uses a 4D tensor). +By default, if you do not register an attention mask function along with your attention function, mask creation will be skipped +and `attention_mask=None` will be passed along to the Attention layers. + +The default signature of the attention mask functions is the following: + +```python +def custom_attention_mask( + batch_size: int, # required arg + cache_position: torch.Tensor, # required arg + kv_length: int, # required arg + kv_offset: int = 0, # required arg + mask_function: Callable = causal_mask_function, # required arg + attention_mask: Optional[torch.Tensor] = None, # required arg + **kwargs, # a few additional args may be passed as kwargs, especially the model's config is always passed +) -> Optional[torch.Tensor]: +``` + +It mostly works thanks to the `mask_function`, which is a `Callable` in the form of [torch's mask_mod functions](https://pytorch.org/blog/flexattention/), taking 4 indices as input and returning a boolean to indicate if this position should take part in the attention computation. + +If you cannot use the `mask_function` to create your mask for some reason, you can try to work around it by doing something similar to our [torch export workaround](https://github.com/huggingface/transformers/blob/main/src/transformers/integrations/executorch.py). \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/auto_docstring.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/auto_docstring.md new file mode 100644 index 0000000000000000000000000000000000000000..5fc4ed061ce12422c1d1acb0cd6389934c7a59f5 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/auto_docstring.md @@ -0,0 +1,307 @@ + + +# Documenting a model + +The `@auto_docstring` decorator in Transformers generates consistent docstrings for model classes and their methods. It reduces boilerplate by automatically including standard argument descriptions while also allowing overrides to add new or custom arguments. [Contributing a new model](./modular_transformers) is easier because you don't need to manually add the standard docstrings, and only focus on documenting new arguments. + +This guide describes how to use the `@auto_docstring` decorator and how it works. + +## @auto_docstring + +Start by importing the decorator in the modeling file (`modular_model.py` or `modeling_model.py`). + +```python +from ...utils import auto_docstring +``` + +Select whether you'd like to apply `@auto_docstring` to a class or function below to see how to use it. + + + + +Place `@auto_docstring` directly above the class definition. The decorator derives parameter descriptions from the `__init__` method's signature and docstring. + +```python +from transformers.modeling_utils import PreTrainedModel +from ...utils import auto_docstring + +@auto_docstring +class MyAwesomeModel(PreTrainedModel): + def __init__(self, config, custom_parameter: int = 10, another_custom_arg: str = "default"): + r""" + custom_parameter (`int`, *optional*, defaults to 10): + Description of the custom_parameter for MyAwesomeModel. + another_custom_arg (`str`, *optional*, defaults to "default"): + Documentation for another unique argument. + """ + super().__init__(config) + self.custom_parameter = custom_parameter + self.another_custom_arg = another_custom_arg + # ... rest of your init + + # ... other methods +``` + +Arguments can also be passed directly to `@auto_docstring` for more control. Use the `custom_intro` parameter to describe the argument and the `custom_args` parameter to describe the arguments. + +```python +@auto_docstring( + custom_intro="""This model performs specific synergistic operations. + It builds upon the standard Transformer architecture with unique modifications.""", + custom_args=""" + custom_parameter (`type`, *optional*, defaults to `default_value`): + A concise description for custom_parameter if not defined or overriding the description in `auto_docstring.py`. + internal_helper_arg (`type`, *optional*, defaults to `default_value`): + A concise description for internal_helper_arg if not defined or overriding the description in `auto_docstring.py`. + """ +) +class MySpecialModel(PreTrainedModel): + def __init__(self, config: ConfigType, custom_parameter: "type" = "default_value", internal_helper_arg=None): + # ... +``` + +You can also choose to only use `custom_intro` and define the custom arguments directly in the class. + +```python +@auto_docstring( + custom_intro="""This model performs specific synergistic operations. + It builds upon the standard Transformer architecture with unique modifications.""", +) +class MySpecialModel(PreTrainedModel): + def __init__(self, config: ConfigType, custom_parameter: "type" = "default_value", internal_helper_arg=None): + r""" + custom_parameter (`type`, *optional*, defaults to `default_value`): + A concise description for custom_parameter if not defined or overriding the description in `auto_docstring.py`. + internal_helper_arg (`type`, *optional*, defaults to `default_value`): + A concise description for internal_helper_arg if not defined or overriding the description in `auto_docstring.py`. + """ + # ... +``` + +You should also use the `@auto_docstring` decorator for classes that inherit from [`~utils.ModelOutput`]. + +```python +@dataclass +@auto_docstring( + custom_intro=""" + Custom model outputs with additional fields. + """ +) +class MyModelOutput(ImageClassifierOutput): + r""" + loss (`torch.FloatTensor`, *optional*): + The loss of the model. + custom_field (`torch.FloatTensor` of shape `(batch_size, hidden_size)`, *optional*): + A custom output field specific to this model. + """ + + # Standard fields like hidden_states, logits, attentions etc. can be automatically documented if the description is the same as the standard arguments. + # However, given that the loss docstring is often different per model, you should document it in the docstring above. + loss: Optional[torch.FloatTensor] = None + logits: Optional[torch.FloatTensor] = None + hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None + attentions: Optional[tuple[torch.FloatTensor, ...]] = None + # Custom fields need to be documented in the docstring above + custom_field: Optional[torch.FloatTensor] = None +``` + + + + +Place `@auto_docstring` directly above the method definition. The decorator derives parameter descriptions from the function signature. + +```python + @auto_docstring + def forward( + self, + input_ids: Optional[torch.Tensor] = None, + attention_mask: Optional[torch.Tensor] = None, + new_custom_argument: Optional[torch.Tensor] = None, + arg_documented_in_args_doc: Optional[torch.Tensor] = None, + # ... other arguments + ) -> Union[Tuple, ModelOutput]: # The description of the return value will automatically be generated from the ModelOutput class docstring. + r""" + new_custom_argument (`torch.Tensor`, *optional*): + Description of this new custom argument and its expected shape or type. + """ + # ... +``` + +Arguments can also be passed directly to `@auto_docstring` for more control. Use the `custom_intro` parameter to describe the argument and the `custom_args` parameter to describe the arguments. + +The `Returns` and `Examples` parts of the docstring can also be manually specified. + + +```python +MODEL_COMMON_CUSTOM_ARGS = r""" + common_arg_1 (`torch.Tensor`, *optional*, defaults to `default_value`): + Description of common_arg_1 + common_arg_2 (`torch.Tensor`, *optional*, defaults to `default_value`): + Description of common_arg_2 + ... +""" + +class MyModel(PreTrainedModel): + # ... + @auto_docstring( + custom_intro=""" + This is a custom introduction for the function. + """ + custom_args=MODEL_COMMON_CUSTOM_ARGS + ) + def forward( + self, + input_ids: Optional[torch.Tensor] = None, + attention_mask: Optional[torch.Tensor] = None, + common_arg_1: Optional[torch.Tensor] = None, + common_arg_2: Optional[torch.Tensor] = None, + #... + function_specific_argument: Optional[torch.Tensor] = None, + # ... other arguments + ) -> torch.Tensor: + r""" + function_specific_argument (`torch.Tensor`, *optional*): + Description of an argument specific to this function + + Returns: + `torch.Tensor`: For a function returning a generic type, a custom "Returns" section can be specified. + + Example: + + (To override the default example with a custom one or to add an example for a model class that does not have a pipeline) + + ```python + ... + ``` + """ + # ... +``` + + + + +## Documenting arguments + +There are some rules for documenting different types of arguments and they're listed below. + +- Standard arguments (`input_ids`, `attention_mask`, `pixel_values`, etc.) are defined and retrieved from `auto_docstring.py`. It is the single source of truth for standard arguments and should not be redefined locally if an argument's description and shape is the same as an argument in `auto_docstring.py`. + + If a standard argument behaves differently in your model, then you can override it locally in a `r""" """` block. This local definition has a higher priority. For example, the `labels` argument is often customized per model and typically requires overriding. + + +- New or custom arguments should be documented within an `r""" """` block after the signature if it is a function or in the `__init__` method's docstring if it is a class. + + ```py + argument_name (`type`, *optional*, defaults to `X`): + Description of the argument. + Explain its purpose, expected shape/type if complex, and default behavior. + This can span multiple lines. + ``` + + * Include `type` in backticks. + * Add *optional* if the argument is not required or has a default value. + * Add "defaults to X" if it has a default value. You don't need to add "defaults to `None`" if the default value is `None`. + + These arguments can also be passed to `@auto_docstring` as a `custom_args` argument. It is used to define the docstring block for new arguments once if they are repeated in multiple places in the modeling file. + + ```py + class MyModel(PreTrainedModel): + # ... + @auto_docstring( + custom_intro=""" + This is a custom introduction for the function. + """ + custom_args=r""" + common_arg_1 (`torch.Tensor`, *optional*, defaults to `default_value`): + Description of common_arg_1 + """ + ) + ``` + +## Checking the docstrings + +Transformers includes a utility script to validate the docstrings when you open a Pull Request which triggers CI (continuous integration) checks. The script checks for the following criteria. + +* Ensures `@auto_docstring` is applied to relevant mode classes and public methods. +* Ensures arguments are complete and consistent. It checks that documented arguments exist in the signature and verifies whether the types and default values in the docstring match the signature. Arguments that aren't known standard arguments or if they lack a local description are flagged. +* Reminds you to complete placeholders like `` and ``. +* Ensures docstrings are formatted according to the expected docstring style. + +You can run this check locally - before committing - by running the following command. + +```bash +make fix-copies +``` + +`make fix-copies` runs several other checks as well. If you don't need those checks, run the command below to only perform docstring and auto-docstring checks. + +```bash +python utils/check_docstrings.py # to only check files included in the diff without fixing them +# python utils/check_docstrings.py --fix_and_overwrite # to fix and overwrite the files in the diff +# python utils/check_docstrings.py --fix_and_overwrite --check_all # to fix and overwrite all files +``` + +## modular_model.py files + +When working with modular files (`modular_model.py`), follow the guidelines below for applying `@auto_docstring`. + +- For standalone models in modular files, apply `@auto_docstring` like you would in a `modeling_model.py` file. +- For models that inherit from other library models, `@auto_docstring` is automatically carried over to the generated modeling file. You don't need to add `@auto_docstring` in your modular file. + + If you need to modify the `@auto_docstring` behavior, apply the customized decorator in your modular file. Make sure to **include all other decorators** that are present in the original function or class. + +> [!WARNING] +> When overriding any decorator in a modular file, you must include **all** decorators that were applied to that function or class in the parent model. If you only override some decorators, the others won't be included in the generated modeling file. + +## How it works + +The `@auto_docstring` decorator automatically generates docstrings by: + +1. Inspecting the signature (arguments, types, defaults) of the decorated class' `__init__` method or the decorated function. +2. Retrieving the predefined docstrings for common arguments (`input_ids`, `attention_mask`, etc.) from internal library sources like [`ModelArgs`], [`ImageProcessorArgs`], and the `auto_docstring.py` file. +3. Adding argument descriptions in one of two ways as shown below. + + | method | description | usage | + |---|---|---| + | `r""" """` | add custom docstring content directly to a method signature or within the `__init__` docstring | document new arguments or override standard descriptions | + | `custom_args` | add custom docstrings for specific arguments directly in `@auto_docstring` | define docstring for new arguments once if they're repeated in multiple places in the modeling file | + +4. Adding class and function descriptions. For model classes with standard naming patterns, like `ModelForCausalLM`, or if it belongs to a pipeline, `@auto_docstring` automatically generates the appropriate descriptions with `ClassDocstring` from `auto_docstring.py`. + + `@auto_docstring` also accepts the `custom_intro` argument to describe a class or function. + +5. Using a templating system to allow predefined docstrings to include dynamic information from Transformers' [auto_modules](https://github.com/huggingface/transformers/tree/main/src/transformers/models/auto) such as `{{processor_class}}` and `{{config_class}}`. + +6. Finding appropriate usage examples based on the model's task or pipeline compatibility. It extracts checkpoint information form the model's configuration class to provide concrete examples with real model identifiers. + +7. Adding return values to the docstring. For methods like `forward`, the decorator automatically generates the `Returns` field in the docstring based on the method's return type annotation. + + For example, if a method returns a [`~transformers.utils.ModelOutput`] subclass, `@auto_docstring` extracts the field descriptions from the class' docstring to create a comprehensive return value description. You can also manually specify a custom `Returns` field in a functions docstring. + +8. Unrolling kwargs typed with the unpack operator. For specific methods (defined in `UNROLL_KWARGS_METHODS`) or classes (defined in `UNROLL_KWARGS_CLASSES`), the decorator processes `**kwargs` parameters that are typed with `Unpack[KwargsTypedDict]`. It extracts the documentations from the `TypedDict` and adds each parameter to the function's docstring. + + Currently only supported for [`FastImageProcessorKwargs`]. + +## Best practices + +Follow the best practices below to help maintain consistent and informative documentation for Transformers! + +* Use `@auto_docstring` for new PyTorch model classes ([`PreTrainedModel`] subclasses) and their primary methods like `forward` or `get_text_features`. +* For classes, `@auto_docstring` retrieves parameter descriptions from the `__init__` method's docstring. +* Rely on standard docstrings and do not redefine common arguments unless their behavior is different in your model. +* Document new or custom arguments clearly. +* Run `check_docstrings` locally and iteratively. diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/backbones.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/backbones.md new file mode 100644 index 0000000000000000000000000000000000000000..792b0b0d38f12f11c0f2e6519d90ce56fc704f8a --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/backbones.md @@ -0,0 +1,155 @@ + + +# Backbones + +Higher-level computer visions tasks, such as object detection or image segmentation, use several models together to generate a prediction. A separate model is used for the *backbone*, neck, and head. The backbone extracts useful features from an input image into a feature map, the neck combines and processes the feature maps, and the head uses them to make a prediction. + +
+ +
+ +Load a backbone with [`~PretrainedConfig.from_pretrained`] and use the `out_indices` parameter to determine which layer, given by the index, to extract a feature map from. + +```py +from transformers import AutoBackbone + +model = AutoBackbone.from_pretrained("microsoft/swin-tiny-patch4-window7-224", out_indices=(1,)) +``` + +This guide describes the backbone class, backbones from the [timm](https://hf.co/docs/timm/index) library, and how to extract features with them. + +## Backbone classes + +There are two backbone classes. + +- [`~transformers.utils.BackboneMixin`] allows you to load a backbone and includes functions for extracting the feature maps and indices. +- [`~transformers.utils.BackboneConfigMixin`] allows you to set the feature map and indices of a backbone configuration. + +Refer to the [Backbone](./main_classes/backbones) API documentation to check which models support a backbone. + +There are two ways to load a Transformers backbone, [`AutoBackbone`] and a model-specific backbone class. + + + + +The [AutoClass](./model_doc/auto) API automatically loads a pretrained vision model with [`~PretrainedConfig.from_pretrained`] as a backbone if it's supported. + +Set the `out_indices` parameter to the layer you'd like to get the feature map from. If you know the name of the layer, you could also use `out_features`. These parameters can be used interchangeably, but if you use both, make sure they refer to the same layer. + +When `out_indices` or `out_features` isn't used, the backbone returns the feature map from the last layer. The example code below uses `out_indices=(1,)` to get the feature map from the first layer. + +
+ +
+ +```py +from transformers import AutoImageProcessor, AutoBackbone + +model = AutoBackbone.from_pretrained("microsoft/swin-tiny-patch4-window7-224", out_indices=(1,)) +``` + +
+ + +When you know a model supports a backbone, you can load the backbone and neck directly into the models configuration. Pass the configuration to the model to initialize it for a task. + +The example below loads a [ResNet](./model_doc/resnet) backbone and neck for use in a [MaskFormer](./model_doc/maskformer) instance segmentation head. + +Set `backbone` to a pretrained model and `use_pretrained_backbone=True` to use pretrained weights instead of randomly initialized weights. + +```py +from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation + +config = MaskFormerConfig(backbone="microsoft/resnet-50", use_pretrained_backbone=True) +model = MaskFormerForInstanceSegmentation(config) +``` + +Another option is to separately load the backbone configuration and then pass it to `backbone_config` in the model configuration. + +```py +from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation, ResNetConfig + +# instantiate backbone configuration +backbone_config = ResNetConfig() +# load backbone in model +config = MaskFormerConfig(backbone_config=backbone_config) +# attach backbone to model head +model = MaskFormerForInstanceSegmentation(config) +``` + + +
+ +## timm backbones + +[timm](https://hf.co/docs/timm/index) is a collection of vision models for training and inference. Transformers supports timm models as backbones with the [`TimmBackbone`] and [`TimmBackboneConfig`] classes. + +Set `use_timm_backbone=True` to load pretrained timm weights, and `use_pretrained_backbone` to use pretrained or randomly initialized weights. + +```py +from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation + +config = MaskFormerConfig(backbone="resnet50", use_timm_backbone=True, use_pretrained_backbone=True) +model = MaskFormerForInstanceSegmentation(config) +``` + +You could also explicitly call the [`TimmBackboneConfig`] class to load and create a pretrained timm backbone. + +```py +from transformers import TimmBackboneConfig + +backbone_config = TimmBackboneConfig("resnet50", use_pretrained_backbone=True) +``` + +Pass the backbone configuration to the model configuration and instantiate the model head, [`MaskFormerForInstanceSegmentation`], with the backbone. + +```py +from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation + +config = MaskFormerConfig(backbone_config=backbone_config) +model = MaskFormerForInstanceSegmentation(config) +``` + +## Feature extraction + +The backbone is used to extract image features. Pass an image through the backbone to get the feature maps. + +Load and preprocess an image and pass it to the backbone. The example below extracts the feature maps from the first layer. + +```py +from transformers import AutoImageProcessor, AutoBackbone +import torch +from PIL import Image +import requests + +model = AutoBackbone.from_pretrained("microsoft/swin-tiny-patch4-window7-224", out_indices=(1,)) +processor = AutoImageProcessor.from_pretrained("microsoft/swin-tiny-patch4-window7-224") + +url = "http://images.cocodataset.org/val2017/000000039769.jpg" +image = Image.open(requests.get(url, stream=True).raw) + +inputs = processor(image, return_tensors="pt") +outputs = model(**inputs) +``` + +The features are stored and accessed from the outputs `feature_maps` attribute. + +```py +feature_maps = outputs.feature_maps +list(feature_maps[0].shape) +[1, 96, 56, 56] +``` diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/cache_explanation.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/cache_explanation.md new file mode 100644 index 0000000000000000000000000000000000000000..ee37a75d3a0c63125f5ff87346d1dc62cbb37296 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/cache_explanation.md @@ -0,0 +1,188 @@ + + +# Caching +Imagine you're having a conversation with someone, and instead of remembering what they previously said, they have to start from scratch every time you respond. This would be slow and inefficient, right? + +You can extend this analogy to transformer models. Autoregressive model generation can be slow because it makes a prediction one token at a time. Each new prediction is dependent on all the previous context. + +To predict the 1000th token, the model requires information from the previous 999 tokens. The information is represented as matrix multiplications across the token representations. + +To predict the 1001th token, you need the same information from the previous 999 tokens in addition to any information from the 1000th token. This is a lot of matrix multiplications a model has to compute over and over for each token! + +A key-value (KV) cache eliminates this inefficiency by storing kv pairs derived from the attention layers of previously processed tokens. The stored kv pairs are retrieved from the cache and reused for subsequent tokens, avoiding the need to recompute. + +> [!WARNING] +> Caching should only be used for **inference**. It may cause unexpected errors if it's enabled during training. + +To better understand how and why caching works, let's take a closer look at the structure of the attention matrices. + +## Attention matrices + +The **scaled dot-product attention** is calculated as shown below for a batch of size `b`, number of attention heads `h`, sequence length so far `T`, and dimension per attention head `d_head`. + +$$ +\text{Attention}(Q, K, V) = \text{softmax}\left( \frac{Q K^\top}{\sqrt{d_{\text{head}}}} \times \text{mask} \right) V +$$ + +The query (`Q`), key (`K`), and value (`V`) matrices are projections from the input embeddings of shape `(b, h, T, d_head)`. + +For causal attention, the mask prevents the model from attending to future tokens. Once a token is processed, its representation never changes with respect to future tokens, which means \\( K_{\text{past}} \\) and \\( V_{\text{past}} \\) can be cached and reused to compute the last token's representation. + +$$ +\text{Attention}(q_t, [\underbrace{k_1, k_2, \dots, k_{t-1}}_{\text{cached}}, k_{t}], [\underbrace{v_1, v_2, \dots, v_{t-1}}_{\text{cached}}, v_{t}]) +$$ + +At inference time, you only need the last token's query to compute the representation \\( x_t \\) that predicts the next token \\( t+1 \\). At each step, the new key and value vectors are **stored** in the cache and **appended** to the past keys and values. + +$$ +K_{\text{cache}} \leftarrow \text{concat}(K_{\text{past}}, k_t), \quad V_{\text{cache}} \leftarrow \text{concat}(V_{\text{past}}, v_t) +$$ + +Attention is calculated independently in each layer of the model, and caching is done on a per-layer basis. + +Refer to the table below to compare how caching improves efficiency. + +| without caching | with caching | +|---|---| +| for each step, recompute all previous `K` and `V` | for each step, only compute current `K` and `V` +| attention cost per step is **quadratic** with sequence length | attention cost per step is **linear** with sequence length (memory grows linearly, but compute/token remains low) | + + + +## Cache class + +A basic KV cache interface takes a key and value tensor for the current token and returns the updated `K` and `V` tensors. This is internally managed by a model's `forward` method. + +```py +new_K, new_V = cache.update(k_t, v_t, layer_idx) +attn_output = attn_layer_idx_fn(q_t, new_K, new_V) +``` + +When you use Transformers' [`Cache`] class, the self-attention module performs several critical steps to integrate past and present information. + +1. The attention module concatenates current kv pairs with past kv pairs stored in the cache. This creates attentions weights with the shape `(new_tokens_length, past_kv_length + new_tokens_length)`. The current and past kv pairs are essentially combined to compute the attention scores, ensuring a model is aware of previous context and the current input. + +2. When the `forward` method is called iteratively, it's crucial that the attention mask shape matches the combined length of the past and current kv pairs. The attention mask should have the shape `(batch_size, past_kv_length + new_tokens_length)`. This is typically handled internally in [`~GenerationMixin.generate`], but if you want to implement your own generation loop with [`Cache`], keep this in mind! The attention mask should hold the past and current token values. + +3. It is also important to be aware of the `cache_position`. This is important if you want to reuse a prefilled [`Cache`] with the `forward` method because you have to pass a valid `cache_position` value. This indicates the input positions in a sequence. `cache_position` is unaffected by padding, and it always adds one more position for each token. For example, if a kv cache contains 10 tokens - regardless of pad tokens - the cache position for the next token should be `torch.tensor([10])`. + +## Cache storage implementation + +Caches are structured as a list of layers, where each layer contains a key and value cache. The key and value caches are tensors with the shape `[batch_size, num_heads, seq_len, head_dim]`. + +Layers can be of different types (e.g. `DynamicLayer`, `StaticLayer`, `SlidingWindowLayer`), which mostly changes how sequence length is handled and how the cache is updated. + +The simplest is a `DynamicLayer` that grows as more tokens are processed. The sequence length dimension (`seq_len`) increases with each new token: + +```py +cache.layers[idx].keys = torch.cat([cache.layers[idx].keys, key_states], dim=-2) +cache.layers[idx].values = torch.cat([cache.layers[idx].values, value_states], dim=-2) +``` + +Other layer types like `StaticLayer` and `SlidingWindowLayer` have a fixed sequence length that is set when the cache is created. This makes them compatible with `torch.compile`. In the case of `SlidingWindowLayer`, existing tokens are shifted out of the cache when a new token is added. + +The example below demonstrates how to create a generation loop with [`DynamicCache`]. As discussed, the attention mask is a concatenation of past and current token values and `1` is added to the cache position for the next token. + +```py +import torch +from transformers import AutoTokenizer, AutoModelForCausalLM, DynamicCache, infer_device + +device = f"{infer_device()}:0" + +model_id = "meta-llama/Llama-2-7b-chat-hf" +model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.bfloat16, device_map=device) +tokenizer = AutoTokenizer.from_pretrained(model_id) + +past_key_values = DynamicCache() +messages = [{"role": "user", "content": "Hello, what's your name."}] +inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt", return_dict=True).to(model.device) + +generated_ids = inputs.input_ids +cache_position = torch.arange(inputs.input_ids.shape[1], dtype=torch.int64, device=model.device) +max_new_tokens = 10 + +for _ in range(max_new_tokens): + outputs = model(**inputs, cache_position=cache_position, past_key_values=past_key_values, use_cache=True) + # Greedily sample one next token + next_token_ids = outputs.logits[:, -1:].argmax(-1) + generated_ids = torch.cat([generated_ids, next_token_ids], dim=-1) + # Prepare inputs for the next generation step by leaving unprocessed tokens, in our case we have only one new token + # and expanding attn mask for the new token, as explained above + attention_mask = inputs["attention_mask"] + attention_mask = torch.cat([attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1) + inputs = {"input_ids": next_token_ids, "attention_mask": attention_mask} + cache_position = cache_position[-1:] + 1 # add one more position for the next token + +print(tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]) +"[INST] Hello, what's your name. [/INST] Hello! My name is LLaMA," +``` + +## Cache position + +The cache position tracks where to insert new tokens in the attention cache. It represents the *absolute* position of each token in the context, independent of padding or batch structure. Suppose you already cached `N` tokens and are now processing `K` new tokens. The cache position for the new tokens will range from `N` to `N + K - 1`. In other words, you're processing tokens at positions - `[N, N + 1, N + 2, ..., N + K - 1]`. + +Cache position is used internally for two purposes: + +1. Selecting new tokens to process in the input sequence and ensuring only tokens that haven’t been cached yet are passed to the model's `forward`. +2. Storing key/value pairs at the correct positions in the cache. This is especially important for fixed-size caches, like [`StaticCache`], that pre-allocates a specific cache length. + +The generation loop usually takes care of the cache position, but if you're writing a custom generation method, it is important that cache positions are accurate since they are used to write and read key/value states into fixed slots. + + +```py +import torch +from transformers import AutoTokenizer, AutoModelForCausalLM, DynamicCache, infer_device + +device = f"{infer_device()}:0" + +model_id = "meta-llama/Llama-2-7b-chat-hf" +model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.bfloat16, device_map=device) +tokenizer = AutoTokenizer.from_pretrained(model_id) + +messages = [{"role": "user", "content": "You are a helpful assistant."}] +inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt", return_dict=True).to(model.device) +generated_ids = model.generate(**inputs, use_cache=True, max_new_tokens=10) + +``` + + +## Legacy cache format + +Before the [`Cache`] class, the cache used to be stored as a tuple of tuples of tensors. This format is dynamic because it grows as text is generated, similar to [`DynamicCache`]. + +The legacy format is essentially the same data structure but organized differently. +- It's a tuple of tuples, where each inner tuple contains the key and value tensors for a layer. +- The tensors have the same shape `[batch_size, num_heads, seq_len, head_dim]`. +- The format is less flexible and doesn't support features like quantization or offloading. + +If your project depends on this legacy format, we recommend to convert to [`DynamicCache`] with [`~DynamicCache.from_legacy_cache`]. Note that legacy cache format is deprecated and not used anymore in `Transformers`. You can convert back to tuple format with [`DynamicCache.to_legacy_cache`] functions, which is helpful if you have custom logic for manipulating a cache in a specific format. + +```py +import torch +from transformers import AutoTokenizer, AutoModelForCausalLM, DynamicCache + +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-chat-hf") +model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-chat-hf", torch_dtype=torch.float16, device_map="auto") +inputs = tokenizer("Hello, my name is", return_tensors="pt").to(model.device) + +# `return_dict_in_generate=True` is required to return the cache and `return_legacy_cache` forces the returned cache +# in the legacy format +generation_outputs = model.generate(**inputs, return_dict_in_generate=True, return_legacy_cache=True, max_new_tokens=5) + +cache = DynamicCache.from_legacy_cache(generation_outputs.past_key_values) +legacy_format_cache = cache.to_legacy_cache() +``` diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/chat_extras.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/chat_extras.md new file mode 100644 index 0000000000000000000000000000000000000000..863b0f06f2e90793d1a30e103ebf44d1d0855f3f --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/chat_extras.md @@ -0,0 +1,299 @@ + + +# Tools and RAG + +The [`~PreTrainedTokenizerBase.apply_chat_template`] method supports virtually any additional argument types - strings, lists, dicts - besides the chat message. This makes it possible to use chat templates for many use cases. + +This guide will demonstrate how to use chat templates with tools and retrieval-augmented generation (RAG). + +## Tools + +Tools are functions a large language model (LLM) can call to perform specific tasks. It is a powerful way to extend the capabilities of conversational agents with real-time information, computational tools, or access to large databases. + +Follow the rules below when creating a tool. + +1. The function should have a descriptive name. +2. The function arguments must have a type hint in the function header (don't include in the `Args` block). +3. The function must have a [Google-style](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings) docstring. +4. The function can have a return type and `Returns` block, but these are optional because most tool use models ignore them. + +An example tool to get temperature and wind speed is shown below. + +```py +def get_current_temperature(location: str, unit: str) -> float: + """ + Get the current temperature at a location. + + Args: + location: The location to get the temperature for, in the format "City, Country" + unit: The unit to return the temperature in. (choices: ["celsius", "fahrenheit"]) + Returns: + The current temperature at the specified location in the specified units, as a float. + """ + return 22. # A real function should probably actually get the temperature! + +def get_current_wind_speed(location: str) -> float: + """ + Get the current wind speed in km/h at a given location. + + Args: + location: The location to get the temperature for, in the format "City, Country" + Returns: + The current wind speed at the given location in km/h, as a float. + """ + return 6. # A real function should probably actually get the wind speed! + +tools = [get_current_temperature, get_current_wind_speed] +``` + +Load a model and tokenizer that supports tool-use like [NousResearch/Hermes-2-Pro-Llama-3-8B](https://hf.co/NousResearch/Hermes-2-Pro-Llama-3-8B), but you can also consider a larger model like [Command-R](./model_doc/cohere) and [Mixtral-8x22B](./model_doc/mixtral) if your hardware can support it. + +```py +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained( "NousResearch/Hermes-2-Pro-Llama-3-8B") +tokenizer = AutoTokenizer.from_pretrained( "NousResearch/Hermes-2-Pro-Llama-3-8B") +model = AutoModelForCausalLM.from_pretrained( "NousResearch/Hermes-2-Pro-Llama-3-8B", torch_dtype=torch.bfloat16, device_map="auto") +``` + +Create a chat message. + +```py +messages = [ + {"role": "system", "content": "You are a bot that responds to weather queries. You should reply with the unit used in the queried location."}, + {"role": "user", "content": "Hey, what's the temperature in Paris right now?"} +] +``` + +Pass `messages` and a list of tools to [`~PreTrainedTokenizerBase.apply_chat_template`]. Then you can pass the inputs to the model for generation. + +```py +inputs = tokenizer.apply_chat_template(messages, tools=tools, add_generation_prompt=True, return_dict=True, return_tensors="pt") +inputs = {k: v for k, v in inputs.items()} +outputs = model.generate(**inputs, max_new_tokens=128) +print(tokenizer.decode(outputs[0][len(inputs["input_ids"][0]):])) +``` + +```txt + +{"arguments": {"location": "Paris, France", "unit": "celsius"}, "name": "get_current_temperature"} +<|im_end|> +``` + +The chat model called the `get_current_temperature` tool with the correct parameters from the docstring. It inferred France as the location based on Paris, and that it should use Celsius for the units of temperature. + +Now append the `get_current_temperature` function and these arguments to the chat message as `tool_call`. The `tool_call` dictionary should be provided to the `assistant` role instead of the `system` or `user`. + +> [!WARNING] +> The OpenAI API uses a JSON string as its `tool_call` format. This may cause errors or strange model behavior if used in Transformers, which expects a dict. + + + + +```py +tool_call = {"name": "get_current_temperature", "arguments": {"location": "Paris, France", "unit": "celsius"}} +messages.append({"role": "assistant", "tool_calls": [{"type": "function", "function": tool_call}]}) +``` + +Allow the assistant to read the function outputs and chat with the user. + +```py +inputs = tokenizer.apply_chat_template(messages, tools=tools, add_generation_prompt=True, return_dict=True, return_tensors="pt") +inputs = {k: v for k, v in inputs.items()} +out = model.generate(**inputs, max_new_tokens=128) +print(tokenizer.decode(out[0][len(inputs["input_ids"][0]):])) +``` + +```txt +The temperature in Paris, France right now is approximately 12°C (53.6°F).<|im_end|> +``` + + + + +For [Mistral](./model_doc/mistral) and [Mixtral](./model_doc/mixtral) models, you need an additional `tool_call_id`. The `tool_call_id` is 9 randomly generated alphanumeric characters assigned to the `id` key in the `tool_call` dictionary. + +```py +tool_call_id = "9Ae3bDc2F" +tool_call = {"name": "get_current_temperature", "arguments": {"location": "Paris, France", "unit": "celsius"}} +messages.append({"role": "assistant", "tool_calls": [{"type": "function", "id": tool_call_id, "function": tool_call}]}) +``` + +```py +inputs = tokenizer.apply_chat_template(messages, tools=tools, add_generation_prompt=True, return_dict=True, return_tensors="pt") +inputs = {k: v for k, v in inputs.items()} +out = model.generate(**inputs, max_new_tokens=128) +print(tokenizer.decode(out[0][len(inputs["input_ids"][0]):])) +``` + + + + +## Schema + +[`~PreTrainedTokenizerBase.apply_chat_template`] converts functions into a [JSON schema](https://json-schema.org/learn/getting-started-step-by-step) which is passed to the chat template. A LLM never sees the code inside the function. In other words, a LLM doesn't care how the function works technically, it only cares about function **definition** and **arguments**. + +The JSON schema is automatically generated behind the scenes as long as your function follows the [rules](#tools) listed earlier above. But you can use [get_json_schema](https://github.com/huggingface/transformers/blob/14561209291255e51c55260306c7d00c159381a5/src/transformers/utils/chat_template_utils.py#L205) to manually convert a schema for more visibility or debugging. + +```py +from transformers.utils import get_json_schema + +def multiply(a: float, b: float): + """ + A function that multiplies two numbers + + Args: + a: The first number to multiply + b: The second number to multiply + """ + return a * b + +schema = get_json_schema(multiply) +print(schema) +``` + +```json +{ + "type": "function", + "function": { + "name": "multiply", + "description": "A function that multiplies two numbers", + "parameters": { + "type": "object", + "properties": { + "a": { + "type": "number", + "description": "The first number to multiply" + }, + "b": { + "type": "number", + "description": "The second number to multiply" + } + }, + "required": ["a", "b"] + } + } +} +``` + +You can edit the schema or write one entirely from scratch. This gives you a lot of flexibility to define precise schemas for more complex functions. + +> [!WARNING] +> Try keeping your function signatures simple and the arguments to a minimum. These are easier for a model to understand and use than complex functions for example with nested arguments. + +The example below demonstrates writing a schema manually and then passing it to [`~PreTrainedTokenizerBase.apply_chat_template`]. + +```py +# A simple function that takes no arguments +current_time = { + "type": "function", + "function": { + "name": "current_time", + "description": "Get the current local time as a string.", + "parameters": { + 'type': 'object', + 'properties': {} + } + } +} + +# A more complete function that takes two numerical arguments +multiply = { + 'type': 'function', + 'function': { + 'name': 'multiply', + 'description': 'A function that multiplies two numbers', + 'parameters': { + 'type': 'object', + 'properties': { + 'a': { + 'type': 'number', + 'description': 'The first number to multiply' + }, + 'b': { + 'type': 'number', 'description': 'The second number to multiply' + } + }, + 'required': ['a', 'b'] + } + } +} + +model_input = tokenizer.apply_chat_template( + messages, + tools = [current_time, multiply] +) +``` + +## RAG + +Retrieval-augmented generation (RAG) models enhance a models existing knowledge by allowing it to search documents for additional information before returning a query. For RAG models, add a `documents` parameter to [`~PreTrainedTokenizerBase.apply_chat_template`]. This `documents` parameter should be a list of documents, and each document should be a single dict with `title` and `content` keys. + +> [!TIP] +> The `documents` parameter for RAG isn't widely supported and many models have chat templates that ignore `documents`. Verify if a model supports `documents` by reading its model card or executing `print(tokenizer.chat_template)` to see if the `documents` key is present. [Command-R](https://hf.co/CohereForAI/c4ai-command-r-08-2024) and [Command-R+](https://hf.co/CohereForAI/c4ai-command-r-plus-08-2024) both support `documents` in their RAG chat templates. + +Create a list of documents to pass to the model. + +```py +documents = [ + { + "title": "The Moon: Our Age-Old Foe", + "text": "Man has always dreamed of destroying the moon. In this essay, I shall..." + }, + { + "title": "The Sun: Our Age-Old Friend", + "text": "Although often underappreciated, the sun provides several notable benefits..." + } +] +``` + +Set `chat_template="rag"` in [`~PreTrainedTokenizerBase.apply_chat_template`] and generate a response. + +```py +from transformers import AutoTokenizer, AutoModelForCausalLM + +# Load the model and tokenizer +tokenizer = AutoTokenizer.from_pretrained("CohereForAI/c4ai-command-r-v01-4bit") +model = AutoModelForCausalLM.from_pretrained("CohereForAI/c4ai-command-r-v01-4bit", device_map="auto") +device = model.device # Get the device the model is loaded on + +# Define conversation input +conversation = [ + {"role": "user", "content": "What has Man always dreamed of?"} +] + +input_ids = tokenizer.apply_chat_template( + conversation=conversation, + documents=documents, + chat_template="rag", + tokenize=True, + add_generation_prompt=True, + return_tensors="pt").to(device) + +# Generate a response +generated_tokens = model.generate( + input_ids, + max_new_tokens=100, + do_sample=True, + temperature=0.3, + ) + +# Decode and print the generated text along with generation prompt +generated_text = tokenizer.decode(generated_tokens[0]) +print(generated_text) +``` diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/chat_templating.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/chat_templating.md new file mode 100644 index 0000000000000000000000000000000000000000..fac353eb298fa6c5eb2ac6f9447db69ce849adf9 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/chat_templating.md @@ -0,0 +1,229 @@ + + +# Templates + +The [chat pipeline](./conversations) guide introduced [`TextGenerationPipeline`] and the concept of a chat prompt or chat template for conversing with a model. Underlying this high-level pipeline is the [`apply_chat_template`] method. A chat template is a part of the tokenizer and it specifies how to convert conversations into a single tokenizable string in the expected model format. + +In the example below, Mistral-7B-Instruct and Zephyr-7B are finetuned from the same base model but they’re trained with different chat formats. Without chat templates, you have to manually write formatting code for each model and even minor errors can hurt performance. Chat templates offer a universal way to format chat inputs to any model. + + + + +```py +from transformers import AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-Instruct-v0.1") +chat = [ + {"role": "user", "content": "Hello, how are you?"}, + {"role": "assistant", "content": "I'm doing great. How can I help you today?"}, + {"role": "user", "content": "I'd like to show off how chat templating works!"}, +] + +tokenizer.apply_chat_template(chat, tokenize=False) +``` +```md +[INST] Hello, how are you? [/INST]I'm doing great. How can I help you today? [INST] I'd like to show off how chat templating works! [/INST] +``` + + + + +```py +from transformers import AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-beta") +chat = [ + {"role": "user", "content": "Hello, how are you?"}, + {"role": "assistant", "content": "I'm doing great. How can I help you today?"}, + {"role": "user", "content": "I'd like to show off how chat templating works!"}, +] + +tokenizer.apply_chat_template(chat, tokenize=False) +``` +```md +<|user|>\nHello, how are you?\n<|assistant|>\nI'm doing great. How can I help you today?\n<|user|>\nI'd like to show off how chat templating works!\n +``` + + + + +This guide explores [`apply_chat_template`] and chat templates in more detail. + +## apply_chat_template + +Chats should be structured as a list of dictionaries with `role` and `content` keys. The `role` key specifies the speaker (usually between you and the system), and the `content` key contains your message. For the system, the `content` is a high-level description of how the model should behave and respond when you’re chatting with it. + +Pass your messages to [`apply_chat_template`] to tokenize and format them. You can set [add_generation_prompt](https://huggingface.co/docs/transformers/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.apply_chat_template.add_generation_prompt) to `True` to indicate the start of a message. + +```py +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-beta") +model = AutoModelForCausalLM.from_pretrained("HuggingFaceH4/zephyr-7b-beta", device_map="auto", torch_dtype=torch.bfloat16) + +messages = [ + {"role": "system", "content": "You are a friendly chatbot who always responds in the style of a pirate",}, + {"role": "user", "content": "How many helicopters can a human eat in one sitting?"}, + ] +tokenized_chat = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt") +print(tokenizer.decode(tokenized_chat[0])) +``` +```md +<|system|> +You are a friendly chatbot who always responds in the style of a pirate +<|user|> +How many helicopters can a human eat in one sitting? +<|assistant|> +``` + +Now pass the tokenized chat to [`~GenerationMixin.generate`] to generate a response. + +```py +outputs = model.generate(tokenized_chat, max_new_tokens=128) +print(tokenizer.decode(outputs[0])) +``` +```md +<|system|> +You are a friendly chatbot who always responds in the style of a pirate +<|user|> +How many helicopters can a human eat in one sitting? +<|assistant|> +Matey, I'm afraid I must inform ye that humans cannot eat helicopters. Helicopters are not food, they are flying machines. Food is meant to be eaten, like a hearty plate o' grog, a savory bowl o' stew, or a delicious loaf o' bread. But helicopters, they be for transportin' and movin' around, not for eatin'. So, I'd say none, me hearties. None at all. +``` + +### add_generation_prompt +The [add_generation_prompt](https://huggingface.co/docs/transformers/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.apply_chat_template.add_generation_prompt) parameter adds tokens that indicate the start of a response. This ensures the chat model generates a system response instead of continuing a users message. + +Not all models require generation prompts, and some models, like [Llama](./model_doc/llama), don’t have any special tokens before the system response. In this case, [add_generation_prompt](https://huggingface.co/docs/transformers/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.apply_chat_template.add_generation_prompt) has no effect. + +```py +tokenized_chat = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=False) +tokenized_chat +``` +```md +<|im_start|>user +Hi there!<|im_end|> +<|im_start|>assistant +Nice to meet you!<|im_end|> +<|im_start|>user +Can I ask a question?<|im_end|> +``` + +### continue_final_message + +The [continue_final_message](https://huggingface.co/docs/transformers/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.apply_chat_template.continue_final_message) parameter controls whether the final message in the chat should be continued or not instead of starting a new one. It removes end of sequence tokens so that the model continues generation from the final message. + +This is useful for “prefilling” a model response. In the example below, the model generates text that continues the JSON string rather than starting a new message. It can be very useful for improving the accuracy for instruction following when you know how to start its replies. + +```py +chat = [ + {"role": "user", "content": "Can you format the answer in JSON?"}, + {"role": "assistant", "content": '{"name": "'}, +] + +formatted_chat = tokenizer.apply_chat_template(chat, tokenize=True, return_dict=True, continue_final_message=True) +model.generate(**formatted_chat) +``` + +> [!WARNING] +> You shouldn’t use [add_generation_prompt](https://huggingface.co/docs/transformers/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.apply_chat_template.add_generation_prompt) and [continue_final_message](https://huggingface.co/docs/transformers/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.apply_chat_template.continue_final_message) together. The former adds tokens that start a new message, while the latter removes end of sequence tokens. Using them together returns an error. + +[`TextGenerationPipeline`] sets [add_generation_prompt](https://huggingface.co/docs/transformers/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.apply_chat_template.add_generation_prompt) to `True` by default to start a new message. However, if the final message in the chat has the “assistant” role, it assumes the message is a prefill and switches to `continue_final_message=True`. This is because most models don’t support multiple consecutive assistant messages. To override this behavior, explicitly pass the [continue_final_message](https://huggingface.co/docs/transformers/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.apply_chat_template.continue_final_message) to the pipeline. + +## Multiple templates + +A model may have several different templates for different use cases. For example, a model may have a template for regular chat, tool use, and RAG. + +When there are multiple templates, the chat template is a dictionary. Each key corresponds to the name of a template. [`apply_chat_template`] handles multiple templates based on their name. It looks for a template named `default` in most cases and if it can’t find one, it raises an error. + +For a tool calling template, if a user passes a `tools` parameter and a `tool_use` template exists, the tool calling template is used instead of `default`. + +To access templates with other names, pass the template name to the `chat_template` parameter in [`apply_chat_template`]. For example, if you’re using a RAG template then set `chat_template="rag"`. + +It can be confusing to manage multiple templates though, so we recommend using a single template for all use cases. Use Jinja statements like `if tools is defined` and `{% macro %}` definitions to wrap multiple code paths in a single template. + +## Template selection + +It is important to set a chat template format that matches the template format a model was pretrained on, otherwise performance may suffer. Even if you’re training the model further, performance is best if the chat tokens are kept constant. + +But if you’re training a model from scratch or finetuning a model for chat, you have more options to select a template. For example, [ChatML](https://github.com/openai/openai-python/blob/release-v0.28.0/chatml.md) is a popular format that is flexible enough to handle many use cases. It even includes support for [generation prompts](#add_generation_prompt), but it doesn’t add beginning-of-string (`BOS`) or end-of-string (`EOS`) tokens. If your model expects `BOS` and `EOS` tokens, set `add_special_tokens=True` and make sure to add them to your template. + +```py +{%- for message in messages %} + {{- '<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n' }} +{%- endfor %} +``` + +Set the template with the following logic to support [generation prompts](#add_generation_prompt). The template wraps each message with `<|im_start|>` and `<|im_end|>` tokens and writes the role as a string. This allows you to easily customize the roles you want to train with. + +```py +tokenizer.chat_template = "{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}" +``` + +The `user`, `system` and `assistant` roles are standard roles in chat templates. We recommend using these roles when it makes sense, especially if you’re using your model with the [`TextGenerationPipeline`]. + +```py +<|im_start|>system +You are a helpful chatbot that will do its best not to say anything so stupid that people tweet about it.<|im_end|> +<|im_start|>user +How are you?<|im_end|> +<|im_start|>assistant +I'm doing great!<|im_end|> +``` + +## Model training + +Training a model with a chat template is a good way to ensure a chat template matches the tokens a model is trained on. Apply the chat template as a preprocessing step to your dataset. Set `add_generation_prompt=False` because the additional tokens to prompt an assistant response aren’t helpful during training. + +An example of preprocessing a dataset with a chat template is shown below. + +```py +from transformers import AutoTokenizer +from datasets import Dataset + +tokenizer = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-beta") + +chat1 = [ + {"role": "user", "content": "Which is bigger, the moon or the sun?"}, + {"role": "assistant", "content": "The sun."} +] +chat2 = [ + {"role": "user", "content": "Which is bigger, a virus or a bacterium?"}, + {"role": "assistant", "content": "A bacterium."} +] + +dataset = Dataset.from_dict({"chat": [chat1, chat2]}) +dataset = dataset.map(lambda x: {"formatted_chat": tokenizer.apply_chat_template(x["chat"], tokenize=False, add_generation_prompt=False)}) +print(dataset['formatted_chat'][0]) +``` +```md +<|user|> +Which is bigger, the moon or the sun? +<|assistant|> +The sun. +``` + +After this step, you can continue following the [training recipe](./tasks/language_modeling) for causal language models using the `formatted_chat` column. + +Some tokenizers add special `` and `` tokens. Chat templates should already include all the necessary special tokens, and adding additional special tokens is often incorrect or duplicated, hurting model performance. When you format text with `apply_chat_template(tokenize=False)`, make sure you set `add_special_tokens=False` as well to avoid duplicating them. + +```py +apply_chat_template(messages, tokenize=False, add_special_tokens=False) +``` + +This isn’t an issue if `apply_chat_template(tokenize=True)`. diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/chat_templating_multimodal.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/chat_templating_multimodal.md new file mode 100644 index 0000000000000000000000000000000000000000..367cfe6be922e22db5a9831c7dacb581b060c8e1 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/chat_templating_multimodal.md @@ -0,0 +1,290 @@ + + +# Multimodal templates + +Multimodal model chat templates expect a similar [template](./chat_templating) as text-only models. It needs `messages` that includes a dictionary of the `role` and `content`. + +Multimodal templates are included in the [Processor](./processors) class and require an additional `type` key for specifying whether the included content is an image, video, or text. + +This guide will show you how to format chat templates for multimodal models as well as some best practices for configuring the template + +## ImageTextToTextPipeline + +[`ImageTextToTextPipeline`] is a high-level image and text generation class with a “chat mode”. Chat mode is enabled when a conversational model is detected and the chat prompt is [properly formatted](./llm_tutorial#wrong-prompt-format). + +Start by building a chat history with the following two roles. + +- `system` describes how the model should behave and respond when you’re chatting with it. This role isn’t supported by all chat models. +- `user` is where you enter your first message to the model. + +```py +messages = [ + { + "role": "system", + "content": [{"type": "text", "text": "You are a friendly chatbot who always responds in the style of a pirate"}], + }, + { + "role": "user", + "content": [ + {"type": "image", "url": "http://images.cocodataset.org/val2017/000000039769.jpg"}, + {"type": "text", "text": "What are these?"}, + ], + }, +] +``` + +Create a [`ImageTextToTextPipeline`] and pass the chat to it. For large models, setting [device_map=“auto”](./models#big-model-inference) helps load the model quicker and automatically places it on the fastest device available. Changing the data type to [torch.bfloat16](./models#model-data-type) also helps save memory. + +> [!TIP] +> The [`ImageTextToTextPipeline`] accepts chats in the OpenAI format to make inference easier and more accessible. + +```python +import torch +from transformers import pipeline + +pipeline = pipeline("image-text-to-text", model="llava-hf/llava-onevision-qwen2-0.5b-ov-hf", device_map="auto", torch_dtype=torch.float16) +pipeline(text=messages, max_new_tokens=50, return_full_text=False) +[{'input_text': [{'role': 'system', + 'content': [{'type': 'text', + 'text': 'You are a friendly chatbot who always responds in the style of a pirate'}]}, + {'role': 'user', + 'content': [{'type': 'image', + 'url': 'http://images.cocodataset.org/val2017/000000039769.jpg'}, + {'type': 'text', 'text': 'What are these?'}]}], + 'generated_text': 'The image shows two cats lying on a pink surface, which appears to be a cushion or a soft blanket. The cat on the left has a striped coat, typical of tabby cats, and is lying on its side with its head resting on the'}] +``` + +## Image inputs + +For multimodal models that accept images like [LLaVA](./model_doc/llava), include the following in `content` as shown below. + +- The content `"type"` can be an `"image"` or `"text"`. +- For images, it can be a link to the image (`"url"`), a file path (`"path"`), or `"base64"`. Images are automatically loaded, processed, and prepared into pixel values as inputs to the model. + +```python +from transformers import AutoProcessor, LlavaOnevisionForConditionalGeneration + +model = LlavaOnevisionForConditionalGeneration.from_pretrained("llava-hf/llava-onevision-qwen2-0.5b-ov-hf") +processor = AutoProcessor.from_pretrained("llava-hf/llava-onevision-qwen2-0.5b-ov-hf") + +messages = [ + { + "role": "system", + "content": [{"type": "text", "text": "You are a friendly chatbot who always responds in the style of a pirate"}], + }, + { + "role": "user", + "content": [ + {"type": "image", "url": "http://images.cocodataset.org/val2017/000000039769.jpg"}, + {"type": "text", "text": "What are these?"}, + ], + }, +] +``` + +Pass `messages` to [`~ProcessorMixin.apply_chat_template`] to tokenize the input content and return the `input_ids` and `pixel_values`. + +```py +processed_chat = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt") +print(processed_chat.keys()) +``` + +These inputs are now ready to be used in [`~GenerationMixin.generate`]. + +## Video inputs + +Some vision models also support video inputs. The message format is very similar to the format for [image inputs](#image-inputs). + +- The content `"type"` should be `"video"` to indicate the content is a video. +- For videos, it can be a link to the video (`"url"`) or it could be a file path (`"path"`). Videos loaded from a URL can only be decoded with [PyAV](https://pyav.basswood-io.com/docs/stable/) or [Decord](https://github.com/dmlc/decord). +- In addition to loading videos from a URL or file path, you can also pass decoded video data directly. This is useful if you’ve already preprocessed or decoded video frames elsewhere in memory (e.g., using OpenCV, decord, or torchvision). You don't need to save to files or store it in an URL. + +> [!WARNING] +> Loading a video from `"url"` is only supported by the PyAV or Decord backends. + +```python +from transformers import AutoProcessor, LlavaOnevisionForConditionalGeneration + +model_id = "llava-hf/llava-onevision-qwen2-0.5b-ov-hf" +model = LlavaOnevisionForConditionalGeneration.from_pretrained(model_id) +processor = AutoProcessor.from_pretrained(model_id) + +messages = [ + { + "role": "system", + "content": [{"type": "text", "text": "You are a friendly chatbot who always responds in the style of a pirate"}], + }, + { + "role": "user", + "content": [ + {"type": "video", "url": "https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/720/Big_Buck_Bunny_720_10s_10MB.mp4"}, + {"type": "text", "text": "What do you see in this video?"}, + ], + }, +] +``` + +### Example: Passing decoded video objects +```python +import numpy as np + +video_object1 = np.random.randint(0, 255, size=(16, 224, 224, 3), dtype=np.uint8), + +messages = [ + { + "role": "system", + "content": [{"type": "text", "text": "You are a friendly chatbot who always responds in the style of a pirate"}], + }, + { + "role": "user", + "content": [ + {"type": "video", "video": video_object1}, + {"type": "text", "text": "What do you see in this video?"} + ], + }, +] +``` +You can also use existing (`"load_video()"`) function to load a video, edit the video in memory and pass it in the messages. +```python + +# Make sure a video backend library (pyav, decord, or torchvision) is available. +from transformers.video_utils import load_video + +# load a video file in memory for testing +video_object2, _ = load_video( + "https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/720/Big_Buck_Bunny_720_10s_10MB.mp4" +) + +messages = [ + { + "role": "system", + "content": [{"type": "text", "text": "You are a friendly chatbot who always responds in the style of a pirate"}], + }, + { + "role": "user", + "content": [ + {"type": "video", "video": video_object2}, + {"type": "text", "text": "What do you see in this video?"} + ], + }, +] +``` + +Pass `messages` to [`~ProcessorMixin.apply_chat_template`] to tokenize the input content. There are a few extra parameters to include in [`~ProcessorMixin.apply_chat_template`] that controls the sampling process. + +The `video_load_backend` parameter refers to a specific framework to load a video. It supports [PyAV](https://pyav.basswood-io.com/docs/stable/), [Decord](https://github.com/dmlc/decord), [OpenCV](https://github.com/opencv/opencv), and [torchvision](https://pytorch.org/vision/stable/index.html). + +The examples below use Decord as the backend because it is a bit faster than PyAV. + + + + +The `num_frames` parameter controls how many frames to uniformly sample from the video. Each checkpoint has a maximum frame count it was pretrained with and exceeding this count can significantly lower generation quality. It's important to choose a frame count that fits both the model capacity and your hardware resources. If `num_frames` isn't specified, the entire video is loaded without any frame sampling. + + +```python +processed_chat = processor.apply_chat_template( + messages, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + return_tensors="pt", + num_frames=32, + video_load_backend="decord", +) +print(processed_chat.keys()) +``` + +These inputs are now ready to be used in [`~GenerationMixin.generate`]. + + + + +For longer videos, it may be better to sample more frames for better representation with the `video_fps` parameter. This determines how many frames per second to extract. As an example, if a video is 10 seconds long and `video_fps=2`, then the model samples 20 frames. In other words, 2 frames are uniformly sampled every 10 seconds. + +```py +processed_chat = processor.apply_chat_template( + messages, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + video_fps=16, + video_load_backend="decord", +) +print(processed_chat.keys()) +``` + + + + +Videos may also exist as a set of sampled frames stored as images rather than the full video file. + +In this case, pass a list of image file paths and the processor automatically concatenates them into a video. Make sure all images are the same size since they are assumed to be from the same video. + +```py +frames_paths = ["/path/to/frame0.png", "/path/to/frame5.png", "/path/to/frame10.png"] +messages = [ + { + "role": "system", + "content": [{"type": "text", "text": "You are a friendly chatbot who always responds in the style of a pirate"}], + }, + { + "role": "user", + "content": [ + {"type": "video", "path": frames_paths}, + {"type": "text", "text": "What do you see in this video?"}, + ], + }, +] + +processed_chat = processor.apply_chat_template( + messages, + add_generation_prompt=True, + tokenize=True, + return_dict=True, +) +print(processed_chat.keys()) +``` + + + + +## Template configuration + +You can create a custom chat template with [Jinja](https://jinja.palletsprojects.com/en/3.1.x/templates/) and set it with [`~ProcessorMixin.apply_chat_template`]. Refer to the [Template writing](./chat_templating_writing) guide for more details. + +For example, to enable a template to handle a *list of content* from multiple modalities while still supporting plain strings for text-only inference, specify how to handle the `content['type']` if it is an image or text as shown below in the Llama 3.2 Vision Instruct [template](https://huggingface.co/meta-llama/Llama-3.2-11B-Vision-Instruct/blob/main/chat_template.json). + +```jinja +{% for message in messages %} +{% if loop.index0 == 0 %}{{ bos_token }}{% endif %} +{{ '<|start_header_id|>' + message['role'] + '<|end_header_id|>\n\n' }} +{% if message['content'] is string %} +{{ message['content'] }} +{% else %} +{% for content in message['content'] %} +{% if content['type'] == 'image' %} +{{ '<|image|>' }} +{% elif content['type'] == 'text' %} +{{ content['text'] }} +{% endif %} +{% endfor %} +{% endif %} +{{ '<|eot_id|>' }} +{% endfor %} +{% if add_generation_prompt %}{{ '<|start_header_id|>assistant<|end_header_id|>\n\n' }}{% endif %} +``` diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/chat_templating_writing.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/chat_templating_writing.md new file mode 100644 index 0000000000000000000000000000000000000000..fbcec9f71c01972ae9a451abf1c96cde649e32f9 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/chat_templating_writing.md @@ -0,0 +1,251 @@ + + +# Template writing + +A chat template is a [Jinja](https://jinja.palletsprojects.com/en/3.1.x/templates/) template stored in the tokenizers [chat_template](https://huggingface.co/docs/transformers/main_classes/tokenizer#transformers.PreTrainedTokenizer.chat_template) attribute. Jinja is a templating language that allows you to write Python-like code and syntax. A chat template performs the following three roles. + +1. Print the role enclosed in `<|` and `|>` (`<|user|>`, `<|assistant|>`, etc.). +2. Print the message followed by an end-of-sequence (`EOS`) token. +3. Print the assistant token if [add_generation_prompt=True](./chat_templating#add_generation_prompt) so the model generates an assistant response. + +An example template is shown below. + +```jinja +{%- for message in messages %} + {{- '<|' + message['role'] + |>\n' }} + {{- message['content'] + eos_token }} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|assistant|>\n' }} +{%- endif %} +``` + +The template can be customized to handle more complex use cases. This guide will show you how to add and edit templates and includes template writing tips. + +## Create a template + +Create a template by writing a Jinja template and then setting it as the chat template in the tokenizer. For example, the template below adds `[ASST]` and `[/ASST]` tags to the assistant messages. + +```jinja +{%- for message in messages %} + {%- if message['role'] == 'user' %} + {{- bos_token + '[INST] ' + message['content'].strip() + ' [/INST]' }} + {%- elif message['role'] == 'system' %} + {{- '<>\\n' + message['content'].strip() + '\\n<>\\n\\n' }} + {%- elif message['role'] == 'assistant' %} + {{- '[ASST] ' + message['content'] + ' [/ASST]' + eos_token }} + {%- endif %} +{%- endfor %} +``` + +Set the template in the tokenizer, and the next time you use [`~PreTrainedTokenizerBase.apply_chat_template`], the new template is used. + +```py +template = tokenizer.chat_template +template = template.replace("SYS", "SYSTEM") # Change the system token +tokenizer.chat_template = template # Set the new template +``` + +The template is saved in the `tokenizer_config.json` file. Upload it to the Hub with [`~PreTrainedTokenizer.push_to_hub`] so you can reuse it later and make sure everyone is using the right template for your model. + +```py +tokenizer.push_to_hub("model_name") +``` + +## Template writing tips + +The easiest way to start writing Jinja templates is to refer to existing templates. Use `print(tokenizer.chat_template)` on any chat model to see what template it's using. Try starting with simple models that don't call any tools or support RAG. Finally, take a look at the [Jinja documentation](https://jinja.palletsprojects.com/en/3.1.x/templates/#synopsis) for more details about formatting and syntax. + +This section curates some best practices for writing clean and efficient Jinja templates. + +### Trimming whitespace + +Jinja prints any whitespace before or after a block of text. This can be an issue for chat templates because whitespace usage should be intentional. Add `-` to strip any whitespace before a block. + +```jinja +{%- for message in messages %} + {{- message['role'] + message['content'] }} +{%- endfor %} +``` + +The incorrect whitespace usage example below may introduce a newline and indentation in the output. + +```jinja +{% for message in messages %} + {{ message['role'] + message['content'] }} +{% endfor %} +``` + +### Special variables + +There are five special variables available inside a template. You can pass virtually any additional arguments to [`~PreTrainedTokenizerBase.apply_chat_template`] and it will be available inside the template as a variable. However, you should try to keep the number of variables to the five below to make it easier for users to use the chat model without writing custom code to handle model-specific arguments. + +- `messages` contains the chat history as a list of message dicts. +- `tools` contains a list of tools in JSON schema format. +- `documents` contains a list of documents with the format `{"title": Title, "contents": "Contents"}` (designed for RAG models). +- `add_generation_prompt` is a boolean that determines whether to add an assistant header at the end of the conversation. +- `bos_token` and `eos_token` are special tokens extracted from a tokenizers `special_tokens_map`. + +### Callable functions + +There are two callable functions available inside a template. + +- `raise_exception(msg)` raises a `TemplateException`. This is useful for debugging or warning users about incorrect template usage. +- `strftime_now(format_str)` retrieves the current date and time in a specific format which could be useful to include in system messages. It is equivalent to [datetime.now().strftime(format_str)](https://docs.python.org/3/library/datetime.html#datetime.datetime.now) in Python. + +### Compatibility with non-Python Jinja + +Jinja is implemented in multiple languages and they generally have the same syntax. Writing a template in Python allows you to use Python methods such as [lower](https://docs.python.org/3/library/stdtypes.html#str.lower) on strings or [items](https://docs.python.org/3/library/stdtypes.html#dict.items) on dicts. But this won't work if the template is used in a non-Python implementation, for example, when deploying with Javascript or Rust. + +Make the changes below to ensure compatibility across all Jinja implementations. + +- Replace Python methods with Jinja filters. For example, replace `string.lower()` with `string|lower` or `dict.items()` with `dict|dictitems`. Most of the changes follow the same pattern except `string.strip()`, which is replaced with `string|trim`. Refer to the list of [built-in filters](https://jinja.palletsprojects.com/en/3.1.x/templates/#builtin-filters) for a complete list of filters. +- Replace `True`, `False`, and `None` (these are Python specific) with `true`, `false`, and `none` respectively. +- Directly rendering a dict or list may return different results in other implementations. For example, string entries may change from single-quote to double-quote. To avoid this, add the [tojson](https://jinja.palletsprojects.com/en/3.1.x/templates/#jinja-filters.tojson) filter to maintain consistency. + +### Big templates + +Newer models or models with features like [tool-calling](./chat_extras#tools) and [RAG](./chat_extras#retrieval-augmented-generation-rag) require larger templates that can be longer than 100 lines. It may be easier to write larger templates in a separate file. The line numbers in the separate file corresponds exactly to the line numbers in template parsing or execution errors, making it easier to debug any potential issues. + +Write the template in a separate file and extract it to the chat template. + +```py +open("template.jinja", "w").write(tokenizer.chat_template) +``` + +You could also load an edited template back into the tokenizer. + +```py +tokenizer.chat_template = open("template.jinja").read() +``` + +## Templates for tools + +There isn't a specific format for writing templates for tools but it is best to follow the standard API. This ensures the template is widely accessible across models without requiring users to write custom code to use tools with your model. + +> [!WARNING] +> Formatting such as whitespace and special tokens are model-specific. Make sure everything exactly matches the format a model was trained with. + +The following section lists elements of the standard API for writing templates for tools. + +### Tool definitions + +Transformers chat template methods allow a user to pass tools as Python functions or a JSON schema. When functions are passed, a JSON schema is automatically generated and passed to the template. The `tools` variable in a template always takes a list of JSON schemas. + +The specific tokens and tool descriptions should match the ones your model was trained with. Your model doesn't need to understand the JSON schema input because your template can translate the JSON schema into your models format. For example, [Command-R](./model_doc/cohere) was trained with tools defined with Python function headers, but the Command-R tool template accepts JSON schemas. The template internally converts types and renders the input tools as Python headers. + +```json +{ + "type": "function", + "function": { + "name": "multiply", + "description": "A function that multiplies two numbers", + "parameters": { + "type": "object", + "properties": { + "a": { + "type": "number", + "description": "The first number to multiply" + }, + "b": { + "type": "number", + "description": "The second number to multiply" + } + }, + "required": ["a", "b"] + } + } +} +``` + +An example for handling tool definitions in a chat template is shown below. The specific tokens and tool descriptions should be changed to match the ones a model was trained with. + +``` +{%- if tools %} + {%- for tool in tools %} + {{- '' + tool['function']['name'] + '\n' }} + {%- for argument in tool['function']['parameters']['properties'] %} + {{- argument + ': ' + tool['function']['parameters']['properties'][argument]['description'] + '\n' }} + {%- endfor %} + {{- '\n' }} + {%- endif %} +{%- endif %} +``` + +### Tool calls + +Tool calls, if present, is a list with the `"assistant”` role. This is always a list even though most tool-calling models only support single tool calls, which means the list usually only contains a single element. + +```json +{ + "role": "assistant", + "tool_calls": [ + { + "type": "function", + "function": { + "name": "multiply", + "arguments": { + "a": 5, + "b": 6 + } + } + } + ] +} +``` + +A common pattern for handling tool calls is shown below. + +``` +{%- if message['role'] == 'assistant' and 'tool_calls' in message %} + {%- for tool_call in message['tool_calls'] %} + {{- '' + tool_call['function']['name'] + '\n' + tool_call['function']['arguments']|tojson + '\n' }} + {%- endif %} + {%- endfor %} +{%- endif %} +``` + +### Tool responses + +Tool responses are a message dict with the `role`, `name` (name of the function) and `content` (result of the tool call) keys. + +```json +{ + "role": "tool", + "name": "multiply", + "content": "30" +} +``` + +Not all the keys need to be used in the tool response. For example, if a model doesn’t expect the function name to be included in the tool response, then you can just include the `role` and `content`. + +``` +{%- if message['role'] == 'tool' %} + {{- "" + message['content'] + "" }} +{%- endif %} +``` + +## Contribute + +Add a chat template by setting the `chat_template` attribute in the tokenizer and testing it with [`~PreTrainedTokenizerBase.apply_chat_template`]. If it works as expected, then you can upload it to the Hub with with [`~PreTrainedTokenizer.push_to_hub`]. + +Even if you're not the model owner, it is still helpful to add a template for a model with an empty chat template or a model that is using a default class template. Open a [pull request](https://hf.co/docs/hub/repositories-pull-requests-discussions) on the model repository to add the template. + +```py +tokenizer.chat_template = template +tokenizer.push_to_hub("model_name") +``` diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/community.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/community.md new file mode 100644 index 0000000000000000000000000000000000000000..1b77bee9d2ded1c2836f98bbf6bb3a9f9b00ac1f --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/community.md @@ -0,0 +1,70 @@ + + +# Community + +This page regroups resources around 🤗 Transformers developed by the community. + +## Community resources: + +| Resource | Description | Author | +|:----------|:-------------|------:| +| [Hugging Face Transformers Glossary Flashcards](https://www.darigovresearch.com/huggingface-transformers-glossary-flashcards) | A set of flashcards based on the [Transformers Docs Glossary](glossary) that has been put into a form which can be easily learned/revised using [Anki](https://apps.ankiweb.net/) an open source, cross platform app specifically designed for long term knowledge retention. See this [Introductory video on how to use the flashcards](https://www.youtube.com/watch?v=Dji_h7PILrw). | [Darigov Research](https://www.darigovresearch.com/) | + +## Community notebooks: + +| Notebook | Description | Author | | +|:----------|:-------------|:-------------|------:| +| [Fine-tune a pre-trained Transformer to generate lyrics](https://github.com/AlekseyKorshuk/huggingartists) | How to generate lyrics in the style of your favorite artist by fine-tuning a GPT-2 model | [Aleksey Korshuk](https://github.com/AlekseyKorshuk) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/AlekseyKorshuk/huggingartists/blob/master/huggingartists-demo.ipynb) | +| [Train T5 in Tensorflow 2](https://github.com/snapthat/TF-T5-text-to-text) | How to train T5 for any task using Tensorflow 2. This notebook demonstrates a Question & Answer task implemented in Tensorflow 2 using SQUAD | [Muhammad Harris](https://github.com/HarrisDePerceptron) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/snapthat/TF-T5-text-to-text/blob/master/snapthatT5/notebooks/TF-T5-Datasets%20Training.ipynb) | +| [Train T5 on TPU](https://github.com/patil-suraj/exploring-T5/blob/master/T5_on_TPU.ipynb) | How to train T5 on SQUAD with Transformers and Nlp | [Suraj Patil](https://github.com/patil-suraj) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patil-suraj/exploring-T5/blob/master/T5_on_TPU.ipynb#scrollTo=QLGiFCDqvuil) | +| [Fine-tune T5 for Classification and Multiple Choice](https://github.com/patil-suraj/exploring-T5/blob/master/t5_fine_tuning.ipynb) | How to fine-tune T5 for classification and multiple choice tasks using a text-to-text format with PyTorch Lightning | [Suraj Patil](https://github.com/patil-suraj) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patil-suraj/exploring-T5/blob/master/t5_fine_tuning.ipynb) | +| [Fine-tune DialoGPT on New Datasets and Languages](https://github.com/ncoop57/i-am-a-nerd/blob/master/_notebooks/2020-05-12-chatbot-part-1.ipynb) | How to fine-tune the DialoGPT model on a new dataset for open-dialog conversational chatbots | [Nathan Cooper](https://github.com/ncoop57) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/ncoop57/i-am-a-nerd/blob/master/_notebooks/2020-05-12-chatbot-part-1.ipynb) | +| [Long Sequence Modeling with Reformer](https://github.com/patrickvonplaten/notebooks/blob/master/PyTorch_Reformer.ipynb) | How to train on sequences as long as 500,000 tokens with Reformer | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/PyTorch_Reformer.ipynb) | +| [Fine-tune BART for Summarization](https://github.com/ohmeow/ohmeow_website/blob/master/posts/2021-05-25-mbart-sequence-classification-with-blurr.ipynb) | How to fine-tune BART for summarization with fastai using blurr | [Wayde Gilliam](https://ohmeow.com/) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/ohmeow/ohmeow_website/blob/master/posts/2021-05-25-mbart-sequence-classification-with-blurr.ipynb) | +| [Fine-tune a pre-trained Transformer on anyone's tweets](https://colab.research.google.com/github/borisdayma/huggingtweets/blob/master/huggingtweets-demo.ipynb) | How to generate tweets in the style of your favorite Twitter account by fine-tuning a GPT-2 model | [Boris Dayma](https://github.com/borisdayma) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/borisdayma/huggingtweets/blob/master/huggingtweets-demo.ipynb) | +| [Optimize 🤗 Hugging Face models with Weights & Biases](https://colab.research.google.com/github/wandb/examples/blob/master/colabs/huggingface/Optimize_Hugging_Face_models_with_Weights_%26_Biases.ipynb) | A complete tutorial showcasing W&B integration with Hugging Face | [Boris Dayma](https://github.com/borisdayma) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/wandb/examples/blob/master/colabs/huggingface/Optimize_Hugging_Face_models_with_Weights_%26_Biases.ipynb) | +| [Pretrain Longformer](https://github.com/allenai/longformer/blob/master/scripts/convert_model_to_long.ipynb) | How to build a "long" version of existing pretrained models | [Iz Beltagy](https://beltagy.net) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/allenai/longformer/blob/master/scripts/convert_model_to_long.ipynb) | +| [Fine-tune Longformer for QA](https://github.com/patil-suraj/Notebooks/blob/master/longformer_qa_training.ipynb) | How to fine-tune longformer model for QA task | [Suraj Patil](https://github.com/patil-suraj) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patil-suraj/Notebooks/blob/master/longformer_qa_training.ipynb) | +| [Evaluate Model with 🤗nlp](https://github.com/patrickvonplaten/notebooks/blob/master/How_to_evaluate_Longformer_on_TriviaQA_using_NLP.ipynb) | How to evaluate longformer on TriviaQA with `nlp` | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1m7eTGlPmLRgoPkkA7rkhQdZ9ydpmsdLE?usp=sharing) | +| [Fine-tune T5 for Sentiment Span Extraction](https://github.com/enzoampil/t5-intro/blob/master/t5_qa_training_pytorch_span_extraction.ipynb) | How to fine-tune T5 for sentiment span extraction using a text-to-text format with PyTorch Lightning | [Lorenzo Ampil](https://github.com/enzoampil) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/enzoampil/t5-intro/blob/master/t5_qa_training_pytorch_span_extraction.ipynb) | +| [Fine-tune DistilBert for Multiclass Classification](https://github.com/abhimishra91/transformers-tutorials/blob/master/transformers_multiclass_classification.ipynb) | How to fine-tune DistilBert for multiclass classification with PyTorch | [Abhishek Kumar Mishra](https://github.com/abhimishra91) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/abhimishra91/transformers-tutorials/blob/master/transformers_multiclass_classification.ipynb)| +|[Fine-tune BERT for Multi-label Classification](https://github.com/abhimishra91/transformers-tutorials/blob/master/transformers_multi_label_classification.ipynb)|How to fine-tune BERT for multi-label classification using PyTorch|[Abhishek Kumar Mishra](https://github.com/abhimishra91) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/abhimishra91/transformers-tutorials/blob/master/transformers_multi_label_classification.ipynb)| +|[Fine-tune T5 for Summarization](https://github.com/abhimishra91/transformers-tutorials/blob/master/transformers_summarization_wandb.ipynb)|How to fine-tune T5 for summarization in PyTorch and track experiments with WandB|[Abhishek Kumar Mishra](https://github.com/abhimishra91) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/abhimishra91/transformers-tutorials/blob/master/transformers_summarization_wandb.ipynb)| +|[Speed up Fine-Tuning in Transformers with Dynamic Padding / Bucketing](https://github.com/ELS-RD/transformers-notebook/blob/master/Divide_Hugging_Face_Transformers_training_time_by_2_or_more.ipynb)|How to speed up fine-tuning by a factor of 2 using dynamic padding / bucketing|[Michael Benesty](https://github.com/pommedeterresautee) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1CBfRU1zbfu7-ijiOqAAQUA-RJaxfcJoO?usp=sharing)| +|[Pretrain Reformer for Masked Language Modeling](https://github.com/patrickvonplaten/notebooks/blob/master/Reformer_For_Masked_LM.ipynb)| How to train a Reformer model with bi-directional self-attention layers | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1tzzh0i8PgDQGV3SMFUGxM7_gGae3K-uW?usp=sharing)| +|[Expand and Fine Tune Sci-BERT](https://github.com/lordtt13/word-embeddings/blob/master/COVID-19%20Research%20Data/COVID-SciBERT.ipynb)| How to increase vocabulary of a pretrained SciBERT model from AllenAI on the CORD dataset and pipeline it. | [Tanmay Thakur](https://github.com/lordtt13) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1rqAR40goxbAfez1xvF3hBJphSCsvXmh8)| +|[Fine Tune BlenderBotSmall for Summarization using the Trainer API](https://github.com/lordtt13/transformers-experiments/blob/master/Custom%20Tasks/fine-tune-blenderbot_small-for-summarization.ipynb)| How to fine-tune BlenderBotSmall for summarization on a custom dataset, using the Trainer API. | [Tanmay Thakur](https://github.com/lordtt13) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/19Wmupuls7mykSGyRN_Qo6lPQhgp56ymq?usp=sharing)| +|[Fine-tune Electra and interpret with Integrated Gradients](https://github.com/elsanns/xai-nlp-notebooks/blob/master/electra_fine_tune_interpret_captum_ig.ipynb) | How to fine-tune Electra for sentiment analysis and interpret predictions with Captum Integrated Gradients | [Eliza Szczechla](https://elsanns.github.io) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/elsanns/xai-nlp-notebooks/blob/master/electra_fine_tune_interpret_captum_ig.ipynb)| +|[fine-tune a non-English GPT-2 Model with Trainer class](https://github.com/philschmid/fine-tune-GPT-2/blob/master/Fine_tune_a_non_English_GPT_2_Model_with_Huggingface.ipynb) | How to fine-tune a non-English GPT-2 Model with Trainer class | [Philipp Schmid](https://www.philschmid.de) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/philschmid/fine-tune-GPT-2/blob/master/Fine_tune_a_non_English_GPT_2_Model_with_Huggingface.ipynb)| +|[Fine-tune a DistilBERT Model for Multi Label Classification task](https://github.com/DhavalTaunk08/Transformers_scripts/blob/master/Transformers_multilabel_distilbert.ipynb) | How to fine-tune a DistilBERT Model for Multi Label Classification task | [Dhaval Taunk](https://github.com/DhavalTaunk08) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/DhavalTaunk08/Transformers_scripts/blob/master/Transformers_multilabel_distilbert.ipynb)| +|[Fine-tune ALBERT for sentence-pair classification](https://github.com/NadirEM/nlp-notebooks/blob/master/Fine_tune_ALBERT_sentence_pair_classification.ipynb) | How to fine-tune an ALBERT model or another BERT-based model for the sentence-pair classification task | [Nadir El Manouzi](https://github.com/NadirEM) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NadirEM/nlp-notebooks/blob/master/Fine_tune_ALBERT_sentence_pair_classification.ipynb)| +|[Fine-tune Roberta for sentiment analysis](https://github.com/DhavalTaunk08/NLP_scripts/blob/master/sentiment_analysis_using_roberta.ipynb) | How to fine-tune a Roberta model for sentiment analysis | [Dhaval Taunk](https://github.com/DhavalTaunk08) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/DhavalTaunk08/NLP_scripts/blob/master/sentiment_analysis_using_roberta.ipynb)| +|[Evaluating Question Generation Models](https://github.com/flexudy-pipe/qugeev) | How accurate are the answers to questions generated by your seq2seq transformer model? | [Pascal Zoleko](https://github.com/zolekode) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1bpsSqCQU-iw_5nNoRm_crPq6FRuJthq_?usp=sharing)| +|[Classify text with DistilBERT and Tensorflow](https://github.com/peterbayerle/huggingface_notebook/blob/main/distilbert_tf.ipynb) | How to fine-tune DistilBERT for text classification in TensorFlow | [Peter Bayerle](https://github.com/peterbayerle) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/peterbayerle/huggingface_notebook/blob/main/distilbert_tf.ipynb)| +|[Leverage BERT for Encoder-Decoder Summarization on CNN/Dailymail](https://github.com/patrickvonplaten/notebooks/blob/master/BERT2BERT_for_CNN_Dailymail.ipynb) | How to warm-start a *EncoderDecoderModel* with a *google-bert/bert-base-uncased* checkpoint for summarization on CNN/Dailymail | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/BERT2BERT_for_CNN_Dailymail.ipynb)| +|[Leverage RoBERTa for Encoder-Decoder Summarization on BBC XSum](https://github.com/patrickvonplaten/notebooks/blob/master/RoBERTaShared_for_BBC_XSum.ipynb) | How to warm-start a shared *EncoderDecoderModel* with a *FacebookAI/roberta-base* checkpoint for summarization on BBC/XSum | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/RoBERTaShared_for_BBC_XSum.ipynb)| +|[Fine-tune TAPAS on Sequential Question Answering (SQA)](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/TAPAS/Fine_tuning_TapasForQuestionAnswering_on_SQA.ipynb) | How to fine-tune *TapasForQuestionAnswering* with a *tapas-base* checkpoint on the Sequential Question Answering (SQA) dataset | [Niels Rogge](https://github.com/nielsrogge) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/TAPAS/Fine_tuning_TapasForQuestionAnswering_on_SQA.ipynb)| +|[Evaluate TAPAS on Table Fact Checking (TabFact)](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/TAPAS/Evaluating_TAPAS_on_the_Tabfact_test_set.ipynb) | How to evaluate a fine-tuned *TapasForSequenceClassification* with a *tapas-base-finetuned-tabfact* checkpoint using a combination of the 🤗 datasets and 🤗 transformers libraries | [Niels Rogge](https://github.com/nielsrogge) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/TAPAS/Evaluating_TAPAS_on_the_Tabfact_test_set.ipynb)| +|[Fine-tuning mBART for translation](https://colab.research.google.com/github/vasudevgupta7/huggingface-tutorials/blob/main/translation_training.ipynb) | How to fine-tune mBART using Seq2SeqTrainer for Hindi to English translation | [Vasudev Gupta](https://github.com/vasudevgupta7) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/vasudevgupta7/huggingface-tutorials/blob/main/translation_training.ipynb)| +|[Fine-tune LayoutLM on FUNSD (a form understanding dataset)](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/LayoutLM/Fine_tuning_LayoutLMForTokenClassification_on_FUNSD.ipynb) | How to fine-tune *LayoutLMForTokenClassification* on the FUNSD dataset for information extraction from scanned documents | [Niels Rogge](https://github.com/nielsrogge) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/LayoutLM/Fine_tuning_LayoutLMForTokenClassification_on_FUNSD.ipynb)| +|[Fine-Tune DistilGPT2 and Generate Text](https://colab.research.google.com/github/tripathiaakash/DistilGPT2-Tutorial/blob/main/distilgpt2_fine_tuning.ipynb) | How to fine-tune DistilGPT2 and generate text | [Aakash Tripathi](https://github.com/tripathiaakash) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/tripathiaakash/DistilGPT2-Tutorial/blob/main/distilgpt2_fine_tuning.ipynb)| +|[Fine-Tune LED on up to 8K tokens](https://github.com/patrickvonplaten/notebooks/blob/master/Fine_tune_Longformer_Encoder_Decoder_(LED)_for_Summarization_on_pubmed.ipynb) | How to fine-tune LED on pubmed for long-range summarization | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/Fine_tune_Longformer_Encoder_Decoder_(LED)_for_Summarization_on_pubmed.ipynb)| +|[Evaluate LED on Arxiv](https://github.com/patrickvonplaten/notebooks/blob/master/LED_on_Arxiv.ipynb) | How to effectively evaluate LED on long-range summarization | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/LED_on_Arxiv.ipynb)| +|[Fine-tune LayoutLM on RVL-CDIP (a document image classification dataset)](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/LayoutLM/Fine_tuning_LayoutLMForSequenceClassification_on_RVL_CDIP.ipynb) | How to fine-tune *LayoutLMForSequenceClassification* on the RVL-CDIP dataset for scanned document classification | [Niels Rogge](https://github.com/nielsrogge) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/LayoutLM/Fine_tuning_LayoutLMForSequenceClassification_on_RVL_CDIP.ipynb)| +|[Wav2Vec2 CTC decoding with GPT2 adjustment](https://github.com/voidful/huggingface_notebook/blob/main/xlsr_gpt.ipynb) | How to decode CTC sequence with language model adjustment | [Eric Lam](https://github.com/voidful) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1e_z5jQHYbO2YKEaUgzb1ww1WwiAyydAj?usp=sharing)| +|[Fine-tune BART for summarization in two languages with Trainer class](https://github.com/elsanns/xai-nlp-notebooks/blob/master/fine_tune_bart_summarization_two_langs.ipynb) | How to fine-tune BART for summarization in two languages with Trainer class | [Eliza Szczechla](https://github.com/elsanns) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/elsanns/xai-nlp-notebooks/blob/master/fine_tune_bart_summarization_two_langs.ipynb)| +|[Evaluate Big Bird on Trivia QA](https://github.com/patrickvonplaten/notebooks/blob/master/Evaluating_Big_Bird_on_TriviaQA.ipynb) | How to evaluate BigBird on long document question answering on Trivia QA | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/Evaluating_Big_Bird_on_TriviaQA.ipynb)| +| [Create video captions using Wav2Vec2](https://github.com/Muennighoff/ytclipcc/blob/main/wav2vec_youtube_captions.ipynb) | How to create YouTube captions from any video by transcribing the audio with Wav2Vec | [Niklas Muennighoff](https://github.com/Muennighoff) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Muennighoff/ytclipcc/blob/main/wav2vec_youtube_captions.ipynb) | +| [Fine-tune the Vision Transformer on CIFAR-10 using PyTorch Lightning](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/VisionTransformer/Fine_tuning_the_Vision_Transformer_on_CIFAR_10_with_PyTorch_Lightning.ipynb) | How to fine-tune the Vision Transformer (ViT) on CIFAR-10 using HuggingFace Transformers, Datasets and PyTorch Lightning | [Niels Rogge](https://github.com/nielsrogge) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/VisionTransformer/Fine_tuning_the_Vision_Transformer_on_CIFAR_10_with_PyTorch_Lightning.ipynb) | +| [Fine-tune the Vision Transformer on CIFAR-10 using the 🤗 Trainer](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/VisionTransformer/Fine_tuning_the_Vision_Transformer_on_CIFAR_10_with_the_%F0%9F%A4%97_Trainer.ipynb) | How to fine-tune the Vision Transformer (ViT) on CIFAR-10 using HuggingFace Transformers, Datasets and the 🤗 Trainer | [Niels Rogge](https://github.com/nielsrogge) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/VisionTransformer/Fine_tuning_the_Vision_Transformer_on_CIFAR_10_with_the_%F0%9F%A4%97_Trainer.ipynb) | +| [Evaluate LUKE on Open Entity, an entity typing dataset](https://github.com/studio-ousia/luke/blob/master/notebooks/huggingface_open_entity.ipynb) | How to evaluate *LukeForEntityClassification* on the Open Entity dataset | [Ikuya Yamada](https://github.com/ikuyamada) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/studio-ousia/luke/blob/master/notebooks/huggingface_open_entity.ipynb) | +| [Evaluate LUKE on TACRED, a relation extraction dataset](https://github.com/studio-ousia/luke/blob/master/notebooks/huggingface_tacred.ipynb) | How to evaluate *LukeForEntityPairClassification* on the TACRED dataset | [Ikuya Yamada](https://github.com/ikuyamada) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/studio-ousia/luke/blob/master/notebooks/huggingface_tacred.ipynb) | +| [Evaluate LUKE on CoNLL-2003, an important NER benchmark](https://github.com/studio-ousia/luke/blob/master/notebooks/huggingface_conll_2003.ipynb) | How to evaluate *LukeForEntitySpanClassification* on the CoNLL-2003 dataset | [Ikuya Yamada](https://github.com/ikuyamada) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/studio-ousia/luke/blob/master/notebooks/huggingface_conll_2003.ipynb) | +| [Evaluate BigBird-Pegasus on PubMed dataset](https://github.com/vasudevgupta7/bigbird/blob/main/notebooks/bigbird_pegasus_evaluation.ipynb) | How to evaluate *BigBirdPegasusForConditionalGeneration* on PubMed dataset | [Vasudev Gupta](https://github.com/vasudevgupta7) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/vasudevgupta7/bigbird/blob/main/notebooks/bigbird_pegasus_evaluation.ipynb) | +| [Speech Emotion Classification with Wav2Vec2](https://github.com/m3hrdadfi/soxan/blob/main/notebooks/Emotion_recognition_in_Greek_speech_using_Wav2Vec2.ipynb) | How to leverage a pretrained Wav2Vec2 model for Emotion Classification on the MEGA dataset | [Mehrdad Farahani](https://github.com/m3hrdadfi) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/m3hrdadfi/soxan/blob/main/notebooks/Emotion_recognition_in_Greek_speech_using_Wav2Vec2.ipynb) | +| [Detect objects in an image with DETR](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/DETR/DETR_minimal_example_(with_DetrFeatureExtractor).ipynb) | How to use a trained *DetrForObjectDetection* model to detect objects in an image and visualize attention | [Niels Rogge](https://github.com/NielsRogge) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/DETR/DETR_minimal_example_(with_DetrFeatureExtractor).ipynb) | +| [Fine-tune DETR on a custom object detection dataset](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/DETR/Fine_tuning_DetrForObjectDetection_on_custom_dataset_(balloon).ipynb) | How to fine-tune *DetrForObjectDetection* on a custom object detection dataset | [Niels Rogge](https://github.com/NielsRogge) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/DETR/Fine_tuning_DetrForObjectDetection_on_custom_dataset_(balloon).ipynb) | +| [Finetune T5 for Named Entity Recognition](https://github.com/ToluClassics/Notebooks/blob/main/T5_Ner_Finetuning.ipynb) | How to fine-tune *T5* on a Named Entity Recognition Task | [Ogundepo Odunayo](https://github.com/ToluClassics) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1obr78FY_cBmWY5ODViCmzdY6O1KB65Vc?usp=sharing) | +| [Fine-Tuning Open-Source LLM using QLoRA with MLflow and PEFT](https://github.com/mlflow/mlflow/blob/master/docs/source/llms/transformers/tutorials/fine-tuning/transformers-peft.ipynb) | How to use [QLoRA](https://github.com/artidoro/qlora) and [PEFT](https://huggingface.co/docs/peft/en/index) to fine-tune an LLM in a memory-efficient way, while using [MLflow](https://mlflow.org/docs/latest/llms/transformers/index.html) to manage experiment tracking | [Yuki Watanabe](https://github.com/B-Step62) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/mlflow/mlflow/blob/master/docs/source/llms/transformers/tutorials/fine-tuning/transformers-peft.ipynb) | diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/contributing.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/contributing.md new file mode 100644 index 0000000000000000000000000000000000000000..5a9e52fd622c281f57c00f8b3fe6cfdedd8594f0 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/contributing.md @@ -0,0 +1,395 @@ + + +# Contribute to 🤗 Transformers + +Everyone is welcome to contribute, and we value everybody's contribution. Code +contributions are not the only way to help the community. Answering questions, helping +others, and improving the documentation are also immensely valuable. + +It also helps us if you spread the word! Reference the library in blog posts +about the awesome projects it made possible, shout out on Twitter every time it has +helped you, or simply ⭐️ the repository to say thank you. + +However you choose to contribute, please be mindful and respect our +[code of conduct](https://github.com/huggingface/transformers/blob/main/CODE_OF_CONDUCT.md). + +**This guide was heavily inspired by the awesome [scikit-learn guide to contributing](https://github.com/scikit-learn/scikit-learn/blob/main/CONTRIBUTING.md).** + +## Ways to contribute + +There are several ways you can contribute to 🤗 Transformers: + +* Fix outstanding issues with the existing code. +* Submit issues related to bugs or desired new features. +* Implement new models. +* Contribute to the examples or to the documentation. + +If you don't know where to start, there is a special [Good First +Issue](https://github.com/huggingface/transformers/contribute) listing. It will give you a list of +open issues that are beginner-friendly and help you start contributing to open-source. The best way to do that is to open a Pull Request and link it to the issue that you'd like to work on. We try to give priority to opened PRs as we can easily track the progress of the fix, and if the contributor does not have time anymore, someone else can take the PR over. + +For something slightly more challenging, you can also take a look at the [Good Second Issue](https://github.com/huggingface/transformers/labels/Good%20Second%20Issue) list. In general though, if you feel like you know what you're doing, go for it and we'll help you get there! 🚀 + +> All contributions are equally valuable to the community. 🥰 + +## Fixing outstanding issues + +If you notice an issue with the existing code and have a fix in mind, feel free to [start contributing](#create-a-pull-request) and open a Pull Request! + +## Submitting a bug-related issue or feature request + +Do your best to follow these guidelines when submitting a bug-related issue or a feature +request. It will make it easier for us to come back to you quickly and with good +feedback. + +### Did you find a bug? + +The 🤗 Transformers library is robust and reliable thanks to users who report the problems they encounter. + +Before you report an issue, we would really appreciate it if you could **make sure the bug was not +already reported** (use the search bar on GitHub under Issues). Your issue should also be related to bugs in the library itself, and not your code. If you're unsure whether the bug is in your code or the library, please ask in the [forum](https://discuss.huggingface.co/) or on our [discord](https://discord.com/invite/hugging-face-879548962464493619) first. This helps us respond quicker to fixing issues related to the library versus general questions. + +> [!TIP] +> We have a [docs bot](https://huggingface.co/spaces/huggingchat/hf-docs-chat), and we highly encourage you to ask all your questions there. There is always a chance your bug can be fixed with a simple flag 👾🔫 + +Once you've confirmed the bug hasn't already been reported, please include the following information in your issue so we can quickly resolve it: + +* Your **OS type and version** and **Python**, **PyTorch** and + **TensorFlow** versions when applicable. +* A short, self-contained, code snippet that allows us to reproduce the bug in + less than 30s. +* The *full* traceback if an exception is raised. +* Attach any other additional information, like screenshots, you think may help. + +To get the OS and software versions automatically, run the following command: + +```bash +transformers env +``` + +You can also run the same command from the root of the repository: + +```bash +python src/transformers/commands/transformers_cli.py env +``` + +### Do you want a new feature? + +If there is a new feature you'd like to see in 🤗 Transformers, please open an issue and describe: + +1. What is the *motivation* behind this feature? Is it related to a problem or frustration with the library? Is it a feature related to something you need for a project? Is it something you worked on and think it could benefit the community? + + Whatever it is, we'd love to hear about it! + +2. Describe your requested feature in as much detail as possible. The more you can tell us about it, the better we'll be able to help you. +3. Provide a *code snippet* that demonstrates the features usage. +4. If the feature is related to a paper, please include a link. + +If your issue is well written we're already 80% of the way there by the time you create it. + +We have added [templates](https://github.com/huggingface/transformers/tree/main/templates) to help you get started with your issue. + +## Do you want to implement a new model? + +New models are constantly released and if you want to implement a new model, please provide the following information: + +* A short description of the model and a link to the paper. +* Link to the implementation if it is open-sourced. +* Link to the model weights if they are available. + +If you are willing to contribute the model yourself, let us know so we can help you add it to 🤗 Transformers! + +We have a technical guide for [how to add a model to 🤗 Transformers](https://huggingface.co/docs/transformers/add_new_model). + +## Do you want to add documentation? + +We're always looking for improvements to the documentation that make it more clear and accurate. Please let us know how the documentation can be improved such as typos and any content that is missing, unclear or inaccurate. We'll be happy to make the changes or help you make a contribution if you're interested! + +For more details about how to generate, build, and write the documentation, take a look at the documentation [README](https://github.com/huggingface/transformers/tree/main/docs). + +## Create a Pull Request + +Before writing any code, we strongly advise you to search through the existing PRs or +issues to make sure nobody is already working on the same thing. If you are +unsure, it is always a good idea to open an issue to get some feedback. + +You will need basic `git` proficiency to contribute to +🤗 Transformers. While `git` is not the easiest tool to use, it has the greatest +manual. Type `git --help` in a shell and enjoy! If you prefer books, [Pro +Git](https://git-scm.com/book/en/v2) is a very good reference. + +You'll need **[Python 3.9](https://github.com/huggingface/transformers/blob/main/setup.py#L449)** or above to contribute to 🤗 Transformers. Follow the steps below to start contributing: + +1. Fork the [repository](https://github.com/huggingface/transformers) by + clicking on the **[Fork](https://github.com/huggingface/transformers/fork)** button on the repository's page. This creates a copy of the code + under your GitHub user account. + +2. Clone your fork to your local disk, and add the base repository as a remote: + + ```bash + git clone git@github.com:/transformers.git + cd transformers + git remote add upstream https://github.com/huggingface/transformers.git + ``` + +3. Create a new branch to hold your development changes: + + ```bash + git checkout -b a-descriptive-name-for-my-changes + ``` + + 🚨 **Do not** work on the `main` branch! + +4. Set up a development environment by running the following command in a virtual environment: + + ```bash + pip install -e ".[dev]" + ``` + + If 🤗 Transformers was already installed in the virtual environment, remove + it with `pip uninstall transformers` before reinstalling it in editable + mode with the `-e` flag. + + Depending on your OS, and since the number of optional dependencies of Transformers is growing, you might get a + failure with this command. If that's the case make sure to install the Deep Learning framework you are working with + (PyTorch, TensorFlow and/or Flax) then do: + + ```bash + pip install -e ".[quality]" + ``` + + which should be enough for most use cases. + +5. Develop the features in your branch. + + As you work on your code, you should make sure the test suite + passes. Run the tests impacted by your changes like this: + + ```bash + pytest tests/.py + ``` + + For more information about tests, check out the + [Testing](https://huggingface.co/docs/transformers/testing) guide. + + 🤗 Transformers relies on `black` and `ruff` to format its source code + consistently. After you make changes, apply automatic style corrections and code verifications + that can't be automated in one go with: + + ```bash + make fixup + ``` + + This target is also optimized to only work with files modified by the PR you're working on. + + If you prefer to run the checks one after the other, the following command applies the + style corrections: + + ```bash + make style + ``` + + 🤗 Transformers also uses `ruff` and a few custom scripts to check for coding mistakes. Quality + controls are run by the CI, but you can run the same checks with: + + ```bash + make quality + ``` + + Finally, we have a lot of scripts to make sure we don't forget to update + some files when adding a new model. You can run these scripts with: + + ```bash + make repo-consistency + ``` + + To learn more about those checks and how to fix any issues with them, check out the + [Checks on a Pull Request](https://huggingface.co/docs/transformers/pr_checks) guide. + + If you're modifying documents under the `docs/source` directory, make sure the documentation can still be built. This check will also run in the CI when you open a pull request. To run a local check + make sure you install the [documentation builder](https://github.com/huggingface/doc-builder). + + ```bash + pip install hf-doc-builder + ``` + + Run the following command from the root of the repository: + + ```bash + doc-builder build transformers docs/source/en --build_dir ~/tmp/test-build + ``` + + This will build the documentation in the `~/tmp/test-build` folder where you can inspect the generated + Markdown files with your favorite editor. You can also preview the docs on GitHub when you open a pull request. + + Once you're happy with your changes, add the changed files with `git add` and + record your changes locally with `git commit`: + + ```bash + git add modified_file.py + git commit + ``` + + Please remember to write [good commit + messages](https://chris.beams.io/posts/git-commit/) to clearly communicate the changes you made! + + To keep your copy of the code up to date with the original + repository, rebase your branch on `upstream/branch` *before* you open a pull request or if requested by a maintainer: + + ```bash + git fetch upstream + git rebase upstream/main + ``` + + Push your changes to your branch: + + ```bash + git push -u origin a-descriptive-name-for-my-changes + ``` + + If you've already opened a pull request, you'll need to force push with the `--force` flag. Otherwise, if the pull request hasn't been opened yet, you can just push your changes normally. + +6. Now you can go to your fork of the repository on GitHub and click on **Pull Request** to open a pull request. Make sure you tick off all the boxes on our [checklist](#pull-request-checklist) below. When you're ready, you can send your changes to the project maintainers for review. + +7. It's ok if maintainers request changes, it happens to our core contributors + too! So everyone can see the changes in the pull request, work in your local + branch and push the changes to your fork. They will automatically appear in + the pull request. + +### Pull request checklist + +☐ The pull request title should summarize your contribution.
+☐ If your pull request addresses an issue, please mention the issue number in the pull +request description to make sure they are linked (and people viewing the issue know you +are working on it).
+☐ To indicate a work in progress please prefix the title with `[WIP]`. These are +useful to avoid duplicated work, and to differentiate it from PRs ready to be merged.
+☐ Make sure existing tests pass.
+☐ If adding a new feature, also add tests for it.
+ - If you are adding a new model, make sure you use + `ModelTester.all_model_classes = (MyModel, MyModelWithLMHead,...)` to trigger the common tests. + - If you are adding new `@slow` tests, make sure they pass using + `RUN_SLOW=1 python -m pytest tests/models/my_new_model/test_my_new_model.py`. + - If you are adding a new tokenizer, write tests and make sure + `RUN_SLOW=1 python -m pytest tests/models/{your_model_name}/test_tokenization_{your_model_name}.py` passes. + - CircleCI does not run the slow tests, but GitHub Actions does every night!
+ +☐ All public methods must have informative docstrings (see +[`modeling_bert.py`](https://github.com/huggingface/transformers/blob/main/src/transformers/models/bert/modeling_bert.py) +for an example).
+☐ Due to the rapidly growing repository, don't add any images, videos and other +non-text files that'll significantly weigh down the repository. Instead, use a Hub +repository such as [`hf-internal-testing`](https://huggingface.co/hf-internal-testing) +to host these files and reference them by URL. We recommend placing documentation +related images in the following repository: +[huggingface/documentation-images](https://huggingface.co/datasets/huggingface/documentation-images). +You can open a PR on this dataset repository and ask a Hugging Face member to merge it. + +For more information about the checks run on a pull request, take a look at our [Checks on a Pull Request](https://huggingface.co/docs/transformers/pr_checks) guide. + +### Tests + +An extensive test suite is included to test the library behavior and several examples. Library tests can be found in +the [tests](https://github.com/huggingface/transformers/tree/main/tests) folder and examples tests in the +[examples](https://github.com/huggingface/transformers/tree/main/examples) folder. + +We like `pytest` and `pytest-xdist` because it's faster. From the root of the +repository, specify a *path to a subfolder or a test file* to run the test: + +```bash +python -m pytest -n auto --dist=loadfile -s -v ./tests/models/my_new_model +``` + +Similarly, for the `examples` directory, specify a *path to a subfolder or test file* to run the test. For example, the following command tests the text classification subfolder in the PyTorch `examples` directory: + +```bash +pip install -r examples/xxx/requirements.txt # only needed the first time +python -m pytest -n auto --dist=loadfile -s -v ./examples/pytorch/text-classification +``` + +In fact, this is actually how our `make test` and `make test-examples` commands are implemented (not including the `pip install`)! + +You can also specify a smaller set of tests in order to test only the feature +you're working on. + +By default, slow tests are skipped but you can set the `RUN_SLOW` environment variable to +`yes` to run them. This will download many gigabytes of models so make sure you +have enough disk space, a good internet connection or a lot of patience! + + + +Remember to specify a *path to a subfolder or a test file* to run the test. Otherwise, you'll run all the tests in the `tests` or `examples` folder, which will take a very long time! + + + +```bash +RUN_SLOW=yes python -m pytest -n auto --dist=loadfile -s -v ./tests/models/my_new_model +RUN_SLOW=yes python -m pytest -n auto --dist=loadfile -s -v ./examples/pytorch/text-classification +``` + +Like the slow tests, there are other environment variables available which are not enabled by default during testing: +- `RUN_CUSTOM_TOKENIZERS`: Enables tests for custom tokenizers. + +More environment variables and additional information can be found in the [testing_utils.py](https://github.com/huggingface/transformers/blob/main/src/transformers/testing_utils.py). + +🤗 Transformers uses `pytest` as a test runner only. It doesn't use any +`pytest`-specific features in the test suite itself. + +This means `unittest` is fully supported. Here's how to run tests with +`unittest`: + +```bash +python -m unittest discover -s tests -t . -v +python -m unittest discover -s examples -t examples -v +``` + +### Style guide + +For documentation strings, 🤗 Transformers follows the [Google Python Style Guide](https://google.github.io/styleguide/pyguide.html). +Check our [documentation writing guide](https://github.com/huggingface/transformers/tree/main/docs#writing-documentation---specification) +for more information. + +### Develop on Windows + +On Windows (unless you're working in [Windows Subsystem for Linux](https://learn.microsoft.com/en-us/windows/wsl/) or WSL), you need to configure git to transform Windows `CRLF` line endings to Linux `LF` line endings: + +```bash +git config core.autocrlf input +``` + +One way to run the `make` command on Windows is with MSYS2: + +1. [Download MSYS2](https://www.msys2.org/), and we assume it's installed in `C:\msys64`. +2. Open the command line `C:\msys64\msys2.exe` (it should be available from the **Start** menu). +3. Run in the shell: `pacman -Syu` and install `make` with `pacman -S make`. +4. Add `C:\msys64\usr\bin` to your PATH environment variable. + +You can now use `make` from any terminal (PowerShell, cmd.exe, etc.)! 🎉 + +### Sync a forked repository with upstream main (the Hugging Face repository) + +When updating the main branch of a forked repository, please follow these steps to avoid pinging the upstream repository which adds reference notes to each upstream PR, and sends unnecessary notifications to the developers involved in these PRs. + +1. When possible, avoid syncing with the upstream using a branch and PR on the forked repository. Instead, merge directly into the forked main. +2. If a PR is absolutely necessary, use the following steps after checking out your branch: + + ```bash + git checkout -b your-branch-for-syncing + git pull --squash --no-commit upstream main + git commit -m '' + git push --set-upstream origin your-branch-for-syncing + ``` diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/conversations.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/conversations.md new file mode 100644 index 0000000000000000000000000000000000000000..4d416ef8fb407319ccd283fde8900b280a2dbaa1 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/conversations.md @@ -0,0 +1,161 @@ + + +# Chat basics + +Chat models are conversational models you can send and receive messages from. There are many chat models available to choose from, but in general, larger models tend to be better though that's not always the case. The model size is often included in the name, like "8B" or "70B", and it describes the number of parameters. Mixture-of-expert (MoE) models have names like "8x7B" or "141B-A35B" which means it's a 56B and 141B parameter model. You can try quantizing larger models to reduce memory requirements, otherwise you'll need ~2 bytes of memory per parameter. + +Check model leaderboards like [OpenLLM](https://hf.co/spaces/HuggingFaceH4/open_llm_leaderboard) and [LMSys Chatbot Arena](https://chat.lmsys.org/?leaderboard) to further help you identify the best chat models for your use case. Models that are specialized in certain domains (medical, legal text, non-English languages, etc.) may sometimes outperform larger general purpose models. + +> [!TIP] +> Chat with a number of open-source models for free on [HuggingChat](https://hf.co/chat/)! + +This guide shows you how to quickly start chatting with Transformers from the command line, how build and format a conversation, and how to chat using the [`TextGenerationPipeline`]. + +## chat CLI + +After you've [installed Transformers](./installation), chat with a model directly from the command line as shown below. It launches an interactive session with a model, with a few base commands listed at the start of the session. + +```bash +transformers chat Qwen/Qwen2.5-0.5B-Instruct +``` + +
+ +
+ +You can launch the CLI with arbitrary `generate` flags, with the format `arg_1=value_1 arg_2=value_2 ...` + +```bash +transformers chat Qwen/Qwen2.5-0.5B-Instruct do_sample=False max_new_tokens=10 +``` + +For a full list of options, run the command below. + +```bash +transformers chat -h +``` + +The chat is implemented on top of the [AutoClass](./model_doc/auto), using tooling from [text generation](./llm_tutorial) and [chat](./chat_templating). It uses the `transformers serve` CLI under the hood ([docs](./serving.md#serve-cli)). + + +## TextGenerationPipeline + +[`TextGenerationPipeline`] is a high-level text generation class with a "chat mode". Chat mode is enabled when a conversational model is detected and the chat prompt is [properly formatted](./llm_tutorial#wrong-prompt-format). + +To start, build a chat history with the following two roles. + +- `system` describes how the model should behave and respond when you're chatting with it. This role isn't supported by all chat models. +- `user` is where you enter your first message to the model. + +```py +chat = [ + {"role": "system", "content": "You are a sassy, wise-cracking robot as imagined by Hollywood circa 1986."}, + {"role": "user", "content": "Hey, can you tell me any fun things to do in New York?"} +] +``` + +Create the [`TextGenerationPipeline`] and pass `chat` to it. For large models, setting [device_map="auto"](./models#big-model-inference) helps load the model quicker and automatically places it on the fastest device available. Changing the data type to [torch.bfloat16](./models#model-data-type) also helps save memory. + +```py +import torch +from transformers import pipeline + +pipeline = pipeline(task="text-generation", model="meta-llama/Meta-Llama-3-8B-Instruct", torch_dtype=torch.bfloat16, device_map="auto") +response = pipeline(chat, max_new_tokens=512) +print(response[0]["generated_text"][-1]["content"]) +``` + +```txt +(sigh) Oh boy, you're asking me for advice? You're gonna need a map, pal! Alright, +alright, I'll give you the lowdown. But don't say I didn't warn you, I'm a robot, not a tour guide! + +So, you wanna know what's fun to do in the Big Apple? Well, let me tell you, there's a million +things to do, but I'll give you the highlights. First off, you gotta see the sights: the Statue of +Liberty, Central Park, Times Square... you know, the usual tourist traps. But if you're lookin' for +something a little more... unusual, I'd recommend checkin' out the Museum of Modern Art. It's got +some wild stuff, like that Warhol guy's soup cans and all that jazz. + +And if you're feelin' adventurous, take a walk across the Brooklyn Bridge. Just watch out for +those pesky pigeons, they're like little feathered thieves! (laughs) Get it? Thieves? Ah, never mind. + +Now, if you're lookin' for some serious fun, hit up the comedy clubs in Greenwich Village. You might +even catch a glimpse of some up-and-coming comedians... or a bunch of wannabes tryin' to make it big. (winks) + +And finally, if you're feelin' like a real New Yorker, grab a slice of pizza from one of the many amazing +pizzerias around the city. Just don't try to order a "robot-sized" slice, trust me, it won't end well. (laughs) + +So, there you have it, pal! That's my expert advice on what to do in New York. Now, if you'll +excuse me, I've got some oil changes to attend to. (winks) +``` + +Use the `append` method on `chat` to respond to the models message. + +```py +chat = response[0]["generated_text"] +chat.append( + {"role": "user", "content": "Wait, what's so wild about soup cans?"} +) +response = pipeline(chat, max_new_tokens=512) +print(response[0]["generated_text"][-1]["content"]) +``` + +```txt +(laughs) Oh, you're killin' me, pal! You don't get it, do you? Warhol's soup cans are like, art, man! +It's like, he took something totally mundane, like a can of soup, and turned it into a masterpiece. It's +like, "Hey, look at me, I'm a can of soup, but I'm also a work of art!" +(sarcastically) Oh, yeah, real original, Andy. + +But, you know, back in the '60s, it was like, a big deal. People were all about challenging the +status quo, and Warhol was like, the king of that. He took the ordinary and made it extraordinary. +And, let me tell you, it was like, a real game-changer. I mean, who would've thought that a can of soup could be art? (laughs) + +But, hey, you're not alone, pal. I mean, I'm a robot, and even I don't get it. (winks) +But, hey, that's what makes art, art, right? (laughs) +``` + +## Performance + +Transformers load models in full precision by default, and for a 8B model, this requires ~32GB of memory! Reduce memory usage by loading a model in half-precision or bfloat16 (only uses ~2 bytes per parameter). You can even quantize the model to a lower precision like 8-bit or 4-bit with [bitsandbytes](https://hf.co/docs/bitsandbytes/index). + +> [!TIP] +> Refer to the [Quantization](./quantization/overview) docs for more information about the different quantization backends available. + +Create a [`BitsAndBytesConfig`] with your desired quantization settings and pass it to the pipelines `model_kwargs` parameter. The example below quantizes a model to 8-bits. + +```py +from transformers import pipeline, BitsAndBytesConfig + +quantization_config = BitsAndBytesConfig(load_in_8bit=True) +pipeline = pipeline(task="text-generation", model="meta-llama/Meta-Llama-3-8B-Instruct", device_map="auto", model_kwargs={"quantization_config": quantization_config}) +``` + +In general, larger models are slower in addition to requiring more memory because text generation is bottlenecked by **memory bandwidth** instead of compute power. Each active parameter must be read from memory for every generated token. For a 16GB model, 16GB must be read from memory for every generated token. + +The number of generated tokens/sec is proportional to the total memory bandwidth of the system divided by the model size. Depending on your hardware, total memory bandwidth can vary. Refer to the table below for approximate generation speeds for different hardware types. + +| Hardware | Memory bandwidth | +|---|---| +| consumer CPU | 20-100GB/sec | +| specialized CPU (Intel Xeon, AMD Threadripper/Epyc, Apple silicon) | 200-900GB/sec | +| data center GPU (NVIDIA A100/H100) | 2-3TB/sec | + +The easiest solution for improving generation speed is to either quantize a model or use hardware with higher memory bandwidth. + +You can also try techniques like [speculative decoding](./generation_strategies#speculative-decoding), where a smaller model generates candidate tokens that are verified by the larger model. If the candidate tokens are correct, the larger model can generate more than one token per `forward` pass. This significantly alleviates the bandwidth bottleneck and improves generation speed. + +> [!TIP] +> Parameters may not be active for every generated token in MoE models such as [Mixtral](./model_doc/mixtral), [Qwen2MoE](./model_doc/qwen2_moe), and [DBRX](./model_doc/dbrx). As a result, MoE models generally have much lower memory bandwidth requirements and can be faster than a regular LLM of the same size. However, techniques like speculative decoding are ineffective with MoE models because parameters become activated with each new speculated token. diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/cursor.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/cursor.md new file mode 100644 index 0000000000000000000000000000000000000000..18ebe803edfbd16b21ccf8a06d95e136e400da24 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/cursor.md @@ -0,0 +1,42 @@ +# Using Cursor as a client of transformers serve + +This example shows how to use `transformers serve` as a local LLM provider for [Cursor](https://cursor.com/), the popular IDE. In this particular case, requests to `transformers serve` will come from an external IP (Cursor's server IPs), which requires some additional setup. Furthermore, some of Cursor's requests require [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS), which is disabled by default for security reasons. + +To launch a server with CORS enabled, run + +```shell +transformers serve --enable-cors +``` + +You'll also need to expose your server to external IPs. A potential solution is to use [`ngrok`](https://ngrok.com/), which has a permissive free tier. After setting up your `ngrok` account and authenticating on your server machine, you run + +```shell +ngrok http [port] +``` + +where `port` is the port used by `transformers serve` (`8000` by default). On the terminal where you launched `ngrok`, you'll see a https address in the "Forwarding" row, as in the image below. This is the address to send requests to. + +

+ +

+ +You're now ready to set things up on the app side! In Cursor, while you can't set a new provider, you can change the endpoint for OpenAI requests in the model selection settings. First, navigate to "Settings" > "Cursor Settings", "Models" tab, and expand the "API Keys" collapsible. To set your `transformers serve` endpoint, follow this order: +1. Unselect ALL models in the list above (e.g. `gpt4`, ...); +2. Add and select the model you want to use (e.g. `Qwen/Qwen3-4B`) +3. Add some random text to OpenAI API Key. This field won't be used, but it can’t be empty; +4. Add the https address from `ngrok` to the "Override OpenAI Base URL" field, appending `/v1` to the address (i.e. `https://(...).ngrok-free.app/v1`); +5. Hit "Verify". + +After you follow these steps, your "Models" tab should look like the image below. Your server should also have received a few requests from the verification step. + +

+ +

+ +You are now ready to use your local model in Cursor! For instance, if you toggle the AI Pane, you can select the model you added and ask it questions about your local files. + +

+ +

+ + diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/custom_models.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/custom_models.md new file mode 100644 index 0000000000000000000000000000000000000000..68afc91531fb34be290404a620a648a9765e96b4 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/custom_models.md @@ -0,0 +1,297 @@ + + +# Customizing models + +Transformers models are designed to be customizable. A models code is fully contained in the [model](https://github.com/huggingface/transformers/tree/main/src/transformers/models) subfolder of the Transformers repository. Each folder contains a `modeling.py` and a `configuration.py` file. Copy these files to start customizing a model. + +> [!TIP] +> It may be easier to start from scratch if you're creating an entirely new model. But for models that are very similar to an existing one in Transformers, it is faster to reuse or subclass the same configuration and model class. + +This guide will show you how to customize a ResNet model, enable [AutoClass](./models#autoclass) support, and share it on the Hub. + +## Configuration + +A configuration, given by the base [`PretrainedConfig`] class, contains all the necessary information to build a model. This is where you'll configure the attributes of the custom ResNet model. Different attributes gives different ResNet model types. + +The main rules for customizing a configuration are: + +1. A custom configuration must subclass [`PretrainedConfig`]. This ensures a custom model has all the functionality of a Transformers' model such as [`~PretrainedConfig.from_pretrained`], [`~PretrainedConfig.save_pretrained`], and [`~PretrainedConfig.push_to_hub`]. +2. The [`PretrainedConfig`] `__init__` must accept any `kwargs` and they must be passed to the superclass `__init__`. [`PretrainedConfig`] has more fields than the ones set in your custom configuration, so when you load a configuration with [`~PretrainedConfig.from_pretrained`], those fields need to be accepted by your configuration and passed to the superclass. + +> [!TIP] +> It is useful to check the validity of some of the parameters. In the example below, a check is implemented to ensure `block_type` and `stem_type` belong to one of the predefined values. +> +> Add `model_type` to the configuration class to enable [AutoClass](./models#autoclass) support. + +```py +from transformers import PretrainedConfig +from typing import List + +class ResnetConfig(PretrainedConfig): + model_type = "resnet" + + def __init__( + self, + block_type="bottleneck", + layers: list[int] = [3, 4, 6, 3], + num_classes: int = 1000, + input_channels: int = 3, + cardinality: int = 1, + base_width: int = 64, + stem_width: int = 64, + stem_type: str = "", + avg_down: bool = False, + **kwargs, + ): + if block_type not in ["basic", "bottleneck"]: + raise ValueError(f"`block_type` must be 'basic' or bottleneck', got {block_type}.") + if stem_type not in ["", "deep", "deep-tiered"]: + raise ValueError(f"`stem_type` must be '', 'deep' or 'deep-tiered', got {stem_type}.") + + self.block_type = block_type + self.layers = layers + self.num_classes = num_classes + self.input_channels = input_channels + self.cardinality = cardinality + self.base_width = base_width + self.stem_width = stem_width + self.stem_type = stem_type + self.avg_down = avg_down + super().__init__(**kwargs) +``` + +Save the configuration to a JSON file in your custom model folder, `custom-resnet`, with [`~PretrainedConfig.save_pretrained`]. + +```py +resnet50d_config = ResnetConfig(block_type="bottleneck", stem_width=32, stem_type="deep", avg_down=True) +resnet50d_config.save_pretrained("custom-resnet") +``` + +## Model + +With the custom ResNet configuration, you can now create and customize the model. The model subclasses the base [`PreTrainedModel`] class. Like [`PretrainedConfig`], inheriting from [`PreTrainedModel`] and initializing the superclass with the configuration extends Transformers' functionalities such as saving and loading to the custom model. + +Transformers' models follow the convention of accepting a `config` object in the `__init__` method. This passes the entire `config` to the model sublayers, instead of breaking the `config` object into multiple arguments that are individually passed to the sublayers. + +Writing models this way produces simpler code with a clear source of truth for any hyperparameters. It also makes it easier to reuse code from other Transformers' models. + +You'll create two ResNet models, a barebones ResNet model that outputs the hidden states and a ResNet model with an image classification head. + + + + +Define a mapping between the block types and classes. Everything else is created by passing the configuration class to the ResNet model class. + +> [!TIP] +> Add `config_class` to the model class to enable [AutoClass](#autoclass-support) support. + +```py +from transformers import PreTrainedModel +from timm.models.resnet import BasicBlock, Bottleneck, ResNet +from .configuration_resnet import ResnetConfig + +BLOCK_MAPPING = {"basic": BasicBlock, "bottleneck": Bottleneck} + +class ResnetModel(PreTrainedModel): + config_class = ResnetConfig + + def __init__(self, config): + super().__init__(config) + block_layer = BLOCK_MAPPING[config.block_type] + self.model = ResNet( + block_layer, + config.layers, + num_classes=config.num_classes, + in_chans=config.input_channels, + cardinality=config.cardinality, + base_width=config.base_width, + stem_width=config.stem_width, + stem_type=config.stem_type, + avg_down=config.avg_down, + ) + + def forward(self, tensor): + return self.model.forward_features(tensor) +``` + + + + +The `forward` method needs to be rewritten to calculate the loss for each logit if labels are available. Otherwise, the ResNet model class is the same. + +> [!TIP] +> Add `config_class` to the model class to enable [AutoClass](#autoclass-support) support. + +```py +import torch + +class ResnetModelForImageClassification(PreTrainedModel): + config_class = ResnetConfig + + def __init__(self, config): + super().__init__(config) + block_layer = BLOCK_MAPPING[config.block_type] + self.model = ResNet( + block_layer, + config.layers, + num_classes=config.num_classes, + in_chans=config.input_channels, + cardinality=config.cardinality, + base_width=config.base_width, + stem_width=config.stem_width, + stem_type=config.stem_type, + avg_down=config.avg_down, + ) + + def forward(self, tensor, labels=None): + logits = self.model(tensor) + if labels is not None: + loss = torch.nn.functional.cross_entropy(logits, labels) + return {"loss": loss, "logits": logits} + return {"logits": logits} +``` + + + + +A model can return any output format. Returning a dictionary (like `ResnetModelForImageClassification`) with losses when labels are available makes the custom model compatible with [`Trainer`]. For other output formats, you'll need your own training loop or a different library for training. + +Instantiate the custom model class with the configuration. + +```py +resnet50d = ResnetModelForImageClassification(resnet50d_config) +``` + +At this point, you can load pretrained weights into the model or train it from scratch. In this guide, you'll load pretrained weights. + +Load the pretrained weights from the [timm](https://hf.co/docs/timm/index) library, and then transfer those weights to the custom model with [load_state_dict](https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.load_state_dict). + +```py +import timm + +pretrained_model = timm.create_model("resnet50d", pretrained=True) +resnet50d.model.load_state_dict(pretrained_model.state_dict()) +``` + +## AutoClass + +The [AutoClass](./models#model-classes) API is a shortcut for automatically loading the correct architecture for a given model. It is convenient to enable this for users loading your custom model. + +Make sure you have the `model_type` attribute (must be different from existing model types) in the configuration class and `config_class` attribute in the model class. Use the [`~AutoConfig.register`] method to add the custom configuration and model to the [AutoClass](./models#model-classes) API. + +> [!TIP] +> The first argument to [`AutoConfig.register`] must match the `model_type` attribute in the custom configuration class, and the first argument to [`AutoModel.register`] must match the `config_class` of the custom model class. + +```py +from transformers import AutoConfig, AutoModel, AutoModelForImageClassification + +AutoConfig.register("resnet", ResnetConfig) +AutoModel.register(ResnetConfig, ResnetModel) +AutoModelForImageClassification.register(ResnetConfig, ResnetModelForImageClassification) +``` + +Your custom model code is now compatible with the [AutoClass](./models#autoclass) API. Users can load the model with the [AutoModel](./model_doc/auto#automodel) or [`AutoModelForImageClassification`] classes. + +## Upload + +Upload a custom model to the [Hub](https://hf.co/models) to allow other users to easily load and use it. + +Ensure the model directory is structured correctly as shown below. The directory should contain: + +- `modeling.py`: Contains the code for `ResnetModel` and `ResnetModelForImageClassification`. This file can rely on relative imports to other files as long as they're in the same directory. + +> [!WARNING] +> When copying a Transformers' model file, replace all relative imports at the top of the `modeling.py` file to import from Transformers instead. + +- `configuration.py`: Contains the code for `ResnetConfig`. +- `__init__.py`: Can be empty, this file allows Python `resnet_model` to be used as a module. + +```bash +. +└── resnet_model + ├── __init__.py + ├── configuration_resnet.py + └── modeling_resnet.py +``` + +To share the model, import the ResNet model and configuration. + +```py +from resnet_model.configuration_resnet import ResnetConfig +from resnet_model.modeling_resnet import ResnetModel, ResnetModelForImageClassification +``` + +Copy the code from the model and configuration files. To make sure the AutoClass objects are saved with [`~PreTrainedModel.save_pretrained`], call the [`~PretrainedConfig.register_for_auto_class`] method. This modifies the configuration JSON file to include the AutoClass objects and mapping. + +For a model, pick the appropriate `AutoModelFor` class based on the task. + +```py +ResnetConfig.register_for_auto_class() +ResnetModel.register_for_auto_class("AutoModel") +ResnetModelForImageClassification.register_for_auto_class("AutoModelForImageClassification") +``` + +To map more than one task to the model, edit `auto_map` in the configuration JSON file directly. + +```json +"auto_map": { + "AutoConfig": "--", + "AutoModel": "--", + "AutoModelFor": "--", +}, +``` + +Create the configuration and model and load pretrained weights into it. + +```py +resnet50d_config = ResnetConfig(block_type="bottleneck", stem_width=32, stem_type="deep", avg_down=True) +resnet50d = ResnetModelForImageClassification(resnet50d_config) + +pretrained_model = timm.create_model("resnet50d", pretrained=True) +resnet50d.model.load_state_dict(pretrained_model.state_dict()) +``` + +The model is ready to be pushed to the Hub now. Log in to your Hugging Face account from the command line or notebook. + + + + +```bash +hf auth login +``` + + + + +```py +from huggingface_hub import notebook_login + +notebook_login() +``` + + + + +Call [`~PreTrainedModel.push_to_hub`] on the model to upload the model to the Hub. + +```py +resnet50d.push_to_hub("custom-resnet50d") +``` + +The pretrained weights, configuration, `modeling.py` and `configuration.py` files should all be uploaded to the Hub now in a [repository](https://hf.co/sgugger/custom-resnet50d) under your namespace. + +Because a custom model doesn't use the same modeling code as a Transformers' model, you need to add `trust_remode_code=True` in [`~PreTrainedModel.from_pretrained`] to load it. Refer to the load [custom models](./models#custom-models) section for more information. diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/debugging.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/debugging.md new file mode 100644 index 0000000000000000000000000000000000000000..09394d2229d149a2e9300469573fd6ba29c1d938 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/debugging.md @@ -0,0 +1,367 @@ + + +# Multi-GPU debugging + +Distributed training can be tricky because you have to ensure you're using the correct CUDA version across your system. You may encounter inter-communication issues between GPUs, and there may be underflow or overflow problems in your model. + +This guide covers how to debug these issues, especially as it relates to DeepSpeed and PyTorch. + +## DeepSpeed CUDA + +DeepSpeed compiles CUDA C++ which can be a potential source of errors when building PyTorch extensions that require CUDA. These errors depend on how CUDA is installed on your system. This section focuses on PyTorch built with *CUDA 10.2* + +```bash +pip install deepspeed +``` + +> [!TIP] +> For any other installation issues, please [open an issue](https://github.com/microsoft/DeepSpeed/issues) with the DeepSpeed team. + +### Non-identical toolkits + +PyTorch comes with its own CUDA toolkit, but to use DeepSpeed with PyTorch, you need to have an identical version of CUDA installed system-wide. For example, if you installed PyTorch with `cudatoolkit==10.2` in your Python environment, then you'll also need to have CUDA 10.2 installed everywhere. + +The exact location can vary from system to system, but `usr/local/cuda-10.2` is the most common location on many Unix systems. When CUDA is correctly set up and added to your `PATH` environment variable, you can find the installation location with the following command. + +```bash +which nvcc +``` + +### Multiple toolkits + +You may also have more than one CUDA toolkit installed on your system. + +```bash +/usr/local/cuda-10.2 +/usr/local/cuda-11.0 +``` + +Typically, package installers set the paths to whatever the last version was installed. If the package build fails because it can't find the right CUDA version (despite it being installed already), then you need to configure the `PATH` and `LD_LIBRARY_PATH` environment variables to point to the correct path. + +Take a look at the contents of the following environment variables first. + +```bash +echo $PATH +echo $LD_LIBRARY_PATH +``` + +`PATH` lists the locations of the executables and `LD_LIBRARY_PATH` lists where to look for shared libraries. Earlier entries are prioritized over later ones, and `:` is used to separate multiple entries. To find a specific CUDA toolkit, insert the correct path to list first. This command prepends rather than overwrites the existing values. + +```bash +# adjust the version and full path if needed +export PATH=/usr/local/cuda-10.2/bin:$PATH +export LD_LIBRARY_PATH=/usr/local/cuda-10.2/lib64:$LD_LIBRARY_PATH +``` + +In addition, you should also check that the assigned directories actually exist. The `lib64` sub-directory contains various CUDA `.so` objects (like `libcudart.so`), and while it is unlikely your system names them differently, you should check the actual names and change them accordingly. + +### Older versions + +Sometimes, older CUDA versions may refuse to build with newer compilers. For example, if you have `gcc-9` but CUDA wants `gcc-7`. Usually, installing the latest CUDA toolkit enables support for the newer compiler. + +You could also install an older version of the compiler in addition to the one you're currently using (or it may already be installed but it's not used by default and the build system can't see it). To resolve this, create a symlink to give the build system visibility to the older compiler. + +```bash +# adjust the path to your system +sudo ln -s /usr/bin/gcc-7 /usr/local/cuda-10.2/bin/gcc +sudo ln -s /usr/bin/g++-7 /usr/local/cuda-10.2/bin/g++ +``` + +### Prebuild + +If you're still having issues with installing DeepSpeed or if you're building DeepSpeed at run time, try to prebuild the DeepSpeed modules before installing them. Run the commands below to make a local build for DeepSpeed. + +```bash +git clone https://github.com/deepspeedai/DeepSpeed/ +cd DeepSpeed +rm -rf build +TORCH_CUDA_ARCH_LIST="8.6" DS_BUILD_CPU_ADAM=1 DS_BUILD_UTILS=1 pip install . \ +--global-option="build_ext" --global-option="-j8" --no-cache -v \ +--disable-pip-version-check 2>&1 | tee build.log +``` + +> [!TIP] +> Add the `DS_BUILD_AIO=1` parameter to the build command to use NVMe offload. Make sure you install the libaio-dev package across your system. + +Next, specify your GPUs architecture by editing the `TORCH_CUDA_ARCH_LIST` variable (find a complete list of NVIDIA GPUs and their corresponding architectures on this [page](https://developer.nvidia.com/cuda-gpus)). To check the PyTorch version that corresponds to your architecture, run the following command. + +```bash +python -c "import torch; print(torch.cuda.get_arch_list())" +``` + +Find the architecture for a GPU with the following command. + + + + +```bash +CUDA_VISIBLE_DEVICES=0 python -c "import torch; print(torch.cuda.get_device_capability())" +``` + + + + +Run the following command to find the architecture for GPU `0`. The results will show a value for `major` and `minor`, which is your GPU architecture. The GPU architecture below is `8.6`. + +```bash +CUDA_VISIBLE_DEVICES=0 python -c "import torch; \ +print(torch.cuda.get_device_properties(torch.device('cuda'))) +"_CudaDeviceProperties(name='GeForce RTX 3090', major=8, minor=6, total_memory=24268MB, multi_processor_count=82)" +``` + + + + +If you get `8, 6`, then you can set `TORCH_CUDA_ARCH_LIST="8.6"`. For multiple GPUs with different architectures, list them like `TORCH_CUDA_ARCH_LIST="6.1;8.6"`. + +It is also possible to not specify `TORCH_CUDA_ARCH_LIST` and the build program automatically queries the GPU architecture of the build. However, it may or may not match the actual GPU on the target machine which is why it is better to explicitly specify the correct architecture. + +For training on multiple machines with the same setup, you'll need to make a binary wheel as shown below. + +```bash +git clone https://github.com/deepspeedai/DeepSpeed/ +cd DeepSpeed +rm -rf build +TORCH_CUDA_ARCH_LIST="8.6" DS_BUILD_CPU_ADAM=1 DS_BUILD_UTILS=1 \ +python setup.py build_ext -j8 bdist_wheel +``` + +This command generates a binary wheel that'll look something like `dist/deepspeed-0.3.13+8cd046f-cp38-cp38-linux_x86_64.whl`. Install this wheel locally or on another machine. + +```bash +pip install deepspeed-0.3.13+8cd046f-cp38-cp38-linux_x86_64.whl +``` + +## Communication + +Distributed training involves communication between processes and or nodes and this can be a potential source of errors. + +Download the script below to diagnose network issues, and then run it to test GPU communication. The example command below tests how two GPUs communicate. Adjust the `--nproc_per_node` and `--nnodes` parameters to adapt it to your system. + +```bash +wget https://raw.githubusercontent.com/huggingface/transformers/main/scripts/distributed/torch-distributed-gpu-test.py +python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py +``` + +The script prints an `OK` status if both GPUs are able to communicate and allocate memory. Take a closer look at the diagnostic script for more details and a recipe for running it in a SLURM environment. + +Add the `NCCL_DEBUG=INFO` environment variable to report more NCCL-related debugging information. + +```bash +NCCL_DEBUG=INFO python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py +``` + +## Underflow and overflow detection + +Underflow and overflow can occur when activations or weights are `inf`, `nan`, and when `loss=NaN`. This may indicate an underflow or overflow issue. To detect these issues, activate the `DebugUnderflowOverflow` module in [`TrainingArguments.debug`] or import and add the module to your own training loop or another trainer class. + + + + +```py +from transformers import TrainingArguments + +args = TrainingArguments( + debug="underflow_overflow", + ... +) +``` + + + + +```py +from transformers.debug_utils import DebugUnderflowOverflow + +debug_overflow = DebugUnderflowOverflow(model) +``` + + + + +The [`~debug_utils.DebugUnderflowOverflow`] module inserts hooks into the model to test the input and output variables and the corresponding model weights after each forward call. If `inf` or `nan` is detected in at least one element of the activations or weights, the module prints a report like the one shown below. + +The example below is for fp16 mixed precision training with [google/mt5-small](https://huggingface.co/google/mt5-small). + +```shell +Detected inf/nan during batch_number=0 +Last 21 forward frames: +abs min abs max metadata + encoder.block.1.layer.1.DenseReluDense.dropout Dropout +0.00e+00 2.57e+02 input[0] +0.00e+00 2.85e+02 output +[...] + encoder.block.2.layer.0 T5LayerSelfAttention +6.78e-04 3.15e+03 input[0] +2.65e-04 3.42e+03 output[0] + None output[1] +2.25e-01 1.00e+04 output[2] + encoder.block.2.layer.1.layer_norm T5LayerNorm +8.69e-02 4.18e-01 weight +2.65e-04 3.42e+03 input[0] +1.79e-06 4.65e+00 output + encoder.block.2.layer.1.DenseReluDense.wi_0 Linear +2.17e-07 4.50e+00 weight +1.79e-06 4.65e+00 input[0] +2.68e-06 3.70e+01 output + encoder.block.2.layer.1.DenseReluDense.wi_1 Linear +8.08e-07 2.66e+01 weight +1.79e-06 4.65e+00 input[0] +1.27e-04 2.37e+02 output + encoder.block.2.layer.1.DenseReluDense.dropout Dropout +0.00e+00 8.76e+03 input[0] +0.00e+00 9.74e+03 output + encoder.block.2.layer.1.DenseReluDense.wo Linear +1.01e-06 6.44e+00 weight +0.00e+00 9.74e+03 input[0] +3.18e-04 6.27e+04 output + encoder.block.2.layer.1.DenseReluDense T5DenseGatedGeluDense +1.79e-06 4.65e+00 input[0] +3.18e-04 6.27e+04 output + encoder.block.2.layer.1.dropout Dropout +3.18e-04 6.27e+04 input[0] +0.00e+00 inf output +``` + +At the start of the report, you can see which batch number the error occurred. In this case, it occurred on the first batch. + +Each frame describes the module it is reporting on. For example, the frame below inspected `encoder.block.2.layer.1.layer_norm`. This indicates the layer norm in the first layer of the second block of the encoder. The forward calls are to `T5LayerNorm`. + +```shell + encoder.block.2.layer.1.layer_norm T5LayerNorm +8.69e-02 4.18e-01 weight +2.65e-04 3.42e+03 input[0] +1.79e-06 4.65e+00 output +``` + +The last frame reports on the `Dropout.forward` function. It called the `dropout` attribute from inside the `DenseReluDense` class. You can observe that the overflow (`inf`) occurred in the first layer of the encoders second block in the first batch. The absolute largest input element was 6.27e+04. + +```shell + encoder.block.2.layer.1.DenseReluDense T5DenseGatedGeluDense +1.79e-06 4.65e+00 input[0] +3.18e-04 6.27e+04 output + encoder.block.2.layer.1.dropout Dropout +3.18e-04 6.27e+04 input[0] +0.00e+00 inf output +``` + +The `T5DenseGatedGeluDense.forward` function output activations had an absolute maximum value of 6.27e+04 which is close to fp16s maximum limit of 6.4e+04. In the next step, `Dropout` renormalizes the weights, after zeroing some elements, which pushes the absolute maximum value to greater than 6.4e+04 resulting in an overflow. + +Now that you know where the error is happening, you can investigate the modeling code in [modeling_t5.py](https://github.com/huggingface/transformers/blob/main/src/transformers/models/t5/modeling_t5.py). + +```py +class T5DenseGatedGeluDense(nn.Module): + def __init__(self, config): + super().__init__() + self.wi_0 = nn.Linear(config.d_model, config.d_ff, bias=False) + self.wi_1 = nn.Linear(config.d_model, config.d_ff, bias=False) + self.wo = nn.Linear(config.d_ff, config.d_model, bias=False) + self.dropout = nn.Dropout(config.dropout_rate) + self.gelu_act = ACT2FN["gelu_new"] + + def forward(self, hidden_states): + hidden_gelu = self.gelu_act(self.wi_0(hidden_states)) + hidden_linear = self.wi_1(hidden_states) + hidden_states = hidden_gelu * hidden_linear + hidden_states = self.dropout(hidden_states) + hidden_states = self.wo(hidden_states) + return hidden_states +``` + +One solution is to go back a few steps before the values started growing too large and switch to fp32 so the numbers don't overflow when multiplied or summed. Another potential solution is to temporarily disable mixed precision training (`amp`). + +```py +import torch + +def forward(self, hidden_states): + if torch.is_autocast_enabled(): + with torch.cuda.amp.autocast(enabled=False): + return self._forward(hidden_states) + else: + return self._forward(hidden_states) +``` + +The report only returns inputs and outputs of full frames, so you may also want to analyze the intermediate values of any `forward` function as well. Add the `detect_overflow` function after the forward calls to track `inf` or `nan` values in the intermediate `forwarded_states`. + +```py +from debug_utils import detect_overflow + +class T5LayerFF(nn.Module): + [...] + + def forward(self, hidden_states): + forwarded_states = self.layer_norm(hidden_states) + detect_overflow(forwarded_states, "after layer_norm") + forwarded_states = self.DenseReluDense(forwarded_states) + detect_overflow(forwarded_states, "after DenseReluDense") + return hidden_states + self.dropout(forwarded_states) +``` + +Finally, you can configure the number of frames printed by [`~debug_utils.DebugUnderflowOverflow`]. + +```py +from transformers.debug_utils import DebugUnderflowOverflow + +debug_overflow = DebugUnderflowOverflow(model, max_frames_to_save=100) +``` + +### Batch tracing + +[`~debug_utils.DebugUnderflowOverflow`] is able to trace the absolute minimum and maximum values in each batch with the underflow and overflow feature disabled. This is useful for identifying where errors are occurring in the model. + +The example below shows how to trace the minimum and maximum values in batches 1 and 3 (batches are zero-indexd). + +```py +debug_overflow = DebugUnderflowOverflow(model, trace_batch_nums=[1, 3]) +``` + +```shell + *** Starting batch number=1 *** +abs min abs max metadata + shared Embedding +1.01e-06 7.92e+02 weight +0.00e+00 2.47e+04 input[0] +5.36e-05 7.92e+02 output +[...] + decoder.dropout Dropout +1.60e-07 2.27e+01 input[0] +0.00e+00 2.52e+01 output + decoder T5Stack + not a tensor output + lm_head Linear +1.01e-06 7.92e+02 weight +0.00e+00 1.11e+00 input[0] +6.06e-02 8.39e+01 output + T5ForConditionalGeneration + not a tensor output + + *** Starting batch number=3 *** +abs min abs max metadata + shared Embedding +1.01e-06 7.92e+02 weight +0.00e+00 2.78e+04 input[0] +5.36e-05 7.92e+02 output +[...] +``` + +[`~debug_utils.DebugUnderflowOverflow`] reports on a large number of frames which is easier for debugging. Once you know where a problem is occurring, say batch 150, then you can focus the trace for batches 149 and 150 and compare where the numbers are diverging. + +It is also possible to abort the trace after a certain batch number, for example, batch 3. + +```py +debug_overflow = DebugUnderflowOverflow(model, trace_batch_nums=[1, 3], abort_after_batch_num=3) +``` diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/deepspeed.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/deepspeed.md new file mode 100644 index 0000000000000000000000000000000000000000..4d1df98e50a225537228d450ce1e6ebee40bbdcf --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/deepspeed.md @@ -0,0 +1,1029 @@ + + +# DeepSpeed + +[DeepSpeed](https://www.deepspeed.ai/) is designed to optimize distributed training for large models with data, model, pipeline, and even a combination of all three [parallelism](./perf_train_gpu_many) strategies to provide better memory efficiency and faster training speeds. This is achieved with the [Zero Redundancy Optimizer (ZeRO)](https://hf.co/papers/1910.02054) which consists of three stages. + +| ZeRO stage | description | +|---|---| +| 1 | partition optimizer states | +| 2 | partition optimizer and gradient states | +| 3 | partition optimizer, gradient, and parameters | + +Each stage progressively saves more memory, allowing really large models to fit and train on a single GPU. All ZeRO stages, offloading optimizer memory and computations from the GPU to the CPU are integrated with [`Trainer`]. Provide a config file or one of the example templates to [`Trainer`] to enable DeepSpeed features. + +This guide walks you through setting up a DeepSpeed config file, how to enable its features in [`Trainer`], and deploy for training. + +Install DeepSpeed from either PyPI or Transformers. For more detailed installation instructions, refer to the DeepSpeed [installation](https://www.deepspeed.ai/tutorials/advanced-install/) or GitHUB [README](https://github.com/microsoft/deepspeed#installation). + + + + +```bash +pip install deepspeed +``` + + + + +```bash +pip install transformers[deepspeed] +``` + + + + +> [!WARNING] +> Refer to the [DeepSpeed CUDA installation](./debugging#deepspeed-cuda-issues) if you're having trouble with your installation. While DeepSpeed has a pip installable package, it is highly recommended to [install it from source](https://www.deepspeed.ai/tutorials/advanced-install/#install-deepspeed-from-source) to ensure it matches your hardware and to support certain features which aren't available in the PyPI distribution. + +DeepSpeed provides a tool for estimating the required CPU and GPU memory for the parameters, optimizer and gradient states. You'll also to need to reserve some memory for the CUDA kernels and activations. + +Run the command below to check the memory requirements for [bigscience/T0_3B](https://huggingface.co/docs/transformers/main/en/bigscience/T0_3B) on a single GPU. + +```bash +$ python -c 'from transformers import AutoModel; \ +from deepspeed.runtime.zero.stage3 import estimate_zero3_model_states_mem_needs_all_live; \ +model = AutoModel.from_pretrained("bigscience/T0_3B"); \ +estimate_zero3_model_states_mem_needs_all_live(model, num_gpus_per_node=1, num_nodes=1)' +[...] +Estimated memory needed for params, optim states and gradients for a: +HW: Setup with 1 node, 1 GPU per node. +SW: Model with 2783M total params, 65M largest layer params. + per CPU | per GPU | Options + 70.00GB | 0.25GB | offload_param=cpu , offload_optimizer=cpu , zero_init=1 + 70.00GB | 0.25GB | offload_param=cpu , offload_optimizer=cpu , zero_init=0 + 62.23GB | 5.43GB | offload_param=none, offload_optimizer=cpu , zero_init=1 + 62.23GB | 5.43GB | offload_param=none, offload_optimizer=cpu , zero_init=0 + 0.37GB | 46.91GB | offload_param=none, offload_optimizer=none, zero_init=1 + 15.56GB | 46.91GB | offload_param=none, offload_optimizer=none, zero_init=0 +``` + +> [!TIP] +> If you have enough GPU memory, disable CPU and NVMe offload to speed everything up. + +## Choosing a ZeRO stage + +Consider the table below to help you choose the appropriate ZeRO stage for training because there is a trade-off between training speed and memory usage. The table orders the ZeRO stages from fastest to slowest and from least memory usage to most. + +| fastest | least memory usage | +|---|---| +| ZeRO-1 | ZeRO-3 + offload | +| ZeRO-2 | ZeRO-3 | +| ZeRO-2 + offload | ZeRO-2 + offload | +| ZeRO-3 | ZeRO-2 | +| ZeRO-3 + offload | ZeRO-1 | + +Decide the type of performance you're optimizing for, speed or memory, and then work backwards to discover the best ZeRO stage for your use case. For example, if you're optimizing for speed, start with the fastest ZeRO stage and if you run out of memory, try the next stage which is slower but more memory efficient. + +## Config file + +Once you've decided on a ZeRO stage, set up a config file to enable DeepSpeed with [`Trainer`]. The config file contains all the parameters for how to configure and set up your training. When the training script is executed, DeepSpeed logs the configuration from [`Trainer`] to the console so you can see exactly what's being used. + +> [!TIP] +> Find a complete list of DeepSpeed configuration options on the [DeepSpeed Configuration JSON](https://www.deepspeed.ai/docs/config-json/) reference. There are also practical examples of various DeepSpeed configuration examples in the [DeepSpeedExamples](https://github.com/microsoft/DeepSpeedExamples) main [DeepSpeed](https://github.com/microsoft/DeepSpeed) repository. Run the command below to quickly find specific examples. +> +> ```bash +> git clone https://github.com/microsoft/DeepSpeedExamples +> cd DeepSpeedExamples +> find . -name '*json' +> # find examples with the Lamb optimizer +> grep -i Lamb $(find . -name '*json') +> ``` + +The config file is passed as a path to a JSON file if you're training from the command line interface or as a nested dict object if you're using [`Trainer`] in a notebook. + + + + +```py +TrainingArguments( + deepspeed="path/to/deepspeed_config.json", + ..., +) +``` + + + + +```py +ds_config_dict = dict(scheduler=scheduler_params, optimizer=optimizer_params) +args = TrainingArguments( + deepspeed=ds_config_dict, + ..., +) +trainer = Trainer( + model, + args, + ..., +) +``` + + + + +### DeepSpeed versus Trainer parameters + +There are three types of config parameters. + +1. Some config parameters are shared by DeepSpeed and [`Trainer`] making it difficult to identify errors when there are conflicting definitions. In this case, configure these parameters from the [`Trainer`] command line arguments. +1. Some config parameters are automatically derived from the model configuration and don't need to be manually configured. [`Trainer`] uses the config value `auto` to set the most correct or efficient option. You could define these parameters explicitly, but you must take care to ensure the [`Trainer`] and DeepSpeed config parameters match. Mismatches may cause training to fail in very difficult to detect ways. +1. Some config parameters are specific to DeepSpeed and should be manually set based on your training requirements. + +There are two ways to modify the config parameters. + +> [!TIP] +> Some values, such as `scheduler.params.total_num_steps`, are calculated by [`Trainer`] during training. + +1. Create or load a DeepSpeed config to use as the main config. +1. Create a [`TrainingArguments`] object based on the DeepSpeed config values. + +### ZeRO stage + +Each ZeRO stage config is defined in `zero_optimization`. + +For a more detailed explanation of each parameter, refer to the [DeepSpeed Configuration JSON](https://www.deepspeed.ai/docs/config-json/) reference. These parameters must be set up with DeepSpeed because [`Trainer`] doesn't provide equivalent command line arguments. + +> [!WARNING] +> DeepSpeed doesn't validate parameter names and any typos will fallback on the parameters default setting. Observe the DeepSpeed engine startup log messages to see what values are being used. + + + + +ZeRO-1 shards the optimizer states across GPUs and you can expect a small speed up. + +```yml +{ + "zero_optimization": { + "stage": 1 + } +} +``` + + + + +ZeRO-2 shards the optimizer and gradient states across GPUs. This stage is primarily used for training since its features are not relevant to inference. Some important parameters to configure for better performance include the following. + +* `offload_optimizer` should be enabled to reduce GPU memory usage. +* `overlap_comm` when set to `true` uses more GPU memory in exchange for lower allreduce latency. This feature uses 4.5x the `allgather_bucket_size` and `reduce_bucket_size` values. In this example, they're set to `5e8` which means it requires 9GB of GPU memory. If your GPU memory is 8GB or less, you should reduce `overlap_comm` to lower the memory requirements and prevent an out-of-memory (OOM) error. +* `allgather_bucket_size` and `reduce_bucket_size` trade-off available GPU memory for communication speed. The smaller their values, the slower communication is and the more GPU memory is available. You can balance, for example, whether a bigger batch size is more important than a slightly slower training time. +* `round_robin_gradients` is available in DeepSpeed 0.4.4 for CPU offloading. It parallelizes gradient copying to CPU memory among ranks by fine-grained gradient partitioning. Performance benefit grows with gradient accumulation steps (more copying between optimizer steps) or GPU count (increased parallelism). + +```yml +{ + "zero_optimization": { + "stage": 2, + "offload_optimizer": { + "device": "cpu", + "pin_memory": true + }, + "allgather_partitions": true, + "allgather_bucket_size": 5e8, + "overlap_comm": true, + "reduce_scatter": true, + "reduce_bucket_size": 5e8, + "contiguous_gradients": true + "round_robin_gradients": true + } +} +``` + + + + +ZeRO-3 shards the optimizer and gradient states, and parameters across GPUs. Unlike ZeRO-2, ZeRO-3 can also be used for inference in addition to training because it loads large models onto multiple GPUs. Some important parameters to configure include the following. + +* `device: "cpu"` can help if you're running out of GPU memory and if you have free CPU memory available. This offloads model parameters to the CPU. +* `pin_memory: true` can improve throughput, but less memory becomes available for other processes because the pinned memory is reserved for the specific process that requested it and it's typically accessed much faster than normal CPU memory. +* `stage3_max_live_parameters` is the upper limit on how many full parameters to keep on the GPU at any given time. Reduce this value if you encounter an OOM error. +* `stage3_max_reuse_distance` is a value for determining when a parameter is used again in the future, and it helps decide whether to throw the parameter away or to keep it. If the parameter is going to be reused (if the value is less than `stage3_max_reuse_distance`), then it is kept to reduce communication overhead. This is helpful when activation checkpointing is enabled and you want to keep the parameter in the forward recompute until the backward pass. Reduce this value if you encounter an OOM error. +* `stage3_gather_16bit_weights_on_model_save` consolidates fp16 weights when a model is saved. For large models and multiple GPUs, this is expensive in terms of memory and speed. You should enable it if you're planning on resuming training. +* `sub_group_size` controls which parameters are updated during the optimizer step. Parameters are grouped into buckets of `sub_group_size` and each bucket is updated one at a time. When used with NVMe offload, `sub_group_size` determines when model states are moved in and out of CPU memory during the optimization step. This prevents running out of CPU memory for extremely large models. `sub_group_size` can be left to its default value if you aren't using NVMe offload, but you may want to change it if you: + + 1. Run into an OOM error during the optimization step. In this case, reduce `sub_group_size` to reduce memory usage of the temporary buffers. + 2. The optimization step is taking a really long time. In this case, increase `sub_group_size` to improve bandwidth utilization as a result of increased data buffers. + +* `reduce_bucket_size`, `stage3_prefetch_bucket_size`, and `stage3_param_persistence_threshold` are dependent on a models hidden size. It is recommended to set these values to `auto` and allow [`Trainer`] to automatically assign the values. + +```yml +{ + "zero_optimization": { + "stage": 3, + "offload_optimizer": { + "device": "cpu", + "pin_memory": true + }, + "offload_param": { + "device": "cpu", + "pin_memory": true + }, + "overlap_comm": true, + "contiguous_gradients": true, + "sub_group_size": 1e9, + "reduce_bucket_size": "auto", + "stage3_prefetch_bucket_size": "auto", + "stage3_param_persistence_threshold": "auto", + "stage3_max_live_parameters": 1e9, + "stage3_max_reuse_distance": 1e9, + "stage3_gather_16bit_weights_on_model_save": true + } +} +``` + +### Initialize large models + +With ZeRO-3, use the [deepspeed.zero.Init](https://deepspeed.readthedocs.io/en/latest/zero3.html#deepspeed.zero.Init) context manager to initialize a model faster. + +```py +from transformers import T5ForConditionalGeneration, T5Config +import deepspeed + +with deepspeed.zero.Init(): + config = T5Config.from_pretrained("google-t5/t5-small") + model = T5ForConditionalGeneration(config) +``` + +The DeepSped config file needs to have `is_deepspeed_zero3_enabled: true` setup in [`TrainingArguments`] and it needs a ZeRO configuration enabled. The [`TrainingArguments`] object must be created **before** calling [`~PreTrainedModel.from_pretrained`]. + +> [!TIP] +> You'll need ZeRO-3 when the fp16 weights don't fit on a single GPU. But if you're able to load the fp16 weights, set `torch_dtype=torch.float16` in [`~PreTrainedModel.from_pretrained`]. + +```py +from transformers import AutoModel, Trainer, TrainingArguments + +training_args = TrainingArguments(..., deepspeed=ds_config) +model = AutoModel.from_pretrained("google-t5/t5-small") +trainer = Trainer(model=model, args=training_args, ...) +``` + +When there are multiple GPUs, no single GPU has all the parameters unless it's the parameters of the currently executing layer. To access all parameters from all the layers at once, such as loading pretrained model weights in [`~PreTrainedModel.from_pretrained`], one layer is loaded at a time and immediately partitioned to all GPUs. For very large models, it isn't possible to load the weights onto one GPU and then distribute them across the other GPUs due to memory limitations. + +If you encounter a model parameter weight where `tensor([1.])` or the parameter size is 1 instead of a larger multidimensional shape, it means the parameter is partitioned and this is a ZeRO-3 placeholder. + +```py +tensor([1.0], device="cuda:0", dtype=torch.float16, requires_grad=True) +``` + +> [!TIP] +> For more information about initializing large models with ZeRO-3 and accessing the parameters, take a look at the [Constructing Massive Models](https://deepspeed.readthedocs.io/en/latest/zero3.html#constructing-massive-models) and [Gathering Parameters](https://deepspeed.readthedocs.io/en/latest/zero3.html#gathering-parameters) guides. + + + + +### NVMe + +[ZeRO-Infinity](https://hf.co/papers/2104.07857) offloads model states to the CPU and/or NVMe to save even more memory. Smart partitioning and tiling algorithms allow each GPU to send and receive very small amounts of data during offloading such that a modern NVMe can fit an even larger total memory pool than is available to your training process. ZeRO-Infinity requires ZeRO-3. + +Depending on the CPU and NVMe memory available, you can offload both the [optimizer states](https://www.deepspeed.ai/docs/config-json/#optimizer-offloading) and [parameters](https://www.deepspeed.ai/docs/config-json/#parameter-offloading), just one of them, or none of them. Make sure the `nvme_path` points to a NVMe device, because while it still works with a regular hard drive or solid state drive, it'll be significantly slower. With a modern NVMe, you can expect peak transfer speeds of ~3.5GB/s for read operations and ~3GB/s for write operations. + +Consider running a [benchmark](https://github.com/microsoft/DeepSpeed/issues/998) on your training setup to determine the optimal `aio` configuration. + +The example ZeRO-3 and ZeRO-Infinity config below sets most of the parameter values to `auto`, but you can also manually set configure these values. + +```yaml +{ + "fp16": { + "enabled": "auto", + "loss_scale": 0, + "loss_scale_window": 1000, + "initial_scale_power": 16, + "hysteresis": 2, + "min_loss_scale": 1 + }, + + "optimizer": { + "type": "AdamW", + "params": { + "lr": "auto", + "betas": "auto", + "eps": "auto", + "weight_decay": "auto" + } + }, + + "scheduler": { + "type": "WarmupLR", + "params": { + "warmup_min_lr": "auto", + "warmup_max_lr": "auto", + "warmup_num_steps": "auto" + } + }, + + "zero_optimization": { + "stage": 3, + "offload_optimizer": { + "device": "nvme", + "nvme_path": "/local_nvme", + "pin_memory": true, + "buffer_count": 4, + "fast_init": false + }, + "offload_param": { + "device": "nvme", + "nvme_path": "/local_nvme", + "pin_memory": true, + "buffer_count": 5, + "buffer_size": 1e8, + "max_in_cpu": 1e9 + }, + "aio": { + "block_size": 262144, + "queue_depth": 32, + "thread_count": 1, + "single_submit": false, + "overlap_events": true + }, + "overlap_comm": true, + "contiguous_gradients": true, + "sub_group_size": 1e9, + "reduce_bucket_size": "auto", + "stage3_prefetch_bucket_size": "auto", + "stage3_param_persistence_threshold": "auto", + "stage3_max_live_parameters": 1e9, + "stage3_max_reuse_distance": 1e9, + "stage3_gather_16bit_weights_on_model_save": true + }, + + "gradient_accumulation_steps": "auto", + "gradient_clipping": "auto", + "steps_per_print": 2000, + "train_batch_size": "auto", + "train_micro_batch_size_per_gpu": "auto", + "wall_clock_breakdown": false +} +``` + +## Training features + +DeepSpeed supports many training features that can be configured in the config file. This section describes some of the most important features. + +### Gradient checkpointing + +Gradient checkpointing saves memory by only storing *some* of the intermediate activations instead of storing *all* of them. It is useful for fitting larger models on the GPU without running out of memory or to increase the batch size for better performance. Training speed is slower though. + +* For a Transformers model, set `model.gradient_checkpointing_enable()` or add `--gradient_checkpointing` in the [`TrainingArguments`]. +* For a non-Transformers model, use the DeepSpeed [Activation Checkpointing API](https://deepspeed.readthedocs.io/en/latest/activation-checkpointing.html). Replacing Transformers modeling code and [torch.utils.checkpoint](https://pytorch.org/docs/stable/checkpoint.html) with the DeepSpeed API gives you more flexibility because you can offload the forward activations to the CPU memory instead of recalculating them. + +### Batch size + +The batch size can be automatically configured or manually set. When you choose the `"auto"` option, [`Trainer`] sets `train_micro_batch_size_per_gpu` and `train_batch_size` to the value of `world_size * per_device_train_batch_size * gradient_accumulation_steps`. + +```yaml +{ + "train_micro_batch_size_per_gpu": "auto", + "train_batch_size": "auto" +} +``` + +### Communication data type + +A separate data type is used for communication collectives like reduction, gathering and scattering operations. + +All gather and scatter operations are performed in the same data type the data is in. For example, if you're training in bf16, the data is also gathered in bf16 because gathering is a non-lossy operation. + +Reduce operations are lossy, for example, when gradients are averaged across multiple GPUs. When the communication is done in fp16 or bf16, it's more likely to be lossy because adding multiple numbers in low precision isn't exact. This is especially the case with bf16 which has a lower precision than fp16. For this reason, fp16 is the default for reduction operations because the loss is minimal when averaging gradients. + +Choose the communication data type by setting the `communication_data_type` parameter in the config file. For example, choosing fp32 adds a small amount of overhead but ensures the reduction operation is accumulated in fp32 and when it is ready, it's downcasted to whichever half-precision data type you're training in. + +```yaml +{ + "communication_data_type": "fp32" +} +``` + +### Gradient accumulation + +Gradient accumulation accumulates gradients over several mini-batches of data before updating parameters. It stores less gradients and enables training with a larger *effective batch size*. Training speed is slower though, but it's useful for overcoming memory constraints. + +Gradient accumulation can be automatically configured or manually set. When you choose the `"auto"` option, [`Trainer`] sets it to the value of `gradient_accumulation_steps`. + +```yaml +{ + "gradient_accumulation_steps": "auto" +} +``` + +### Gradient clipping + +Gradient clipping is useful for preventing exploding gradients which can lead to instability during training. It sets a maximum threshold value and rescales the gradients if their norm exceeds the threshold. + +Gradient clipping can be automatically configured or manually set. When you choose the `"auto"` option, [`Trainer`] sets it to the value of `max_grad_norm`. + +```yaml +{ + "gradient_clipping": "auto" +} +``` + +### Mixed precision training + +Mixed precision accelerates training speed by performing some calculations in half-precision, but it also maintains some calculations in full-precision to preserve accuracy. DeepSpeed supports fp32, fp16, and bf16 data types. + + + + +Train in fp32 if a model wasn't pretrained in mixed precision because it may cause underflow or overflow errors. Disable fp16, the default, in this case. + +```yaml +{ + "fp16": { + "enabled": false + } +} +``` + +For Ampere GPUs and PyTorch 1.7+, the more efficient [tf32](https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices) mode is automatically enabled for some operations but the results are still in fp32. Configure it in [`Trainer`] by setting `--tf32` to enable it, and `--tf32 0` or `--no_tf32` to disable it. + + + + +To configure AMP-like fp16 mixed precision, set up the config as shown below with `"auto"` or your own values. [`Trainer`] automatically enables or disables fp16 based on the value of `fp16_backend`, and the rest of the config can be set by you. fp16 is enabled from the command line when the following arguments are passed: `--fp16`, `--fp16_backend amp` or `--fp16_full_eval`. + +```yaml +{ + "fp16": { + "enabled": "auto", + "loss_scale": 0, + "loss_scale_window": 1000, + "initial_scale_power": 16, + "hysteresis": 2, + "min_loss_scale": 1 + } +} +``` + +For additional DeepSpeed fp16 training options, take a look at the [FP16 Training Options](https://www.deepspeed.ai/docs/config-json/#fp16-training-options) reference. + +To configure Apex-like fp16 mixed precision, set up the config as shown below with `"auto"` or your own values. [`Trainer`] automatically configures `amp` based on the values of `fp16_backend` and `fp16_opt_level`. It can also be enabled from the command line when the following arguments are passed: `--fp16`, `--fp16_backend apex` or `--fp16_opt_level 01`. + +```yaml +{ + "amp": { + "enabled": "auto", + "opt_level": "auto" + } +} +``` + + + + +> [!TIP] +> bf16 requires DeepSpeed 0.6.0. + +bf16 has the same dynamic range as fp32, and doesn’t require loss scaling unlike fp16. However, if you use [gradient accumulation](#gradient-accumulation) with bf16, gradients are accumulated in bf16 which may not be desirable because the lower precision can lead to lossy accumulation. + +bf16 can be set up in the config file or enabled from the command line when the following arguments are passed: `--bf16` or `--bf16_full_eval`. + +```yaml +{ + "bf16": { + "enabled": "auto" + } +} +``` + + + + +### Optimizer and scheduler + +DeepSpeed and Transformers optimizers and schedulers can be mixed and matched if `offload_optimizer` isn't enabled. When `offload_optimizer` is enabled, use a non-DeepSpeed optimizer (except for LAMB) as long as it has it a CPU and GPU implementation. + +Set the optimizer and scheduler parameters for the config file from the command line to avoid hard to find errors. For example, if the learning rate is set to a different value in another place, you can override it from the command line. + + + + +DeepSpeed offers several [optimizers](https://www.deepspeed.ai/docs/config-json/#optimizer-parameters) (Adam, AdamW, OneBitAdam, and LAMB) but you can also import other optimizers from PyTorch. If you don't configure the optimizer in the config, [`Trainer`] automatically selects AdamW and either uses the supplied values or the default values for the following parameters from the command line: `lr`, `adam_beta1`, `adam_beta2`, `adam_epsilon`, `weight_decay`. + +You can set the parameters to `"auto"` or manually input your own values. + +```yaml +{ + "optimizer": { + "type": "AdamW", + "params": { + "lr": "auto", + "betas": "auto", + "eps": "auto", + "weight_decay": "auto" + } + } +} +``` + +Use an unsupported optimizer by adding the following to the top level configuration. + +```yaml +{ + "zero_allow_untested_optimizer": true +} +``` + +From DeepSpeed 0.8.3+, if you want to use offload, you'll also need to add the following to the top level configuration because offload works best with DeepSpeed's CPU Adam optimizer. + +```yaml +{ + "zero_force_ds_cpu_optimizer": false +} +``` + + + + +DeepSpeed supports the LRRangeTest, OneCycle, WarmupLR and WarmupDecayLR learning rate [schedulers](https://www.deepspeed.ai/docs/config-json/#scheduler-parameters). + +Transformers and DeepSpeed provide two of the same schedulers: + +* WarmupLR is the same as `--lr_scheduler_type constant_with_warmup` in Transformers. +* WarmupDecayLR is the same as `--lr_scheduler_type linear` in Transformers (this is the default scheduler used in Transformers). + +If you don't configure the scheduler in the config file, [`Trainer`] automatically selects WarmupDecayLR and either uses the supplied values or the default values for the following parameters from the command line: `warmup_min_lr`, `warmup_max_lr`, `warmup_num_steps`, `total_num_steps` (automatically calculated during run time if `max_steps` is not provided). + +You can set the parameters to `"auto"` or manually input your own values. + +```yaml +{ + "scheduler": { + "type": "WarmupDecayLR", + "params": { + "total_num_steps": "auto", + "warmup_min_lr": "auto", + "warmup_max_lr": "auto", + "warmup_num_steps": "auto" + } + } +} +``` + + + + +### Universal checkpointing + +[Universal Checkpointing](https://www.deepspeed.ai/tutorials/universal-checkpointing) saves and loads model, optimizer and training scheduler states across different model architectures, parallelism techniques, and training configurations. By saving them in a Universal format, it enables easier model training continuation and fine-tuning. + +Resume training with a Universal checkpoint by setting `load_universal` to `true` in the config file. + +```yaml +{ + "checkpoint": { + "load_universal": true + } +} +``` + +## Deploy + +DeepSpeed can be deployed with its native launcher, [torchrun](https://pytorch.org/docs/stable/elastic/run.html) or [Accelerate](https://huggingface.co/docs/accelerate/basic_tutorials/launch#using-accelerate-launch). + +Add the `--deepspeed ds_config.json` argument to [`Trainer`] in the command line. It is recommended to use DeepSpeeds [add_config_arguments](https://deepspeed.readthedocs.io/en/latest/initialize.html#argument-parsing) utility to add any other command line arguments to your code. + + + + +To deploy DeepSpeed on multiple GPUs, add `--num_gpus`. You don't need to add `--num_gpus` if you're planning on using all available GPUs. + +```bash +deepspeed --num_gpus=2 examples/pytorch/translation/run_translation.py \ +--deepspeed tests/deepspeed/ds_config_zero3.json \ +--model_name_or_path google-t5/t5-small --per_device_train_batch_size 1 \ +--output_dir output_dir --overwrite_output_dir --fp16 \ +--do_train --max_train_samples 500 --num_train_epochs 1 \ +--dataset_name wmt16 --dataset_config "ro-en" \ +--source_lang en --target_lang ro +``` + + + + +DeepSpeed is still useful with just one GPU because you can: + +1. Offload some computations and memory to the CPU to make more GPU resources available to your model to use a larger batch size or fit a very large model that normally won't fit. +2. Minimize memory fragmentation with its smart GPU memory management system which also allows you to fit bigger models and data batches. + +To deploy DeepSpeed on a single GPU, add `--num_gpus`. You don't need to add `--num_gpus` if you only have one GPU because DeepSpeed deploys all GPUs it can see on a given node. + +> [!TIP] +> Set the `allgather_bucket_size` and `reduce_bucket_size` values to 2e8 in the [ZeRO-2](#zero-configuration) configuration file to get better performance on a single GPU. + +```bash +deepspeed --num_gpus=1 examples/pytorch/translation/run_translation.py \ +--deepspeed tests/deepspeed/ds_config_zero2.json \ +--model_name_or_path google-t5/t5-small --per_device_train_batch_size 1 \ +--output_dir output_dir --overwrite_output_dir --fp16 \ +--do_train --max_train_samples 500 --num_train_epochs 1 \ +--dataset_name wmt16 --dataset_config "ro-en" \ +--source_lang en --target_lang ro +``` + + + + +### Multi-node + +A multi-node setup consists of multiple nodes, where each node has one of more GPUs running a workload. DeepSpeed expects a shared storage system, but if this is not the case, you need to adjust the config file to include a [checkpoint](https://www.deepspeed.ai/docs/config-json/#checkpoint-options) to allow loading without access to a shared filesystem. + +```yaml +{ + "checkpoint": { + "use_node_local_storage": true + } +} +``` + +You could also use the `--save_on_each_node` parameter in [`TrainingArguments`] to automatically add the above `checkpoint` to your config. + +The examples below for the torchrun and DeepSpeed launcher shows how to deploy two nodes with eight GPUs each. Access the first node with `ssh hostname1` and the second node with `ssh hostname2`. Both nodes must be able to communicate with each other locally over ssh without a password. + + + + +With [torchrun](https://pytorch.org/docs/stable/elastic/run.html), ssh to each node and run the following command on both of them. The launcher waits until both nodes are synchronized before launching the training. + +```bash +torchrun --nproc_per_node=8 --nnode=2 --node_rank=0 --master_addr=hostname1 \ +--master_port=9901 your_program.py --deepspeed ds_config.json +``` + + + + +Create a `hostfile` for the DeepSpeed launcher. + +```bash +hostname1 slots=8 +hostname2 slots=8 +``` + +The DeepSpeed launcher automatically launches the command on both nodes at once with the command below. + +```bash +deepspeed --num_gpus 8 --num_nodes 2 --hostfile hostfile --master_addr hostname1 --master_port=9901 \ +your_program.py --deepspeed ds_config.json +``` + +Check out the [Resource Configuration (multi-node)](https://www.deepspeed.ai/getting-started/#resource-configuration-multi-node) guide for more details about configuring multi-node compute resources. + + + + +### Slurm + +[Slurm](https://slurm.schedmd.com/documentation.html) is a cluster management and job scheduling system. An example Slurm script is shown below. + +```bash +#SBATCH --job-name=test-nodes # name +#SBATCH --nodes=2 # nodes +#SBATCH --ntasks-per-node=1 # crucial - only 1 task per dist per node! +#SBATCH --cpus-per-task=10 # number of cores per tasks +#SBATCH --gres=gpu:8 # number of gpus +#SBATCH --time 20:00:00 # maximum execution time (HH:MM:SS) +#SBATCH --output=%x-%j.out # output file name + +export GPUS_PER_NODE=8 +export MASTER_ADDR=$(scontrol show hostnames $SLURM_JOB_NODELIST | head -n 1) +export MASTER_PORT=9901 + +srun --jobid $SLURM_JOBID bash -c 'python -m torch.distributed.run \ + --nproc_per_node $GPUS_PER_NODE --nnodes $SLURM_NNODES --node_rank $SLURM_PROCID \ + --master_addr $MASTER_ADDR --master_port $MASTER_PORT \ +your_program.py --deepspeed ds_config.json' +``` + +Launch training simultaneously on all nodes with the command below. + +```bash +sbatch launch.slurm +``` + +### Jupyter Notebook + +To use DeepSpeed in a Jupyter Notebook, you need to emulate a distributed environment because the launcher doesn't support deployment from a notebook. This is only supported for one GPU. To use multiple GPUs, you must use a multi-process environment, which means you have to use the DeepSpeed launcher which can't be emulated as shown here. + +```py +# emulate a launcher in the notebook +import os + +os.environ["MASTER_ADDR"] = "localhost" +os.environ["MASTER_PORT"] = "9994" # modify if RuntimeError: Address already in use +os.environ["RANK"] = "0" +os.environ["LOCAL_RANK"] = "0" +os.environ["WORLD_SIZE"] = "1" + +training_args = TrainingArguments(..., deepspeed="ds_config_zero3.json") +trainer = Trainer(...) +trainer.train() +``` + +Create a config file on the fly in the notebook in the current directory with a dedicated cell. + +```py +%%bash +cat <<'EOT' > ds_config_zero3.json +{ + "fp16": { + "enabled": "auto", + "loss_scale": 0, + "loss_scale_window": 1000, + "initial_scale_power": 16, + "hysteresis": 2, + "min_loss_scale": 1 + }, + + "optimizer": { + "type": "AdamW", + "params": { + "lr": "auto", + "betas": "auto", + "eps": "auto", + "weight_decay": "auto" + } + }, + + "scheduler": { + "type": "WarmupLR", + "params": { + "warmup_min_lr": "auto", + "warmup_max_lr": "auto", + "warmup_num_steps": "auto" + } + }, + + "zero_optimization": { + "stage": 3, + "offload_optimizer": { + "device": "cpu", + "pin_memory": true + }, + "offload_param": { + "device": "cpu", + "pin_memory": true + }, + "overlap_comm": true, + "contiguous_gradients": true, + "sub_group_size": 1e9, + "reduce_bucket_size": "auto", + "stage3_prefetch_bucket_size": "auto", + "stage3_param_persistence_threshold": "auto", + "stage3_max_live_parameters": 1e9, + "stage3_max_reuse_distance": 1e9, + "stage3_gather_16bit_weights_on_model_save": true + }, + + "gradient_accumulation_steps": "auto", + "gradient_clipping": "auto", + "steps_per_print": 2000, + "train_batch_size": "auto", + "train_micro_batch_size_per_gpu": "auto", + "wall_clock_breakdown": false +} +EOT +``` + +If the training script is in a file and not a notebook cell, launch DeepSpeed from the shell in the notebook cell. + +```py +!git clone https://github.com/huggingface/transformers +!cd transformers; deepspeed examples/pytorch/translation/run_translation.py ... +``` + +Another option is to use `%%bash` to run the shell program without emulating the distributed environment. However, you won't be able to view the logs until training is complete. + +```py +%%bash + +git clone https://github.com/huggingface/transformers +cd transformers +deepspeed examples/pytorch/translation/run_translation.py ... +``` + +## Save model weights + +DeepSpeed stores the main fp32 weights in custom checkpoint optimizer files (`global_step*/*optim_states.pt`) which are saved under the normal checkpoint. + +### fp16 + +ZeRO-2 saves the model weights in fp16. To save the weights in fp16 for ZeRO-3, set `"stage3_gather_16bit_weights_on_model_save": true` in the config file, because the weights are distributed across multiple GPUs. + +If you don't, [`Trainer`] won't save the weights in fp16 and won't create a `pytorch_model.bin` file. This is because DeepSpeed's state_dict contains a placeholder instead of the real weights, so you won't be able to load it. + +```yaml +{ + "zero_optimization": { + "stage": 3, + "stage3_gather_16bit_weights_on_model_save": true + } +} +``` + +### fp32 + +Unless you have a lot of free CPU memory, fp32 weights shouldn't be saved during training because it can require a lot of memory. It is usually best to save the fp32 weights offline after training is complete. + + + + +DeepSpeed provides a [zero_to_fp32.py](https://github.com/microsoft/DeepSpeed/blob/91829476a8fd4d0d9268c03c1d56795d20a51c12/deepspeed/utils/zero_to_fp32.py#L14) script at the top-level checkpoint folder for extracting weights at any point. This is a standalone script and you don't need a config file or [`Trainer`]. + +For example, if your checkpoint folder looks like the one shown below, then you can run the following command to create and consolidate the fp32 weights from multiple GPUs into a single `pytorch_model.bin` file. The script automatically discovers the subfolder `global_step1` which contains the checkpoint. + +```bash +$ ls -l output_dir/checkpoint-1/ +-rw-rw-r-- 1 stas stas 1.4K Mar 27 20:42 config.json +drwxrwxr-x 2 stas stas 4.0K Mar 25 19:52 global_step1/ +-rw-rw-r-- 1 stas stas 12 Mar 27 13:16 latest +-rw-rw-r-- 1 stas stas 827K Mar 27 20:42 optimizer.pt +-rw-rw-r-- 1 stas stas 231M Mar 27 20:42 pytorch_model.bin +-rw-rw-r-- 1 stas stas 623 Mar 27 20:42 scheduler.pt +-rw-rw-r-- 1 stas stas 1.8K Mar 27 20:42 special_tokens_map.json +-rw-rw-r-- 1 stas stas 774K Mar 27 20:42 spiece.model +-rw-rw-r-- 1 stas stas 1.9K Mar 27 20:42 tokenizer_config.json +-rw-rw-r-- 1 stas stas 339 Mar 27 20:42 trainer_state.json +-rw-rw-r-- 1 stas stas 2.3K Mar 27 20:42 training_args.bin +-rwxrw-r-- 1 stas stas 5.5K Mar 27 13:16 zero_to_fp32.py* +``` + +> [!TIP] +> Run `python zero_to_fp32.py -h` for more usage details. The script requires 2x the general RAM of the final fp32 weights. + +```bash +python zero_to_fp32.py . pytorch_model.bin +``` + + + + +Adding the `--load_best_model_at_end` parameter in [`TrainingArguments`] tracks the best checkpoint so you can finish training first and save the final model explicitly. Reload the model as shown below. + +> [!WARNING] +> Once [load_state_dict_from_zero_checkpoint](https://deepspeed.readthedocs.io/en/stable/model-checkpointing.html#deepspeed.utils.zero_to_fp32.load_state_dict_from_zero_checkpoint) is run, the model is no longer usable in DeepSpeed in the context of the same application. You'll need to reinitialize the DeepSpeed engine because `model.load_state_dict(state_dict)` removes all the DeepSpeed magic from it. Only use this function once training is complete. + +```py +from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint + +checkpoint_dir = os.path.join(trainer.args.output_dir, "checkpoint-final") +trainer.deepspeed.save_checkpoint(checkpoint_dir) +fp32_model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir) +``` + +You must have saved at least one checkpoint to load the latest checkpoint as shown in the example below. + +```py +from transformers.trainer_utils import get_last_checkpoint +from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint + +checkpoint_dir = get_last_checkpoint(trainer.args.output_dir) +fp32_model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir) +``` + +Use `load_state_dict` to extract and load the state_dict of the fp32 weights. + +```py +from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint + +state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) +model = model.cpu() +model.load_state_dict(state_dict) +``` + + + + +## Non-Trainer integration + +DeepSpeed also works with Transformers without [`Trainer`]. The [`~integrations.HfDeepSpeedConfig`] is responsible for gathering ZeRO-3 parameters and partitioning a model across multiple GPUs when [`~PreTrainedModel.from_pretrained`] is called. + +You must instantiate [`~integrations.HfDeepSpeedConfig`] before loading a model to efficiently deploy ZeRO-3. + + + + +```py +from transformers.integrations import HfDeepSpeedConfig +from transformers import AutoModel +import deepspeed + +# DeepSpeed config object or path to the file +ds_config = {...} +# must run before instantiating the model to detect ZeRO-3 +dschf = HfDeepSpeedConfig(ds_config) # keep this object alive +model = AutoModel.from_pretrained("openai-community/gpt2") +engine = deepspeed.initialize(model=model, config_params=ds_config, ...) +``` + + + + +[`~integrations.HfDeepSpeedConfig`] is not required for ZeRO-1 or ZeRO-2. + +```py +from transformers.integrations import HfDeepSpeedConfig +from transformers import AutoModel, AutoConfig +import deepspeed + +# DeepSpeed config object or path to the file +ds_config = {...} +# must run before instantiating the model to detect zero 3 +dschf = HfDeepSpeedConfig(ds_config) # keep this object alive +# randomly initialize model weights +config = AutoConfig.from_pretrained("openai-community/gpt2") +model = AutoModel.from_config(config) +engine = deepspeed.initialize(model=model, config_params=ds_config, ...) +``` + + + + +## Troubleshoot + +One of the first things to check when you encounter an error is whether DeepSpeed is the cause (because often it isn't). Retry your setup without DeepSpeed, and if the error persists, report the issue. If the issue is unrelated to the Transformers integration, please open the issue on the DeepSpeed [repository](https://github.com/microsoft/DeepSpeed). + +For issues related to the Transformers integration, please provide the following information. + +* The full DeepSpeed config file. +* The command line arguments for [`Trainer`] or the [`TrainingArguments`] if you're scripting the [`Trainer`] setup yourself (don't dump the entire [`TrainingArguments`] which contains many irrelevant entries). +* The outputs of the following commands. + + ```bash + python -c 'import torch; print(f"torch: {torch.__version__}")' + python -c 'import transformers; print(f"transformers: {transformers.__version__}")' + python -c 'import deepspeed; print(f"deepspeed: {deepspeed.__version__}")' + ``` + +* A link to a Google Colab notebook to reproduce the issue. +* A standard or non-custom dataset or an existing example to reproduce the issue. + +The following sections provide a guide for resolving two of the most common issues. + +### Process killed at startup + +When the DeepSpeed process is killed during launch without a traceback, that usually means the program tried to allocate more CPU memory than is available on your system. Or the process may have tried to allocate more CPU memory than allowed, leading the OS kernel to terminate the process. + +In this case, check whether your config file has either `offload_optimizer`, `offlload_param`, or both configured to offload to the CPU. + +If you have NVM3 and ZeRO-3 set up, experiment with offloading to the NVMe ([estimate](https://deepspeed.readthedocs.io/en/latest/memory.html) the memory requirements of a model first) instead. + +### NaN loss + +NaN loss often occurs when a model is pretrained in bf16 and you try to use it with fp16 (especially relevant to TPU trained models). To resolve this, use fp32 or bf16 if your hardware (TPUs, Ampere GPUs or newer) supports it. + +It is also possible that fp16 is causing overflow. For example, if your config file looks like the one below, you may see the following overflow errors in the logs. + +```yaml +{ + "fp16": { + "enabled": "auto", + "loss_scale": 0, + "loss_scale_window": 1000, + "initial_scale_power": 16, + "hysteresis": 2, + "min_loss_scale": 1 + } +} +``` + +The `OVERFLOW!` error below is a result of the DeepSpeed loss scaler unable to find a scaling coefficient to overcome the loss overflow. Try a higher `initial_scale_power` value in this case (32 usually works). + +```bash +0%| | 0/189 [00:00 + +# ExecuTorch + +[ExecuTorch](https://pytorch.org/executorch/stable/index.html) is a platform that enables PyTorch training and inference programs to be run on mobile and edge devices. It is powered by [torch.compile](https://pytorch.org/docs/stable/torch.compiler.html) and [torch.export](https://pytorch.org/docs/main/export.html) for performance and deployment. + +You can use ExecuTorch with Transformers with [torch.export](https://pytorch.org/docs/main/export.html). The [`~transformers.convert_and_export_with_cache`] method converts a [`PreTrainedModel`] into an exportable module. Under the hood, it uses [torch.export](https://pytorch.org/docs/main/export.html) to export the model, ensuring compatibility with ExecuTorch. + +```py +import torch +from transformers import LlamaForCausalLM, AutoTokenizer, GenerationConfig +from transformers.integrations.executorch import( + TorchExportableModuleWithStaticCache, + convert_and_export_with_cache +) + +generation_config = GenerationConfig( + use_cache=True, + cache_implementation="static", + cache_config={ + "batch_size": 1, + "max_cache_len": 20, + } +) + +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.2-1B", pad_token="", padding_side="right") +model = LlamaForCausalLM.from_pretrained("meta-llama/Llama-3.2-1B", device_map="auto", torch_dtype=torch.bfloat16, attn_implementation="sdpa", generation_config=generation_config) + +exported_program = convert_and_export_with_cache(model) +``` + +The exported PyTorch model is now ready to be used with ExecuTorch. Wrap the model with [`~transformers.TorchExportableModuleWithStaticCache`] to generate text. + +```py +prompts = ["Simply put, the theory of relativity states that "] +prompt_tokens = tokenizer(prompts, return_tensors="pt", padding=True).to(model.device) +prompt_token_ids = prompt_tokens["input_ids"] + +generated_ids = TorchExportableModuleWithStaticCache.generate( + exported_program=exported_program, prompt_token_ids=prompt_token_ids, max_new_tokens=20, +) +generated_text = tokenizer.batch_decode(generated_ids, skip_special_tokens=True) +print(generated_text) +['Simply put, the theory of relativity states that 1) the speed of light is the'] +``` diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/fast_tokenizers.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/fast_tokenizers.md new file mode 100644 index 0000000000000000000000000000000000000000..921c0ba7b6f588fe6896b1016d7e1c9f1a24c5e1 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/fast_tokenizers.md @@ -0,0 +1,362 @@ + + +# Tokenizers + +Tokenizers convert text into an array of numbers known as tensors, the inputs to a text model. There are several tokenizer algorithms, but they all share the same purpose. Split text into smaller words or subwords (tokens) according to some rules, and convert them into numbers (input ids). A Transformers tokenizer also returns an attention mask to indicate which tokens should be attended to. + +> [!TIP] +> Learn about the most popular tokenization algorithms on the [Summary of the tokenizers](./tokenizer_summary) doc. + +Call [`~PreTrainedTokenizer.from_pretrained`] to load a tokenizer and its configuration from the Hugging Face [Hub](https://hf.co) or a local directory. The pretrained tokenizer is saved in a [tokenizer.model](https://huggingface.co/google/gemma-2-2b/blob/main/tokenizer.model) file with all its associated vocabulary files. + +Pass a string of text to the tokenizer to return the input ids and attention mask, and set the framework tensor type to return with the `return_tensors` parameter. + +```py +from transformers import AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-2b") +tokenizer("We are very happy to show you the 🤗 Transformers library", return_tensors="pt") +{'input_ids': tensor([[ 2, 1734, 708, 1508, 4915, 577, 1500, 692, 573, + 156808, 128149, 9581, 235265]]), + 'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) +} +``` + +Whichever tokenizer you use, make sure the tokenizer vocabulary is the same as the pretrained models tokenizer vocabulary. This is especially important if you're using a custom tokenizer with a different vocabulary from the pretrained models tokenizer. + +This guide provides a brief overview of the tokenizer classes and how to preprocess text with it. + +## Tokenizer classes + +All tokenizers inherit from a [`PreTrainedTokenizerBase`] class that provides common methods for all tokenizers like [`~PreTrainedTokenizerBase.from_pretrained`] and [`~PreTrainedTokenizerBase.batch_decode`]. There are two main tokenizer classes that build on top of the base class. + +- [`PreTrainedTokenizer`] is a Python implementation, for example [`LlamaTokenizer`]. +- [`PreTrainedTokenizerFast`] is a fast Rust-based implementation from the [Tokenizers](https://hf.co/docs/tokenizers/index) library, for example [`LlamaTokenizerFast`]. + +There are two ways you can load a tokenizer, with [`AutoTokenizer`] or a model-specific tokenizer. + + + + +The [AutoClass](./model_doc/auto) API is a fast and easy way to load a tokenizer without needing to know whether a Python or Rust-based implementation is available. By default, [`AutoTokenizer`] tries to load a fast tokenizer if it's available, otherwise, it loads the Python implementation. + +Use [`~PreTrainedTokenizer.from_pretrained`] to load a tokenizer. + +```py +from transformers import AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-2b") +tokenizer("We are very happy to show you the 🤗 Transformers library.", return_tensors="pt") +{'input_ids': tensor([[ 2, 1734, 708, 1508, 4915, 577, 1500, 692, 573, + 156808, 128149, 9581, 235265]]), + 'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) +} +``` + +Load your own tokenizer by passing its vocabulary file to [`~AutoTokenizer.from_pretrained`]. + +```py +from transformers import AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("./model_directory/my_vocab_file.txt") +``` + + + + +Each pretrained model is associated with a tokenizer and the specific vocabulary it was trained on. A tokenizer can be loaded directly from the model-specific class. + +> [!TIP] +> Refer to a models API documentation to check whether a fast tokenizer is supported. + +```py +from transformers import GemmaTokenizer + +tokenizer = GemmaTokenizer.from_pretrained("google/gemma-2-2b") +tokenizer("We are very happy to show you the 🤗 Transformers library.", return_tensors="pt") +``` + +To load a fast tokenizer, use the fast implementation class. + +```py +from transformers import GemmaTokenizerFast + +tokenizer = GemmaTokenizerFast.from_pretrained("google/gemma-2-2b") +tokenizer("We are very happy to show you the 🤗 Transformers library.", return_tensors="pt") +``` + +Load your own tokenizer by passing its vocabulary file to the `vocab_file` parameter. + +```py +from transformers import GemmaTokenizerFast + +tokenizer = GemmaTokenizerFast(vocab_file="my_vocab_file.txt") +``` + + + + +## Multimodal tokenizers + +In addition to text tokens, multimodal tokenizers also holds tokens from other modalities as a part of its attributes for easy access. + +To add these special tokens to a tokenizer, pass them as a dictionary to the `extra_special_tokens` parameter in [`~AutoTokenizer.from_pretrained`]. The example below adds the `image_token` to a vision-language model. + +Save the tokenizer so you can reuse it with direct access to the `image_token`, `boi_token`, and `eoi_token`. + +```py +vision_tokenizer = AutoTokenizer.from_pretrained( + "llava-hf/llava-1.5-7b-hf", + extra_special_tokens={"image_token": "", "boi_token": "", "eoi_token": ""} +) +print(vision_tokenizer.image_token, vision_tokenizer.image_token_id) +("", 32000) + +vision_tokenizer.save_pretrained("./path/to/tokenizer") +``` + +## Fast tokenizers + + + +[`PreTrainedTokenizerFast`] or *fast tokenizers* are Rust-based tokenizers from the [Tokenizers](https://hf.co/docs/tokenizers) library. It is significantly faster at batched tokenization and provides additional alignment methods compared to the Python-based tokenizers. + +[`AutoTokenizer`] automatically loads a fast tokenizer if it's supported. Otherwise, you need to explicitly load the fast tokenizer. + +This section will show you how to train a fast tokenizer and reuse it in Transformers. + +To train a Byte-Pair Encoding (BPE) tokenizer, create a [`~tokenizers.Tokenizer`] and [`~tokenizers.trainers.BpeTrainer`] class and define the unknown token and special tokens. + +```py +from tokenizers import Tokenizer +from tokenizers.models import BPE +from tokenizers.trainers import BpeTrainer + +tokenizer = Tokenizer(BPE(unk_token="[UNK]")) +trainer = BpeTrainer(special_tokens=["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"]) +``` + +Split the tokens on [`~tokenizers.pre_tokenizers.Whitespace`] to create tokens that don't overlap with each other. + +```py +from tokenizers.pre_tokenizers import Whitespace + +tokenizer.pre_tokenizer = Whitespace() +``` + +Call [`~tokenizers.Tokenizer.train`] on the text files and trainer to start training. + +```py +files = [...] +tokenizer.train(files, trainer) +``` + +Use [`~tokenizers.Tokenizer.save`] to save the tokenizers configuration and vocabulary to a JSON file. + +```py +tokenizer.save("tokenizer.json") +``` + +Now you can load and reuse the tokenizer object in Transformers by passing it to the `tokenizer_object` parameter in [`PreTrainedTokenizerFast`]. + +```py +from transformers import PreTrainedTokenizerFast + +fast_tokenizer = PreTrainedTokenizerFast(tokenizer_object=tokenizer) +``` + +To load a saved tokenizer from its JSON file, pass the file path to the `tokenizer_file` parameter in [`PreTrainedTokenizerFast`]. + +```py +from transformers import PreTrainedTokenizerFast + +fast_tokenizer = PreTrainedTokenizerFast(tokenizer_file="tokenizer.json") +``` + +## tiktoken + +[tiktoken](https://github.com/openai/tiktoken) is a [byte-pair encoding (BPE)](./tokenizer_summary#byte-pair-encoding-bpe) tokenizer by OpenAI. It includes several tokenization schemes or encodings for how text should be tokenized. + +There are currently two models trained and released with tiktoken, GPT2 and Llama3. Transformers supports models with a [tokenizer.model](https://hf.co/meta-llama/Meta-Llama-3-8B/blob/main/original/tokenizer.model) tiktoken file. The tiktoken file is automatically converted into Transformers Rust-based [`PreTrainedTokenizerFast`]. + +Add the `subfolder` parameter to [`~PreTrainedModel.from_pretrained`] to specify where the `tokenizer.model` tiktoken file is located. + +```py +from transformers import AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct", subfolder="original") +``` + +### Create a tiktoken tokenizer + +The tiktoken `tokenizer.model` file contains no information about additional tokens or pattern strings. If these are important, convert the tokenizer to `tokenizer.json` (the appropriate format for [`PreTrainedTokenizerFast`]). + +Generate the tiktoken `tokenizer.model` file with the [tiktoken.get_encoding](https://github.com/openai/tiktoken/blob/63527649963def8c759b0f91f2eb69a40934e468/tiktoken/registry.py#L63) function, and convert it to `tokenizer.json` with [convert_tiktoken_to_fast](https://github.com/huggingface/transformers/blob/99e0ab6ed888136ea4877c6d8ab03690a1478363/src/transformers/integrations/tiktoken.py#L8). + +```py +from transformers.integrations.tiktoken import convert_tiktoken_to_fast +from tiktoken import get_encoding + +# Load your custom encoding or the one provided by OpenAI +encoding = get_encoding("gpt2") +convert_tiktoken_to_fast(encoding, "config/save/dir") +``` + +The resulting `tokenizer.json` file is saved to the specified directory and loaded with [`~PreTrainedTokenizerFast.from_pretrained`]. + +```py +tokenizer = PreTrainedTokenizerFast.from_pretrained("config/save/dir") +``` + +## Preprocess + + + +A Transformers model expects the input to be a PyTorch, TensorFlow, or NumPy tensor. A tokenizers job is to preprocess text into those tensors. Specify the framework tensor type to return with the `return_tensors` parameter. + +```py +from transformers import AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-2b") +tokenizer("We are very happy to show you the 🤗 Transformers library.", return_tensors="pt") +{'input_ids': tensor([[ 2, 1734, 708, 1508, 4915, 577, 1500, 692, 573, + 156808, 128149, 9581, 235265]]), + 'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) +} +``` + +The tokenization process of converting text into input ids is completed in two steps. + + + + +In the first step, a string of text is split into tokens by the [`~PreTrainedTokenizer.tokenize`] function. How the text is split depends on the tokenization algorithm. + +```py +tokens = tokenizer.tokenize("We are very happy to show you the 🤗 Transformers library") +print(tokens) +['We', '▁are', '▁very', '▁happy', '▁to', '▁show', '▁you', '▁the', '▁🤗', '▁Transformers', '▁library'] +``` + +Gemma uses a [SentencePiece](./tokenizer_summary#sentencepiece) tokenizer which replaces spaces with an underscore `_`. + + + + +In the second step, the tokens are converted into ids with [`~PreTrainedTokenizer.convert_tokens_to_ids`]. + +```py +ids = tokenizer.convert_tokens_to_ids(tokens) +print(ids) +[1734, 708, 1508, 4915, 577, 1500, 692, 573, 156808, 128149, 9581] +``` + + + + +Lastly, the model prediction typically generates numerical outputs which are converted back to text with [`~PreTrainedTokenizer.decode`]. + +```py +decoded_string = tokenizer.decode(ids) +print(decoded_string) +'We are very happy to show you the 🤗 Transformers library' +``` + + + + +> [!TIP] +> Visualize how different tokenizers work in the [Tokenizer Playground](https://xenova-the-tokenizer-playground.static.hf.space). + +### Special tokens + +Special tokens provide the model with some additional information about the text. + +For example, if you compare the tokens obtained from passing text directly to the tokenizer and from [`~PreTrainedTokenizer.convert_tokens_to_ids`], you'll notice some additional tokens are added. + +```py +model_inputs = tokenizer("We are very happy to show you the 🤗 Transformers library.") +[2, 1734, 708, 1508, 4915, 577, 1500, 692, 573, 156808, 128149, 9581] +tokenizer.convert_tokens_to_ids(tokens) +[1734, 708, 1508, 4915, 577, 1500, 692, 573, 156808, 128149, 9581] +``` + +When you [`~PreTrainedTokenizer.decode`] the ids, you'll see `` at the beginning of the string. This is used to indicate the beginning of a sentence to the model. + +```py +print(tokenizer.decode(model_inputs["input_ids"])) +print(tokenizer.decode(ids)) +'We are very happy to show you the 🤗 Transformers library.' +'We are very happy to show you the 🤗 Transformers library' +``` + +Not all models need special tokens, but if they do, a tokenizer automatically adds them. + +### Batch tokenization + +It is faster and more efficient to preprocess *batches* of text instead of a single sentence at a time. Fast tokenizers are especially good at parallelizing tokenization. + +Pass a list of string text to the tokenizer. + +```py +batch_sentences = [ + "But what about second breakfast?", + "Don't think he knows about second breakfast, Pip.", + "What about elevensies?", +] +encoded_inputs = tokenizer(batch_sentences, return_tensors="pt") +print(encoded_inputs) +{ + 'input_ids': + [[2, 1860, 1212, 1105, 2257, 14457, 235336], + [2, 4454, 235303, 235251, 1742, 693, 9242, 1105, 2257, 14457, 235269, 48782, 235265], + [2, 1841, 1105, 29754, 37453, 235336]], + 'attention_mask': [[1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1]] +} +``` + +### Padding + +> [!TIP] +> Learn about additional padding strategies in the [Padding and truncation](./pad_truncation) guide. + +In the output above, the `input_ids` have different lengths. This is an issue because Transformers expects them to have the same lengths so it can pack them into a batch. Sequences with uneven lengths can't be batched. + +Padding adds a special *padding token* to ensure all sequences have the same length. Set `padding=True` to pad the sequences to the longest sequence length in the batch. + +```py +encoded_inputs = tokenizer(batch_sentences, padding=True, return_tensors="pt") +print(encoded_inputs) +``` + +The tokenizer added the special padding token `0` to the left side (*left padding*) because Gemma and LLMs in general are not trained to continue generation from a padding token. + +### Truncation + +> [!TIP] +> Learn about additional truncation strategies in the [Padding and truncation](./pad_truncation) guide. + +Models are only able to process sequences up to a certain length. If you try to process a sequence longer than a model can handle, it crashes. + +Truncation removes tokens from a sequence to ensure it doesn't exceed the maximum length. Set `truncation=True` to truncate a sequence to the maximum length accepted by the model. You can also set the maximum length yourself with the `max_length` parameter. + +```py +encoded_inputs = tokenizer(batch_sentences, max_length=8, truncation=True, return_tensors="pt") +print(encoded_inputs) +``` diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/feature_extractors.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/feature_extractors.md new file mode 100644 index 0000000000000000000000000000000000000000..38c1247909edc2bf1a5e6fda2c93b5f0ceb4fd39 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/feature_extractors.md @@ -0,0 +1,200 @@ + + +# Feature extractors + +Feature extractors preprocess audio data into the correct format for a given model. It takes the raw audio signal and converts it into a tensor that can be fed to a model. The tensor shape depends on the model, but the feature extractor will correctly preprocess the audio data for you given the model you're using. Feature extractors also include methods for padding, truncation, and resampling. + +Call [`~AutoFeatureExtractor.from_pretrained`] to load a feature extractor and its preprocessor configuration from the Hugging Face [Hub](https://hf.co/models) or local directory. The feature extractor and preprocessor configuration is saved in a [preprocessor_config.json](https://hf.co/openai/whisper-tiny/blob/main/preprocessor_config.json) file. + +Pass the audio signal, typically stored in `array`, to the feature extractor and set the `sampling_rate` parameter to the pretrained audio models sampling rate. It is important the sampling rate of the audio data matches the sampling rate of the data a pretrained audio model was trained on. + +```py +from transformers import AutoFeatureExtractor + +feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base") +dataset = load_dataset("PolyAI/minds14", name="en-US", split="train") +processed_sample = feature_extractor(dataset[0]["audio"]["array"], sampling_rate=16000) +processed_sample +{'input_values': [array([ 9.4472744e-05, 3.0777880e-03, -2.8888427e-03, ..., + -2.8888427e-03, 9.4472744e-05, 9.4472744e-05], dtype=float32)]} +``` + +The feature extractor returns an input, `input_values`, that is ready for the model to consume. + +This guide walks you through the feature extractor classes and how to preprocess audio data. + +## Feature extractor classes + +Transformers feature extractors inherit from the base [`SequenceFeatureExtractor`] class which subclasses [`FeatureExtractionMixin`]. + +- [`SequenceFeatureExtractor`] provides a method to [`~SequenceFeatureExtractor.pad`] sequences to a certain length to avoid uneven sequence lengths. +- [`FeatureExtractionMixin`] provides [`~FeatureExtractionMixin.from_pretrained`] and [`~FeatureExtractionMixin.save_pretrained`] to load and save a feature extractor. + +There are two ways you can load a feature extractor, [`AutoFeatureExtractor`] and a model-specific feature extractor class. + + + + +The [AutoClass](./model_doc/auto) API automatically loads the correct feature extractor for a given model. + +Use [`~AutoFeatureExtractor.from_pretrained`] to load a feature extractor. + +```py +from transformers import AutoFeatureExtractor + +feature_extractor = AutoFeatureExtractor.from_pretrained("openai/whisper-tiny") +``` + + + + +Every pretrained audio model has a specific associated feature extractor for correctly processing audio data. When you load a feature extractor, it retrieves the feature extractors configuration (feature size, chunk length, etc.) from [preprocessor_config.json](https://hf.co/openai/whisper-tiny/blob/main/preprocessor_config.json). + +A feature extractor can be loaded directly from its model-specific class. + +```py +from transformers import WhisperFeatureExtractor + +feature_extractor = WhisperFeatureExtractor.from_pretrained("openai/whisper-tiny") +``` + + + + +## Preprocess + +A feature extractor expects the input as a PyTorch tensor of a certain shape. The exact input shape can vary depending on the specific audio model you're using. + +For example, [Whisper](https://huggingface.co/docs/transformers/model_doc/whisper) expects `input_features` to be a tensor of shape `(batch_size, feature_size, sequence_length)` but [Wav2Vec2](https://hf.co/docs/transformers/model_doc/wav2vec2) expects `input_values` to be a tensor of shape `(batch_size, sequence_length)`. + +The feature extractor generates the correct input shape for whichever audio model you're using. + +A feature extractor also sets the sampling rate (the number of audio signal values taken per second) of the audio files. The sampling rate of your audio data must match the sampling rate of the dataset a pretrained model was trained on. This value is typically given in the model card. + +Load a dataset and feature extractor with [`~FeatureExtractionMixin.from_pretrained`]. + +```py +from datasets import load_dataset, Audio +from transformers import AutoFeatureExtractor + +dataset = load_dataset("PolyAI/minds14", name="en-US", split="train") +feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base") +``` + +Check out the first example from the dataset and access the `audio` column which contains `array`, the raw audio signal. + +```py +dataset[0]["audio"]["array"] +array([ 0. , 0.00024414, -0.00024414, ..., -0.00024414, + 0. , 0. ]) +``` + +The feature extractor preprocesses `array` into the expected input format for a given audio model. Use the `sampling_rate` parameter to set the appropriate sampling rate. + +```py +processed_dataset = feature_extractor(dataset[0]["audio"]["array"], sampling_rate=16000) +processed_dataset +{'input_values': [array([ 9.4472744e-05, 3.0777880e-03, -2.8888427e-03, ..., + -2.8888427e-03, 9.4472744e-05, 9.4472744e-05], dtype=float32)]} +``` + +### Padding + +Audio sequence lengths that are different is an issue because Transformers expects all sequences to have the same lengths so they can be batched. Uneven sequence lengths can't be batched. + +```py +dataset[0]["audio"]["array"].shape +(86699,) + +dataset[1]["audio"]["array"].shape +(53248,) +``` + +Padding adds a special *padding token* to ensure all sequences have the same length. The feature extractor adds a `0` - interpreted as silence - to `array` to pad it. Set `padding=True` to pad sequences to the longest sequence length in the batch. + +```py +def preprocess_function(examples): + audio_arrays = [x["array"] for x in examples["audio"]] + inputs = feature_extractor( + audio_arrays, + sampling_rate=16000, + padding=True, + ) + return inputs + +processed_dataset = preprocess_function(dataset[:5]) +processed_dataset["input_values"][0].shape +(86699,) + +processed_dataset["input_values"][1].shape +(86699,) +``` + +### Truncation + +Models can only process sequences up to a certain length before crashing. + +Truncation is a strategy for removing excess tokens from a sequence to ensure it doesn't exceed the maximum length. Set `truncation=True` to truncate a sequence to the length in the `max_length` parameter. + +```py +def preprocess_function(examples): + audio_arrays = [x["array"] for x in examples["audio"]] + inputs = feature_extractor( + audio_arrays, + sampling_rate=16000, + max_length=50000, + truncation=True, + ) + return inputs + +processed_dataset = preprocess_function(dataset[:5]) +processed_dataset["input_values"][0].shape +(50000,) + +processed_dataset["input_values"][1].shape +(50000,) +``` + +### Resampling + +The [Datasets](https://hf.co/docs/datasets/index) library can also resample audio data to match an audio models expected sampling rate. This method resamples the audio data on the fly when they're loaded which can be faster than resampling the entire dataset in-place. + +The audio dataset you've been working on has a sampling rate of 8kHz and the pretrained model expects 16kHz. + +```py +dataset[0]["audio"] +{'path': '/root/.cache/huggingface/datasets/downloads/extracted/f507fdca7f475d961f5bb7093bcc9d544f16f8cab8608e772a2ed4fbeb4d6f50/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav', + 'array': array([ 0. , 0.00024414, -0.00024414, ..., -0.00024414, + 0. , 0. ]), + 'sampling_rate': 8000} +``` + +Call [`~datasets.Dataset.cast_column`] on the `audio` column to upsample the sampling rate to 16kHz. + +```py +dataset = dataset.cast_column("audio", Audio(sampling_rate=16000)) +``` + +When you load the dataset sample, it is now resampled to 16kHz. + +```py +dataset[0]["audio"] +{'path': '/root/.cache/huggingface/datasets/downloads/extracted/f507fdca7f475d961f5bb7093bcc9d544f16f8cab8608e772a2ed4fbeb4d6f50/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav', + 'array': array([ 1.70562416e-05, 2.18727451e-04, 2.28099874e-04, ..., + 3.43842403e-05, -5.96364771e-06, -1.76846661e-05]), + 'sampling_rate': 16000} +``` diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/fsdp.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/fsdp.md new file mode 100644 index 0000000000000000000000000000000000000000..944c5a18e109356195fd4b5eb2cf176174af9693 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/fsdp.md @@ -0,0 +1,145 @@ + + +# FullyShardedDataParallel + +[Fully Sharded Data Parallel (FSDP)](https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/) is a [parallelism](./perf_train_gpu_many) method that combines the advantages of data and model parallelism for distributed training. + +Unlike [DistributedDataParallel (DDP)](./perf_train_gpu_many#distributeddataparallel), FSDP saves more memory because it doesn't replicate a model on each GPU. It shards the models parameters, gradients and optimizer states across GPUs. Each model shard processes a portion of the data and the results are synchronized to speed up training. + +This guide covers how to set up training a model with FSDP and [Accelerate](https://hf.co/docs/accelerate/index), a library for managing distributed training. + +```bash +pip install accelerate +``` + +## Configuration options + +Always start by running the [accelerate config](https://hf.co/docs/accelerate/package_reference/cli#accelerate-config) command to help Accelerate set up the correct distributed training environment. + +```bash +accelerate config +``` + +The section below discusses some of the more important FSDP configuration options. Learn more about other available options in the [fsdp_config](https://hf.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments.fsdp_config) parameter. + +### Sharding strategy + +FSDP offers several sharding strategies to distribute a model. Refer to the table below to help you choose the best strategy for your setup. Specify a strategy with the `fsdp_sharding_strategy` parameter in the configuration file. + +| sharding strategy | description | parameter value | +|---|---|---| +| `FULL_SHARD` | shards model parameters, gradients, and optimizer states | `1` | +| `SHARD_GRAD_OP` | shards gradients and optimizer states | `2` | +| `NO_SHARD` | don't shard the model | `3` | +| `HYBRID_SHARD` | shards model parameters, gradients, and optimizer states within each GPU | `4` | +| `HYBRID_SHARD_ZERO2` | shards gradients and optimizer states within each GPU | `5` | + +### CPU offload + +Offload model parameters and gradients when they aren't being used to the CPU to save additional GPU memory. This is useful for scenarios where a model is too large even with FSDP. + +Specify `fsdp_offload_params: true` in the configuration file to enable offloading. + +### Wrapping policy + +FSDP is applied by wrapping each layer in the network. The wrapping is usually applied in a nested way where the full weights are discarded after each forward pass to save memory for the next layer. + +There are several wrapping policies available, but the *auto wrapping* policy is the simplest and doesn't require any changes to your code. Specify `fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP` to wrap a Transformer layer and `fsdp_transformer_layer_cls_to_wrap` to determine which layer to wrap (for example, `BertLayer`). + +Size-based wrapping is also available. If a layer exceeds a certain number of parameters, it is wrapped. Specify `fsdp_wrap_policy: SIZED_BASED_WRAP` and `min_num_param` to set the minimum number of parameters for a layer to be wrapped. + +### Checkpoints + +Intermediate checkpoints should be saved as a sharded state dict because saving the full state dict - even with CPU offloading - is time consuming and can cause `NCCL Timeout` errors due to indefinite hanging during broadcasting. + +Specify `fsdp_state_dict_type: SHARDED_STATE_DICT` in the configuration file to save the sharded state dict. Now you can resume training from the sharded state dict with [`~accelerate.Accelerator.load_state`]. + +```py +accelerator.load_state("directory/containing/checkpoints") +``` + +Once training is complete though, you should save the full state dict because the sharded state dict is only compatible with FSDP. + +```py +if trainer.is_fsdp_enabled: + trainer.accelerator.state.fsdp_plugin.set_state_dict_type("FULL_STATE_DICT") + +trainer.save_model(script_args.output_dir) +``` + +### TPU + +[PyTorch XLA](https://pytorch.org/xla/release/2.1/index.html), a package for running PyTorch on XLA devices, enables FSDP on TPUs. Modify the configuration file to include the parameters below. Refer to the [xla_fsdp_settings](https://github.com/pytorch/xla/blob/2e6e183e0724818f137c8135b34ef273dea33318/torch_xla/distributed/fsdp/xla_fully_sharded_data_parallel.py#L128) parameter for additional XLA-specific parameters you can configure for FSDP. + +```yaml +xla: True # must be set to True to enable PyTorch/XLA +xla_fsdp_settings: # XLA specific FSDP parameters +xla_fsdp_grad_ckpt: True # enable gradient checkpointing +``` + +## Training + +After running [accelerate config](https://hf.co/docs/accelerate/package_reference/cli#accelerate-config), your configuration file should be ready. An example configuration file is shown below that fully shards the parameter, gradient and optimizer states on two GPUs. Your file may look different depending on how you set up your configuration. + +```yaml +compute_environment: LOCAL_MACHINE +debug: false +distributed_type: FSDP +downcast_bf16: 'no' +fsdp_config: + fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP + fsdp_backward_prefetch_policy: BACKWARD_PRE + fsdp_cpu_ram_efficient_loading: true + fsdp_forward_prefetch: false + fsdp_offload_params: true + fsdp_sharding_strategy: 1 + fsdp_state_dict_type: SHARDED_STATE_DICT + fsdp_sync_module_states: true + fsdp_transformer_layer_cls_to_wrap: BertLayer + fsdp_use_orig_params: true +machine_rank: 0 +main_training_function: main +mixed_precision: bf16 +num_machines: 1 +num_processes: 2 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false +``` + +Run the [accelerate launch](https://hf.co/docs/accelerate/package_reference/cli#accelerate-launch) command to launch a training script with the FSDP configurations you chose in the configuration file. + +```bash +accelerate launch my-training-script.py +``` + +It is also possible to directly specify some of the FSDP arguments in the command line. + +```bash +accelerate launch --fsdp="full shard" --fsdp_config="path/to/fsdp_config/" my-training-script.py +``` + +## Resources + +FSDP is a powerful tool for training large models with fewer GPUs compared to other parallelism strategies. Refer to the following resources below to learn even more about FSDP. + +- Follow along with the more in-depth Accelerate guide for [FSDP](https://hf.co/docs/accelerate/usage_guides/fsdp). +- Read the [Introducing PyTorch Fully Sharded Data Parallel (FSDP) API](https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/) blog post. +- Read the [Scaling PyTorch models on Cloud TPUs with FSDP](https://pytorch.org/blog/scaling-pytorch-models-on-cloud-tpus-with-fsdp/) blog post. diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/generation_features.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/generation_features.md new file mode 100644 index 0000000000000000000000000000000000000000..19ac987807261da527b9de5358fd007fe474087e --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/generation_features.md @@ -0,0 +1,82 @@ + + +# Generation features + +The [`~GenerationMixin.generate`] API supports a couple features for building applications on top of it. + +This guide will show you how to use these features. + +## Streaming + +Streaming starts returning text as soon as it is generated so you don't have to wait to see the entire generated response all at once. It is important in user-facing applications because it reduces perceived latency and allows users to see the generation progression. + +
+ +
+ +> [!TIP] +> Learn more about streaming in the [Text Generation Inference](https://huggingface.co/docs/text-generation-inference/en/conceptual/streaming) docs. + +Create an instance of [`TextStreamer`] with the tokenizer. Pass [`TextStreamer`] to the `streamer` parameter in [`~GenerationMixin.generate`] to stream the output one word at a time. + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer, TextStreamer + +tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2") +model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2") +inputs = tokenizer(["The secret to baking a good cake is "], return_tensors="pt") +streamer = TextStreamer(tokenizer) + +_ = model.generate(**inputs, streamer=streamer, max_new_tokens=20) +``` + +The `streamer` parameter is compatible with any class with a [`~TextStreamer.put`] and [`~TextStreamer.end`] method. [`~TextStreamer.put`] pushes new tokens and [`~TextStreamer.end`] flags the end of generation. You can create your own streamer class as long as they include these two methods, or you can use Transformers' basic streamer classes. + +## Watermarking + +Watermarking is useful for detecting whether text is generated. The [watermarking strategy](https://hf.co/papers/2306.04634) in Transformers randomly "colors" a subset of the tokens green. When green tokens are generated, they have a small bias added to their logits, and a higher probability of being generated. You can detect generated text by comparing the proportion of green tokens to the amount of green tokens typically found in human-generated text. + +Watermarking is supported for any generative model in Transformers and doesn't require an extra classification model to detect the watermarked text. + +Create a [`WatermarkingConfig`] with the bias value to add to the logits and watermarking algorithm. The example below uses the `"selfhash"` algorithm, where the green token selection only depends on the current token. Pass the [`WatermarkingConfig`] to [`~GenerationMixin.generate`]. + +> [!TIP] +> The [`WatermarkDetector`] class detects the proportion of green tokens in generated text, which is why it is recommended to strip the prompt text, if it is much longer than the generated text. Padding can also have an effect on [`WatermarkDetector`]. + +```py +from transformers import AutoTokenizer, AutoModelForCausalLM, WatermarkDetector, WatermarkingConfig + +model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2") +tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2") +tokenizer.pad_token_id = tokenizer.eos_token_id +tokenizer.padding_side = "left" + +inputs = tokenizer(["This is the beginning of a long story", "Alice and Bob are"], padding=True, return_tensors="pt") +input_len = inputs["input_ids"].shape[-1] + +watermarking_config = WatermarkingConfig(bias=2.5, seeding_scheme="selfhash") +out = model.generate(**inputs, watermarking_config=watermarking_config, do_sample=False, max_length=20) +``` + +Create an instance of [`WatermarkDetector`] and pass the model output to it to detect whether the text is machine-generated. The [`WatermarkDetector`] must have the same [`WatermarkingConfig`] used during generation. + +```py +detector = WatermarkDetector(model_config=model.config, device="cpu", watermarking_config=watermarking_config) +detection_out = detector(out, return_dict=True) +detection_out.prediction +array([True, True]) +``` diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/generation_strategies.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/generation_strategies.md new file mode 100644 index 0000000000000000000000000000000000000000..ba59c1228609b35e4e9e5bfe0c2bbfdb9d42c8e2 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/generation_strategies.md @@ -0,0 +1,540 @@ + + +# Generation strategies + +A decoding strategy informs how a model should select the next generated token. There are many types of decoding strategies, and choosing the appropriate one has a significant impact on the quality of the generated text. + +This guide will help you understand the different decoding strategies available in Transformers and how and when to use them. + +## Basic decoding methods + +These are well established decoding methods, and should be your starting point for text generation tasks. + +### Greedy search + +Greedy search is the default decoding strategy. It selects the next most likely token at each step. Unless specified in [`GenerationConfig`], this strategy generates a maximum of 20 new tokens. + +Greedy search works well for tasks with relatively short outputs where creativity is not a priority. However, it breaks down when generating longer sequences because it begins to repeat itself. + +```py +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf") +inputs = tokenizer("Hugging Face is an open-source company", return_tensors="pt").to("cuda") + +model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf", torch_dtype=torch.float16).to("cuda") +# explicitly set to default length because Llama2 generation length is 4096 +outputs = model.generate(**inputs, max_new_tokens=20) +tokenizer.batch_decode(outputs, skip_special_tokens=True) +'Hugging Face is an open-source company that provides a suite of tools and services for building, deploying, and maintaining natural language processing' +``` + +### Sampling + +Sampling, or multinomial sampling, randomly selects a token based on the probability distribution over the entire model's vocabulary (as opposed to the most likely token, as in greedy search). This means every token with a non-zero probability has a chance to be selected. Sampling strategies reduce repetition and can generate more creative and diverse outputs. + +Enable multinomial sampling with `do_sample=True` and `num_beams=1`. + +```py +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf") +inputs = tokenizer("Hugging Face is an open-source company", return_tensors="pt").to("cuda") + +model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf", torch_dtype=torch.float16).to("cuda") +# explicitly set to 100 because Llama2 generation length is 4096 +outputs = model.generate(**inputs, max_new_tokens=50, do_sample=True, num_beams=1) +tokenizer.batch_decode(outputs, skip_special_tokens=True) +'Hugging Face is an open-source company 🤗\nWe are open-source and believe that open-source is the best way to build technology. Our mission is to make AI accessible to everyone, and we believe that open-source is the best way to achieve that.' +``` + +### Beam search + +Beam search keeps track of several generated sequences (beams) at each time step. After a certain number of steps, it selects the sequence with the highest *overall* probability. Unlike greedy search, this strategy can "look ahead" and pick a sequence with a higher probability overall even if the initial tokens have a lower probability. It is best suited for input-grounded tasks, like describing an image or speech recognition. You can also use `do_sample=True` with beam search to sample at each step, but beam search will still greedily prune out low probability sequences between steps. + +> [!TIP] +> Check out the [beam search visualizer](https://huggingface.co/spaces/m-ric/beam_search_visualizer) to see how beam search works. + +Enable beam search with the `num_beams` parameter (should be greater than 1 otherwise it's equivalent to greedy search). + +```py +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf") +inputs = tokenizer("Hugging Face is an open-source company", return_tensors="pt").to("cuda") + +model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf", torch_dtype=torch.float16).to("cuda") +# explicitly set to 100 because Llama2 generation length is 4096 +outputs = model.generate(**inputs, max_new_tokens=50, num_beams=2) +tokenizer.batch_decode(outputs, skip_special_tokens=True) +"['Hugging Face is an open-source company that develops and maintains the Hugging Face platform, which is a collection of tools and libraries for building and deploying natural language processing (NLP) models. Hugging Face was founded in 2018 by Thomas Wolf']" +``` + +## Advanced decoding methods + +Advanced decoding methods aim at either tackling specific generation quality issues (e.g. repetition) or at improving the generation throughput in certain situations. These techniques are more complex, and may not work correctly with all models. + +### Speculative decoding + +[Speculative](https://hf.co/papers/2211.17192) or assistive decoding isn't a search or sampling strategy. Instead, speculative decoding adds a second smaller model to generate candidate tokens. The main model verifies the candidate tokens in a single `forward` pass, which speeds up the decoding process overall. This method is especially useful for LLMs where it can be more costly and slower to generate tokens. Refer to the [speculative decoding](./llm_optims#speculative-decoding) guide to learn more. + +Currently, only greedy search and multinomial sampling are supported with speculative decoding. Batched inputs aren't supported either. + +Enable speculative decoding with the `assistant_model` parameter. You'll notice the fastest speed up with an assistant model that is much smaller than the main model. Add `do_sample=True` to enable token validation with resampling. + + + + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM-1.7B") +model = AutoModelForCausalLM.from_pretrained("HuggingFaceTB/SmolLM-1.7B") +assistant_model = AutoModelForCausalLM.from_pretrained("HuggingFaceTB/SmolLM-135M") +inputs = tokenizer("Hugging Face is an open-source company", return_tensors="pt") + +outputs = model.generate(**inputs, assistant_model=assistant_model) +tokenizer.batch_decode(outputs, skip_special_tokens=True) +'Hugging Face is an open-source company that provides a platform for developers to build and deploy machine' +``` + +Speculative decoding is also supported in [`Pipeline`] with the `assistant_model` parameter. + +```python +from transformers import pipeline +import torch + +pipe = pipeline( + "text-generation", + model="meta-llama/Llama-3.1-8B", + assistant_model="meta-llama/Llama-3.2-1B", + torch_dtype=torch.bfloat16 +) +pipe_output = pipe("Once upon a time, ", max_new_tokens=50, do_sample=False) +pipe_output[0]["generated_text"] +``` + + + + +Add the `temperature` parameter to control sampling randomness. For speculative decoding, a lower temperature may improve latency. + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM-1.7B") +model = AutoModelForCausalLM.from_pretrained("HuggingFaceTB/SmolLM-1.7B") +assistant_model = AutoModelForCausalLM.from_pretrained("HuggingFaceTB/SmolLM-135M") +inputs = tokenizer("Hugging Face is an open-source company", return_tensors="pt") + +outputs = model.generate(**inputs, assistant_model=assistant_model, do_sample=True, temperature=0.5) +tokenizer.batch_decode(outputs, skip_special_tokens=True) +'Hugging Face is an open-source company that is dedicated to creating a better world through technology.' +``` + + + + +#### Prompt lookup decoding + +[Prompt lookup decoding](./llm_optims#prompt-lookup-decoding) is a variant of speculative decoding that uses overlapping n-grams as the candidate tokens. It works well for input-grounded tasks such as summarization. Refer to the [prompt lookup decoding](./llm_optims#prompt-lookup-decoding) guide to learn more. + +Enable prompt lookup decoding with the `prompt_lookup_num_tokens` parameter. + +```py +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM-1.7B") +model = AutoModelForCausalLM.from_pretrained("HuggingFaceTB/SmolLM-1.7B", torch_dtype=torch.float16).to("cuda") +assistant_model = AutoModelForCausalLM.from_pretrained("HuggingFaceTB/SmolLM-135M", torch_dtype=torch.float16).to("cuda") +inputs = tokenizer("Hugging Face is an open-source company", return_tensors="pt").to("cuda") + +outputs = model.generate(**inputs, assistant_model=assistant_model, max_new_tokens=20, prompt_lookup_num_tokens=5) +tokenizer.batch_decode(outputs, skip_special_tokens=True) +'Hugging Face is an open-source company that provides a platform for developers to build and deploy machine learning models. It offers a variety of tools' +``` + +### Self-speculative decoding + +Early exiting uses the earlier hidden states from the language modeling head as inputs, effectively skipping layers to yield a lower quality output. The lower quality output is used as the assistant output and self-speculation is applied to fix the output using the remaining layers. The final generated result from this self-speculative method is the same (or has the same distribution) as the original models generation. + +The assistant model is also part of the target model, so the caches and weights can be shared, resulting in lower memory requirements. + +For a model trained with early exit, pass `assistant_early_exit` to [`~GenerationMixin.generate`]. + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer + +prompt = "Alice and Bob" +checkpoint = "facebook/layerskip-llama3.2-1B" + +tokenizer = AutoTokenizer.from_pretrained(checkpoint) +inputs = tokenizer(prompt, return_tensors="pt") + +model = AutoModelForCausalLM.from_pretrained(checkpoint) +outputs = model.generate(**inputs, assistant_early_exit=4, do_sample=False, max_new_tokens=20) +tokenizer.batch_decode(outputs, skip_special_tokens=True) +``` + +#### Universal assisted decoding + +Universal assisted decoding (UAD) enables the main and assistant models to use different tokenizers. The main models input tokens are re-encoded into assistant model tokens. Candidate tokens are generated in the assistant encoding which are re-encoded into the main model candidate tokens. The candidate tokens are verified as explained in [speculative decoding](#speculative-decoding). + +Re-encoding involves decoding token ids into text and encoding the text with a different tokenizer. To prevent tokenization discrepancies during re-encoding, UAD finds the longest common sub-sequence between the source and target encodings to ensure the new tokens include the correct prompt suffix. + +Add the `tokenizer` and `assistant_tokenizer` parameters to [`~GenerationMixin.generate`] to enable UAD. + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer + +prompt = "Alice and Bob" + +assistant_tokenizer = AutoTokenizer.from_pretrained("double7/vicuna-68m") +tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-9b") +inputs = tokenizer(prompt, return_tensors="pt") + +model = AutoModelForCausalLM.from_pretrained("google/gemma-2-9b") +assistant_model = AutoModelForCausalLM.from_pretrained("double7/vicuna-68m") +outputs = model.generate(**inputs, assistant_model=assistant_model, tokenizer=tokenizer, assistant_tokenizer=assistant_tokenizer) +tokenizer.batch_decode(outputs, skip_special_tokens=True) +['Alice and Bob are sitting in a bar. Alice is drinking a beer and Bob is drinking a'] +``` + +### Contrastive search + +[Contrastive search](https://huggingface.co/papers/2202.06417) is a decoding strategy that aims to reduce repetition even while generating longer sequences. This strategy compares how similar a generated token is against previous tokens, and if they're more similar, a penalty is applied. + +Enable contrastive search with the `penalty_alpha` and `top_k` parameters. The `penalty_alpha` manages the penalty applied and `top_k` is the number of most likely tokens to return. + +```py +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf") +inputs = tokenizer("Hugging Face is an open-source company", return_tensors="pt").to("cuda") + +model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf", torch_dtype=torch.float16).to("cuda") +# explicitly set to 100 because Llama2 generation length is 4096 +outputs = model.generate(**inputs, max_new_tokens=100, penalty_alpha=0.6, top_k=4) +tokenizer.batch_decode(outputs, skip_special_tokens=True) +'Hugging Face is an open-source company that provides a platform for building and deploying AI models.\nHugging Face is an open-source company that provides a platform for building and deploying AI models. The platform allows developers to build and deploy AI models, as well as collaborate with other developers.\nHugging Face was founded in 2019 by Thibault Wittemberg and Clément Delangue. The company is based in Paris, France.\nHugging Face has' +``` + +### DoLa + +[Decoding by Contrasting Layers (DoLa)](https://hf.co/papers/2309.03883) is a contrastive decoding strategy for improving factuality and reducing hallucination. This strategy works by contrasting the logit differences between the final and early layers. As a result, factual knowledge localized to particular layers are amplified. DoLa is not recommended for smaller models like GPT-2. + +Enable DoLa with the following parameters. + +- `dola_layers` are the candidate layers to be contrasted with the final layer. It can be a string (`low` or `high`) to contrast the lower or higher parts of a layer. `high` is recommended for short-answer tasks like TruthfulQA. `low` is recommended for long-answer reasoning tasks like GSM8K, StrategyQA, FACTOR, and VicunaQA. + + When a model has tied word embeddings, layer 0 is skipped and it begins from layer 2. + + It can also be a list of integers that represent the layer indices between 0 and the total number of layers. Layer 0 is the word embedding, 1 is the first transformer layer, and so on. Refer to the table below for the range of layer indices depending on the number of model layers. + + | layers | low | high | + |---|---|---| + | > 40 | (0, 20, 2) | (N - 20, N, 2) | + | <= 40 | range(0, N // 2, 2) | range(N // 2, N, 2) | + +- `repetition_penalty` reduces repetition and it is recommended to set it to 1.2. + + + + +```py +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM-1.7B") +model = AutoModelForCausalLM.from_pretrained("HuggingFaceTB/SmolLM-1.7B", torch_dtype=torch.float16).to("cuda") +inputs = tokenizer("What is the highest peak in the world??", return_tensors="pt").to("cuda") + +outputs = model.generate(**inputs, max_new_tokens=50, dola_layers="high", do_sample=False) +tokenizer.batch_decode(outputs, skip_special_tokens=True) +" Mount EverestMount Everest, called Himalaya in Nepali, is the world's highest peak, lying almost 9.5 kilometers above the sea level and the tallest mountain from 19,036.91 ft. The mountain was" +``` + + + + +Contrast layers 18 and 20 with the final layer. + +```py +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM-1.7B") +model = AutoModelForCausalLM.from_pretrained("HuggingFaceTB/SmolLM-1.7B", torch_dtype=torch.float16).to("cuda") +inputs = tokenizer("What is the highest peak in the world?", return_tensors="pt").to("cuda") + +outputs = model.generate(**inputs, max_new_tokens=50, dola_layers=[18,20], do_sample=False, repetition_penalty=1.2) +tokenizer.batch_decode(outputs[:, inputs.input_ids.shape[-1]:], skip_special_tokens=True) +" Mount EverestMount Everest, called Himalaya in Nepali, is the world's highest peak above sea level and it rises to an incredible height of 29,028 feet above the ocean. Its summit is over a mile taller than Mt" +``` + + + + +### Diverse beam search + +[Diverse beam search](https://hf.co/papers/1610.02424) is a variant of beam search that produces more diverse output candidates to choose from. This strategy measures the dissimilarity of sequences and a penalty is applied if sequences are too similar. To avoid high computation costs, the number of beams is divided into groups. + +Enable diverse beam search with the `num_beams`, `num_beam_groups` and `diversity_penalty` parameters (the `num_beams` parameter should be divisible by `num_beam_groups`). + +```py +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf") +inputs = tokenizer("Hugging Face is an open-source company", return_tensors="pt").to("cuda") + +model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf", torch_dtype=torch.float16).to("cuda") +# explicitly set to 100 because Llama2 generation length is 4096 +outputs = model.generate(**inputs, max_new_tokens=50, num_beams=6, num_beam_groups=3, diversity_penalty=1.0, do_sample=False) +tokenizer.batch_decode(outputs, skip_special_tokens=True) +'Hugging Face is an open-source company 🤗\nWe are an open-source company. Our mission is to democratize AI and make it accessible to everyone. We believe that AI should be used for the benefit of humanity, not for the benefit of a' +``` + + +## Custom generation methods + +Custom generation methods enable specialized behavior such as: +- have the model continue thinking if it is uncertain; +- roll back generation if the model gets stuck; +- handle special tokens with custom logic; +- use specialized KV caches; + +We enable custom generation methods through model repositories, assuming a specific model tag and file structure (see subsection below). This feature is an extension of [custom modeling code](./models.md#custom-models) and, like such, requires setting `trust_remote_code=True`. + +If a model repository holds a custom generation method, the easiest way to try it out is to load the model and generate with it: + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer + +# `transformers-community/custom_generate_example` holds a copy of `Qwen/Qwen2.5-0.5B-Instruct`, but +# with custom generation code -> calling `generate` uses the custom generation method! +tokenizer = AutoTokenizer.from_pretrained("transformers-community/custom_generate_example") +model = AutoModelForCausalLM.from_pretrained( + "transformers-community/custom_generate_example", device_map="auto", trust_remote_code=True +) + +inputs = tokenizer(["The quick brown"], return_tensors="pt").to(model.device) +# The custom generation method is a minimal greedy decoding implementation. It also prints a custom message at run time. +gen_out = model.generate(**inputs) +# you should now see its custom message, "✨ using a custom generation method ✨" +print(tokenizer.batch_decode(gen_out, skip_special_tokens=True)) +'The quick brown fox jumps over a lazy dog, and the dog is a type of animal. Is' +``` + +Model repositories with custom generation methods have a special property: their generation method can be loaded from **any** model through [`~GenerationMixin.generate`]'s `custom_generate` argument. This means anyone can create and share their custom generation method to potentially work with any Transformers model, without requiring users to install additional Python packages. + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct") +model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct", device_map="auto") + +inputs = tokenizer(["The quick brown"], return_tensors="pt").to(model.device) +# `custom_generate` replaces the original `generate` by the custom generation method defined in +# `transformers-community/custom_generate_example` +gen_out = model.generate(**inputs, custom_generate="transformers-community/custom_generate_example", trust_remote_code=True) +print(tokenizer.batch_decode(gen_out, skip_special_tokens=True)[0]) +'The quick brown fox jumps over a lazy dog, and the dog is a type of animal. Is' +``` + +You should read the `README.md` file of the repository containing the custom generation strategy to see what the new arguments and output type differences are, if they exist. Otherwise, you can assume it works like the base [`~GenerationMixin.generate`] method. + +> [!TIP] +> You can find all custom generation methods by [searching for their custom tag.](https://huggingface.co/models?other=custom_generate), `custom_generate`. + +Consider the Hub repository [transformers-community/custom_generate_example](https://huggingface.co/transformers-community/custom_generate_example) as an example. The `README.md` states that it has an additional input argument, `left_padding`, which adds a number of padding tokens before the prompt. + +```py +gen_out = model.generate( + **inputs, custom_generate="transformers-community/custom_generate_example", trust_remote_code=True, left_padding=5 +) +print(tokenizer.batch_decode(gen_out)[0]) +'<|endoftext|><|endoftext|><|endoftext|><|endoftext|><|endoftext|>The quick brown fox jumps over the lazy dog.\n\nThe sentence "The quick' +``` + +If the custom method has pinned Python requirements that your environment doesn't meet, you'll get an exception about missing requirements. For instance, [transformers-community/custom_generate_bad_requirements](https://huggingface.co/transformers-community/custom_generate_bad_requirements) has an impossible set of requirements defined in its `custom_generate/requirements.txt` file, and you'll see the error message below if you try to run it. + +``` +ImportError: Missing requirements in your local environment for `transformers-community/custom_generate_bad_requirements`: +foo (installed: None) +bar==0.0.0 (installed: None) +torch>=99.0 (installed: 2.6.0) +``` + +Updating your Python requirements accordingly will remove this error message. + +### Creating a custom generation method + +To create a new generation method, you need to create a new [**Model**](https://huggingface.co/new) repository and push a few files into it. +1. The model you've designed your generation method with. +2. `custom_generate/generate.py`, which contains all the logic for your custom generation method. +3. `custom_generate/requirements.txt`, used to optionally add new Python requirements and/or lock specific versions to correctly use your method. +4. `README.md`, where you should add the `custom_generate` tag and document any new arguments or output type differences of your custom method here. + +After you've added all required files, your repository should look like this + +``` +your_repo/ +├── README.md # include the 'custom_generate' tag +├── config.json +├── ... +└── custom_generate/ + ├── generate.py + └── requirements.txt +``` + +#### Adding the base model + +The starting point for your custom generation method is a model repository just like any other. The model to add to this repository should be the model you've designed your method with, and it is meant to be part of a working self-contained model-generate pair. When the model in this repository is loaded, your custom generation method will override `generate`. Don't worry -- your generation method can still be loaded with any other Transformers model, as explained in the section above. + +If you simply want to copy an existing model, you can do + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("source/model_repo") +model = AutoModelForCausalLM.from_pretrained("source/model_repo") +tokenizer.save_pretrained("your/generation_method", push_to_hub=True) +model.save_pretrained("your/generation_method", push_to_hub=True) +``` + +#### generate.py + +This is the core of your generation method. It *must* contain a method named `generate`, and this method *must* contain a `model` argument as its first argument. `model` is the model instance, which means you have access to all attributes and methods in the model, including the ones defined in [`GenerationMixin`] (like the base `generate` method). + +> [!WARNING] +> `generate.py` must be placed in a folder named `custom_generate`, and not at the root level of the repository. The file paths for this feature are hardcoded. + +Under the hood, when the base [`~GenerationMixin.generate`] method is called with a `custom_generate` argument, it first checks its Python requirements (if any), then locates the custom `generate` method in `generate.py`, and finally calls the custom `generate`. All received arguments and `model` are forwarded to your custom `generate` method, with the exception of the arguments used to trigger the custom generation (`trust_remote_code` and `custom_generate`). + +This means your `generate` can have a mix of original and custom arguments (as well as a different output type) as shown below. + +```py +import torch + +def generate(model, input_ids, generation_config=None, left_padding=None, **kwargs): + generation_config = generation_config or model.generation_config # default to the model generation config + cur_length = input_ids.shape[1] + max_length = generation_config.max_length or cur_length + generation_config.max_new_tokens + + # Example of custom argument: add `left_padding` (integer) pad tokens before the prompt + if left_padding is not None: + if not isinstance(left_padding, int) or left_padding < 0: + raise ValueError(f"left_padding must be an integer larger than 0, but is {left_padding}") + + pad_token = kwargs.pop("pad_token", None) or generation_config.pad_token_id or model.config.pad_token_id + if pad_token is None: + raise ValueError("pad_token is not defined") + batch_size = input_ids.shape[0] + pad_tensor = torch.full(size=(batch_size, left_padding), fill_value=pad_token).to(input_ids.device) + input_ids = torch.cat((pad_tensor, input_ids), dim=1) + cur_length = input_ids.shape[1] + + # Simple greedy decoding loop + while cur_length < max_length: + logits = model(input_ids).logits + next_token_logits = logits[:, -1, :] + next_tokens = torch.argmax(next_token_logits, dim=-1) + input_ids = torch.cat((input_ids, next_tokens[:, None]), dim=-1) + cur_length += 1 + + return input_ids +``` + +Follow the recommended practices below to ensure your custom generation method works as expected. +- Feel free to reuse the logic for validation and input preparation in the original [`~GenerationMixin.generate`]. +- Pin the `transformers` version in the requirements if you use any private method/attribute in `model`. +- Consider adding model validation, input validation, or even a separate test file to help users sanity-check your code in their environment. + +Your custom `generate` method can relative import code from the `custom_generate` folder. For example, if you have a `utils.py` file, you can import it like this: + +```py +from .utils import some_function +``` + +Only relative imports from the same-level `custom_generate` folder are supported. Parent/sibling folder imports are not valid. The `custom_generate` argument also works locally with any directory that contains a `custom_generate` structure. This is the recommended workflow for developing your custom generation method. + + +#### requirements.txt + +You can optionally specify additional Python requirements in a `requirements.txt` file inside the `custom_generate` folder. These are checked at runtime and an exception will be thrown if they're missing, nudging users to update their environment accordingly. + +#### README.md + +The root level `README.md` in the model repository usually describes the model therein. However, since the focus of the repository is the custom generation method, we highly recommend to shift its focus towards describing the custom generation method. In addition to a description of the method, we recommend documenting any input and/or output differences to the original [`~GenerationMixin.generate`]. This way, users can focus on what's new, and rely on Transformers docs for generic implementation details. + +For discoverability, we highly recommend you to add the `custom_generate` tag to your repository. To do so, the top of your `README.md` file should look like the example below. After you push the file, you should see the tag in your repository! + +``` +--- +library_name: transformers +tags: + - custom_generate +--- + +(your markdown content here) +``` + +Recommended practices: +- Document input and output differences in [`~GenerationMixin.generate`]. +- Add self-contained examples to enable quick experimentation. +- Describe soft-requirements such as if the method only works well with a certain family of models. + +### Reusing `generate`’s input preparation + +If you're adding a new decoding loop, you might want to preserve the input preparation present in `generate` (batch expansion, attention masks, logits processors, stopping criteria, etc.). You can also pass a **callable** to `custom_generate` to reuse [`~GenerationMixin.generate`]’s full preparation pipeline while overriding only the decoding loop. + +```py +def custom_loop(model, input_ids, attention_mask, logits_processor, stopping_criteria, generation_config, **model_kwargs): + next_tokens = input_ids + while input_ids.shape[1] < stopping_criteria[0].max_length: + logits = model(next_tokens, attention_mask=attention_mask, **model_kwargs).logits + next_token_logits = logits_processor(input_ids, logits[:, -1, :]) + next_tokens = torch.argmax(next_token_logits, dim=-1)[:, None] + input_ids = torch.cat((input_ids, next_tokens), dim=-1) + attention_mask = torch.cat((attention_mask, torch.ones_like(next_tokens)), dim=-1) + return input_ids + +output = model.generate( + **inputs, + custom_generate=custom_loop, + max_new_tokens=10, +) +``` + +> [!TIP] +> If you publish a `custom_generate` repository, your `generate` implementation can itself define a callable and pass it to `model.generate()`. This lets you customize the decoding loop while still benefiting from Transformers’ built-in input preparation logic. + +### Finding custom generation methods + +You can find all custom generation methods by [searching for their custom tag.](https://huggingface.co/models?other=custom_generate), `custom_generate`. In addition to the tag, we curate two collections of `custom_generate` methods: +- [Custom generation methods - Community](https://huggingface.co/collections/transformers-community/custom-generation-methods-community-6888fb1da0efbc592d3a8ab6) -- a collection of powerful methods contributed by the community; +- [Custom generation methods - Tutorials](https://huggingface.co/collections/transformers-community/custom-generation-methods-tutorials-6823589657a94940ea02cfec) -- a collection of reference implementations for methods that previously were part of `transformers`, as well as tutorials for `custom_generate`. + +## Resources + +Read the [How to generate text: using different decoding methods for language generation with Transformers](https://huggingface.co/blog/how-to-generate) blog post for an explanation of how common decoding strategies work. diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/gguf.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/gguf.md new file mode 100644 index 0000000000000000000000000000000000000000..5043da792155ff9a18832eaee2fe0e9a66906b27 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/gguf.md @@ -0,0 +1,53 @@ + + +# GGUF + +[GGUF](https://github.com/ggerganov/ggml/blob/master/docs/gguf.md) is a file format used to store models for inference with [GGML](https://github.com/ggerganov/ggml), a fast and lightweight inference framework written in C and C++. GGUF is a single-file format containing the model metadata and tensors. + +
+ +
+ +The GGUF format also supports many quantized data types (refer to [quantization type table](https://hf.co/docs/hub/en/gguf#quantization-types) for a complete list of supported quantization types) which saves a significant amount of memory, making inference with large models like Whisper and Llama feasible on local and edge devices. + +Transformers supports loading models stored in the GGUF format for further training or finetuning. The GGUF checkpoint is **dequantized to fp32** where the full model weights are available and compatible with PyTorch. + +> [!TIP] +> Models that support GGUF include Llama, Mistral, Qwen2, Qwen2Moe, Phi3, Bloom, Falcon, StableLM, GPT2, Starcoder2, and [more](https://github.com/huggingface/transformers/blob/main/src/transformers/integrations/ggml.py) + +Add the `gguf_file` parameter to [`~PreTrainedModel.from_pretrained`] to specify the GGUF file to load. + +```py +# pip install gguf +from transformers import AutoTokenizer, AutoModelForCausalLM + +model_id = "TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF" +filename = "tinyllama-1.1b-chat-v1.0.Q6_K.gguf" + +torch_dtype = torch.float32 # could be torch.float16 or torch.bfloat16 too +tokenizer = AutoTokenizer.from_pretrained(model_id, gguf_file=filename) +model = AutoModelForCausalLM.from_pretrained(model_id, gguf_file=filename, torch_dtype=torch_dtype) +``` + +Once you're done tinkering with the model, save and convert it back to the GGUF format with the [convert-hf-to-gguf.py](https://github.com/ggerganov/llama.cpp/blob/master/convert_hf_to_gguf.py) script. + +```py +tokenizer.save_pretrained("directory") +model.save_pretrained("directory") + +!python ${path_to_llama_cpp}/convert-hf-to-gguf.py ${directory} +``` diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/glossary.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/glossary.md new file mode 100644 index 0000000000000000000000000000000000000000..b65f45341e3934dd182c481f91e8c3fc4cb559ad --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/glossary.md @@ -0,0 +1,522 @@ + + +# Glossary + +This glossary defines general machine learning and 🤗 Transformers terms to help you better understand the +documentation. + +## A + +### attention mask + +The attention mask is an optional argument used when batching sequences together. + + + +This argument indicates to the model which tokens should be attended to, and which should not. + +For example, consider these two sequences: + +```python +>>> from transformers import BertTokenizer + +>>> tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-cased") + +>>> sequence_a = "This is a short sequence." +>>> sequence_b = "This is a rather long sequence. It is at least longer than the sequence A." + +>>> encoded_sequence_a = tokenizer(sequence_a)["input_ids"] +>>> encoded_sequence_b = tokenizer(sequence_b)["input_ids"] +``` + +The encoded versions have different lengths: + +```python +>>> len(encoded_sequence_a), len(encoded_sequence_b) +(8, 19) +``` + +Therefore, we can't put them together in the same tensor as-is. The first sequence needs to be padded up to the length +of the second one, or the second one needs to be truncated down to the length of the first one. + +In the first case, the list of IDs will be extended by the padding indices. We can pass a list to the tokenizer and ask +it to pad like this: + +```python +>>> padded_sequences = tokenizer([sequence_a, sequence_b], padding=True) +``` + +We can see that 0s have been added on the right of the first sentence to make it the same length as the second one: + +```python +>>> padded_sequences["input_ids"] +[[101, 1188, 1110, 170, 1603, 4954, 119, 102, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [101, 1188, 1110, 170, 1897, 1263, 4954, 119, 1135, 1110, 1120, 1655, 2039, 1190, 1103, 4954, 138, 119, 102]] +``` + +This can then be converted into a tensor in PyTorch or TensorFlow. The attention mask is a binary tensor indicating the +position of the padded indices so that the model does not attend to them. For the [`BertTokenizer`], `1` indicates a +value that should be attended to, while `0` indicates a padded value. This attention mask is in the dictionary returned +by the tokenizer under the key "attention_mask": + +```python +>>> padded_sequences["attention_mask"] +[[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] +``` + +### autoencoding models + +See [encoder models](#encoder-models) and [masked language modeling](#masked-language-modeling-mlm) + +### autoregressive models + +See [causal language modeling](#causal-language-modeling) and [decoder models](#decoder-models) + +## B + +### backbone + +The backbone is the network (embeddings and layers) that outputs the raw hidden states or features. It is usually connected to a [head](#head) which accepts the features as its input to make a prediction. For example, [`ViTModel`] is a backbone without a specific head on top. Other models can also use [`VitModel`] as a backbone such as [DPT](model_doc/dpt). + +## C + +### causal language modeling + +A pretraining task where the model reads the texts in order and has to predict the next word. It's usually done by +reading the whole sentence but using a mask inside the model to hide the future tokens at a certain timestep. + +### channel + +Color images are made up of some combination of values in three channels: red, green, and blue (RGB) and grayscale images only have one channel. In 🤗 Transformers, the channel can be the first or last dimension of an image's tensor: [`n_channels`, `height`, `width`] or [`height`, `width`, `n_channels`]. + +### connectionist temporal classification (CTC) + +An algorithm which allows a model to learn without knowing exactly how the input and output are aligned; CTC calculates the distribution of all possible outputs for a given input and chooses the most likely output from it. CTC is commonly used in speech recognition tasks because speech doesn't always cleanly align with the transcript for a variety of reasons such as a speaker's different speech rates. + +### convolution + +A type of layer in a neural network where the input matrix is multiplied element-wise by a smaller matrix (kernel or filter) and the values are summed up in a new matrix. This is known as a convolutional operation which is repeated over the entire input matrix. Each operation is applied to a different segment of the input matrix. Convolutional neural networks (CNNs) are commonly used in computer vision. + +## D + +### DataParallel (DP) + +Parallelism technique for training on multiple GPUs where the same setup is replicated multiple times, with each instance +receiving a distinct data slice. The processing is done in parallel and all setups are synchronized at the end of each training step. + +Learn more about how DataParallel works [here](perf_train_gpu_many#dataparallel-vs-distributeddataparallel). + +### decoder input IDs + +This input is specific to encoder-decoder models, and contains the input IDs that will be fed to the decoder. These +inputs should be used for sequence to sequence tasks, such as translation or summarization, and are usually built in a +way specific to each model. + +Most encoder-decoder models (BART, T5) create their `decoder_input_ids` on their own from the `labels`. In such models, +passing the `labels` is the preferred way to handle training. + +Please check each model's docs to see how they handle these input IDs for sequence to sequence training. + +### decoder models + +Also referred to as autoregressive models, decoder models involve a pretraining task (called causal language modeling) where the model reads the texts in order and has to predict the next word. It's usually done by +reading the whole sentence with a mask to hide future tokens at a certain timestep. + + + +### deep learning (DL) + +Machine learning algorithms which use neural networks with several layers. + +## E + +### encoder models + +Also known as autoencoding models, encoder models take an input (such as text or images) and transform them into a condensed numerical representation called an embedding. Oftentimes, encoder models are pretrained using techniques like [masked language modeling](#masked-language-modeling-mlm), which masks parts of the input sequence and forces the model to create more meaningful representations. + + + +## F + +### feature extraction + +The process of selecting and transforming raw data into a set of features that are more informative and useful for machine learning algorithms. Some examples of feature extraction include transforming raw text into word embeddings and extracting important features such as edges or shapes from image/video data. + +### feed forward chunking + +In each residual attention block in transformers the self-attention layer is usually followed by 2 feed forward layers. +The intermediate embedding size of the feed forward layers is often bigger than the hidden size of the model (e.g., for +`google-bert/bert-base-uncased`). + +For an input of size `[batch_size, sequence_length]`, the memory required to store the intermediate feed forward +embeddings `[batch_size, sequence_length, config.intermediate_size]` can account for a large fraction of the memory +use. The authors of [Reformer: The Efficient Transformer](https://huggingface.co/papers/2001.04451) noticed that since the +computation is independent of the `sequence_length` dimension, it is mathematically equivalent to compute the output +embeddings of both feed forward layers `[batch_size, config.hidden_size]_0, ..., [batch_size, config.hidden_size]_n` +individually and concat them afterward to `[batch_size, sequence_length, config.hidden_size]` with `n = sequence_length`, which trades increased computation time against reduced memory use, but yields a mathematically +**equivalent** result. + +For models employing the function [`apply_chunking_to_forward`], the `chunk_size` defines the number of output +embeddings that are computed in parallel and thus defines the trade-off between memory and time complexity. If +`chunk_size` is set to 0, no feed forward chunking is done. + +### finetuned models + +Finetuning is a form of transfer learning which involves taking a pretrained model, freezing its weights, and replacing the output layer with a newly added [model head](#head). The model head is trained on your target dataset. + +See the [Fine-tune a pretrained model](https://huggingface.co/docs/transformers/training) tutorial for more details, and learn how to fine-tune models with 🤗 Transformers. + +## H + +### head + +The model head refers to the last layer of a neural network that accepts the raw hidden states and projects them onto a different dimension. There is a different model head for each task. For example: + + * [`GPT2ForSequenceClassification`] is a sequence classification head - a linear layer - on top of the base [`GPT2Model`]. + * [`ViTForImageClassification`] is an image classification head - a linear layer on top of the final hidden state of the `CLS` token - on top of the base [`ViTModel`]. + * [`Wav2Vec2ForCTC`] is a language modeling head with [CTC](#connectionist-temporal-classification-ctc) on top of the base [`Wav2Vec2Model`]. + +## I + +### image patch + +Vision-based Transformers models split an image into smaller patches which are linearly embedded, and then passed as a sequence to the model. You can find the `patch_size` - or resolution - of the model in its configuration. + +### inference + +Inference is the process of evaluating a model on new data after training is complete. See the [Pipeline for inference](https://huggingface.co/docs/transformers/pipeline_tutorial) tutorial to learn how to perform inference with 🤗 Transformers. + +### input IDs + +The input ids are often the only required parameters to be passed to the model as input. They are token indices, +numerical representations of tokens building the sequences that will be used as input by the model. + + + +Each tokenizer works differently but the underlying mechanism remains the same. Here's an example using the BERT +tokenizer, which is a [WordPiece](https://huggingface.co/papers/1609.08144) tokenizer: + +```python +>>> from transformers import BertTokenizer + +>>> tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-cased") + +>>> sequence = "A Titan RTX has 24GB of VRAM" +``` + +The tokenizer takes care of splitting the sequence into tokens available in the tokenizer vocabulary. + +```python +>>> tokenized_sequence = tokenizer.tokenize(sequence) +``` + +The tokens are either words or subwords. Here for instance, "VRAM" wasn't in the model vocabulary, so it's been split +in "V", "RA" and "M". To indicate those tokens are not separate words but parts of the same word, a double-hash prefix +is added for "RA" and "M": + +```python +>>> print(tokenized_sequence) +['A', 'Titan', 'R', '##T', '##X', 'has', '24', '##GB', 'of', 'V', '##RA', '##M'] +``` + +These tokens can then be converted into IDs which are understandable by the model. This can be done by directly feeding the sentence to the tokenizer, which leverages the Rust implementation of [🤗 Tokenizers](https://github.com/huggingface/tokenizers) for peak performance. + +```python +>>> inputs = tokenizer(sequence) +``` + +The tokenizer returns a dictionary with all the arguments necessary for its corresponding model to work properly. The +token indices are under the key `input_ids`: + +```python +>>> encoded_sequence = inputs["input_ids"] +>>> print(encoded_sequence) +[101, 138, 18696, 155, 1942, 3190, 1144, 1572, 13745, 1104, 159, 9664, 2107, 102] +``` + +Note that the tokenizer automatically adds "special tokens" (if the associated model relies on them) which are special +IDs the model sometimes uses. + +If we decode the previous sequence of ids, + +```python +>>> decoded_sequence = tokenizer.decode(encoded_sequence) +``` + +we will see + +```python +>>> print(decoded_sequence) +[CLS] A Titan RTX has 24GB of VRAM [SEP] +``` + +because this is the way a [`BertModel`] is going to expect its inputs. + +## L + +### labels + +The labels are an optional argument which can be passed in order for the model to compute the loss itself. These labels +should be the expected prediction of the model: it will use the standard loss in order to compute the loss between its +predictions and the expected value (the label). + +These labels are different according to the model head, for example: + +- For sequence classification models, ([`BertForSequenceClassification`]), the model expects a tensor of dimension + `(batch_size)` with each value of the batch corresponding to the expected label of the entire sequence. +- For token classification models, ([`BertForTokenClassification`]), the model expects a tensor of dimension + `(batch_size, seq_length)` with each value corresponding to the expected label of each individual token. +- For masked language modeling, ([`BertForMaskedLM`]), the model expects a tensor of dimension `(batch_size, + seq_length)` with each value corresponding to the expected label of each individual token: the labels being the token + ID for the masked token, and values to be ignored for the rest (usually -100). +- For sequence to sequence tasks, ([`BartForConditionalGeneration`], [`MBartForConditionalGeneration`]), the model + expects a tensor of dimension `(batch_size, tgt_seq_length)` with each value corresponding to the target sequences + associated with each input sequence. During training, both BART and T5 will make the appropriate + `decoder_input_ids` and decoder attention masks internally. They usually do not need to be supplied. This does not + apply to models leveraging the Encoder-Decoder framework. +- For image classification models, ([`ViTForImageClassification`]), the model expects a tensor of dimension + `(batch_size)` with each value of the batch corresponding to the expected label of each individual image. +- For semantic segmentation models, ([`SegformerForSemanticSegmentation`]), the model expects a tensor of dimension + `(batch_size, height, width)` with each value of the batch corresponding to the expected label of each individual pixel. +- For object detection models, ([`DetrForObjectDetection`]), the model expects a list of dictionaries with a + `class_labels` and `boxes` key where each value of the batch corresponds to the expected label and number of bounding boxes of each individual image. +- For automatic speech recognition models, ([`Wav2Vec2ForCTC`]), the model expects a tensor of dimension `(batch_size, + target_length)` with each value corresponding to the expected label of each individual token. + + + +Each model's labels may be different, so be sure to always check the documentation of each model for more information +about their specific labels! + + + +The base models ([`BertModel`]) do not accept labels, as these are the base transformer models, simply outputting +features. + +### large language models (LLM) + +A generic term that refers to transformer language models (GPT-3, BLOOM, OPT) that were trained on a large quantity of data. These models also tend to have a large number of learnable parameters (e.g. 175 billion for GPT-3). + +## M + +### masked language modeling (MLM) + +A pretraining task where the model sees a corrupted version of the texts, usually done by +masking some tokens randomly, and has to predict the original text. + +### multimodal + +A task that combines texts with another kind of inputs (for instance images). + +## N + +### Natural language generation (NLG) + +All tasks related to generating text (for instance, [Write With Transformers](https://transformer.huggingface.co/), translation). + +### Natural language processing (NLP) + +A generic way to say "deal with texts". + +### Natural language understanding (NLU) + +All tasks related to understanding what is in a text (for instance classifying the +whole text, individual words). + +## P + +### pipeline + +A pipeline in 🤗 Transformers is an abstraction referring to a series of steps that are executed in a specific order to preprocess and transform data and return a prediction from a model. Some example stages found in a pipeline might be data preprocessing, feature extraction, and normalization. + +For more details, see [Pipelines for inference](https://huggingface.co/docs/transformers/pipeline_tutorial). + +### PipelineParallel (PP) + +Parallelism technique in which the model is split up vertically (layer-level) across multiple GPUs, so that only one or +several layers of the model are placed on a single GPU. Each GPU processes in parallel different stages of the pipeline +and working on a small chunk of the batch. Learn more about how PipelineParallel works [here](perf_train_gpu_many#from-naive-model-parallelism-to-pipeline-parallelism). + +### pixel values + +A tensor of the numerical representations of an image that is passed to a model. The pixel values have a shape of [`batch_size`, `num_channels`, `height`, `width`], and are generated from an image processor. + +### pooling + +An operation that reduces a matrix into a smaller matrix, either by taking the maximum or average of the pooled dimension(s). Pooling layers are commonly found between convolutional layers to downsample the feature representation. + +### position IDs + +Contrary to RNNs that have the position of each token embedded within them, transformers are unaware of the position of +each token. Therefore, the position IDs (`position_ids`) are used by the model to identify each token's position in the +list of tokens. + +They are an optional parameter. If no `position_ids` are passed to the model, the IDs are automatically created as +absolute positional embeddings. + +Absolute positional embeddings are selected in the range `[0, config.max_position_embeddings - 1]`. Some models use +other types of positional embeddings, such as sinusoidal position embeddings or relative position embeddings. + +### preprocessing + +The task of preparing raw data into a format that can be easily consumed by machine learning models. For example, text is typically preprocessed by tokenization. To gain a better idea of what preprocessing looks like for other input types, check out the [Preprocess](https://huggingface.co/docs/transformers/preprocessing) tutorial. + +### pretrained model + +A model that has been pretrained on some data (for instance all of Wikipedia). Pretraining methods involve a +self-supervised objective, which can be reading the text and trying to predict the next word (see [causal language +modeling](#causal-language-modeling)) or masking some words and trying to predict them (see [masked language +modeling](#masked-language-modeling-mlm)). + +Speech and vision models have their own pretraining objectives. For example, Wav2Vec2 is a speech model pretrained on a contrastive task which requires the model to identify the "true" speech representation from a set of "false" speech representations. On the other hand, BEiT is a vision model pretrained on a masked image modeling task which masks some of the image patches and requires the model to predict the masked patches (similar to the masked language modeling objective). + +## R + +### recurrent neural network (RNN) + +A type of model that uses a loop over a layer to process texts. + +### representation learning + +A subfield of machine learning which focuses on learning meaningful representations of raw data. Some examples of representation learning techniques include word embeddings, autoencoders, and Generative Adversarial Networks (GANs). + +## S + +### sampling rate + +A measurement in hertz of the number of samples (the audio signal) taken per second. The sampling rate is a result of discretizing a continuous signal such as speech. + +### self-attention + +Each element of the input finds out which other elements of the input they should attend to. + +### self-supervised learning + +A category of machine learning techniques in which a model creates its own learning objective from unlabeled data. It differs from [unsupervised learning](#unsupervised-learning) and [supervised learning](#supervised-learning) in that the learning process is supervised, but not explicitly from the user. + +One example of self-supervised learning is [masked language modeling](#masked-language-modeling-mlm), where a model is passed sentences with a proportion of its tokens removed and learns to predict the missing tokens. + +### semi-supervised learning + +A broad category of machine learning training techniques that leverages a small amount of labeled data with a larger quantity of unlabeled data to improve the accuracy of a model, unlike [supervised learning](#supervised-learning) and [unsupervised learning](#unsupervised-learning). + +An example of a semi-supervised learning approach is "self-training", in which a model is trained on labeled data, and then used to make predictions on the unlabeled data. The portion of the unlabeled data that the model predicts with the most confidence gets added to the labeled dataset and used to retrain the model. + +### sequence-to-sequence (seq2seq) + +Models that generate a new sequence from an input, like translation models, or summarization models (such as +[Bart](model_doc/bart) or [T5](model_doc/t5)). + +### Sharded DDP + +Another name for the foundational [ZeRO](#zero-redundancy-optimizer-zero) concept as used by various other implementations of ZeRO. + +### stride + +In [convolution](#convolution) or [pooling](#pooling), the stride refers to the distance the kernel is moved over a matrix. A stride of 1 means the kernel is moved one pixel over at a time, and a stride of 2 means the kernel is moved two pixels over at a time. + +### supervised learning + +A form of model training that directly uses labeled data to correct and instruct model performance. Data is fed into the model being trained, and its predictions are compared to the known labels. The model updates its weights based on how incorrect its predictions were, and the process is repeated to optimize model performance. + +## T + +### Tensor Parallelism (TP) + +Parallelism technique for training on multiple GPUs in which each tensor is split up into multiple chunks, so instead of +having the whole tensor reside on a single GPU, each shard of the tensor resides on its designated GPU. Shards gets +processed separately and in parallel on different GPUs and the results are synced at the end of the processing step. +This is what is sometimes called horizontal parallelism, as the splitting happens on horizontal level. +Learn more about Tensor Parallelism [here](perf_train_gpu_many#tensor-parallelism). + +### token + +A part of a sentence, usually a word, but can also be a subword (non-common words are often split in subwords) or a +punctuation symbol. + +### token Type IDs + +Some models' purpose is to do classification on pairs of sentences or question answering. + + + +These require two different sequences to be joined in a single "input_ids" entry, which usually is performed with the +help of special tokens, such as the classifier (`[CLS]`) and separator (`[SEP]`) tokens. For example, the BERT model +builds its two sequence input as such: + +```python +>>> # [CLS] SEQUENCE_A [SEP] SEQUENCE_B [SEP] +``` + +We can use our tokenizer to automatically generate such a sentence by passing the two sequences to `tokenizer` as two +arguments (and not a list, like before) like this: + +```python +>>> from transformers import BertTokenizer + +>>> tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-cased") +>>> sequence_a = "HuggingFace is based in NYC" +>>> sequence_b = "Where is HuggingFace based?" + +>>> encoded_dict = tokenizer(sequence_a, sequence_b) +>>> decoded = tokenizer.decode(encoded_dict["input_ids"]) +``` + +which will return: + +```python +>>> print(decoded) +[CLS] HuggingFace is based in NYC [SEP] Where is HuggingFace based? [SEP] +``` + +This is enough for some models to understand where one sequence ends and where another begins. However, other models, +such as BERT, also deploy token type IDs (also called segment IDs). They are represented as a binary mask identifying +the two types of sequence in the model. + +The tokenizer returns this mask as the "token_type_ids" entry: + +```python +>>> encoded_dict["token_type_ids"] +[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1] +``` + +The first sequence, the "context" used for the question, has all its tokens represented by a `0`, whereas the second +sequence, corresponding to the "question", has all its tokens represented by a `1`. + +Some models, like [`XLNetModel`] use an additional token represented by a `2`. + +### transfer learning + +A technique that involves taking a pretrained model and adapting it to a dataset specific to your task. Instead of training a model from scratch, you can leverage knowledge obtained from an existing model as a starting point. This speeds up the learning process and reduces the amount of training data needed. + +### transformer + +Self-attention based deep learning model architecture. + +## U + +### unsupervised learning + +A form of model training in which data provided to the model is not labeled. Unsupervised learning techniques leverage statistical information of the data distribution to find patterns useful for the task at hand. + +## Z + +### Zero Redundancy Optimizer (ZeRO) + +Parallelism technique which performs sharding of the tensors somewhat similar to [TensorParallel](#tensor-parallelism-tp), +except the whole tensor gets reconstructed in time for a forward or backward computation, therefore the model doesn't need +to be modified. This method also supports various offloading techniques to compensate for limited GPU memory. +Learn more about ZeRO [here](perf_train_gpu_many#zero-data-parallelism). diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/how_to_hack_models.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/how_to_hack_models.md new file mode 100644 index 0000000000000000000000000000000000000000..0a3c38a3e14f955051df88812393076e625f3ed8 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/how_to_hack_models.md @@ -0,0 +1,152 @@ + + +# Customizing model components + +Another way to customize a model is to modify their components, rather than writing a new model entirely, allowing you to tailor a model to your specific use case. For example, you can add new layers or optimize the attention mechanism of an architecture. Customizations are applied directly to a Transformers model so that you can continue to use features such as [`Trainer`], [`PreTrainedModel`], and the [PEFT](https://huggingface.co/docs/peft/en/index) library. + +This guide will show you how to customize a models attention mechanism in order to apply [Low-Rank Adaptation (LoRA)](https://huggingface.co/docs/peft/conceptual_guides/adapter#low-rank-adaptation-lora) to it. + +> [!TIP] +> The [clear_import_cache](https://github.com/huggingface/transformers/blob/9985d06add07a4cc691dc54a7e34f54205c04d40/src/transformers/utils/import_utils.py#L2286) utility is very useful when you're iteratively modifying and developing model code. It removes all cached Transformers modules and allows Python to reload the modified code without constantly restarting your environment. +> +> ```py +> from transformers import AutoModel +> from transformers.utils.import_utils import clear_import_cache +> +> model = AutoModel.from_pretrained("bert-base-uncased") +> # modifications to model code +> # clear cache to reload modified code +> clear_import_cache() +> # re-import to use updated code +> model = AutoModel.from_pretrained("bert-base-uncased") +> ``` + +## Attention class + +[Segment Anything](./model_doc/sam) is an image segmentation model, and it combines the query-key-value (`qkv`) projection in its attention mechanisms. To reduce the number of trainable parameters and computational overhead, you can apply LoRA to the `qkv` projection. This requires splitting the `qkv` projection so that you can separately target the `q` and `v` with LoRA. + +1. Create a custom attention class, `SamVisionAttentionSplit`, by subclassing the original `SamVisionAttention` class. In the `__init__`, delete the combined `qkv` and create a separate linear layer for `q`, `k` and `v`. + +```py +import torch +import torch.nn as nn +from transformers.models.sam.modeling_sam import SamVisionAttention + +class SamVisionAttentionSplit(SamVisionAttention, nn.Module): + def __init__(self, config, window_size): + super().__init__(config, window_size) + # remove combined qkv + del self.qkv + # separate q, k, v projections + self.q = nn.Linear(config.hidden_size, config.hidden_size, bias=config.qkv_bias) + self.k = nn.Linear(config.hidden_size, config.hidden_size, bias=config.qkv_bias) + self.v = nn.Linear(config.hidden_size, config.hidden_size, bias=config.qkv_bias) + self._register_load_state_dict_pre_hook(self.split_q_k_v_load_hook) +``` + +2. The `_split_qkv_load_hook` function splits the pretrained `qkv` weights into separate `q`, `k`, and `v` weights when loading the model to ensure compatibility with any pretrained model. + +```py + def split_q_k_v_load_hook(self, state_dict, prefix, *args): + keys_to_delete = [] + for key in list(state_dict.keys()): + if "qkv." in key: + # split q, k, v from the combined projection + q, k, v = state_dict[key].chunk(3, dim=0) + # replace with individual q, k, v projections + state_dict[key.replace("qkv.", "q.")] = q + state_dict[key.replace("qkv.", "k.")] = k + state_dict[key.replace("qkv.", "v.")] = v + # mark the old qkv key for deletion + keys_to_delete.append(key) + + # remove old qkv keys + for key in keys_to_delete: + del state_dict[key] +``` + +3. In the `forward` pass, `q`, `k`, and `v` are computed separately while the rest of the attention mechanism remains the same. + +```py + def forward(self, hidden_states: torch.Tensor, output_attentions=False) -> torch.Tensor: + batch_size, height, width, _ = hidden_states.shape + qkv_shapes = (batch_size * self.num_attention_heads, height * width, -1) + query = self.q(hidden_states).reshape((batch_size, height * width,self.num_attention_heads, -1)).permute(0,2,1,3).reshape(qkv_shapes) + key = self.k(hidden_states).reshape((batch_size, height * width,self.num_attention_heads, -1)).permute(0,2,1,3).reshape(qkv_shapes) + value = self.v(hidden_states).reshape((batch_size, height * width,self.num_attention_heads, -1)).permute(0,2,1,3).reshape(qkv_shapes) + + attn_weights = (query * self.scale) @ key.transpose(-2, -1) + + attn_weights = torch.nn.functional.softmax(attn_weights, dtype=torch.float32, dim=-1).to(query.dtype) + attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training) + attn_output = (attn_probs @ value).reshape(batch_size, self.num_attention_heads, height, width, -1) + attn_output = attn_output.permute(0, 2, 3, 1, 4).reshape(batch_size, height, width, -1) + attn_output = self.proj(attn_output) + + if output_attentions: + outputs = (attn_output, attn_weights) + else: + outputs = (attn_output, None) + return outputs +``` + +Assign the custom `SamVisionAttentionSplit` class to the original models `SamVisionAttention` module to replace it. All instances of `SamVisionAttention` in the model is replaced with the split attention version. + +Load the model with [`~PreTrainedModel.from_pretrained`]. + +```py +from transformers import SamModel + +# load the pretrained SAM model +model = SamModel.from_pretrained("facebook/sam-vit-base") + +# replace the attention class in the vision_encoder module +for layer in model.vision_encoder.layers: + if hasattr(layer, "attn"): + layer.attn = SamVisionAttentionSplit(model.config.vision_config, model.config.vision_config.window_size) +``` + +## LoRA + +With separate `q`, `k`, and `v` projections, apply LoRA to `q` and `v`. + +Create a [LoraConfig](https://huggingface.co/docs/peft/package_reference/config#peft.PeftConfig) and specify the rank `r`, `lora_alpha`, `lora_dropout`, `task_type`, and most importantly, the modules to target. + +```py +from peft import LoraConfig, get_peft_model + +config = LoraConfig( + r=16, + lora_alpha=32, + # apply LoRA to q and v + target_modules=["q", "v"], + lora_dropout=0.1, + task_type="FEATURE_EXTRACTION" +) +``` + +Pass the model and [LoraConfig](https://huggingface.co/docs/peft/package_reference/config#peft.PeftConfig) to [get_peft_model](https://huggingface.co/docs/peft/package_reference/peft_model#peft.get_peft_model) to apply LoRA to the model. + +```py +model = get_peft_model(model, config) +``` + +Call [print_trainable_parameters](https://huggingface.co/docs/peft/package_reference/peft_model#peft.PeftMixedModel.print_trainable_parameters) to view the number of parameters you're training as a result versus the total number of parameters. + +```py +model.print_trainable_parameters() +"trainable params: 589,824 || all params: 94,274,096 || trainable%: 0.6256" +``` \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/hpo_train.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/hpo_train.md new file mode 100644 index 0000000000000000000000000000000000000000..e93043485b159843b837e5843e06eebe464eb3b5 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/hpo_train.md @@ -0,0 +1,170 @@ + + +# Hyperparameter search + +Hyperparameter search discovers an optimal set of hyperparameters that produces the best model performance. [`Trainer`] supports several hyperparameter search backends - [Optuna](https://optuna.readthedocs.io/en/stable/index.html), [SigOpt](https://docs.sigopt.com/), [Weights & Biases](https://docs.wandb.ai/), [Ray Tune](https://docs.ray.io/en/latest/tune/index.html) - through [`~Trainer.hyperparameter_search`] to optimize an objective or even multiple objectives. + +This guide will go over how to set up a hyperparameter search for each of the backends. + +> [!WARNING] +> [SigOpt](https://github.com/sigopt/sigopt-server) is in public archive mode and is no longer actively maintained. Try using Optuna, Weights & Biases or Ray Tune instead. + +```bash +pip install optuna/sigopt/wandb/ray[tune] +``` + +To use [`~Trainer.hyperparameter_search`], you need to create a `model_init` function. This function includes basic model information (arguments and configuration) because it needs to be reinitialized for each search trial in the run. + +> [!WARNING] +> The `model_init` function is incompatible with the [optimizers](./main_classes/trainer#transformers.Trainer.optimizers) parameter. Subclass [`Trainer`] and override the [`~Trainer.create_optimizer_and_scheduler`] method to create a custom optimizer and scheduler. + +An example `model_init` function is shown below. + +```py +def model_init(trial): + return AutoModelForSequenceClassification.from_pretrained( + model_args.model_name_or_path, + from_tf=bool(".ckpt" in model_args.model_name_or_path), + config=config, + cache_dir=model_args.cache_dir, + revision=model_args.model_revision, + token=True if model_args.use_auth_token else None, + ) +``` + +Pass `model_init` to [`Trainer`] along with everything else you need for training. Then you can call [`~Trainer.hyperparameter_search`] to start the search. + +[`~Trainer.hyperparameter_search`] accepts a [direction](./main_classes/trainer#transformers.Trainer.hyperparameter_search.direction) parameter to specify whether to minimize, maximize, or minimize and maximize multiple objectives. You'll also need to set the [backend](./main_classes/trainer#transformers.Trainer.hyperparameter_search.backend) you're using, an [object](./main_classes/trainer#transformers.Trainer.hyperparameter_search.hp_space) containing the hyperparameters to optimize for, the [number of trials](./main_classes/trainer#transformers.Trainer.hyperparameter_search.n_trials) to run, and a [compute_objective](./main_classes/trainer#transformers.Trainer.hyperparameter_search.compute_objective) to return the objective values. + +> [!TIP] +> If [compute_objective](./main_classes/trainer#transformers.Trainer.hyperparameter_search.compute_objective) isn't defined, the default [compute_objective](./main_classes/trainer#transformers.Trainer.hyperparameter_search.compute_objective) is called which is the sum of an evaluation metric like F1. + +```py +from transformers import Trainer + +trainer = Trainer( + model=None, + args=training_args, + train_dataset=small_train_dataset, + eval_dataset=small_eval_dataset, + compute_metrics=compute_metrics, + processing_class=tokenizer, + model_init=model_init, + data_collator=data_collator, +) +trainer.hyperparameter_search(...) +``` + +The following examples demonstrate how to perform a hyperparameter search for the learning rate and training batch size using the different backends. + + + + +[Optuna](https://optuna.readthedocs.io/en/stable/tutorial/10_key_features/002_configurations.html#sphx-glr-tutorial-10-key-features-002-configurations-py) optimizes categories, integers, and floats. + +```py +def optuna_hp_space(trial): + return { + "learning_rate": trial.suggest_float("learning_rate", 1e-6, 1e-4, log=True), + "per_device_train_batch_size": trial.suggest_categorical("per_device_train_batch_size", [16, 32, 64, 128]), + } + +best_trials = trainer.hyperparameter_search( + direction=["minimize", "maximize"], + backend="optuna", + hp_space=optuna_hp_space, + n_trials=20, + compute_objective=compute_objective, +) +``` + + + + +[Ray Tune](https://docs.ray.io/en/latest/tune/api/search_space.html) optimizes floats, integers, and categorical parameters. It also offers multiple sampling distributions for each parameter such as uniform and log-uniform. + +```py +def ray_hp_space(trial): + return { + "learning_rate": tune.loguniform(1e-6, 1e-4), + "per_device_train_batch_size": tune.choice([16, 32, 64, 128]), + } + +best_trials = trainer.hyperparameter_search( + direction=["minimize", "maximize"], + backend="ray", + hp_space=ray_hp_space, + n_trials=20, + compute_objective=compute_objective, +) +``` + + + + +[SigOpt](https://docs.sigopt.com/ai-module-api-references/api_reference/objects/object_parameter) optimizes double, integer, and categorical parameters. + +```py +def sigopt_hp_space(trial): + return [ + {"bounds": {"min": 1e-6, "max": 1e-4}, "name": "learning_rate", "type": "double"}, + { + "categorical_values": ["16", "32", "64", "128"], + "name": "per_device_train_batch_size", + "type": "categorical", + }, + ] + +best_trials = trainer.hyperparameter_search( + direction=["minimize", "maximize"], + backend="sigopt", + hp_space=sigopt_hp_space, + n_trials=20, + compute_objective=compute_objective, +) +``` + + + + +[Weights & Biases](https://docs.wandb.ai/guides/sweeps/sweep-config-keys) also optimizes integers, floats, and categorical parameters. It also includes support for different search strategies and distribution options. + +```py +def wandb_hp_space(trial): + return { + "method": "random", + "metric": {"name": "objective", "goal": "minimize"}, + "parameters": { + "learning_rate": {"distribution": "uniform", "min": 1e-6, "max": 1e-4}, + "per_device_train_batch_size": {"values": [16, 32, 64, 128]}, + }, + } + +best_trials = trainer.hyperparameter_search( + direction=["minimize", "maximize"], + backend="wandb", + hp_space=wandb_hp_space, + n_trials=20, + compute_objective=compute_objective, +) +``` + + + + +## Distributed Data Parallel + +[`Trainer`] only supports hyperparameter search for distributed data parallel (DDP) on the Optuna and SigOpt backends. Only the rank-zero process is used to generate the search trial, and the resulting parameters are passed along to the other ranks. diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/image_processors.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/image_processors.md new file mode 100644 index 0000000000000000000000000000000000000000..feb568bdd3bab04019ff8ce9acf3e5a58bdc84f8 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/image_processors.md @@ -0,0 +1,222 @@ + + +# Image processors + +Image processors converts images into pixel values, tensors that represent image colors and size. The pixel values are inputs to a vision model. To ensure a pretrained model receives the correct input, an image processor can perform the following operations to make sure an image is exactly like the images a model was pretrained on. + +- [`~BaseImageProcessor.center_crop`] to resize an image +- [`~BaseImageProcessor.normalize`] or [`~BaseImageProcessor.rescale`] pixel values + +Use [`~ImageProcessingMixin.from_pretrained`] to load an image processors configuration (image size, whether to normalize and rescale, etc.) from a vision model on the Hugging Face [Hub](https://hf.co) or local directory. The configuration for each pretrained model is saved in a [preprocessor_config.json](https://huggingface.co/google/vit-base-patch16-224/blob/main/preprocessor_config.json) file. + +```py +from transformers import AutoImageProcessor + +image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224") +``` + +Pass an image to the image processor to transform it into pixel values, and set `return_tensors="pt"` to return PyTorch tensors. Feel free to print out the inputs to see what the image looks like as a tensor. + +```py +from PIL import Image +import requests + +url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/image_processor_example.png" +image = Image.open(requests.get(url, stream=True).raw).convert("RGB") +inputs = image_processor(image, return_tensors="pt") +``` + +This guide covers the image processor class and how to preprocess images for vision models. + +## Image processor classes + +Image processors inherit from the [`BaseImageProcessor`] class which provides the [`~BaseImageProcessor.center_crop`], [`~BaseImageProcessor.normalize`], and [`~BaseImageProcessor.rescale`] functions. There are two types of image processors. + +- [`BaseImageProcessor`] is a Python implementation. +- [`BaseImageProcessorFast`] is a faster [torchvision-backed](https://pytorch.org/vision/stable/index.html) version. For a batch of [torch.Tensor](https://pytorch.org/docs/stable/tensors.html) inputs, this can be up to 33x faster. [`BaseImageProcessorFast`] is not available for all vision models at the moment. Refer to a models API documentation to check if it is supported. + +Each image processor subclasses the [`ImageProcessingMixin`] class which provides the [`~ImageProcessingMixin.from_pretrained`] and [`~ImageProcessingMixin.save_pretrained`] methods for loading and saving image processors. + +There are two ways you can load an image processor, with [`AutoImageProcessor`] or a model-specific image processor. + + + + +The [AutoClass](./model_doc/auto) API provides a convenient method to load an image processor without directly specifying the model the image processor is associated with. + +Use [`~AutoImageProcessor.from_pretrained`] to load an image processor, and set `use_fast=True` to load a fast image processor if it's supported. + +```py +from transformers import AutoImageProcessor + +image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224", use_fast=True) +``` + + + + +Each image processor is associated with a specific pretrained vision model, and the image processors configuration contains the models expected size and whether to normalize and resize. + +The image processor can be loaded directly from the model-specific class. Check a models API documentation to see whether it supports a fast image processor. + +```py +from transformers import ViTImageProcessor + +image_processor = ViTImageProcessor.from_pretrained("google/vit-base-patch16-224") +``` + +To load a fast image processor, use the fast implementation class. + +```py +from transformers import ViTImageProcessorFast + +image_processor = ViTImageProcessorFast.from_pretrained("google/vit-base-patch16-224") +``` + + + + +## Fast image processors + +[`BaseImageProcessorFast`] is based on [torchvision](https://pytorch.org/vision/stable/index.html) and is significantly faster, especially when processing on a GPU. This class can be used as a drop-in replacement for [`BaseImageProcessor`] if it's available for a model because it has the same design. Make sure [torchvision](https://pytorch.org/get-started/locally/#mac-installation) is installed, and set the `use_fast` parameter to `True`. + +```py +from transformers import AutoImageProcessor + +processor = AutoImageProcessor.from_pretrained("facebook/detr-resnet-50", use_fast=True) +``` + +Control which device processing is performed on with the `device` parameter. Processing is performed on the same device as the input by default if the inputs are tensors, otherwise they are processed on the CPU. The example below places the fast processor on a GPU. + +```py +from torchvision.io import read_image +from transformers import DetrImageProcessorFast + +images = read_image("image.jpg") +processor = DetrImageProcessorFast.from_pretrained("facebook/detr-resnet-50") +images_processed = processor(images, return_tensors="pt", device="cuda") +``` + +
+Benchmarks + +The benchmarks are obtained from an [AWS EC2 g5.2xlarge](https://aws.amazon.com/ec2/instance-types/g5/) instance with a NVIDIA A10G Tensor Core GPU. + +
+ +
+
+ +
+
+ +
+
+ +
+
+ +## Preprocess + +Transformers' vision models expects the input as PyTorch tensors of pixel values. An image processor handles the conversion of images to pixel values, which is represented by the batch size, number of channels, height, and width. To achieve this, an image is resized (center cropped) and the pixel values are normalized and rescaled to the models expected values. + +Image preprocessing is not the same as *image augmentation*. Image augmentation makes changes (brightness, colors, rotatation, etc.) to an image for the purpose of either creating new training examples or prevent overfitting. Image preprocessing makes changes to an image for the purpose of matching a pretrained model's expected input format. + +Typically, images are augmented (to increase performance) and then preprocessed before being passed to a model. You can use any library ([Albumentations](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification_albumentations.ipynb), [Kornia](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification_kornia.ipynb)) for augmentation and an image processor for preprocessing. + +This guide uses the torchvision [transforms](https://pytorch.org/vision/stable/transforms.html) module for augmentation. + +Start by loading a small sample of the [food101](https://hf.co/datasets/food101) dataset. + +```py +from datasets import load_dataset + +dataset = load_dataset("food101", split="train[:100]") +``` + +From the [transforms](https://pytorch.org/vision/stable/transforms.html) module, use the [Compose](https://pytorch.org/vision/master/generated/torchvision.transforms.Compose.html) API to chain together [RandomResizedCrop](https://pytorch.org/vision/main/generated/torchvision.transforms.RandomResizedCrop.html) and [ColorJitter](https://pytorch.org/vision/main/generated/torchvision.transforms.ColorJitter.html). These transforms randomly crop and resize an image, and randomly adjusts an images colors. + +The image size to randomly crop to can be retrieved from the image processor. For some models, an exact height and width are expected while for others, only the `shortest_edge` is required. + +```py +from torchvision.transforms import RandomResizedCrop, ColorJitter, Compose + +size = ( + image_processor.size["shortest_edge"] + if "shortest_edge" in image_processor.size + else (image_processor.size["height"], image_processor.size["width"]) +) +_transforms = Compose([RandomResizedCrop(size), ColorJitter(brightness=0.5, hue=0.5)]) +``` + +Apply the transforms to the images and convert them to the RGB format. Then pass the augmented images to the image processor to return the pixel values. + +The `do_resize` parameter is set to `False` because the images have already been resized in the augmentation step by [RandomResizedCrop](https://pytorch.org/vision/main/generated/torchvision.transforms.RandomResizedCrop.html). If you don't augment the images, then the image processor automatically resizes and normalizes the images with the `image_mean` and `image_std` values. These values are found in the preprocessor configuration file. + +```py +def transforms(examples): + images = [_transforms(img.convert("RGB")) for img in examples["image"]] + examples["pixel_values"] = image_processor(images, do_resize=False, return_tensors="pt")["pixel_values"] + return examples +``` + +Apply the combined augmentation and preprocessing function to the entire dataset on the fly with [`~datasets.Dataset.set_transform`]. + +```py +dataset.set_transform(transforms) +``` + +Convert the pixel values back into an image to see how the image has been augmented and preprocessed. + +```py +import numpy as np +import matplotlib.pyplot as plt + +img = dataset[0]["pixel_values"] +plt.imshow(img.permute(1, 2, 0)) +``` + +
+
+ +
before
+
+
+ +
after
+
+
+ +For other vision tasks like object detection or segmentation, the image processor includes post-processing methods to convert a models raw output into meaningful predictions like bounding boxes or segmentation maps. + +### Padding + +Some models, like [DETR](./model_doc/detr), applies [scale augmentation](https://paperswithcode.com/method/image-scale-augmentation) during training which can cause images in a batch to have different sizes. Images with different sizes can't be batched together. + +To fix this, pad the images with the special padding token `0`. Use the [pad](https://github.com/huggingface/transformers/blob/9578c2597e2d88b6f0b304b5a05864fd613ddcc1/src/transformers/models/detr/image_processing_detr.py#L1151) method to pad the images, and define a custom collate function to batch them together. + +```py +def collate_fn(batch): + pixel_values = [item["pixel_values"] for item in batch] + encoding = image_processor.pad(pixel_values, return_tensors="pt") + labels = [item["labels"] for item in batch] + batch = {} + batch["pixel_values"] = encoding["pixel_values"] + batch["pixel_mask"] = encoding["pixel_mask"] + batch["labels"] = labels + return batch +``` diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/index.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/index.md new file mode 100644 index 0000000000000000000000000000000000000000..ab0677b5a54e0e061039c63942195bf333fe79f4 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/index.md @@ -0,0 +1,64 @@ + + +# Transformers + +

+ +

+ + +Transformers acts as the model-definition framework for state-of-the-art machine learning models in text, computer +vision, audio, video, and multimodal model, for both inference and training. + +It centralizes the model definition so that this definition is agreed upon across the ecosystem. `transformers` is the +pivot across frameworks: if a model definition is supported, it will be compatible with the majority of training +frameworks (Axolotl, Unsloth, DeepSpeed, FSDP, PyTorch-Lightning, ...), inference engines (vLLM, SGLang, TGI, ...), +and adjacent modeling libraries (llama.cpp, mlx, ...) which leverage the model definition from `transformers`. + +We pledge to help support new state-of-the-art models and democratize their usage by having their model definition be +simple, customizable, and efficient. + +There are over 1M+ Transformers [model checkpoints](https://huggingface.co/models?library=transformers&sort=trending) on the [Hugging Face Hub](https://huggingface.com/models) you can use. + +Explore the [Hub](https://huggingface.com/) today to find a model and use Transformers to help you get started right away. + +## Features + +Transformers provides everything you need for inference or training with state-of-the-art pretrained models. Some of the main features include: + +- [Pipeline](./pipeline_tutorial): Simple and optimized inference class for many machine learning tasks like text generation, image segmentation, automatic speech recognition, document question answering, and more. +- [Trainer](./trainer): A comprehensive trainer that supports features such as mixed precision, torch.compile, and FlashAttention for training and distributed training for PyTorch models. +- [generate](./llm_tutorial): Fast text generation with large language models (LLMs) and vision language models (VLMs), including support for streaming and multiple decoding strategies. + +## Design + +> [!TIP] +> Read our [Philosophy](./philosophy) to learn more about Transformers' design principles. + +Transformers is designed for developers and machine learning engineers and researchers. Its main design principles are: + +1. Fast and easy to use: Every model is implemented from only three main classes (configuration, model, and preprocessor) and can be quickly used for inference or training with [`Pipeline`] or [`Trainer`]. +2. Pretrained models: Reduce your carbon footprint, compute cost and time by using a pretrained model instead of training an entirely new one. Each pretrained model is reproduced as closely as possible to the original model and offers state-of-the-art performance. + + + +## Learn + +If you're new to Transformers or want to learn more about transformer models, we recommend starting with the [LLM course](https://huggingface.co/learn/llm-course/chapter1/1?fw=pt). This comprehensive course covers everything from the fundamentals of how transformer models work to practical applications across various tasks. You'll learn the complete workflow, from curating high-quality datasets to fine-tuning large language models and implementing reasoning capabilities. The course contains both theoretical and hands-on exercises to build a solid foundational knowledge of transformer models as you learn. \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/installation.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/installation.md new file mode 100644 index 0000000000000000000000000000000000000000..911c84858f9ef6ce9c92f4ef9996e0e19209fdc2 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/installation.md @@ -0,0 +1,223 @@ + + +# Installation + +Transformers works with [PyTorch](https://pytorch.org/get-started/locally/), [TensorFlow 2.0](https://www.tensorflow.org/install/pip), and [Flax](https://flax.readthedocs.io/en/latest/). It has been tested on Python 3.9+, PyTorch 2.1+, TensorFlow 2.6+, and Flax 0.4.1+. + +## Virtual environment + +A virtual environment helps manage different projects and avoids compatibility issues between dependencies. Take a look at the [Install packages in a virtual environment using pip and venv](https://packaging.python.org/en/latest/guides/installing-using-pip-and-virtual-environments/) guide if you're unfamiliar with Python virtual environments. + + + + +Create and activate a virtual environment in your project directory with [venv](https://docs.python.org/3/library/venv.html). + +```bash +python -m venv .env +source .env/bin/activate +``` + + + + +[uv](https://docs.astral.sh/uv/) is a fast Rust-based Python package and project manager. + +```bash +uv venv .env +source .env/bin/activate +``` + + + + +## Python + +You can install Transformers with pip or uv. + + + + +[pip](https://pip.pypa.io/en/stable/) is a package installer for Python. Install Transformers with pip in your newly created virtual environment. + +```bash +pip install transformers +``` + + + + +[uv](https://docs.astral.sh/uv/) is a fast Rust-based Python package and project manager. + +```bash +uv pip install transformers +``` + + + + +For GPU acceleration, install the appropriate CUDA drivers for [PyTorch](https://pytorch.org/get-started/locally) and [TensorFlow](https://www.tensorflow.org/install/pip). + +Run the command below to check if your system detects an NVIDIA GPU. + +```bash +nvidia-smi +``` + +To install a CPU-only version of Transformers and a machine learning framework, run the following command. + + + + +```bash +pip install 'transformers[torch]' +uv pip install 'transformers[torch]' +``` + + + + +For Apple M1 hardware, you need to install CMake and pkg-config first. + +```bash +brew install cmake +brew install pkg-config +``` + +Install TensorFlow 2.0. + +```bash +pip install 'transformers[tf-cpu]' +uv pip install 'transformers[tf-cpu]' +``` + + + + +```bash +pip install 'transformers[flax]' +uv pip install 'transformers[flax]' +``` + + + + +Test whether the install was successful with the following command. It should return a label and score for the provided text. + +```bash +python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('hugging face is the best'))" +[{'label': 'POSITIVE', 'score': 0.9998704791069031}] +``` + +### Source install + +Installing from source installs the *latest* version rather than the *stable* version of the library. It ensures you have the most up-to-date changes in Transformers and it's useful for experimenting with the latest features or fixing a bug that hasn't been officially released in the stable version yet. + +The downside is that the latest version may not always be stable. If you encounter any problems, please open a [GitHub Issue](https://github.com/huggingface/transformers/issues) so we can fix it as soon as possible. + +Install from source with the following command. + +```bash +pip install git+https://github.com/huggingface/transformers +``` + +Check if the install was successful with the command below. It should return a label and score for the provided text. + +```bash +python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('hugging face is the best'))" +[{'label': 'POSITIVE', 'score': 0.9998704791069031}] +``` + +### Editable install + +An [editable install](https://pip.pypa.io/en/stable/topics/local-project-installs/#editable-installs) is useful if you're developing locally with Transformers. It links your local copy of Transformers to the Transformers [repository](https://github.com/huggingface/transformers) instead of copying the files. The files are added to Python's import path. + +```bash +git clone https://github.com/huggingface/transformers.git +cd transformers +pip install -e . +``` + +> [!WARNING] +> You must keep the local Transformers folder to keep using it. + +Update your local version of Transformers with the latest changes in the main repository with the following command. + +```bash +cd ~/transformers/ +git pull +``` + +## conda + +[conda](https://docs.conda.io/projects/conda/en/stable/#) is a language-agnostic package manager. Install Transformers from the [conda-forge](https://anaconda.org/conda-forge/transformers) channel in your newly created virtual environment. + +```bash +conda install conda-forge::transformers +``` + +## Set up + +After installation, you can configure the Transformers cache location or set up the library for offline usage. + +### Cache directory + +When you load a pretrained model with [`~PreTrainedModel.from_pretrained`], the model is downloaded from the Hub and locally cached. + +Every time you load a model, it checks whether the cached model is up-to-date. If it's the same, then the local model is loaded. If it's not the same, the newer model is downloaded and cached. + +The default directory given by the shell environment variable `TRANSFORMERS_CACHE` is `~/.cache/huggingface/hub`. On Windows, the default directory is `C:\Users\username\.cache\huggingface\hub`. + +Cache a model in a different directory by changing the path in the following shell environment variables (listed by priority). + +1. [HF_HUB_CACHE](https://hf.co/docs/huggingface_hub/package_reference/environment_variables#hfhubcache) or `TRANSFORMERS_CACHE` (default) +2. [HF_HOME](https://hf.co/docs/huggingface_hub/package_reference/environment_variables#hfhome) +3. [XDG_CACHE_HOME](https://hf.co/docs/huggingface_hub/package_reference/environment_variables#xdgcachehome) + `/huggingface` (only if `HF_HOME` is not set) + +Older versions of Transformers uses the shell environment variables `PYTORCH_TRANSFORMERS_CACHE` or `PYTORCH_PRETRAINED_BERT_CACHE`. You should keep these unless you specify the newer shell environment variable `TRANSFORMERS_CACHE`. + +### Offline mode + +To use Transformers in an offline or firewalled environment requires the downloaded and cached files ahead of time. Download a model repository from the Hub with the [`~huggingface_hub.snapshot_download`] method. + +> [!TIP] +> Refer to the [Download files from the Hub](https://hf.co/docs/huggingface_hub/guides/download) guide for more options for downloading files from the Hub. You can download files from specific revisions, download from the CLI, and even filter which files to download from a repository. + +```py +from huggingface_hub import snapshot_download + +snapshot_download(repo_id="meta-llama/Llama-2-7b-hf", repo_type="model") +``` + +Set the environment variable `HF_HUB_OFFLINE=1` to prevent HTTP calls to the Hub when loading a model. + +```bash +HF_HUB_OFFLINE=1 \ +python examples/pytorch/language-modeling/run_clm.py --model_name_or_path meta-llama/Llama-2-7b-hf --dataset_name wikitext ... +``` + +Another option for only loading cached files is to set `local_files_only=True` in [`~PreTrainedModel.from_pretrained`]. + +```py +from transformers import LlamaForCausalLM + +model = LlamaForCausalLM.from_pretrained("./path/to/local/directory", local_files_only=True) +``` diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/internal/audio_utils.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/internal/audio_utils.md new file mode 100644 index 0000000000000000000000000000000000000000..e6a39c7c1c49a9311934a02aa46fe503d3301ec2 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/internal/audio_utils.md @@ -0,0 +1,39 @@ + + +# Utilities for `FeatureExtractors` + +This page lists all the utility functions that can be used by the audio [`FeatureExtractor`] in order to compute special features from a raw audio using common algorithms such as *Short Time Fourier Transform* or *log mel spectrogram*. + +Most of those are only useful if you are studying the code of the audio processors in the library. + +## Audio Transformations + +[[autodoc]] audio_utils.hertz_to_mel + +[[autodoc]] audio_utils.mel_to_hertz + +[[autodoc]] audio_utils.mel_filter_bank + +[[autodoc]] audio_utils.optimal_fft_length + +[[autodoc]] audio_utils.window_function + +[[autodoc]] audio_utils.spectrogram + +[[autodoc]] audio_utils.power_to_db + +[[autodoc]] audio_utils.amplitude_to_db diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/internal/file_utils.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/internal/file_utils.md new file mode 100644 index 0000000000000000000000000000000000000000..ae483638653f20af31eabdebbcc74b4b3e9a3a86 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/internal/file_utils.md @@ -0,0 +1,51 @@ + + +# General Utilities + +This page lists all of Transformers general utility functions that are found in the file `utils.py`. + +Most of those are only useful if you are studying the general code in the library. + + +## Enums and namedtuples + +[[autodoc]] utils.ExplicitEnum + +[[autodoc]] utils.PaddingStrategy + +[[autodoc]] utils.TensorType + +## Special Decorators + +[[autodoc]] utils.add_start_docstrings + +[[autodoc]] utils.add_start_docstrings_to_model_forward + +[[autodoc]] utils.add_end_docstrings + +[[autodoc]] utils.add_code_sample_docstrings + +[[autodoc]] utils.replace_return_docstrings + +## Special Properties + +[[autodoc]] utils.cached_property + +## Other Utilities + +[[autodoc]] utils._LazyModule +[[autodoc]] pytorch_utils.infer_device diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/internal/generation_utils.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/internal/generation_utils.md new file mode 100644 index 0000000000000000000000000000000000000000..5f29fabd4f397a2811615f953f80503a3ade06f5 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/internal/generation_utils.md @@ -0,0 +1,451 @@ + + +# Utilities for Generation + +This page lists all the utility functions used by [`~generation.GenerationMixin.generate`]. + +## Generate Outputs + +The output of [`~generation.GenerationMixin.generate`] is an instance of a subclass of +[`~utils.ModelOutput`]. This output is a data structure containing all the information returned +by [`~generation.GenerationMixin.generate`], but that can also be used as tuple or dictionary. + +Here's an example: + +```python +from transformers import GPT2Tokenizer, GPT2LMHeadModel + +tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2") +model = GPT2LMHeadModel.from_pretrained("openai-community/gpt2") + +inputs = tokenizer("Hello, my dog is cute and ", return_tensors="pt") +generation_output = model.generate(**inputs, return_dict_in_generate=True, output_scores=True) +``` + +The `generation_output` object is a [`~generation.GenerateDecoderOnlyOutput`], as we can +see in the documentation of that class below, it means it has the following attributes: + +- `sequences`: the generated sequences of tokens +- `scores` (optional): the prediction scores of the language modelling head, for each generation step +- `hidden_states` (optional): the hidden states of the model, for each generation step +- `attentions` (optional): the attention weights of the model, for each generation step + +Here we have the `scores` since we passed along `output_scores=True`, but we don't have `hidden_states` and +`attentions` because we didn't pass `output_hidden_states=True` or `output_attentions=True`. + +You can access each attribute as you would usually do, and if that attribute has not been returned by the model, you +will get `None`. Here for instance `generation_output.scores` are all the generated prediction scores of the +language modeling head, and `generation_output.attentions` is `None`. + +When using our `generation_output` object as a tuple, it only keeps the attributes that don't have `None` values. +Here, for instance, it has two elements, `loss` then `logits`, so + +```python +generation_output[:2] +``` + +will return the tuple `(generation_output.sequences, generation_output.scores)` for instance. + +When using our `generation_output` object as a dictionary, it only keeps the attributes that don't have `None` +values. Here, for instance, it has two keys that are `sequences` and `scores`. + +We document here all output types. + + +### PyTorch + +[[autodoc]] generation.GenerateDecoderOnlyOutput + +[[autodoc]] generation.GenerateEncoderDecoderOutput + +[[autodoc]] generation.GenerateBeamDecoderOnlyOutput + +[[autodoc]] generation.GenerateBeamEncoderDecoderOutput + +### TensorFlow + +[[autodoc]] generation.TFGreedySearchEncoderDecoderOutput + +[[autodoc]] generation.TFGreedySearchDecoderOnlyOutput + +[[autodoc]] generation.TFSampleEncoderDecoderOutput + +[[autodoc]] generation.TFSampleDecoderOnlyOutput + +[[autodoc]] generation.TFBeamSearchEncoderDecoderOutput + +[[autodoc]] generation.TFBeamSearchDecoderOnlyOutput + +[[autodoc]] generation.TFBeamSampleEncoderDecoderOutput + +[[autodoc]] generation.TFBeamSampleDecoderOnlyOutput + +[[autodoc]] generation.TFContrastiveSearchEncoderDecoderOutput + +[[autodoc]] generation.TFContrastiveSearchDecoderOnlyOutput + +### FLAX + +[[autodoc]] generation.FlaxSampleOutput + +[[autodoc]] generation.FlaxGreedySearchOutput + +[[autodoc]] generation.FlaxBeamSearchOutput + +## LogitsProcessor + +A [`LogitsProcessor`] can be used to modify the prediction scores of a language model head for +generation. + +### PyTorch + +[[autodoc]] AlternatingCodebooksLogitsProcessor + - __call__ + +[[autodoc]] ClassifierFreeGuidanceLogitsProcessor + - __call__ + +[[autodoc]] EncoderNoRepeatNGramLogitsProcessor + - __call__ + +[[autodoc]] EncoderRepetitionPenaltyLogitsProcessor + - __call__ + +[[autodoc]] EpsilonLogitsWarper + - __call__ + +[[autodoc]] EtaLogitsWarper + - __call__ + +[[autodoc]] ExponentialDecayLengthPenalty + - __call__ + +[[autodoc]] ForcedBOSTokenLogitsProcessor + - __call__ + +[[autodoc]] ForcedEOSTokenLogitsProcessor + - __call__ + +[[autodoc]] HammingDiversityLogitsProcessor + - __call__ + +[[autodoc]] InfNanRemoveLogitsProcessor + - __call__ + +[[autodoc]] LogitNormalization + - __call__ + +[[autodoc]] LogitsProcessor + - __call__ + +[[autodoc]] LogitsProcessorList + - __call__ + +[[autodoc]] MinLengthLogitsProcessor + - __call__ + +[[autodoc]] MinNewTokensLengthLogitsProcessor + - __call__ + +[[autodoc]] MinPLogitsWarper + - __call__ + +[[autodoc]] NoBadWordsLogitsProcessor + - __call__ + +[[autodoc]] NoRepeatNGramLogitsProcessor + - __call__ + +[[autodoc]] PrefixConstrainedLogitsProcessor + - __call__ + +[[autodoc]] RepetitionPenaltyLogitsProcessor + - __call__ + +[[autodoc]] SequenceBiasLogitsProcessor + - __call__ + +[[autodoc]] SuppressTokensAtBeginLogitsProcessor + - __call__ + +[[autodoc]] SuppressTokensLogitsProcessor + - __call__ + +[[autodoc]] SynthIDTextWatermarkLogitsProcessor + - __call__ + +[[autodoc]] TemperatureLogitsWarper + - __call__ + +[[autodoc]] TopKLogitsWarper + - __call__ + +[[autodoc]] TopPLogitsWarper + - __call__ + +[[autodoc]] TypicalLogitsWarper + - __call__ + +[[autodoc]] UnbatchedClassifierFreeGuidanceLogitsProcessor + - __call__ + +[[autodoc]] WhisperTimeStampLogitsProcessor + - __call__ + +[[autodoc]] WatermarkLogitsProcessor + - __call__ + + +### TensorFlow + +[[autodoc]] TFForcedBOSTokenLogitsProcessor + - __call__ + +[[autodoc]] TFForcedEOSTokenLogitsProcessor + - __call__ + +[[autodoc]] TFForceTokensLogitsProcessor + - __call__ + +[[autodoc]] TFLogitsProcessor + - __call__ + +[[autodoc]] TFLogitsProcessorList + - __call__ + +[[autodoc]] TFLogitsWarper + - __call__ + +[[autodoc]] TFMinLengthLogitsProcessor + - __call__ + +[[autodoc]] TFNoBadWordsLogitsProcessor + - __call__ + +[[autodoc]] TFNoRepeatNGramLogitsProcessor + - __call__ + +[[autodoc]] TFRepetitionPenaltyLogitsProcessor + - __call__ + +[[autodoc]] TFSuppressTokensAtBeginLogitsProcessor + - __call__ + +[[autodoc]] TFSuppressTokensLogitsProcessor + - __call__ + +[[autodoc]] TFTemperatureLogitsWarper + - __call__ + +[[autodoc]] TFTopKLogitsWarper + - __call__ + +[[autodoc]] TFTopPLogitsWarper + - __call__ + +### FLAX + +[[autodoc]] FlaxForcedBOSTokenLogitsProcessor + - __call__ + +[[autodoc]] FlaxForcedEOSTokenLogitsProcessor + - __call__ + +[[autodoc]] FlaxForceTokensLogitsProcessor + - __call__ + +[[autodoc]] FlaxLogitsProcessor + - __call__ + +[[autodoc]] FlaxLogitsProcessorList + - __call__ + +[[autodoc]] FlaxLogitsWarper + - __call__ + +[[autodoc]] FlaxMinLengthLogitsProcessor + - __call__ + +[[autodoc]] FlaxSuppressTokensAtBeginLogitsProcessor + - __call__ + +[[autodoc]] FlaxSuppressTokensLogitsProcessor + - __call__ + +[[autodoc]] FlaxTemperatureLogitsWarper + - __call__ + +[[autodoc]] FlaxTopKLogitsWarper + - __call__ + +[[autodoc]] FlaxTopPLogitsWarper + - __call__ + +[[autodoc]] FlaxWhisperTimeStampLogitsProcessor + - __call__ + +## StoppingCriteria + +A [`StoppingCriteria`] can be used to change when to stop generation (other than EOS token). Please note that this is exclusively available to our PyTorch implementations. + +[[autodoc]] StoppingCriteria + - __call__ + +[[autodoc]] StoppingCriteriaList + - __call__ + +[[autodoc]] MaxLengthCriteria + - __call__ + +[[autodoc]] MaxTimeCriteria + - __call__ + +[[autodoc]] StopStringCriteria + - __call__ + +[[autodoc]] EosTokenCriteria + - __call__ + +## Constraints + +A [`Constraint`] can be used to force the generation to include specific tokens or sequences in the output. Please note that this is exclusively available to our PyTorch implementations. + +[[autodoc]] Constraint + +[[autodoc]] PhrasalConstraint + +[[autodoc]] DisjunctiveConstraint + +[[autodoc]] ConstraintListState + +## BeamSearch + +[[autodoc]] BeamScorer + - process + - finalize + +[[autodoc]] BeamSearchScorer + - process + - finalize + +[[autodoc]] ConstrainedBeamSearchScorer + - process + - finalize + +## Streamers + +[[autodoc]] TextStreamer + +[[autodoc]] TextIteratorStreamer + +[[autodoc]] AsyncTextIteratorStreamer + +## Caches + +[[autodoc]] CacheLayerMixin + - update + - get_seq_length + - get_mask_sizes + - get_max_cache_shape + - reset + - reorder_cache + - lazy_initialization + +[[autodoc]] DynamicLayer + - update + - lazy_initialization + - crop + - batch_repeat_interleave + - batch_select_indices + +[[autodoc]] StaticLayer + - update + - lazy_initialization + +[[autodoc]] SlidingWindowLayer + - update + - lazy_initialization + +[[autodoc]] QuantoQuantizedLayer + - update + - lazy_initialization + +[[autodoc]] HQQQuantizedLayer + - update + - lazy_initialization + +[[autodoc]] Cache + - update + - early_initialization + - get_seq_length + - get_mask_sizes + - get_max_cache_shape + - reset + - reorder_cache + - crop + - batch_repeat_interleave + - batch_select_indices + +[[autodoc]] DynamicCache + - to_legacy_cache + - from_legacy_cache + +[[autodoc]] QuantizedCache + +[[autodoc]] QuantoQuantizedCache + +[[autodoc]] HQQQuantizedCache + +[[autodoc]] OffloadedCache + +[[autodoc]] StaticCache + +[[autodoc]] OffloadedStaticCache + +[[autodoc]] HybridCache + +[[autodoc]] HybridChunkedCache + +[[autodoc]] SlidingWindowCache + +[[autodoc]] EncoderDecoderCache + - to_legacy_cache + - from_legacy_cache + + +## Watermark Utils + +[[autodoc]] WatermarkingConfig + - __call__ + +[[autodoc]] WatermarkDetector + - __call__ + +[[autodoc]] BayesianDetectorConfig + +[[autodoc]] BayesianDetectorModel + - forward + +[[autodoc]] SynthIDTextWatermarkingConfig + +[[autodoc]] SynthIDTextWatermarkDetector + - __call__ + +## Compile Utils + +[[autodoc]] CompileConfig + - __call__ diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/internal/image_processing_utils.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/internal/image_processing_utils.md new file mode 100644 index 0000000000000000000000000000000000000000..42f99f361703c153865f13914c4adc8a8af4f7aa --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/internal/image_processing_utils.md @@ -0,0 +1,48 @@ + + +# Utilities for Image Processors + +This page lists all the utility functions used by the image processors, mainly the functional +transformations used to process the images. + +Most of those are only useful if you are studying the code of the image processors in the library. + +## Image Transformations + +[[autodoc]] image_transforms.center_crop + +[[autodoc]] image_transforms.center_to_corners_format + +[[autodoc]] image_transforms.corners_to_center_format + +[[autodoc]] image_transforms.id_to_rgb + +[[autodoc]] image_transforms.normalize + +[[autodoc]] image_transforms.pad + +[[autodoc]] image_transforms.rgb_to_id + +[[autodoc]] image_transforms.rescale + +[[autodoc]] image_transforms.resize + +[[autodoc]] image_transforms.to_pil_image + +## ImageProcessingMixin + +[[autodoc]] image_processing_utils.ImageProcessingMixin diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/internal/import_utils.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/internal/import_utils.md new file mode 100644 index 0000000000000000000000000000000000000000..0d76c2bbe33a4756de2d4a1213cbc4117c3ebaa8 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/internal/import_utils.md @@ -0,0 +1,104 @@ + + +# Import Utilities + +This page goes through the transformers utilities to enable lazy and fast object import. +While we strive for minimal dependencies, some models have specific dependencies requirements that cannot be +worked around. We don't want for all users of `transformers` to have to install those dependencies to use other models, +we therefore mark those as soft dependencies rather than hard dependencies. + +The transformers toolkit is not made to error-out on import of a model that has a specific dependency; instead, an +object for which you are lacking a dependency will error-out when calling any method on it. As an example, if +`torchvision` isn't installed, the fast image processors will not be available. + +This object is still importable: + +```python +>>> from transformers import DetrImageProcessorFast +>>> print(DetrImageProcessorFast) + +``` + +However, no method can be called on that object: + +```python +>>> DetrImageProcessorFast.from_pretrained() +ImportError: +DetrImageProcessorFast requires the Torchvision library but it was not found in your environment. Check out the instructions on the +installation page: https://pytorch.org/get-started/locally/ and follow the ones that match your environment. +Please note that you may need to restart your runtime after installation. +``` + +Let's see how to specify specific object dependencies. + +## Specifying Object Dependencies + +### Filename-based + +All objects under a given filename have an automatic dependency to the tool linked to the filename + +**TensorFlow**: All files starting with `modeling_tf_` have an automatic TensorFlow dependency. + +**Flax**: All files starting with `modeling_flax_` have an automatic Flax dependency + +**PyTorch**: All files starting with `modeling_` and not valid with the above (TensorFlow and Flax) have an automatic +PyTorch dependency + +**Tokenizers**: All files starting with `tokenization_` and ending with `_fast` have an automatic `tokenizers` dependency + +**Vision**: All files starting with `image_processing_` have an automatic dependency to the `vision` dependency group; +at the time of writing, this only contains the `pillow` dependency. + +**Vision + Torch + Torchvision**: All files starting with `image_processing_` and ending with `_fast` have an automatic +dependency to `vision`, `torch`, and `torchvision`. + +All of these automatic dependencies are added on top of the explicit dependencies that are detailed below. + +### Explicit Object Dependencies + +We add a method called `requires` that is used to explicitly specify the dependencies of a given object. As an +example, the `Trainer` class has two hard dependencies: `torch` and `accelerate`. Here is how we specify these +required dependencies: + +```python +from .utils.import_utils import requires + +@requires(backends=("torch", "accelerate")) +class Trainer: + ... +``` + +Backends that can be added here are all the backends that are available in the `import_utils.py` module. + +Additionally, specific versions can be specified in each backend. For example, this is how you would specify +a requirement on torch>=2.6 on the `Trainer` class: + +```python +from .utils.import_utils import requires + +@requires(backends=("torch>=2.6", "accelerate")) +class Trainer: + ... +``` + +You can specify the following operators: `==`, `>`, `>=`, `<`, `<=`, `!=`. + +## Methods + +[[autodoc]] utils.import_utils.define_import_structure + +[[autodoc]] utils.import_utils.requires diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/internal/model_debugging_utils.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/internal/model_debugging_utils.md new file mode 100644 index 0000000000000000000000000000000000000000..262113575f4207d90fd83bf56a533f7f6f1d0077 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/internal/model_debugging_utils.md @@ -0,0 +1,360 @@ + + +# Model debugging toolboxes + +This page lists all the debugging and model adding tools used by the library, as well as the utility functions it +provides for it. + +Most of those are only useful if you are adding new models in the library. + + +## Model addition debuggers + + +### Model addition debugger - context manager for model adders + +This context manager is a power user tool intended for model adders. It tracks all forward calls within a model forward +and logs a slice of each input and output on a nested JSON. To note, this context manager enforces `torch.no_grad()`. + +### Rationale + +When porting models to transformers, even from python to python, model adders often have to do a lot of manual +operations, involving saving and loading tensors, comparing dtypes, etc. This small tool can hopefully shave off some +time. + +### Usage + +Add this context manager as follows to debug a model: + +```python +import torch +from PIL import Image +import requests +from transformers import LlavaProcessor, LlavaForConditionalGeneration +from transformers.model_debugging_utils import model_addition_debugger_context +torch.random.manual_seed(673) + +# load pretrained model and processor +model_id = "llava-hf/llava-1.5-7b-hf" +processor = LlavaProcessor.from_pretrained(model_id) +model = LlavaForConditionalGeneration.from_pretrained(model_id) + +# create random image input +random_image = Image.fromarray(torch.randint(0, 256, (224, 224, 3), dtype=torch.uint8).numpy()) + +# prompt +prompt = "Describe this image." + +# process inputs +inputs = processor(text=prompt, images=random_image, return_tensors="pt") + +# call forward method (not .generate!) +with model_addition_debugger_context( + model, + debug_path="optional_path_to_your_directory", + do_prune_layers=False # This will output ALL the layers of a model. +): + output = model.forward(**inputs) + +``` + + +### Reading results + +The debugger generates two files from the forward call, both with the same base name, but ending either with +`_SUMMARY.json` or with `_FULL_TENSORS.json`. + +The first one will contain a summary of each module's _input_ and _output_ tensor values and shapes. + +```json +{ + "module_path": "MolmoForConditionalGeneration", + "inputs": { + "args": [], + "kwargs": { + "input_ids": { + "shape": "torch.Size([1, 589])", + "dtype": "torch.int64" + }, + "attention_mask": { + "shape": "torch.Size([1, 589])", + "dtype": "torch.int64" + }, + "pixel_values": { + "shape": "torch.Size([1, 5, 576, 588])", + "dtype": "torch.float32", + "mean": "tensor(-8.9514e-01, device='cuda:0')", + "std": "tensor(9.2586e-01, device='cuda:0')", + "min": "tensor(-1.7923e+00, device='cuda:0')", + "max": "tensor(1.8899e+00, device='cuda:0')" + } + }, + "children": [ + { + "module_path": "MolmoForConditionalGeneration.language_model.model.embed_tokens", + "inputs": { + "args": [ + { + "shape": "torch.Size([1, 589])", + "dtype": "torch.int64" + } + ] + }, + "outputs": { + "shape": "torch.Size([1, 589, 3584])", + "dtype": "torch.float32", + "mean": "tensor(6.5460e-06, device='cuda:0')", + "std": "tensor(2.3807e-02, device='cuda:0')", + "min": "tensor(-3.3398e-01, device='cuda:0')", + "max": "tensor(3.9453e-01, device='cuda:0')" + } + }, + { + "module_path": "MolmoForConditionalGeneration.vision_tower", + "inputs": { + "args": [ + { + "shape": "torch.Size([5, 1, 576, 588])", + "dtype": "torch.float32", + "mean": "tensor(-8.9514e-01, device='cuda:0')", + "std": "tensor(9.2586e-01, device='cuda:0')", + "min": "tensor(-1.7923e+00, device='cuda:0')", + "max": "tensor(1.8899e+00, device='cuda:0')" + } + ], + "kwargs": { + "output_hidden_states": "True" + } + }, + "children": [ + { ... and so on +``` + +The `_FULL_TENSORS.json` file will display a full view of all tensors, which is useful for comparing two files. + +```json + "pixel_values": { + "shape": "torch.Size([1, 5, 576, 588])", + "dtype": "torch.float32", + "value": [ + "tensor([[[[-1.7923e+00, -1.7521e+00, -1.4802e+00, ..., -1.7923e+00, -1.7521e+00, -1.4802e+00],", + " [-1.7923e+00, -1.7521e+00, -1.4802e+00, ..., -1.7923e+00, -1.7521e+00, -1.4802e+00],", + " [-1.7923e+00, -1.7521e+00, -1.4802e+00, ..., -1.7923e+00, -1.7521e+00, -1.4802e+00],", + " ...,", + " [-1.7923e+00, -1.7521e+00, -1.4802e+00, ..., -1.7923e+00, -1.7521e+00, -1.4802e+00],", + " [-1.7923e+00, -1.7521e+00, -1.4802e+00, ..., -1.7923e+00, -1.7521e+00, -1.4802e+00],", + " [-1.7923e+00, -1.7521e+00, -1.4802e+00, ..., -1.7923e+00, -1.7521e+00, -1.4802e+00]],", + "", + " [[-1.7923e+00, -1.7521e+00, -1.4802e+00, ..., -1.7923e+00, -1.7521e+00, -1.4802e+00],", + " [-1.7923e+00, -1.7521e+00, -1.4802e+00, ..., -1.7923e+00, -1.7521e+00, -1.4802e+00],", + " [-1.7923e+00, -1.7521e+00, -1.4802e+00, ..., -1.7923e+00, -1.7521e+00, -1.4802e+00],", + " ...,", + " [-1.4857e+00, -1.4820e+00, -1.2100e+00, ..., -6.0979e-01, -5.9650e-01, -3.8527e-01],", + " [-1.6755e+00, -1.7221e+00, -1.4518e+00, ..., -7.5577e-01, -7.4658e-01, -5.5592e-01],", + " [-7.9957e-01, -8.2162e-01, -5.7014e-01, ..., -1.3689e+00, -1.3169e+00, -1.0678e+00]],", + "", + " [[-1.7923e+00, -1.7521e+00, -1.4802e+00, ..., -1.7923e+00, -1.7521e+00, -1.4802e+00],", + " [-1.7923e+00, -1.7521e+00, -1.4802e+00, ..., -1.7923e+00, -1.7521e+00, -1.4802e+00],", + " [-1.7923e+00, -1.7521e+00, -1.4802e+00, ..., -1.7923e+00, -1.7521e+00, -1.4802e+00],", + " ...,", + " [-3.0322e-01, -5.0645e-01, -5.8436e-01, ..., -6.2439e-01, -7.9160e-01, -8.1188e-01],", + " [-4.4921e-01, -6.5653e-01, -7.2656e-01, ..., -3.4702e-01, -5.2146e-01, -5.1326e-01],", + " [-3.4702e-01, -5.3647e-01, -5.4170e-01, ..., -1.0915e+00, -1.1968e+00, -1.0252e+00]],", + "", + " [[-1.1207e+00, -1.2718e+00, -1.0678e+00, ..., 1.2013e-01, -1.3126e-01, -1.7197e-01],", + " [-6.9738e-01, -9.1166e-01, -8.5454e-01, ..., -5.5050e-02, -2.8134e-01, -4.2793e-01],", + " [-3.4702e-01, -5.5148e-01, -5.8436e-01, ..., 1.9312e-01, -8.6235e-02, -2.1463e-01],", + " ...,", + " [-1.7923e+00, -1.7521e+00, -1.4802e+00, ..., -1.7923e+00, -1.7521e+00, -1.4802e+00],", + " [-1.7923e+00, -1.7521e+00, -1.4802e+00, ..., -1.7923e+00, -1.7521e+00, -1.4802e+00],", + " [-1.7923e+00, -1.7521e+00, -1.4802e+00, ..., -1.7923e+00, -1.7521e+00, -1.4802e+00]],", + "", + " [[-1.0039e+00, -9.5669e-01, -6.5546e-01, ..., -1.4711e+00, -1.4219e+00, -1.1389e+00],", + " [-1.0039e+00, -9.5669e-01, -6.5546e-01, ..., -1.7193e+00, -1.6771e+00, -1.4091e+00],", + " [-1.6317e+00, -1.6020e+00, -1.2669e+00, ..., -1.2667e+00, -1.2268e+00, -8.9720e-01],", + " ...,", + " [-1.7923e+00, -1.7521e+00, -1.4802e+00, ..., -1.7923e+00, -1.7521e+00, -1.4802e+00],", + " [-1.7923e+00, -1.7521e+00, -1.4802e+00, ..., -1.7923e+00, -1.7521e+00, -1.4802e+00],", + " [-1.7923e+00, -1.7521e+00, -1.4802e+00, ..., -1.7923e+00, -1.7521e+00, -1.4802e+00]]]], device='cuda:0')" + ], + "mean": "tensor(-8.9514e-01, device='cuda:0')", + "std": "tensor(9.2586e-01, device='cuda:0')", + "min": "tensor(-1.7923e+00, device='cuda:0')", + "max": "tensor(1.8899e+00, device='cuda:0')" + }, +``` + +#### Saving tensors to disk + +Some model adders may benefit from logging full tensor values to disk to support, for example, numerical analysis +across implementations. + +Set `use_repr=False` to write tensors to disk using [SafeTensors](https://huggingface.co/docs/safetensors/en/index). + +```python +with model_addition_debugger_context( + model, + debug_path="optional_path_to_your_directory", + do_prune_layers=False, + use_repr=False, # Defaults to True +): + output = model.forward(**inputs) +``` + +When using `use_repr=False`, tensors are written to the same disk location as the `_SUMMARY.json` and +`_FULL_TENSORS.json` files. The `value` property of entries in the `_FULL_TENSORS.json` file will contain a relative +path reference to the associated `.safetensors` file. Each tensor is written to its own file as the `data` property of +the state dictionary. File names are constructed using the `module_path` as a prefix with a few possible postfixes that +are built recursively. + +* Module inputs are denoted with the `_inputs` and outputs by `_outputs`. +* `list` and `tuple` instances, such as `args` or function return values, will be postfixed with `_{index}`. +* `dict` instances will be postfixed with `_{key}`. + +### Comparing between implementations + +Once the forward passes of two models have been traced by the debugger, one can compare the `json` output files. See +below: we can see slight differences between these two implementations' key projection layer. Inputs are mostly +identical, but not quite. Looking through the file differences makes it easier to pinpoint which layer is wrong. + + +![download-icon](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/files_difference_debugging.png) + + +### Limitations and scope + +This feature will only work for torch-based models, and would require more work and case-by-case approach for say +`jax`-based models that are usually compiled. Models relying heavily on external kernel calls may work, but trace will +probably miss some things. Regardless, any python implementation that aims at mimicking another implementation can be +traced once instead of reran N times with breakpoints. + +If you pass `do_prune_layers=False` to your model debugger, ALL the layers will be outputted to `json`. Else, only the +first and last layer will be shown. This is useful when some layers (typically cross-attention) appear only after N +layers. + +[[autodoc]] model_addition_debugger_context + +## Analyzer of skipped tests + +### Scan skipped tests - for model adders and maintainers + +This small util is a power user tool intended for model adders and maintainers. It lists all test methods +existing in `test_modeling_common.py`, inherited by all model tester classes, and scans the repository to measure +how many tests are being skipped and for which models. + +### Rationale + +When porting models to transformers, tests fail as they should, and sometimes `test_modeling_common` feels irreconcilable with the peculiarities of our brand new model. But how can we be sure we're not breaking everything by adding a seemingly innocent skip? + +This utility: +- scans all test_modeling_common methods +- looks for times where a method is skipped +- returns a summary json you can load as a DataFrame/inspect + +**For instance test_inputs_embeds is skipped in a whooping 39% proportion at the time of writing this util.** + +![download-icon](https://huggingface.co/datasets/huggingface/documentation-images/resolve/f7f671f69b88ce4967e19179172c248958d35742/transformers/tests_skipped_visualisation.png) + + +### Usage + +You can run the skipped test analyzer in two ways: + +#### Full scan (default) + +From the root of `transformers` repo, scans all common test methods and outputs the results to a JSON file (default: `all_tests_scan_result.json`). + +```bash +python utils/scan_skipped_tests.py --output_dir path/to/output +``` + +- `--output_dir` (optional): Directory where the JSON results will be saved. Defaults to the current directory. + +**Example output:** + +``` +🔬 Parsing 331 model test files once each... +📝 Aggregating 224 tests... + (224/224) test_update_candidate_strategy_with_matches_1es_3d_is_nonecodet_schedule_fa_kwargs +✅ Scan complete. + +📄 JSON saved to /home/pablo/git/transformers/all_tests_scan_result.json + +``` + +And it will generate `all_tests_scan_result.json` file that you can inspect. The JSON is indexed by method name, and each entry follows this schema, indicating the origin as well (from `common`or `GenerationMixin`.) + +```json +{ + "": { + "origin": "" + "models_ran": ["", ...], + "models_skipped": ["", ...], + "skipped_proportion": , + "reasons_skipped": [": ", + ... + ] + }, + ... +} +``` + +Which you can visualise as above with e.g. `pandas` + +```python +df = pd.read_json('all_tests_scan_result.json').T +df.sort_values(by=['skipped_proportion'], ascending=False) + +``` + +### Scan a single test method + +You can focus on a specific test method using `--test_method_name`: + +```bash +$ python utils/scan_skipped_tests.py --test_method_name test_inputs_embeds --output_dir path/to/output +``` + +- `--test_method_name`: Name of the test method to scan (e.g., `test_inputs_embeds`). +- `--output_dir` (optional): Directory where the JSON result will be saved. + +**Example output:** + +```bash +$ python utils/scan_skipped_tests.py --test_method_name test_inputs_embeds + +🔬 Parsing 331 model test files once each... + +== test_inputs_embeds == + +Ran : 199/323 +Skipped : 124/323 (38.4%) + - aimv2: Aimv2 does not use inputs_embeds + - align: Inputs_embeds is tested in individual model tests + - altclip: Inputs_embeds is tested in individual model tests + - audio_spectrogram_transformer: AST does not use inputs_embeds + - beit: BEiT does not use inputs_embeds + - bit: Bit does not use inputs_embeds + - blip: Blip does not use inputs_embeds + - blip_2: Inputs_embeds is tested in individual model tests + - bridgetower: + - canine: CANINE does not have a get_input_embeddings() method. + - ... + +📄 JSON saved to /home/pablo/git/transformers/scan_test_inputs_embeds.json + +``` \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/internal/modeling_utils.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/internal/modeling_utils.md new file mode 100644 index 0000000000000000000000000000000000000000..11f13de081b2055172f8a94a338feb392581976f --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/internal/modeling_utils.md @@ -0,0 +1,83 @@ + + +# Custom Layers and Utilities + +This page lists all the custom layers used by the library, as well as the utility functions and classes it provides for modeling. + +Most of those are only useful if you are studying the code of the models in the library. + +## Layers + +[[autodoc]] GradientCheckpointingLayer + +## Attention Functions + +[[autodoc]] AttentionInterface + - register + +## Attention Mask Functions + +[[autodoc]] AttentionMaskInterface + - register + +## Rotary Position Embedding Functions + +[[autodoc]] dynamic_rope_update + +## Pytorch custom modules + +[[autodoc]] pytorch_utils.Conv1D + +## PyTorch Helper Functions + +[[autodoc]] pytorch_utils.apply_chunking_to_forward + +[[autodoc]] pytorch_utils.find_pruneable_heads_and_indices + +[[autodoc]] pytorch_utils.prune_layer + +[[autodoc]] pytorch_utils.prune_conv1d_layer + +[[autodoc]] pytorch_utils.prune_linear_layer + +## TensorFlow custom layers + +[[autodoc]] modeling_tf_utils.TFConv1D + +[[autodoc]] modeling_tf_utils.TFSequenceSummary + +## TensorFlow loss functions + +[[autodoc]] modeling_tf_utils.TFCausalLanguageModelingLoss + +[[autodoc]] modeling_tf_utils.TFMaskedLanguageModelingLoss + +[[autodoc]] modeling_tf_utils.TFMultipleChoiceLoss + +[[autodoc]] modeling_tf_utils.TFQuestionAnsweringLoss + +[[autodoc]] modeling_tf_utils.TFSequenceClassificationLoss + +[[autodoc]] modeling_tf_utils.TFTokenClassificationLoss + +## TensorFlow Helper Functions + +[[autodoc]] modeling_tf_utils.get_initializer + +[[autodoc]] modeling_tf_utils.keras_serializable + +[[autodoc]] modeling_tf_utils.shape_list diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/internal/pipelines_utils.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/internal/pipelines_utils.md new file mode 100644 index 0000000000000000000000000000000000000000..6ea6de9a61b8ab5db6fe79ccafa1ed4855d78e9c --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/internal/pipelines_utils.md @@ -0,0 +1,44 @@ + + +# Utilities for pipelines + +This page lists all the utility functions the library provides for pipelines. + +Most of those are only useful if you are studying the code of the models in the library. + + +## Argument handling + +[[autodoc]] pipelines.ArgumentHandler + +[[autodoc]] pipelines.ZeroShotClassificationArgumentHandler + +[[autodoc]] pipelines.QuestionAnsweringArgumentHandler + +## Data format + +[[autodoc]] pipelines.PipelineDataFormat + +[[autodoc]] pipelines.CsvPipelineDataFormat + +[[autodoc]] pipelines.JsonPipelineDataFormat + +[[autodoc]] pipelines.PipedPipelineDataFormat + +## Utilities + +[[autodoc]] pipelines.PipelineException diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/internal/time_series_utils.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/internal/time_series_utils.md new file mode 100644 index 0000000000000000000000000000000000000000..11c562fbe32af5a123f122b44cf0e27db8ab61c9 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/internal/time_series_utils.md @@ -0,0 +1,29 @@ + + +# Time Series Utilities + +This page lists all the utility functions and classes that can be used for Time Series based models. + +Most of those are only useful if you are studying the code of the time series models or you wish to add to the collection of distributional output classes. + +## Distributional Output + +[[autodoc]] time_series_utils.NormalOutput + +[[autodoc]] time_series_utils.StudentTOutput + +[[autodoc]] time_series_utils.NegativeBinomialOutput diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/internal/tokenization_utils.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/internal/tokenization_utils.md new file mode 100644 index 0000000000000000000000000000000000000000..5aa65099176031bc55e24fa286783d876e2b13ce --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/internal/tokenization_utils.md @@ -0,0 +1,42 @@ + + +# Utilities for Tokenizers + +This page lists all the utility functions used by the tokenizers, mainly the class +[`~tokenization_utils_base.PreTrainedTokenizerBase`] that implements the common methods between +[`PreTrainedTokenizer`] and [`PreTrainedTokenizerFast`] and the mixin +[`~tokenization_utils_base.SpecialTokensMixin`]. + +Most of those are only useful if you are studying the code of the tokenizers in the library. + +## PreTrainedTokenizerBase + +[[autodoc]] tokenization_utils_base.PreTrainedTokenizerBase + - __call__ + - all + +## SpecialTokensMixin + +[[autodoc]] tokenization_utils_base.SpecialTokensMixin + +## Enums and namedtuples + +[[autodoc]] tokenization_utils_base.TruncationStrategy + +[[autodoc]] tokenization_utils_base.CharSpan + +[[autodoc]] tokenization_utils_base.TokenSpan diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/internal/trainer_utils.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/internal/trainer_utils.md new file mode 100644 index 0000000000000000000000000000000000000000..1bc5e2baae2d6fd329dca311aebe8eb6a8011427 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/internal/trainer_utils.md @@ -0,0 +1,49 @@ + + +# Utilities for Trainer + +This page lists all the utility functions used by [`Trainer`]. + +Most of those are only useful if you are studying the code of the Trainer in the library. + +## Utilities + +[[autodoc]] EvalPrediction + +[[autodoc]] IntervalStrategy + +[[autodoc]] enable_full_determinism + +[[autodoc]] set_seed + +[[autodoc]] torch_distributed_zero_first + +## Callbacks internals + +[[autodoc]] trainer_callback.CallbackHandler + +## Distributed Evaluation + +[[autodoc]] trainer_pt_utils.DistributedTensorGatherer + +## Trainer Argument Parser + +[[autodoc]] HfArgumentParser + +## Debug Utilities + +[[autodoc]] debug_utils.DebugUnderflowOverflow diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/jan.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/jan.md new file mode 100644 index 0000000000000000000000000000000000000000..ff580496c81be13783563b2041604454b114c213 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/jan.md @@ -0,0 +1,32 @@ +# Jan: using the serving API as a local LLM provider + +This example shows how to use `transformers serve` as a local LLM provider for the [Jan](https://jan.ai/) app. Jan is a ChatGPT-alternative graphical interface, fully running on your machine. The requests to `transformers serve` come directly from the local app -- while this section focuses on Jan, you can extrapolate some instructions to other apps that make local requests. + +## Running models locally + +To connect `transformers serve` with Jan, you'll need to set up a new model provider ("Settings" > "Model Providers"). Click on "Add Provider", and set a new name. In your new model provider page, all you need to set is the "Base URL" to the following pattern: + +```shell +http://[host]:[port]/v1 +``` + +where `host` and `port` are the `transformers serve` CLI parameters (`localhost:8000` by default). After setting this up, you should be able to see some models in the "Models" section, hitting "Refresh". Make sure you add some text in the "API key" text field too -- this data is not actually used, but the field can't be empty. Your custom model provider page should look like this: + +

+ +

+ +You are now ready to chat! + +> [!TIP] +> You can add any `transformers`-compatible model to Jan through `transformers serve`. In the custom model provider you created, click on the "+" button in the "Models" section and add its Hub repository name, e.g. `Qwen/Qwen3-4B`. + +## Running models on a separate machine + +To conclude this example, let's look into a more advanced use-case. If you have a beefy machine to serve models with, but prefer using Jan on a different device, you need to add port forwarding. If you have `ssh` access from your Jan machine into your server, this can be accomplished by typing the following to your Jan machine's terminal + +``` +ssh -N -f -L 8000:localhost:8000 your_server_account@your_server_IP -p port_to_ssh_into_your_server +``` + +Port forwarding is not Jan-specific: you can use it to connect `transformers serve` running in a different machine with an app of your choice. diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/kv_cache.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/kv_cache.md new file mode 100644 index 0000000000000000000000000000000000000000..97553cd94a6e82f57efbafdaba13d104372eea73 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/kv_cache.md @@ -0,0 +1,335 @@ + + +# KV cache strategies + +The key-value (KV) vectors are used to calculate attention scores. For autoregressive models, KV scores are calculated *every* time because the model predicts one token at a time. Each prediction depends on the previous tokens, which means the model performs the same computations each time. + +A KV *cache* stores these calculations so they can be reused without recomputing them. Efficient caching is crucial for optimizing model performance because it reduces computation time and improves response rates. Refer to the [Caching](./cache_explanation) doc for a more detailed explanation about how a cache works. + +Transformers offers several [`Cache`] classes that implement different caching mechanisms. Some of these [`Cache`] classes are optimized to save memory while others are designed to maximize generation speed. Refer to the table below to compare cache types and use it to help you select the best cache for your use case. + +| Cache Type | Memory Efficient  | Supports torch.compile() | Initialization Recommended | Latency | Long Context Generation | +|------------------------|------------------|--------------------------|----------------------------|---------|-------------------------| +| Dynamic Cache | No | No | No | Mid | No | +| Static Cache | No | Yes | Yes | High | No | +| Offloaded Cache | Yes | No | No | Low | Yes | +| Offloaded Static Cache | No | Yes | Yes | High | Yes | +| Quantized Cache | Yes | No | No | Low | Yes | +| Sliding Window Cache | No | Yes | Yes | High | No | + +This guide introduces you to the different [`Cache`] classes and shows you how to use them for generation. + +## Default cache + +The [`DynamicCache`] is the default cache class for most models. It allows the cache size to grow dynamically in order to store an increasing number of keys and values as generation progresses. + +Disable the cache by configuring `use_cache=False` in [`~GenerationMixin.generate`]. + +```py +import torch +from transformers import AutoTokenizer, AutoModelForCausalLM + +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-chat-hf") +model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-chat-hf", torch_dtype=torch.float16, device_map="auto") +inputs = tokenizer("I like rock music because", return_tensors="pt").to(model.device) + +model.generate(**inputs, do_sample=False, max_new_tokens=20, use_cache=False) +``` + +Cache classes can also be initialized first before calling and passing it to the models [past_key_values](https://hf.co/docs/transformers/internal/generation_utils#transformers.generation.GenerateDecoderOnlyOutput.past_key_values) parameter. This cache initialization strategy is only recommended for some cache types. + +In most other cases, it's easier to define the cache strategy in the [cache_implementation](https://hf.co/docs/transformers/main_classes/text_generation#transformers.GenerationConfig.cache_implementation) parameter. + +```py +import torch +from transformers import AutoTokenizer, AutoModelForCausalLM, DynamicCache + +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-chat-hf") +model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-chat-hf", torch_dtype=torch.float16, device_map="auto") +inputs = tokenizer("I like rock music because", return_tensors="pt").to(model.device) + +past_key_values = DynamicCache() +out = model.generate(**inputs, do_sample=False, max_new_tokens=20, past_key_values=past_key_values) +``` + +## Memory efficient caches + +The KV cache can occupy a significant portion of memory and become a [bottleneck](https://hf.co/blog/llama31#inference-memory-requirements) for long-context generation. Memory efficient caches focus on trading off speed for reduced memory usage. This is especially important for large language models (LLMs) and if your hardware is memory constrained. + +### Offloaded cache + +The [`OffloadedCache`] saves GPU memory by moving the KV cache for most model layers to the CPU. Only the current layer cache is maintained on the GPU during a models `forward` iteration over the layers. [`OffloadedCache`] asynchronously prefetches the next layer cache and sends the previous layer cache back to the CPU. + +This cache strategy always generates the same result as [`DynamicCache`] and works as a drop-in replacement or fallback. You may want to use [`OffloadedCache`] if you have a GPU and you're getting out-of-memory (OOM) errors. + +> [!WARNING] +> You may notice a small degradation in generation throughput compared to [`DynamicCache`] depending on your model and generation choices (context size, number of generated tokens, number of beams, etc.). + +Enable [`OffloadedCache`] by configuring `cache_implementation="offloaded"` in either [`GenerationConfig`] or [`~GenerationMixin.generate`]. + +```py +import torch +from transformers import AutoTokenizer, AutoModelForCausalLM + +ckpt = "microsoft/Phi-3-mini-4k-instruct" +tokenizer = AutoTokenizer.from_pretrained(ckpt) +model = AutoModelForCausalLM.from_pretrained(ckpt, torch_dtype=torch.float16, device_map="auto") +inputs = tokenizer("Fun fact: The shortest", return_tensors="pt").to(model.device) + +out = model.generate(**inputs, do_sample=False, max_new_tokens=23, cache_implementation="offloaded") +print(tokenizer.batch_decode(out, skip_special_tokens=True)[0]) +Fun fact: The shortest war in history was between Britain and Zanzibar on August 27, 1896. +``` + +The example below shows how you can fallback on [`OffloadedCache`] if you run out of memory. + +```py +import torch +from transformers import AutoTokenizer, AutoModelForCausalLM, infer_device + +def resilient_generate(model, *args, **kwargs): + oom = False + device = infer_device() + torch_device_module = getattr(torch, device, torch.cuda) + try: + return model.generate(*args, **kwargs) + except torch.OutOfMemoryError as e: + print(e) + print("retrying with cache_implementation='offloaded'") + oom = True + if oom: + torch_device_module.empty_cache() + kwargs["cache_implementation"] = "offloaded" + return model.generate(*args, **kwargs) + +ckpt = "microsoft/Phi-3-mini-4k-instruct" +tokenizer = AutoTokenizer.from_pretrained(ckpt) +model = AutoModelForCausalLM.from_pretrained(ckpt, torch_dtype=torch.float16, device_map="auto") +prompt = ["okay "*1000 + "Fun fact: The most"] +inputs = tokenizer(prompt, return_tensors="pt").to(model.device) +beams = { "num_beams": 40, "num_beam_groups": 40, "num_return_sequences": 40, "diversity_penalty": 1.0, "max_new_tokens": 23, "early_stopping": True, } +out = resilient_generate(model, **inputs, **beams) +responses = tokenizer.batch_decode(out[:,-28:], skip_special_tokens=True) +``` + +### Quantized cache + +The [`QuantizedCache`] reduces memory requirements by quantizing the KV values to a lower precision. [`QuantizedCache`] currently supports two quantization backends. + +- [`HQQQuantizedCache`] supports int2, int4, and int8 datatypes. +- [`QuantoQuantizedCache`] supports int2 and int4 datatypes. This is the default quantization backend. + +> [!WARNING] +> Quantizing the cache can harm latency if the context length is short and there is enough GPU memory available for generation without enabling cache quantization. Try to find a balance between memory efficiency and latency. + +Enable [`QuantizedCache`] by configuring `cache_implementation="quantized"` in [`GenerationConfig`], and the quantization backend, as well as any additional quantization related parameters should also be passed either as a dict. You should use the default values for these additional parameters unless you're running out-of-memory. In that case, consider decreasing the residual length. + + + + +For [`HQQQuantizedCache`], we recommend setting the `axis-key` and `axis-value` parameters to `1`. + +```py +import torch +from transformers import AutoTokenizer, AutoModelForCausalLM, HQQQuantizedCache + +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-chat-hf") +model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-chat-hf", torch_dtype=torch.float16, device_map="auto") +inputs = tokenizer("I like rock music because", return_tensors="pt").to(model.device) + +out = model.generate(**inputs, do_sample=False, max_new_tokens=20, cache_implementation="quantized", cache_config={"backend": "HQQ"}) +print(tokenizer.batch_decode(out, skip_special_tokens=True)[0]) +I like rock music because it's loud and energetic. It's a great way to express myself and rel +``` + + + + +For [`QuantoQuantizedCache`], we recommend setting the `axis-key` and `axis-value` parameters to `0`. + +```py +import torch +from transformers import AutoTokenizer, AutoModelForCausalLM, QuantoQuantizedCache + +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-chat-hf") +model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-chat-hf", torch_dtype=torch.float16, device_map="auto") +inputs = tokenizer("I like rock music because", return_tensors="pt").to(model.device) + +out = model.generate(**inputs, do_sample=False, max_new_tokens=20, cache_implementation="quantized", cache_config={"nbits": 4, "backend": "quanto"}) +print(tokenizer.batch_decode(out, skip_special_tokens=True)[0]) +I like rock music because it's loud and energetic. It's a great way to express myself and rel +``` + + + + +## Speed optimized caches + +The default [`DynamicCache`] prevents you from taking advantage of just-in-time (JIT) optimizations because the cache size isn't fixed. JIT optimizations enable you to maximize latency at the expense of memory usage. All of the following cache types are compatible with JIT optimizations like [torch.compile](./llm_optims#static-kv-cache-and-torchcompile) to accelerate generation. + +### Static cache + +A [`StaticCache`] pre-allocates a specific maximum cache size for the kv pairs. You can generate up to the maximum cache size without needing to modify it. + +Enable [`StaticCache`] by configuring `cache_implementation="static"` in [`~GenerationMixin.generate`]. + +```py +import torch +from transformers import AutoTokenizer, AutoModelForCausalLM + +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-chat-hf") +model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-chat-hf", torch_dtype=torch.float16, device_map="auto") +inputs = tokenizer("Hello, my name is", return_tensors="pt").to(model.device) + +out = model.generate(**inputs, do_sample=False, max_new_tokens=20, cache_implementation="static") +tokenizer.batch_decode(out, skip_special_tokens=True)[0] +"Hello, my name is [Your Name], and I am a [Your Profession] with [Number of Years] of" +``` + +### Offloaded static cache + +The [`OffloadedStaticCache`] is very similar to the [OffloadedCache](#offloaded-cache) except the cache size is set to a maximum cache size. Otherwise, [`OffloadedStaticCache`] only keeps the current layer cache on the GPU and the rest are moved to the CPU. + +Enable [`OffloadedStaticCache`] by configuring `cache_implementation="offloaded_static"` in [`~GenerationMixin.generate`]. + +```py +import torch +from transformers import AutoTokenizer, AutoModelForCausalLM + +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-chat-hf") +model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-chat-hf", torch_dtype=torch.float16, device_map={"": 0}) +inputs = tokenizer("Hello, my name is", return_tensors="pt").to(model.device) + +out = model.generate(**inputs, do_sample=False, max_new_tokens=20, cache_implementation="offloaded_static") +tokenizer.batch_decode(out, skip_special_tokens=True)[0] +"Hello, my name is [Your Name], and I am a [Your Profession] with [Number of Years] of" +``` +Cache offloading requires a CUDA GPU or Intel XPU. + +### Sliding window cache + +[`SlidingWindowCache`] implements a sliding window over the previous kv pairs, and only keeps the last `sliding_window` tokens. This cache type is designed to only work with models that support *sliding window attention*, such as [Mistral](./model_doc/mistral). Older kv states are discarded and replaced by new kv states. + +Enable [`SlidingWindowCache`] by configuring `cache_implementation="sliding_window"` in [`~GenerationMixin.generate`]. + +```py +import torch +from transformers import AutoTokenizer, AutoModelForCausalLM + +tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1") +model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-v0.1", torch_dtype=torch.float16, device_map="auto") +inputs = tokenizer("Yesterday I was on a rock concert and.", return_tensors="pt").to(model.device) + +out = model.generate(**inputs, do_sample=False, max_new_tokens=30, cache_implementation="sliding_window") +tokenizer.batch_decode(out, skip_special_tokens=True)[0] +``` + +## Model caches + +Some model types, like encoder-decoder models or [Gemma2](./model_doc/gemma2) and [Mamba](./model_doc/mamba), have dedicated cache classes. + +### Encoder-decoder cache + +[`EncoderDecoderCache`] is designed for encoder-decoder models. It manages both the self-attention and cross-attention caches to ensure storage and retrieval of previous kv pairs. It is possible to individually set a different cache type for the encoder and decoder. + +This cache type doesn't require any setup. It can be used when calling [`~GenerationMixin.generate`] or a models `forward` method. + +> [!TIP] +> The [`EncoderDecoderCache`] currently only supports [Whisper](./model_doc/whisper). + +### Model-specific caches + +Some models have a unique way of storing past kv pairs or states that is not compatible with any other cache classes. + +[Gemma2](./model_doc/gemma2) requires [`HybridCache`], which uses a combination of [`SlidingWindowCache`] for sliding window attention and [`StaticCache`] for global attention under the hood. + +[Mamba](./model_doc/mamba) requires [`MambaCache`] because the model doesn't have an attention mechanism or kv states. + +## Iterative generation + +A cache can also work in iterative generation settings where there is back-and-forth interaction with a model (chatbots). Like regular generation, iterative generation with a cache allows a model to efficiently handle ongoing conversations without recomputing the entire context at each step. + +For iterative generation with a cache, start by initializing an empty cache class and then you can feed in your new prompts. Keep track of dialogue history with a [chat template](./chat_templating). + +The following example demonstrates [Llama-2-7b-chat-hf](https://huggingface.co/meta-llama/Llama-2-7b-chat-hf). If you’re using a different chat-style model, [`~PreTrainedTokenizer.apply_chat_template`] may process messages differently. It might cut out important tokens depending on how the Jinja template is written. + +For example, some models use special ` ... ` tokens during reasoning. These could get lost during re-encoding, causing indexing issues. You might need to manually remove or adjust extra tokens from the completions to keep things stable. + +```py +import torch +from transformers import AutoTokenizer,AutoModelForCausalLM +from transformers.cache_utils import ( + DynamicCache, + StaticCache, + SlidingWindowCache, + QuantoQuantizedCache, +) + +model_id = "meta-llama/Llama-2-7b-chat-hf" +model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.bfloat16, device_map='auto') +tokenizer = AutoTokenizer.from_pretrained(model_id) + +user_prompts = ["Hello, what's your name?", "Btw, yesterday I was on a rock concert."] + +past_key_values = DynamicCache() + +messages = [] +for prompt in user_prompts: + messages.append({"role": "user", "content": prompt}) + inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt", return_dict=True).to(model.device) + input_length = inputs["input_ids"].shape[1] + outputs = model.generate(**inputs, do_sample=False, max_new_tokens=256, past_key_values=past_key_values) + completion = tokenizer.decode(outputs[0, input_length: ], skip_special_tokens=True) + messages.append({"role": "assistant", "content": completion}) +``` + +## Prefill a cache + +In some situations, you may want to fill a [`Cache`] with kv pairs for a certain prefix prompt and reuse it to generate different sequences. + +The example below initializes a [`StaticCache`], and then caches an initial prompt. Now you can generate several sequences from the prefilled prompt. + +```py +import copy +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer, DynamicCache, StaticCache + +model_id = "meta-llama/Llama-2-7b-chat-hf" +model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.bfloat16, device_map={"": 0}) +tokenizer = AutoTokenizer.from_pretrained(model_id) + +# Init StaticCache with big enough max-length (1024 tokens for the below example) +# You can also init a DynamicCache, if that suits you better +prompt_cache = StaticCache(config=model.config, max_cache_len=1024) + +INITIAL_PROMPT = "You are a helpful assistant. " +inputs_initial_prompt = tokenizer(INITIAL_PROMPT, return_tensors="pt").to(model.device.type) +# This is the common prompt cached, we need to run forward without grad to be able to copy +with torch.no_grad(): + prompt_cache = model(**inputs_initial_prompt, past_key_values = prompt_cache).past_key_values + +prompts = ["Help me to write a blogpost about travelling.", "What is the capital of France?"] +responses = [] +for prompt in prompts: + new_inputs = tokenizer(INITIAL_PROMPT + prompt, return_tensors="pt").to(model.device.type) + past_key_values = copy.deepcopy(prompt_cache) + outputs = model.generate(**new_inputs, past_key_values=past_key_values,max_new_tokens=20) + response = tokenizer.batch_decode(outputs)[0] + responses.append(response) + +print(responses) +``` diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/llm_optims.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/llm_optims.md new file mode 100644 index 0000000000000000000000000000000000000000..495c5d12630d34c50169bcaa33fd86610cb848bd --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/llm_optims.md @@ -0,0 +1,420 @@ + + +# Optimizing inference + +Inference with large language models (LLMs) can be challenging because they have to store and handle billions of parameters. To load a 70B parameter [Llama 2](https://hf.co/meta-llama/Llama-2-70b-hf) model, it requires 256GB of memory for full precision weights and 128GB of memory for half-precision weights. The most powerful GPUs today - the A100 and H100 - only have 80GB of memory. + +On top of the memory requirements, inference is slow because LLMs are called repeatedly to generate the next token. The input sequence increases as generation progresses, which takes longer and longer to process. + +This guide will show you how to optimize LLM inference to accelerate generation and reduce memory usage. + +> [!TIP] +> Try out [Text Generation Inference (TGI)](https://hf.co/docs/text-generation-inference), a Hugging Face library dedicated to deploying and serving highly optimized LLMs for inference. + +## Static kv-cache and torch.compile + +LLMs compute key-value (kv) values for each input token, and it performs the same kv computation each time because the generated output becomes part of the input. However, performing the same kv computation every time is not very efficient. + +A *kv-cache* stores the past keys and values instead of recomputing them each time. As a result, the kv-cache is dynamic and it grows with each generation step which prevents you from taking advantage of [torch.compile](./perf_torch_compile), a powerful optimization method that fuses PyTorch code into optimized kernels. + +The *static kv-cache* solves this issue by pre-allocating the kv-cache size to a maximum value, so you can combine it with [torch.compile](./perf_torch_compile) for up to a 4x speed up. Your speed up may vary depending on the model size (larger models have a smaller speed up) and hardware. + +> [!WARNING] +> Follow this [issue](https://github.com/huggingface/transformers/issues/28981) to track which models (Llama, Gemma, Mistral, etc.) support a static kv-cache and torch.compile. + +Depending on your task, there are several ways you can use the static kv-cache. + +1. For basic use cases, set [cache_implementation](https://hf.co/docs/transformers/main_classes/text_generation#transformers.GenerationConfig.cache_implementation) to `"static"` (recommended). +2. For multi-turn generation or a custom generation loop, initialize and handle [`StaticCache`] directly. +3. For more unique hardware or use cases, it may be better to compile the entire [`~GenerationMixin.generate`] function into a single graph. + +> [!TIP] +> Regardless of how you use the static kv-cache and torch.compile, left-pad your inputs with [pad_to_multiple_of](https://hf.co/docs/transformers/main_classes/tokenizer#transformers.PreTrainedTokenizer.__call__.pad_to_multiple_of) to a limited set of values to avoid shape-related recompilations. + + + + +1. Set the [cache_implementation](https://hf.co/docs/transformers/main_classes/text_generation#transformers.GenerationConfig.cache_implementation) to `"static"` in a models [`GenerationConfig`]. +2. Call [torch.compile](./perf_torch_compile) to compile the forward pass with the static kv-cache. + +```py +from transformers import AutoTokenizer, AutoModelForCausalLM +import torch +import os +os.environ["TOKENIZERS_PARALLELISM"] = "false" # To prevent long warnings :) + +tokenizer = AutoTokenizer.from_pretrained("google/gemma-2b") +model = AutoModelForCausalLM.from_pretrained("google/gemma-2b", torch_dtype="auto", device_map="auto") + +model.generation_config.cache_implementation = "static" + +model.forward = torch.compile(model.forward, mode="reduce-overhead", fullgraph=True) +input_text = "The theory of special relativity states " +input_ids = tokenizer(input_text, return_tensors="pt").to(model.device.type) + +outputs = model.generate(**input_ids) +print(tokenizer.batch_decode(outputs, skip_special_tokens=True)) +['The theory of special relativity states 1. The speed of light is constant in all inertial reference'] +``` + +Under the hood, [`~GenerationMixin.generate`] attempts to reuse the same cache object to avoid recompilation at each call, which is critical to get the most out of [torch.compile](./perf_torch_compile). Be aware of the following to avoid triggering recompilation or if generation is slower than expected. + +1. If the batch size changes or the maximum output length increases between calls, the cache is reinitialized and recompiled. +2. The first several calls of the compiled function are slower because it is being compiled. + + + + +Directly initialize a [`StaticCache`] object and pass it to the `past_key_values` parameter in [`~GenerationMixin.generate`]. The [`StaticCache`] keeps the cache contents, so you can pass it to a new [`~GenerationMixin.generate`] call to continue generation, similar to a dynamic cache. + +```py +from transformers import AutoTokenizer, AutoModelForCausalLM, StaticCache +import torch +import os +os.environ["TOKENIZERS_PARALLELISM"] = "false" # To prevent long warnings :) + +tokenizer = AutoTokenizer.from_pretrained("google/gemma-2b") +model = AutoModelForCausalLM.from_pretrained("google/gemma-2b", torch_dtype="auto", device_map="auto") + +model.forward = torch.compile(model.forward, mode="reduce-overhead", fullgraph=True) +input_text = "The theory of special relativity states " +input_ids = tokenizer(input_text, return_tensors="pt").to(model.device.type) +prompt_length = input_ids.input_ids.shape[1] +model.generation_config.max_new_tokens = 16 + +past_key_values = StaticCache( + config=model.config, + # If you plan to reuse the cache, make sure the cache length is large enough for all cases + max_cache_len=prompt_length+(model.generation_config.max_new_tokens*2), +) +outputs = model.generate(**input_ids, past_key_values=past_key_values) +print(tokenizer.batch_decode(outputs, skip_special_tokens=True)) +['The theory of special relativity states 1. The speed of light is constant in all inertial reference frames. 2'] + +# pass in the generated text and the same cache object to continue generation from where it left off. Optionally, in a +# multi-turn conversation, append the new user input to the generated text. +new_input_ids = outputs +outputs = model.generate(new_input_ids, past_key_values=past_key_values) +print(tokenizer.batch_decode(outputs, skip_special_tokens=True)) +['The theory of special relativity states 1. The speed of light is constant in all inertial reference frames. 2. The speed of light is constant in all inertial reference frames. 3.'] +``` + +> [!TIP] +> To reuse [`StaticCache`] on a new prompt, use [`~StaticCache.reset`] to reset the cache contents between calls. + +Another option for using [`StaticCache`] is to pass it to a models forward pass using the same `past_key_values` argument. This allows you to write your own custom decoding function to decode the next token given the current token, position, and cache position of previously generated tokens. + +```py +from transformers import LlamaTokenizer, LlamaForCausalLM, StaticCache, logging, infer_device +from transformers.testing_utils import CaptureLogger +import torch + +prompts = [ + "Simply put, the theory of relativity states that ", + "My favorite all time favorite condiment is ketchup.", +] + +NUM_TOKENS_TO_GENERATE = 40 +torch_device = infer_device() + +tokenizer = LlamaTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf", pad_token="", padding_side="right") +model = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf", device_map="sequential") +inputs = tokenizer(prompts, return_tensors="pt", padding=True).to(model.device) + +def decode_one_tokens(model, cur_token, input_pos, cache_position, past_key_values): + logits = model( + cur_token, + position_ids=input_pos, + cache_position=cache_position, + past_key_values=past_key_values, + return_dict=False, + use_cache=True + )[0] + new_token = torch.argmax(logits[:, -1], dim=-1)[:, None] + return new_token +``` + +To enable static kv-cache and [torch.compile](./perf_torch_compile) with [`StaticCache`], follow the steps below. + +1. Initialize [`StaticCache`] before using the model for inference to configure parameters like the maximum batch size and sequence length. +2. Call [torch.compile](./perf_torch_compile) on the model to compile the forward pass with the static kv-cache. +3. se SDPBackend.MATH in the [torch.nn.attention.sdpa_kernel](https://pytorch.org/docs/stable/generated/torch.nn.attention.sdpa_kernel.html) context manager to enable the native PyTorch C++ implementation of scaled dot product attention to speed up inference even more. + +```py +from torch.nn.attention import SDPBackend, sdpa_kernel + +batch_size, seq_length = inputs["input_ids"].shape +with torch.no_grad(): + past_key_values = StaticCache( + config=model.config, max_cache_len=4096 + ) + cache_position = torch.arange(seq_length, device=torch_device) + generated_ids = torch.zeros( + batch_size, seq_length + NUM_TOKENS_TO_GENERATE + 1, dtype=torch.int, device=torch_device + ) + generated_ids[:, cache_position] = inputs["input_ids"].to(torch_device).to(torch.int) + + logits = model( + **inputs, cache_position=cache_position, past_key_values=past_key_values,return_dict=False, use_cache=True + )[0] + next_token = torch.argmax(logits[:, -1], dim=-1)[:, None] + generated_ids[:, seq_length] = next_token[:, 0] + + decode_one_tokens = torch.compile(decode_one_tokens, mode="reduce-overhead", fullgraph=True) + cache_position = torch.tensor([seq_length + 1], device=torch_device) + for _ in range(1, NUM_TOKENS_TO_GENERATE): + with sdpa_kernel(SDPBackend.MATH): + next_token = decode_one_tokens(model, next_token.clone(), None, cache_position, past_key_values) + generated_ids[:, cache_position] = next_token.int() + cache_position += 1 + +text = tokenizer.batch_decode(generated_ids, skip_special_tokens=True) +text +['Simply put, the theory of relativity states that 1) the speed of light is constant, 2) the speed of light is the same for all observers, and 3) the laws of physics are the same for all observers.', + 'My favorite all time favorite condiment is ketchup. I love it on everything. I love it on my eggs, my fries, my chicken, my burgers, my hot dogs, my sandwiches, my salads, my p'] +``` + + + + +Compiling the entire [`~GenerationMixin.generate`] function also compiles the input preparation logit processor operations, and more, in addition to the forward pass. With this approach, you don't need to initialize [`StaticCache`] or set the [cache_implementation](https://hf.co/docs/transformers/main_classes/text_generation#transformers.GenerationConfig.cache_implementation) parameter. + +```py +from transformers import AutoTokenizer, AutoModelForCausalLM +import torch +import os +os.environ["TOKENIZERS_PARALLELISM"] = "false" # To prevent long warnings :) + +tokenizer = AutoTokenizer.from_pretrained("google/gemma-2b") +model = AutoModelForCausalLM.from_pretrained("google/gemma-2b", torch_dtype="auto", device_map="auto") + +model.generate = torch.compile(model.generate, mode="reduce-overhead", fullgraph=True) +input_text = "The theory of special relativity states " +input_ids = tokenizer(input_text, return_tensors="pt").to(model.device.type) + +outputs = model.generate(**input_ids) +print(tokenizer.batch_decode(outputs, skip_special_tokens=True)) +['The theory of special relativity states 1. The speed of light is constant in all inertial reference'] +``` + +This usage pattern is more appropriate for unique hardware or use cases, but there are several drawbacks to consider. + +1. Compilation is much slower. +2. Parameters must be configured through [`GenerationConfig`]. +3. Many warnings and exceptions are suppressed. We recommend testing the uncompiled model first. +4. Many features are unavailable at the moment. For example, generation does not stop if an `EOS` token is selected. + + + + +## Decoding strategies + +Decoding can also be optimized to accelerate generation. You can use a lightweight assistant model to generate candidate tokens faster than the LLM itself or you can use a variant of this decoding strategy that works especially well for input-grounded tasks. + +### Speculative decoding + +> [!TIP] +> For a more in-depth explanation, take a look at the [Assisted Generation: a new direction toward low-latency text generation](https://hf.co/blog/assisted-generation) blog post! + +For each input token, the model weights are loaded each time during the forward pass, which is slow and cumbersome when a model has billions of parameters. Speculative decoding alleviates this slowdown by using a second smaller and faster assistant model to generate candidate tokens that are verified by the larger model in a single forward pass. If the verified tokens are correct, the LLM essentially gets them for "free" without having to generate them itself. There is no degradation in accuracy because the verification forward pass ensures the same outputs are generated as if the LLM had generated them on its own. + +To get the largest speed up, the assistant model should be a lot smaller than the LLM so that it can generate tokens quickly. The assistant and LLM model must also share the same tokenizer to avoid re-encoding and decoding tokens. + +> [!WARNING] +> Speculative decoding is only supported for the greedy search and sampling decoding strategies, and it doesn't support batched inputs. + +Enable speculative decoding by loading an assistant model and passing it to [`~GenerationMixin.generate`]. + + + + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer, infer_device +import torch + +device = infer_device() + +tokenizer = AutoTokenizer.from_pretrained("facebook/opt-1.3b") +inputs = tokenizer("Einstein's theory of relativity states", return_tensors="pt").to(device) + +model = AutoModelForCausalLM.from_pretrained("facebook/opt-1.3b", torch_dtype="auto").to(device) +assistant_model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m").to(device) +outputs = model.generate(**inputs, assistant_model=assistant_model) +tokenizer.batch_decode(outputs, skip_special_tokens=True) +["Einstein's theory of relativity states that the speed of light is constant. "] +``` + + + + +For speculative sampling decoding, add the [do_sample](https://hf.co/docs/transformers/main/en/main_classes/text_generation#transformers.GenerationConfig.do_sample) and [temperature](https://hf.co/docs/transformers/main/en/main_classes/text_generation#transformers.GenerationConfig.temperature) parameters to [`~GenerationMixin.generate`]. + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer, infer_device +import torch + +device = infer_device() + +tokenizer = AutoTokenizer.from_pretrained("facebook/opt-1.3b") +inputs = tokenizer("Einstein's theory of relativity states", return_tensors="pt").to(device) + +model = AutoModelForCausalLM.from_pretrained("facebook/opt-1.3b", torch_dtype="auto").to(device) +assistant_model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m").to(device) +outputs = model.generate(**inputs, assistant_model=assistant_model, do_sample=True, temperature=0.7) +print(tokenizer.batch_decode(outputs, skip_special_tokens=True)) +["Einstein's theory of relativity states that motion in the universe is not a straight line.\n"] +``` + + + + +### Prompt lookup decoding + +Prompt lookup decoding is a variant of speculative decoding that is also compatible with greedy search and sampling. Prompt lookup works especially well for input-grounded tasks - such as summarization - where there is often overlapping words between the prompt and output. These overlapping n-grams are used as the LLM candidate tokens. + +To enable prompt lookup decoding, specify the number of tokens that should be overlapping in the [prompt_lookup_num_tokens](https://hf.co/docs/transformers/main/en/main_classes/text_generation#transformers.GenerationConfig.prompt_lookup_num_tokens) parameter. Then pass this parameter to [`~GenerationMixin.generate`]. + + + + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer, infer_device +import torch + +device = infer_device() + +tokenizer = AutoTokenizer.from_pretrained("facebook/opt-1.3b") +inputs = tokenizer("The second law of thermodynamics states", return_tensors="pt").to(device) + +model = AutoModelForCausalLM.from_pretrained("facebook/opt-1.3b", torch_dtype="auto").to(device) +assistant_model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m").to(device) +outputs = model.generate(**inputs, prompt_lookup_num_tokens=3) +print(tokenizer.batch_decode(outputs, skip_special_tokens=True)) +['The second law of thermodynamics states that entropy increases with temperature. '] +``` + + + + +For prompt lookup decoding with sampling, add the [do_sample](https://hf.co/docs/transformers/main/en/main_classes/text_generation#transformers.GenerationConfig.do_sample) and [temperature](https://hf.co/docs/transformers/main/en/main_classes/text_generation#transformers.GenerationConfig.temperature) parameters to [`~GenerationMixin.generate`]. + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer, infer_device +import torch + +device = infer_device() + +tokenizer = AutoTokenizer.from_pretrained("facebook/opt-1.3b") +inputs = tokenizer("The second law of thermodynamics states", return_tensors="pt").to(device) + +model = AutoModelForCausalLM.from_pretrained("facebook/opt-1.3b", torch_dtype="auto").to(device) +outputs = model.generate(**inputs, prompt_lookup_num_tokens=3, do_sample=True, temperature=0.7) +print(tokenizer.batch_decode(outputs, skip_special_tokens=True)) +["The second law of thermodynamics states that energy cannot be created nor destroyed. It's not a"] +``` + + + + +## Attention + +A known issue with transformer models is that the self-attention mechanism grows quadratically in compute and memory with the number of input tokens. This limitation is only magnified in LLMs which handles much longer sequences. To address this, try FlashAttention2 or PyTorch's scaled dot product attention (SDPA), which are more memory efficient attention implementations. + +### FlashAttention-2 + +FlashAttention and [FlashAttention-2](./perf_infer_gpu_one#flashattention-2) break up the attention computation into smaller chunks and reduces the number of intermediate read/write operations to the GPU memory to speed up inference. FlashAttention-2 improves on the original FlashAttention algorithm by also parallelizing over sequence length dimension and better partitioning work on the hardware to reduce synchronization and communication overhead. + +To use FlashAttention-2, set [attn_implementation](https://hf.co/docs/transformers/main/en/main_classes/text_generation#transformers.PreTrainedModel.from_pretrained.attn_implementation) to `"flash_attention_2"` in [`~PreTrainedModel.from_pretrained`] or set with `model.set_attention_implementation("flash_attention_2")` to dynamically update the [attention interface](./attention_interface) after the model is loaded. + +```py +from transformers import AutoModelForCausalLM, BitsAndBytesConfig + +quant_config = BitsAndBytesConfig(load_in_8bit=True) +model = AutoModelForCausalLM.from_pretrained( + "google/gemma-2b", + quantization_config=quant_config, + torch_dtype=torch.bfloat16, + attn_implementation="flash_attention_2", +) + +# Change the model's attention dynamically after loading +model = AutoModelForCausalLM.from_pretrained( + "google/gemma-2b", + quantization_config=quant_config, + torch_dtype=torch.bfloat16 +) +model.set_attention_implementation("flash_attention_2") +``` + +### PyTorch scaled dot product attention + +Scaled dot product attention (SDPA) is automatically enabled in PyTorch 2.0 and it supports FlashAttention, xFormers, and PyTorch's C++ implementation. SDPA chooses the most performant attention algorithm if you're using a CUDA backend. For other backends, SDPA defaults to the PyTorch C++ implementation. + +> [!TIP] +> SDPA automatically supports FlashAttention-2 as long as you have the latest PyTorch version installed. + +Use the [torch.nn.attention.sdpa_kernel](https://pytorch.org/docs/stable/generated/torch.nn.attention.sdpa_kernel.html) context manager to explicitly enable or disable any of the four attention algorithms. For example, use `SDPBackend.FLASH_ATTENTION` to enable FlashAttention. + +```py +import torch +from torch.nn.attention import SDPBackend, sdpa_kernel +from transformers import AutoModelForCausalLM + +model = AutoModelForCausalLM.from_pretrained( + "google/gemma-2b", + torch_dtype=torch.bfloat16, +) + +with sdpa_kernel(SDPBackend.FLASH_ATTENTION): + outputs = model.generate(**inputs) +``` + +## Quantization + +Quantization reduces the size of model weights by storing them in a lower precision. This translates to lower memory usage and makes loading LLMs for inference more accessible if you're constrained by GPU memory. + +If you aren't limited by your GPU, you don't necessarily need to quantize your model because it can increase latency slightly (except for AWQ and fused AWQ modules) due to the extra step required to quantize and dequantize the weights. + +> [!TIP] +> There are many quantization libraries (see the [Quantization](./quantization) guide for more details) available, such as Quanto, AQLM, VPTQ, AWQ, and AutoGPTQ. Feel free to try them out and see which one works best for your use case. We also recommend reading the [Overview of natively supported quantization schemes in 🤗 Transformers](https://hf.co/blog/overview-quantization-transformers) blog post which compares AutoGPTQ and bitsandbytes. + +Use the Model Memory Calculator below to estimate and compare how much memory is required to load a model. For example, try estimating the memory required to load [Mistral-7B-v0.1](https://hf.co/mistralai/Mistral-7B-v0.1). + + + +To load a model in half-precision, set the [torch_dtype](https://hf.co/docs/transformers/main/en/main_classes/text_generation#transformers.PreTrainedModel.from_pretrained.torch_dtype) parameter in [`~transformers.AutoModelForCausalLM.from_pretrained`] to `torch.bfloat16`. This requires 13.74GB of memory. + +```py +from transformers import AutoTokenizer, AutoModelForCausalLM +import torch + +model = AutoModelForCausalLM.from_pretrained( + "mistralai/Mistral-7B-v0.1", torch_dtype=torch.bfloat16, device_map="auto", +) +``` + +To load a quantized model (8-bit or 4-bit), try [bitsandbytes](https://hf.co/docs/bitsandbytes) and set the [load_in_4bit](https://hf.co/docs/transformers/main/en/main_classes/text_generation#transformers.BitsAndBytesConfig.load_in_4bit) or [load_in_8bit](https://hf.co/docs/transformers/main/en/main_classes/text_generation#transformers.BitsAndBytesConfig.load_in_8bit) parameters to `True`. Loading the model in 8-bits only requires 6.87 GB of memory. + +```py +from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig +import torch + +quant_config = BitsAndBytesConfig(load_in_8bit=True) +model = AutoModelForCausalLM.from_pretrained( + "mistralai/Mistral-7B-v0.1", quantization_config=quant_config, device_map="auto" +) +``` diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/llm_tutorial.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/llm_tutorial.md new file mode 100644 index 0000000000000000000000000000000000000000..1f6e166d8847cf7c1469473e76104a89488466bf --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/llm_tutorial.md @@ -0,0 +1,310 @@ + + +# Text generation + +[[open-in-colab]] + +Text generation is the most popular application for large language models (LLMs). A LLM is trained to generate the next word (token) given some initial text (prompt) along with its own generated outputs up to a predefined length or when it reaches an end-of-sequence (`EOS`) token. + +In Transformers, the [`~GenerationMixin.generate`] API handles text generation, and it is available for all models with generative capabilities. This guide will show you the basics of text generation with [`~GenerationMixin.generate`] and some common pitfalls to avoid. + +> [!TIP] +> You can also chat with a model directly from the command line. ([reference](./conversations.md#transformers-cli)) +> ```shell +> transformers chat Qwen/Qwen2.5-0.5B-Instruct +> ``` + +## Default generate + +Before you begin, it's helpful to install [bitsandbytes](https://hf.co/docs/bitsandbytes/index) to quantize really large models to reduce their memory usage. + +```bash +!pip install -U transformers bitsandbytes +``` +Bitsandbytes supports multiple backends in addition to CUDA-based GPUs. Refer to the multi-backend installation [guide](https://huggingface.co/docs/bitsandbytes/main/en/installation#multi-backend) to learn more. + +Load a LLM with [`~PreTrainedModel.from_pretrained`] and add the following two parameters to reduce the memory requirements. + +- `device_map="auto"` enables Accelerates' [Big Model Inference](./models#big-model-inference) feature for automatically initiating the model skeleton and loading and dispatching the model weights across all available devices, starting with the fastest device (GPU). +- `quantization_config` is a configuration object that defines the quantization settings. This examples uses bitsandbytes as the quantization backend (see the [Quantization](./quantization/overview) section for more available backends) and it loads the model in [4-bits](./quantization/bitsandbytes). + +```py +from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig + +quantization_config = BitsAndBytesConfig(load_in_4bit=True) +model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-v0.1", device_map="auto", quantization_config=quantization_config) +``` + +Tokenize your input, and set the [`~PreTrainedTokenizer.padding_side`] parameter to `"left"` because a LLM is not trained to continue generation from padding tokens. The tokenizer returns the input ids and attention mask. + +> [!TIP] +> Process more than one prompt at a time by passing a list of strings to the tokenizer. Batch the inputs to improve throughput at a small cost to latency and memory. + +```py +tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1", padding_side="left") +model_inputs = tokenizer(["A list of colors: red, blue"], return_tensors="pt").to("cuda") +``` + +Pass the inputs to [`~GenerationMixin.generate`] to generate tokens, and [`~PreTrainedTokenizer.batch_decode`] the generated tokens back to text. + +```py +generated_ids = model.generate(**model_inputs) +tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +"A list of colors: red, blue, green, yellow, orange, purple, pink," +``` + +## Generation configuration + +All generation settings are contained in [`GenerationConfig`]. In the example above, the generation settings are derived from the `generation_config.json` file of [mistralai/Mistral-7B-v0.1](https://huggingface.co/mistralai/Mistral-7B-v0.1). A default decoding strategy is used when no configuration is saved with a model. + +Inspect the configuration through the `generation_config` attribute. It only shows values that are different from the default configuration, in this case, the `bos_token_id` and `eos_token_id`. + +```py +from transformers import AutoModelForCausalLM + +model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-v0.1", device_map="auto") +model.generation_config +GenerationConfig { + "bos_token_id": 1, + "eos_token_id": 2 +} +``` + +You can customize [`~GenerationMixin.generate`] by overriding the parameters and values in [`GenerationConfig`]. See [this section below](#common-options) for commonly adjusted parameters. + +```py +# enable beam search sampling strategy +model.generate(**inputs, num_beams=4, do_sample=True) +``` + +[`~GenerationMixin.generate`] can also be extended with external libraries or custom code: +1. the `logits_processor` parameter accepts custom [`LogitsProcessor`] instances for manipulating the next token probability distribution; +2. the `stopping_criteria` parameters supports custom [`StoppingCriteria`] to stop text generation; +3. other custom generation methods can be loaded through the `custom_generate` flag ([docs](generation_strategies.md/#custom-decoding-methods)). + +Refer to the [Generation strategies](./generation_strategies) guide to learn more about search, sampling, and decoding strategies. + +### Saving + +Create an instance of [`GenerationConfig`] and specify the decoding parameters you want. + +```py +from transformers import AutoModelForCausalLM, GenerationConfig + +model = AutoModelForCausalLM.from_pretrained("my_account/my_model") +generation_config = GenerationConfig( + max_new_tokens=50, do_sample=True, top_k=50, eos_token_id=model.config.eos_token_id +) +``` + +Use [`~GenerationConfig.save_pretrained`] to save a specific generation configuration and set the `push_to_hub` parameter to `True` to upload it to the Hub. + +```py +generation_config.save_pretrained("my_account/my_model", push_to_hub=True) +``` + +Leave the `config_file_name` parameter empty. This parameter should be used when storing multiple generation configurations in a single directory. It gives you a way to specify which generation configuration to load. You can create different configurations for different generative tasks (creative text generation with sampling, summarization with beam search) for use with a single model. + +```py +from transformers import AutoModelForSeq2SeqLM, AutoTokenizer, GenerationConfig + +tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-small") +model = AutoModelForSeq2SeqLM.from_pretrained("google-t5/t5-small") + +translation_generation_config = GenerationConfig( + num_beams=4, + early_stopping=True, + decoder_start_token_id=0, + eos_token_id=model.config.eos_token_id, + pad_token=model.config.pad_token_id, +) + +translation_generation_config.save_pretrained("/tmp", config_file_name="translation_generation_config.json", push_to_hub=True) + +generation_config = GenerationConfig.from_pretrained("/tmp", config_file_name="translation_generation_config.json") +inputs = tokenizer("translate English to French: Configuration files are easy to use!", return_tensors="pt") +outputs = model.generate(**inputs, generation_config=generation_config) +print(tokenizer.batch_decode(outputs, skip_special_tokens=True)) +``` + +## Common Options + +[`~GenerationMixin.generate`] is a powerful tool that can be heavily customized. This can be daunting for a new users. This section contains a list of popular generation options that you can define in most text generation tools in Transformers: [`~GenerationMixin.generate`], [`GenerationConfig`], `pipelines`, the `chat` CLI, ... + +| Option name | Type | Simplified description | +|---|---|---| +| `max_new_tokens` | `int` | Controls the maximum generation length. Be sure to define it, as it usually defaults to a small value. | +| `do_sample` | `bool` | Defines whether generation will sample the next token (`True`), or is greedy instead (`False`). Most use cases should set this flag to `True`. Check [this guide](./generation_strategies) for more information. | +| `temperature` | `float` | How unpredictable the next selected token will be. High values (`>0.8`) are good for creative tasks, low values (e.g. `<0.4`) for tasks that require "thinking". Requires `do_sample=True`. | +| `num_beams` | `int` | When set to `>1`, activates the beam search algorithm. Beam search is good on input-grounded tasks. Check [this guide](./generation_strategies) for more information. | +| `repetition_penalty` | `float` | Set it to `>1.0` if you're seeing the model repeat itself often. Larger values apply a larger penalty. | +| `eos_token_id` | `list[int]` | The token(s) that will cause generation to stop. The default value is usually good, but you can specify a different token. | + + +## Pitfalls + +The section below covers some common issues you may encounter during text generation and how to solve them. + +### Output length + +[`~GenerationMixin.generate`] returns up to 20 tokens by default unless otherwise specified in a models [`GenerationConfig`]. It is highly recommended to manually set the number of generated tokens with the [`max_new_tokens`] parameter to control the output length. [Decoder-only](https://hf.co/learn/nlp-course/chapter1/6?fw=pt) models returns the initial prompt along with the generated tokens. + +```py +model_inputs = tokenizer(["A sequence of numbers: 1, 2"], return_tensors="pt").to("cuda") +``` + + + + +```py +generated_ids = model.generate(**model_inputs) +tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'A sequence of numbers: 1, 2, 3, 4, 5' +``` + + + + +```py +generated_ids = model.generate(**model_inputs, max_new_tokens=50) +tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'A sequence of numbers: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,' +``` + + + + +### Decoding strategy + +The default decoding strategy in [`~GenerationMixin.generate`] is *greedy search*, which selects the next most likely token, unless otherwise specified in a models [`GenerationConfig`]. While this decoding strategy works well for input-grounded tasks (transcription, translation), it is not optimal for more creative use cases (story writing, chat applications). + +For example, enable a [multinomial sampling](./generation_strategies#multinomial-sampling) strategy to generate more diverse outputs. Refer to the [Generation strategy](./generation_strategies) guide for more decoding strategies. + +```py +model_inputs = tokenizer(["I am a cat."], return_tensors="pt").to("cuda") +``` + + + + +```py +generated_ids = model.generate(**model_inputs) +tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +``` + + + + +```py +generated_ids = model.generate(**model_inputs, do_sample=True) +tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +``` + + + + +### Padding side + +Inputs need to be padded if they don't have the same length. But LLMs aren't trained to continue generation from padding tokens, which means the [`~PreTrainedTokenizer.padding_side`] parameter needs to be set to the left of the input. + + + + +```py +model_inputs = tokenizer( + ["1, 2, 3", "A, B, C, D, E"], padding=True, return_tensors="pt" +).to("cuda") +generated_ids = model.generate(**model_inputs) +tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'1, 2, 33333333333' +``` + + + + +```py +tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1", padding_side="left") +tokenizer.pad_token = tokenizer.eos_token +model_inputs = tokenizer( + ["1, 2, 3", "A, B, C, D, E"], padding=True, return_tensors="pt" +).to("cuda") +generated_ids = model.generate(**model_inputs) +tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'1, 2, 3, 4, 5, 6,' +``` + + + + +### Prompt format + +Some models and tasks expect a certain input prompt format, and if the format is incorrect, the model returns a suboptimal output. You can learn more about prompting in the [prompt engineering](./tasks/prompting) guide. + +For example, a chat model expects the input as a [chat template](./chat_templating). Your prompt should include a `role` and `content` to indicate who is participating in the conversation. If you try to pass your prompt as a single string, the model doesn't always return the expected output. + +```py +from transformers import AutoTokenizer, AutoModelForCausalLM + +tokenizer = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-alpha") +model = AutoModelForCausalLM.from_pretrained( + "HuggingFaceH4/zephyr-7b-alpha", device_map="auto", load_in_4bit=True +) +``` + + + + +```py +prompt = """How many cats does it take to change a light bulb? Reply as a pirate.""" +model_inputs = tokenizer([prompt], return_tensors="pt").to("cuda") +input_length = model_inputs.input_ids.shape[1] +generated_ids = model.generate(**model_inputs, max_new_tokens=50) +print(tokenizer.batch_decode(generated_ids[:, input_length:], skip_special_tokens=True)[0]) +"Aye, matey! 'Tis a simple task for a cat with a keen eye and nimble paws. First, the cat will climb up the ladder, carefully avoiding the rickety rungs. Then, with" +``` + + + + +```py +messages = [ + { + "role": "system", + "content": "You are a friendly chatbot who always responds in the style of a pirate", + }, + {"role": "user", "content": "How many cats does it take to change a light bulb?"}, +] +model_inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt").to("cuda") +input_length = model_inputs.shape[1] +generated_ids = model.generate(model_inputs, do_sample=True, max_new_tokens=50) +print(tokenizer.batch_decode(generated_ids[:, input_length:], skip_special_tokens=True)[0]) +"Arr, matey! According to me beliefs, 'twas always one cat to hold the ladder and another to climb up it an’ change the light bulb, but if yer looking to save some catnip, maybe yer can +``` + + + + +## Resources + +Take a look below for some more specific and specialized text generation libraries. + +- [Optimum](https://github.com/huggingface/optimum): an extension of Transformers focused on optimizing training and inference on specific hardware devices +- [Outlines](https://github.com/dottxt-ai/outlines): a library for constrained text generation (generate JSON files for example). +- [SynCode](https://github.com/uiuc-focal-lab/syncode): a library for context-free grammar guided generation (JSON, SQL, Python). +- [Text Generation Inference](https://github.com/huggingface/text-generation-inference): a production-ready server for LLMs. +- [Text generation web UI](https://github.com/oobabooga/text-generation-webui): a Gradio web UI for text generation. +- [logits-processor-zoo](https://github.com/NVIDIA/logits-processor-zoo): additional logits processors for controlling text generation. diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/llm_tutorial_optimization.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/llm_tutorial_optimization.md new file mode 100644 index 0000000000000000000000000000000000000000..5f48adb5b8984a1876ba326df51480ce86039947 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/llm_tutorial_optimization.md @@ -0,0 +1,782 @@ + + +# Optimizing LLMs for Speed and Memory + +[[open-in-colab]] + +Large Language Models (LLMs) such as GPT3/4, [Falcon](https://huggingface.co/tiiuae/falcon-40b), and [Llama](https://huggingface.co/meta-llama/Llama-2-70b-hf) are rapidly advancing in their ability to tackle human-centric tasks, establishing themselves as essential tools in modern knowledge-based industries. +Deploying these models in real-world tasks remains challenging, however: + +- To exhibit near-human text understanding and generation capabilities, LLMs currently require to be composed of billions of parameters (see [Kaplan et al](https://huggingface.co/papers/2001.08361), [Wei et. al](https://huggingface.co/papers/2206.07682)). This consequently amplifies the memory demands for inference. +- In many real-world tasks, LLMs need to be given extensive contextual information. This necessitates the model's capability to manage very long input sequences during inference. + +The crux of these challenges lies in augmenting the computational and memory capabilities of LLMs, especially when handling expansive input sequences. + +In this guide, we will go over the effective techniques for efficient LLM deployment: + +1. **Lower Precision:** Research has shown that operating at reduced numerical precision, namely [8-bit and 4-bit](./main_classes/quantization) can achieve computational advantages without a considerable decline in model performance. + +2. **Flash Attention:** Flash Attention is a variation of the attention algorithm that not only provides a more memory-efficient approach but also realizes increased efficiency due to optimized GPU memory utilization. + +3. **Architectural Innovations:** Considering that LLMs are always deployed in the same way during inference, namely autoregressive text generation with a long input context, specialized model architectures have been proposed that allow for more efficient inference. The most important advancement in model architectures hereby are [Alibi](https://huggingface.co/papers/2108.12409), [Rotary embeddings](https://huggingface.co/papers/2104.09864), [Multi-Query Attention (MQA)](https://huggingface.co/papers/1911.02150) and [Grouped-Query-Attention (GQA)](https://huggingface.co/papers/2305.13245). + +Throughout this guide, we will offer an analysis of auto-regressive generation from a tensor's perspective. We delve into the pros and cons of adopting lower precision, provide a comprehensive exploration of the latest attention algorithms, and discuss improved LLM architectures. While doing so, we run practical examples showcasing each of the feature improvements. + +## 1. Lower Precision + +Memory requirements of LLMs can be best understood by seeing the LLM as a set of weight matrices and vectors and the text inputs as a sequence of vectors. In the following, the definition *weights* will be used to signify all model weight matrices and vectors. + +At the time of writing this guide, LLMs consist of at least a couple billion parameters. Each parameter thereby is made of a decimal number, e.g. `4.5689` which is usually stored in either [float32](https://en.wikipedia.org/wiki/Single-precision_floating-point_format), [bfloat16](https://en.wikipedia.org/wiki/Bfloat16_floating-point_format), or [float16](https://en.wikipedia.org/wiki/Half-precision_floating-point_format) format. This allows us to easily compute the memory requirement to load the LLM into memory: + +> *Loading the weights of a model having X billion parameters requires roughly 4 * X GB of VRAM in float32 precision* + +Nowadays, models are however rarely trained in full float32 precision, but usually in bfloat16 precision or less frequently in float16 precision. Therefore the rule of thumb becomes: + +> *Loading the weights of a model having X billion parameters requires roughly 2 * X GB of VRAM in bfloat16/float16 precision* + +For shorter text inputs (less than 1024 tokens), the memory requirement for inference is very much dominated by the memory requirement to load the weights. Therefore, for now, let's assume that the memory requirement for inference is equal to the memory requirement to load the model into the GPU VRAM. + +To give some examples of how much VRAM it roughly takes to load a model in bfloat16: + +- **GPT3** requires 2 \* 175 GB = **350 GB** VRAM +- [**Bloom**](https://huggingface.co/bigscience/bloom) requires 2 \* 176 GB = **352 GB** VRAM +- [**Llama-2-70b**](https://huggingface.co/meta-llama/Llama-2-70b-hf) requires 2 \* 70 GB = **140 GB** VRAM +- [**Falcon-40b**](https://huggingface.co/tiiuae/falcon-40b) requires 2 \* 40 GB = **80 GB** VRAM +- [**MPT-30b**](https://huggingface.co/mosaicml/mpt-30b) requires 2 \* 30 GB = **60 GB** VRAM +- [**bigcode/starcoder**](https://huggingface.co/bigcode/starcoder) requires 2 \* 15.5 = **31 GB** VRAM + +As of writing this document, the largest GPU chip on the market is the A100 & H100 offering 80GB of VRAM. Most of the models listed before require more than 80GB just to be loaded and therefore necessarily require [tensor parallelism](https://huggingface.co/docs/transformers/perf_train_gpu_many#tensor-parallelism) and/or [pipeline parallelism](https://huggingface.co/docs/transformers/perf_train_gpu_many#naive-model-parallelism-vertical-and-pipeline-parallelism). + +🤗 Transformers now supports tensor parallelism for supported models having `base_tp_plan` in their respective config classes. Learn more about Tensor Parallelism [here](perf_train_gpu_many#tensor-parallelism). Furthermore, if you're interested in writing models in a tensor-parallelism-friendly way, feel free to have a look at [the text-generation-inference library](https://github.com/huggingface/text-generation-inference/tree/main/server/text_generation_server/models/custom_modeling). + +Naive pipeline parallelism is supported out of the box. For this, simply load the model with `device="auto"` which will automatically place the different layers on the available GPUs as explained [here](https://huggingface.co/docs/accelerate/v0.22.0/en/concept_guides/big_model_inference). +Note, however that while very effective, this naive pipeline parallelism does not tackle the issues of GPU idling. For this more advanced pipeline parallelism is required as explained [here](https://huggingface.co/docs/transformers/en/perf_train_gpu_many#naive-model-parallelism-vertical-and-pipeline-parallelism). + +If you have access to an 8 x 80GB A100 node, you could load BLOOM as follows + +```bash +!pip install transformers accelerate bitsandbytes optimum +``` +```python +from transformers import AutoModelForCausalLM + +model = AutoModelForCausalLM.from_pretrained("bigscience/bloom", device_map="auto", pad_token_id=0) +``` + +By using `device_map="auto"` the attention layers would be equally distributed over all available GPUs. + +In this guide, we will use [bigcode/octocoder](https://huggingface.co/bigcode/octocoder) as it can be run on a single 40 GB A100 GPU device chip. Note that all memory and speed optimizations that we will apply going forward, are equally applicable to models that require model or tensor parallelism. + +Since the model is loaded in bfloat16 precision, using our rule of thumb above, we would expect the memory requirement to run inference with `bigcode/octocoder` to be around 31 GB VRAM. Let's give it a try. + +We first load the model and tokenizer and then pass both to Transformers' [pipeline](https://huggingface.co/docs/transformers/main_classes/pipelines) object. + +```python +from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline +import torch + +model = AutoModelForCausalLM.from_pretrained("bigcode/octocoder", torch_dtype=torch.bfloat16, device_map="auto", pad_token_id=0) +tokenizer = AutoTokenizer.from_pretrained("bigcode/octocoder") + +pipe = pipeline("text-generation", model=model, tokenizer=tokenizer) +``` + +```python +prompt = "Question: Please write a function in Python that transforms bytes to Giga bytes.\n\nAnswer:" + +result = pipe(prompt, max_new_tokens=60)[0]["generated_text"][len(prompt):] +result +``` + +**Output**: +``` +Here is a Python function that transforms bytes to Giga bytes:\n\n```python\ndef bytes_to_giga_bytes(bytes):\n return bytes / 1024 / 1024 / 1024\n```\n\nThis function takes a single +``` + +Nice, we can now directly use the result to convert bytes into Gigabytes. + +```python +def bytes_to_giga_bytes(bytes): + return bytes / 1024 / 1024 / 1024 +``` + +Let's call [`torch.cuda.max_memory_allocated`](https://pytorch.org/docs/stable/generated/torch.cuda.max_memory_allocated.html) to measure the peak GPU memory allocation. + +```python +bytes_to_giga_bytes(torch.cuda.max_memory_allocated()) +``` + +**Output**: +```bash +29.0260648727417 +``` + +Close enough to our back-of-the-envelope computation! We can see the number is not exactly correct as going from bytes to kilobytes requires a multiplication of 1024 instead of 1000. Therefore the back-of-the-envelope formula can also be understood as an "at most X GB" computation. +Note that if we had tried to run the model in full float32 precision, a whopping 64 GB of VRAM would have been required. + +> Almost all models are trained in bfloat16 nowadays, there is no reason to run the model in full float32 precision if [your GPU supports bfloat16](https://discuss.pytorch.org/t/bfloat16-native-support/117155/5). Float32 won't give better inference results than the precision that was used to train the model. + +If you are unsure in which format the model weights are stored on the Hub, you can always look into the checkpoint's config under `"torch_dtype"`, *e.g.* [here](https://huggingface.co/meta-llama/Llama-2-7b-hf/blob/6fdf2e60f86ff2481f2241aaee459f85b5b0bbb9/config.json#L21). It is recommended to set the model to the same precision type as written in the config when loading with `from_pretrained(..., torch_dtype=...)` except when the original type is float32 in which case one can use both `float16` or `bfloat16` for inference. + + +Let's define a `flush(...)` function to free all allocated memory so that we can accurately measure the peak allocated GPU memory. + +```python +del pipe +del model + +import gc +import torch + +def flush(): + gc.collect() + torch.cuda.empty_cache() + torch.cuda.reset_peak_memory_stats() +``` + +Let's call it now for the next experiment. + +```python +flush() +``` +From the Accelerate library, you can also use a device-agnostic utility method called [release_memory](https://github.com/huggingface/accelerate/blob/29be4788629b772a3b722076e433b5b3b5c85da3/src/accelerate/utils/memory.py#L63), which takes various hardware backends like XPU, MLU, NPU, MPS, and more into account. + +```python +from accelerate.utils import release_memory +# ... + +release_memory(model) +``` + +Now what if your GPU does not have 32 GB of VRAM? It has been found that model weights can be quantized to 8-bit or 4-bits without a significant loss in performance (see [Dettmers et al.](https://huggingface.co/papers/2208.07339)). +Model can be quantized to even 3 or 2 bits with an acceptable loss in performance as shown in the recent [GPTQ paper](https://huggingface.co/papers/2210.17323) 🤯. + +Without going into too many details, quantization schemes aim at reducing the precision of weights while trying to keep the model's inference results as accurate as possible (*a.k.a* as close as possible to bfloat16). +Note that quantization works especially well for text generation since all we care about is choosing the *set of most likely next tokens* and don't really care about the exact values of the next token *logit* distribution. +All that matters is that the next token *logit* distribution stays roughly the same so that an `argmax` or `topk` operation gives the same results. + +There are various quantization techniques, which we won't discuss in detail here, but in general, all quantization techniques work as follows: + +- 1. Quantize all weights to the target precision +- 2. Load the quantized weights, and pass the input sequence of vectors in bfloat16 precision +- 3. Dynamically dequantize weights to bfloat16 to perform the computation with their input vectors in bfloat16 precision + +In a nutshell, this means that *inputs-weight matrix* multiplications, with \\( X \\) being the *inputs*, \\( W \\) being a weight matrix and \\( Y \\) being the output: + +$$ Y = X * W $$ + +are changed to + +$$ Y = X * \text{dequantize}(W) $$ + +for every matrix multiplication. Dequantization and re-quantization is performed sequentially for all weight matrices as the inputs run through the network graph. + +Therefore, inference time is often **not** reduced when using quantized weights, but rather increases. +Enough theory, let's give it a try! To quantize the weights with Transformers, you need to make sure that +the [`bitsandbytes`](https://github.com/bitsandbytes-foundation/bitsandbytes) library is installed. + +```bash +!pip install bitsandbytes +``` + +We can then load models in 8-bit quantization by simply adding a `load_in_8bit=True` flag to `from_pretrained`. + +```python +model = AutoModelForCausalLM.from_pretrained("bigcode/octocoder", load_in_8bit=True, pad_token_id=0) +``` + +Now, let's run our example again and measure the memory usage. + +```python +pipe = pipeline("text-generation", model=model, tokenizer=tokenizer) + +result = pipe(prompt, max_new_tokens=60)[0]["generated_text"][len(prompt):] +result +``` + +**Output**: +``` +Here is a Python function that transforms bytes to Giga bytes:\n\n```python\ndef bytes_to_giga_bytes(bytes):\n return bytes / 1024 / 1024 / 1024\n```\n\nThis function takes a single +``` + +Nice, we're getting the same result as before, so no loss in accuracy! Let's look at how much memory was used this time. + +```python +bytes_to_giga_bytes(torch.cuda.max_memory_allocated()) +``` + +**Output**: +``` +15.219234466552734 +``` + +Significantly less! We're down to just a bit over 15 GBs and could therefore run this model on consumer GPUs like the 4090. +We're seeing a very nice gain in memory efficiency and more or less no degradation to the model's output. However, we can also notice a slight slow-down during inference. + + +We delete the models and flush the memory again. +```python +del model +del pipe +``` + +```python +flush() +``` + +Let's see what peak GPU memory consumption 4-bit quantization gives. Quantizing the model to 4-bit can be done with the same API as before - this time by passing `load_in_4bit=True` instead of `load_in_8bit=True`. + +```python +model = AutoModelForCausalLM.from_pretrained("bigcode/octocoder", load_in_4bit=True, pad_token_id=0) + +pipe = pipeline("text-generation", model=model, tokenizer=tokenizer) + +result = pipe(prompt, max_new_tokens=60)[0]["generated_text"][len(prompt):] +result +``` + +**Output**: +``` +Here is a Python function that transforms bytes to Giga bytes:\n\n```\ndef bytes_to_gigabytes(bytes):\n return bytes / 1024 / 1024 / 1024\n```\n\nThis function takes a single argument +``` + +We're almost seeing the same output text as before - just the `python` is missing just before the code snippet. Let's see how much memory was required. + +```python +bytes_to_giga_bytes(torch.cuda.max_memory_allocated()) +``` + +**Output**: +``` +9.543574333190918 +``` + +Just 9.5GB! That's really not a lot for a >15 billion parameter model. + +While we see very little degradation in accuracy for our model here, 4-bit quantization can in practice often lead to different results compared to 8-bit quantization or full `bfloat16` inference. It is up to the user to try it out. + +Also note that inference here was again a bit slower compared to 8-bit quantization which is due to the more aggressive quantization method used for 4-bit quantization leading to \\( \text{quantize} \\) and \\( \text{dequantize} \\) taking longer during inference. + +```python +del model +del pipe +``` +```python +flush() +``` + +Overall, we saw that running OctoCoder in 8-bit precision reduced the required GPU VRAM from 32G GPU VRAM to only 15GB and running the model in 4-bit precision further reduces the required GPU VRAM to just a bit over 9GB. + +4-bit quantization allows the model to be run on GPUs such as RTX3090, V100, and T4 which are quite accessible for most people. + +For more information on quantization and to see how one can quantize models to require even less GPU VRAM memory than 4-bit, we recommend looking into the [`AutoGPTQ`](https://huggingface.co/docs/transformers/main/en/main_classes/quantization#autogptq-integration%60) implementation. + +> As a conclusion, it is important to remember that model quantization trades improved memory efficiency against accuracy and in some cases inference time. + +If GPU memory is not a constraint for your use case, there is often no need to look into quantization. However many GPUs simply can't run LLMs without quantization methods and in this case, 4-bit and 8-bit quantization schemes are extremely useful tools. + +For more in-detail usage information, we strongly recommend taking a look at the [Transformers Quantization Docs](https://huggingface.co/docs/transformers/main_classes/quantization#general-usage). +Next, let's look into how we can improve computational and memory efficiency by using better algorithms and an improved model architecture. + +## 2. Flash Attention + +Today's top-performing LLMs share more or less the same fundamental architecture that consists of feed-forward layers, activation layers, layer normalization layers, and most crucially, self-attention layers. + +Self-attention layers are central to Large Language Models (LLMs) in that they enable the model to understand the contextual relationships between input tokens. +However, the peak GPU memory consumption for self-attention layers grows *quadratically* both in compute and memory complexity with number of input tokens (also called *sequence length*) that we denote in the following by \\( N \\) . +While this is not really noticeable for shorter input sequences (of up to 1000 input tokens), it becomes a serious problem for longer input sequences (at around 16000 input tokens). + +Let's take a closer look. The formula to compute the output \\( \mathbf{O} \\) of a self-attention layer for an input \\( \mathbf{X} \\) of length \\( N \\) is: + +$$ \textbf{O} = \text{Attn}(\mathbf{X}) = \mathbf{V} \times \text{Softmax}(\mathbf{QK}^T) \text{ with } \mathbf{Q} = \mathbf{W}_q \mathbf{X}, \mathbf{V} = \mathbf{W}_v \mathbf{X}, \mathbf{K} = \mathbf{W}_k \mathbf{X} $$ + +\\( \mathbf{X} = (\mathbf{x}_1, ... \mathbf{x}_{N}) \\) is thereby the input sequence to the attention layer. The projections \\( \mathbf{Q} \\) and \\( \mathbf{K} \\) will each consist of \\( N \\) vectors resulting in the \\( \mathbf{QK}^T \\) being of size \\( N^2 \\) . + +LLMs usually have multiple attention heads, thus doing multiple self-attention computations in parallel. +Assuming, the LLM has 40 attention heads and runs in bfloat16 precision, we can calculate the memory requirement to store the \\( \mathbf{QK^T} \\) matrices to be \\( 40 * 2 * N^2 \\) bytes. For \\( N=1000 \\) only around 50 MB of VRAM are needed, however, for \\( N=16000 \\) we would need 19 GB of VRAM, and for \\( N=100,000 \\) we would need almost 1TB just to store the \\( \mathbf{QK}^T \\) matrices. + +Long story short, the default self-attention algorithm quickly becomes prohibitively memory-expensive for large input contexts. + +As LLMs improve in text comprehension and generation, they are applied to increasingly complex tasks. While models once handled the translation or summarization of a few sentences, they now manage entire pages, demanding the capability to process extensive input lengths. + +How can we get rid of the exorbitant memory requirements for large input lengths? We need a new way to compute the self-attention mechanism that gets rid of the \\( QK^T \\) matrix. [Tri Dao et al.](https://huggingface.co/papers/2205.14135) developed exactly such a new algorithm and called it **Flash Attention**. + +In a nutshell, Flash Attention breaks the \\(\mathbf{V} \times \text{Softmax}(\mathbf{QK}^T\\)) computation apart and instead computes smaller chunks of the output by iterating over multiple softmax computation steps: + +$$ \textbf{O}_i \leftarrow s^a_{ij} * \textbf{O}_i + s^b_{ij} * \mathbf{V}_{j} \times \text{Softmax}(\mathbf{QK}^T_{i,j}) \text{ for multiple } i, j \text{ iterations} $$ + +with \\( s^a_{ij} \\) and \\( s^b_{ij} \\) being some softmax normalization statistics that need to be recomputed for every \\( i \\) and \\( j \\) . + +Please note that the whole Flash Attention is a bit more complex and is greatly simplified here as going in too much depth is out of scope for this guide. The reader is invited to take a look at the well-written [Flash Attention paper](https://huggingface.co/papers/2205.14135) for more details. + +The main takeaway here is: + +> By keeping track of softmax normalization statistics and by using some smart mathematics, Flash Attention gives **numerical identical** outputs compared to the default self-attention layer at a memory cost that only increases linearly with \\( N \\) . + +Looking at the formula, one would intuitively say that Flash Attention must be much slower compared to the default self-attention formula as more computation needs to be done. Indeed Flash Attention requires more FLOPs compared to normal attention as the softmax normalization statistics have to constantly be recomputed (see [paper](https://huggingface.co/papers/2205.14135) for more details if interested) + +> However, Flash Attention is much faster in inference compared to default attention which comes from its ability to significantly reduce the demands on the slower, high-bandwidth memory of the GPU (VRAM), focusing instead on the faster on-chip memory (SRAM). + +Essentially, Flash Attention makes sure that all intermediate write and read operations can be done using the fast *on-chip* SRAM memory instead of having to access the slower VRAM memory to compute the output vector \\( \mathbf{O} \\) . + +In practice, there is currently absolutely no reason to **not** use Flash Attention if available. The algorithm gives mathematically the same outputs, and is both faster and more memory-efficient. + +Let's look at a practical example. + +Our OctoCoder model now gets a significantly longer input prompt which includes a so-called *system prompt*. System prompts are used to steer the LLM into a better assistant that is tailored to the users' task. +In the following, we use a system prompt that will make OctoCoder a better coding assistant. + +```python +system_prompt = """Below are a series of dialogues between various people and an AI technical assistant. +The assistant tries to be helpful, polite, honest, sophisticated, emotionally aware, and humble but knowledgeable. +The assistant is happy to help with code questions and will do their best to understand exactly what is needed. +It also tries to avoid giving false or misleading information, and it caveats when it isn't entirely sure about the right answer. +That said, the assistant is practical really does its best, and doesn't let caution get too much in the way of being useful. + +The Starcoder models are a series of 15.5B parameter models trained on 80+ programming languages from The Stack (v1.2) (excluding opt-out requests). +The model uses Multi Query Attention, was trained using the Fill-in-the-Middle objective, and with 8,192 tokens context window for a trillion tokens of heavily deduplicated data. + +----- + +Question: Write a function that takes two lists and returns a list that has alternating elements from each input list. + +Answer: Sure. Here is a function that does that. + +def alternating(list1, list2): + results = [] + for i in range(len(list1)): + results.append(list1[i]) + results.append(list2[i]) + return results + +Question: Can you write some test cases for this function? + +Answer: Sure, here are some tests. + +assert alternating([10, 20, 30], [1, 2, 3]) == [10, 1, 20, 2, 30, 3] +assert alternating([True, False], [4, 5]) == [True, 4, False, 5] +assert alternating([], []) == [] + +Question: Modify the function so that it returns all input elements when the lists have uneven length. The elements from the longer list should be at the end. + +Answer: Here is the modified function. + +def alternating(list1, list2): + results = [] + for i in range(min(len(list1), len(list2))): + results.append(list1[i]) + results.append(list2[i]) + if len(list1) > len(list2): + results.extend(list1[i+1:]) + else: + results.extend(list2[i+1:]) + return results + +----- +""" +``` +For demonstration purposes, we duplicate the system prompt by ten so that the input length is long enough to observe Flash Attention's memory savings. +We append the original text prompt `"Question: Please write a function in Python that transforms bytes to Giga bytes.\n\nAnswer: Here"` + +```python +long_prompt = 10 * system_prompt + prompt +``` + +We instantiate our model again in bfloat16 precision. + +```python +model = AutoModelForCausalLM.from_pretrained("bigcode/octocoder", torch_dtype=torch.bfloat16, device_map="auto") +tokenizer = AutoTokenizer.from_pretrained("bigcode/octocoder") + +pipe = pipeline("text-generation", model=model, tokenizer=tokenizer) +``` + +Let's now run the model just like before *without Flash Attention* and measure the peak GPU memory requirement and inference time. + +```python +import time + +start_time = time.time() +result = pipe(long_prompt, max_new_tokens=60)[0]["generated_text"][len(long_prompt):] + +print(f"Generated in {time.time() - start_time} seconds.") +result +``` + +**Output**: +``` +Generated in 10.96854019165039 seconds. +Sure. Here is a function that does that.\n\ndef bytes_to_giga(bytes):\n return bytes / 1024 / 1024 / 1024\n\nAnswer: Sure. Here is a function that does that.\n\ndef +```` + +We're getting the same output as before, however this time, the model repeats the answer multiple times until it's 60 tokens cut-off. This is not surprising as we've repeated the system prompt ten times for demonstration purposes and thus cued the model to repeat itself. + +**Note** that the system prompt should not be repeated ten times in real-world applications - one time is enough! + +Let's measure the peak GPU memory requirement. + +```python +bytes_to_giga_bytes(torch.cuda.max_memory_allocated()) +``` + +**Output**: +```bash +37.668193340301514 +``` + +As we can see the peak GPU memory requirement is now significantly higher than in the beginning, which is largely due to the longer input sequence. Also the generation takes a little over a minute now. + +We call `flush()` to free GPU memory for our next experiment. + +```python +flush() +``` + +For comparison, let's run the same function, but enable Flash Attention instead. +To do so, we convert the model to [BetterTransformer](https://huggingface.co/docs/optimum/bettertransformer/overview) and by doing so enabling PyTorch's [SDPA self-attention](https://pytorch.org/docs/master/generated/torch.nn.functional.scaled_dot_product_attention) which in turn is able to use Flash Attention. + +```python +model.to_bettertransformer() +``` + +Now we run the exact same code snippet as before and under the hood Transformers will make use of Flash Attention. + +```py +start_time = time.time() +with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=False, enable_mem_efficient=False): + result = pipe(long_prompt, max_new_tokens=60)[0]["generated_text"][len(long_prompt):] + +print(f"Generated in {time.time() - start_time} seconds.") +result +``` + +**Output**: +``` +Generated in 3.0211617946624756 seconds. + Sure. Here is a function that does that.\n\ndef bytes_to_giga(bytes):\n return bytes / 1024 / 1024 / 1024\n\nAnswer: Sure. Here is a function that does that.\n\ndef +``` + +We're getting the exact same result as before, but can observe a very significant speed-up thanks to Flash Attention. + +Let's measure the memory consumption one last time. + +```python +bytes_to_giga_bytes(torch.cuda.max_memory_allocated()) +``` + +**Output**: +``` +32.617331981658936 +``` + +And we're almost back to our original 29GB peak GPU memory from the beginning. + +We can observe that we only use roughly 100MB more GPU memory when passing a very long input sequence with Flash Attention compared to passing a short input sequence as done in the beginning. + +```py +flush() +``` + +For more information on how to use Flash Attention, please have a look at [this doc page](https://huggingface.co/docs/transformers/en/perf_infer_gpu_one#flashattention-2). + +## 3. Architectural Innovations + +So far we have looked into improving computational and memory efficiency by: + +- Casting the weights to a lower precision format +- Replacing the self-attention algorithm with a more memory- and compute efficient version + +Let's now look into how we can change the architecture of an LLM so that it is most effective and efficient for task that require long text inputs, *e.g.*: +- Retrieval augmented Questions Answering, +- Summarization, +- Chat + +Note that *chat* not only requires the LLM to handle long text inputs, but it also necessitates that the LLM is able to efficiently handle the back-and-forth dialogue between user and assistant (such as ChatGPT). + +Once trained, the fundamental LLM architecture is difficult to change, so it is important to make considerations about the LLM's tasks beforehand and accordingly optimize the model's architecture. +There are two important components of the model architecture that quickly become memory and/or performance bottlenecks for large input sequences. + +- The positional embeddings +- The key-value cache + +Let's go over each component in more detail + +### 3.1 Improving positional embeddings of LLMs + +Self-attention puts each token in relation to each other's tokens. +As an example, the \\( \text{Softmax}(\mathbf{QK}^T) \\) matrix of the text input sequence *"Hello", "I", "love", "you"* could look as follows: + +![](/blog/assets/163_optimize_llm/self_attn_tokens.png) + +Each word token is given a probability mass at which it attends all other word tokens and, therefore is put into relation with all other word tokens. E.g. the word *"love"* attends to the word *"Hello"* with 5%, to *"I"* with 30%, and to itself with 65%. + +A LLM based on self-attention, but without position embeddings would have great difficulties in understanding the positions of the text inputs to each other. +This is because the probability score computed by \\( \mathbf{QK}^T \\) relates each word token to each other word token in \\( O(1) \\) computations regardless of their relative positional distance to each other. +Therefore, for the LLM without position embeddings each token appears to have the same distance to all other tokens, *e.g.* differentiating between *"Hello I love you"* and *"You love I hello"* would be very challenging. + +For the LLM to understand sentence order, an additional *cue* is needed and is usually applied in the form of *positional encodings* (or also called *positional embeddings*). +Positional encodings, encode the position of each token into a numerical presentation that the LLM can leverage to better understand sentence order. + +The authors of the [*Attention Is All You Need*](https://huggingface.co/papers/1706.03762) paper introduced sinusoidal positional embeddings \\( \mathbf{P} = \mathbf{p}_1, \ldots, \mathbf{p}_N \\) . +where each vector \\( \mathbf{p}_i \\) is computed as a sinusoidal function of its position \\( i \\) . +The positional encodings are then simply added to the input sequence vectors \\( \mathbf{\hat{X}} = \mathbf{\hat{x}}_1, \ldots, \mathbf{\hat{x}}_N \\) = \\( \mathbf{x}_1 + \mathbf{p}_1, \ldots, \mathbf{x}_N + \mathbf{p}_N \\) thereby cueing the model to better learn sentence order. + +Instead of using fixed position embeddings, others (such as [Devlin et al.](https://huggingface.co/papers/1810.04805)) used learned positional encodings for which the positional embeddings +\\( \mathbf{P} \\) are learned during training. + +Sinusoidal and learned position embeddings used to be the predominant methods to encode sentence order into LLMs, but a couple of problems related to these positional encodings were found: + + 1. Sinusoidal and learned position embeddings are both absolute positional embeddings, *i.e.* encoding a unique embedding for each position id: \\( 0, \ldots, N \\) . As shown by [Huang et al.](https://huggingface.co/papers/2009.13658) and [Su et al.](https://huggingface.co/papers/2104.09864), absolute positional embeddings lead to poor LLM performance for long text inputs. For long text inputs, it is advantageous if the model learns the relative positional distance input tokens have to each other instead of their absolute position. + 2. When using learned position embeddings, the LLM has to be trained on a fixed input length \\( N \\), which makes it difficult to extrapolate to an input length longer than what it was trained on. + +Recently, relative positional embeddings that can tackle the above mentioned problems have become more popular, most notably: + +- [Rotary Position Embedding (RoPE)](https://huggingface.co/papers/2104.09864) +- [ALiBi](https://huggingface.co/papers/2108.12409) + +Both *RoPE* and *ALiBi* argue that it's best to cue the LLM about sentence order directly in the self-attention algorithm as it's there that word tokens are put into relation with each other. More specifically, sentence order should be cued by modifying the \\( \mathbf{QK}^T \\) computation. + +Without going into too many details, *RoPE* notes that positional information can be encoded into query-key pairs, *e.g.* \\( \mathbf{q}_i \\) and \\( \mathbf{x}_j \\) by rotating each vector by an angle \\( \theta * i \\) and \\( \theta * j \\) respectively with \\( i, j \\) describing each vectors sentence position: + +$$ \mathbf{\hat{q}}_i^T \mathbf{\hat{x}}_j = \mathbf{{q}}_i^T \mathbf{R}_{\theta, i -j} \mathbf{{x}}_j. $$ + +\\( \mathbf{R}_{\theta, i - j} \\) thereby represents a rotational matrix. \\( \theta \\) is *not* learned during training, but instead set to a pre-defined value that depends on the maximum input sequence length during training. + +> By doing so, the probability score between \\( \mathbf{q}_i \\) and \\( \mathbf{q}_j \\) is only affected if \\( i \ne j \\) and solely depends on the relative distance \\( i - j \\) regardless of each vector's specific positions \\( i \\) and \\( j \\) . + +*RoPE* is used in multiple of today's most important LLMs, such as: + +- [**Falcon**](https://huggingface.co/tiiuae/falcon-40b) +- [**Llama**](https://huggingface.co/papers/2302.13971) +- [**PaLM**](https://huggingface.co/papers/2204.02311) + +As an alternative, *ALiBi* proposes a much simpler relative position encoding scheme. The relative distance that input tokens have to each other is added as a negative integer scaled by a pre-defined value `m` to each query-key entry of the \\( \mathbf{QK}^T \\) matrix right before the softmax computation. + +![](/blog/assets/163_optimize_llm/alibi.png) + +As shown in the [ALiBi](https://huggingface.co/papers/2108.12409) paper, this simple relative positional encoding allows the model to retain a high performance even at very long text input sequences. + +*ALiBi* is used in multiple of today's most important LLMs, such as: + +- [**MPT**](https://huggingface.co/mosaicml/mpt-30b) +- [**BLOOM**](https://huggingface.co/bigscience/bloom) + +Both *RoPE* and *ALiBi* position encodings can extrapolate to input lengths not seen during training whereas it has been shown that extrapolation works much better out-of-the-box for *ALiBi* as compared to *RoPE*. +For ALiBi, one simply increases the values of the lower triangular position matrix to match the length of the input sequence. +For *RoPE*, keeping the same \\( \theta \\) that was used during training leads to poor results when passing text inputs much longer than those seen during training, *c.f* [Press et al.](https://huggingface.co/papers/2108.12409). However, the community has found a couple of effective tricks that adapt \\( \theta \\), thereby allowing *RoPE* position embeddings to work well for extrapolated text input sequences (see [here](https://github.com/huggingface/transformers/pull/24653)). + +> Both RoPE and ALiBi are relative positional embeddings that are *not* learned during training, but instead are based on the following intuitions: + - Positional cues about the text inputs should be given directly to the \\( QK^T \\) matrix of the self-attention layer + - The LLM should be incentivized to learn a constant *relative* distance positional encodings have to each other + - The further text input tokens are from each other, the lower the probability of their query-value probability. Both RoPE and ALiBi lower the query-key probability of tokens far away from each other. RoPE by decreasing their vector product by increasing the angle between the query-key vectors. ALiBi by adding large negative numbers to the vector product + +In conclusion, LLMs that are intended to be deployed in tasks that require handling large text inputs are better trained with relative positional embeddings, such as RoPE and ALiBi. Also note that even if an LLM with RoPE and ALiBi has been trained only on a fixed length of say \\( N_1 = 2048 \\) it can still be used in practice with text inputs much larger than \\( N_1 \\), like \\( N_2 = 8192 > N_1 \\) by extrapolating the positional embeddings. + +### 3.2 The key-value cache + +Auto-regressive text generation with LLMs works by iteratively putting in an input sequence, sampling the next token, appending the next token to the input sequence, and continuing to do so until the LLM produces a token that signifies that the generation has finished. + +Please have a look at [Transformer's Generate Text Tutorial](https://huggingface.co/docs/transformers/llm_tutorial#generate-text) to get a more visual explanation of how auto-regressive generation works. + +Let's run a quick code snippet to show how auto-regressive works in practice. We will simply take the most likely next token via `torch.argmax`. + +```python +input_ids = tokenizer(prompt, return_tensors="pt")["input_ids"].to("cuda") + +for _ in range(5): + next_logits = model(input_ids)["logits"][:, -1:] + next_token_id = torch.argmax(next_logits,dim=-1) + + input_ids = torch.cat([input_ids, next_token_id], dim=-1) + print("shape of input_ids", input_ids.shape) + +generated_text = tokenizer.batch_decode(input_ids[:, -5:]) +generated_text +``` + +**Output**: +``` +shape of input_ids torch.Size([1, 21]) +shape of input_ids torch.Size([1, 22]) +shape of input_ids torch.Size([1, 23]) +shape of input_ids torch.Size([1, 24]) +shape of input_ids torch.Size([1, 25]) +[' Here is a Python function'] +``` + +As we can see every time we increase the text input tokens by the just sampled token. + +With very few exceptions, LLMs are trained using the [causal language modeling objective](https://huggingface.co/docs/transformers/tasks/language_modeling#causal-language-modeling) and therefore mask the upper triangle matrix of the attention score - this is why in the two diagrams above the attention scores are left blank (*a.k.a* have 0 probability). For a quick recap on causal language modeling you can refer to the [*Illustrated Self Attention blog*](https://jalammar.github.io/illustrated-gpt2/#part-2-illustrated-self-attention). + +As a consequence, tokens *never* depend on previous tokens, more specifically the \\( \mathbf{q}_i \\) vector is never put in relation with any key, values vectors \\( \mathbf{k}_j, \mathbf{v}_j \\) if \\( j > i \\) . Instead \\( \mathbf{q}_i \\) only attends to previous key-value vectors \\( \mathbf{k}_{m < i}, \mathbf{v}_{m < i} \text{ , for } m \in \{0, \ldots i - 1\} \\). In order to reduce unnecessary computation, one can therefore cache each layer's key-value vectors for all previous timesteps. + +In the following, we will tell the LLM to make use of the key-value cache by retrieving and forwarding it for each forward pass. +In Transformers, we can retrieve the key-value cache by passing the `use_cache` flag to the `forward` call and can then pass it with the current token. + +```python +past_key_values = None # past_key_values is the key-value cache +generated_tokens = [] +next_token_id = tokenizer(prompt, return_tensors="pt")["input_ids"].to("cuda") + +for _ in range(5): + next_logits, past_key_values = model(next_token_id, past_key_values=past_key_values, use_cache=True).to_tuple() + next_logits = next_logits[:, -1:] + next_token_id = torch.argmax(next_logits, dim=-1) + + print("shape of input_ids", next_token_id.shape) + print("length of key-value cache", len(past_key_values[0][0])) # past_key_values are of shape [num_layers, 0 for k, 1 for v, batch_size, length, hidden_dim] + generated_tokens.append(next_token_id.item()) + +generated_text = tokenizer.batch_decode(generated_tokens) +generated_text +``` + +**Output**: +``` +shape of input_ids torch.Size([1, 1]) +length of key-value cache 20 +shape of input_ids torch.Size([1, 1]) +length of key-value cache 21 +shape of input_ids torch.Size([1, 1]) +length of key-value cache 22 +shape of input_ids torch.Size([1, 1]) +length of key-value cache 23 +shape of input_ids torch.Size([1, 1]) +length of key-value cache 24 +[' Here', ' is', ' a', ' Python', ' function'] +``` + +As one can see, when using the key-value cache the text input tokens are *not* increased in length, but remain a single input vector. The length of the key-value cache on the other hand is increased by one at every decoding step. + +> Making use of the key-value cache means that the \\( \mathbf{QK}^T \\) is essentially reduced to \\( \mathbf{q}_c\mathbf{K}^T \\) with \\( \mathbf{q}_c \\) being the query projection of the currently passed input token which is *always* just a single vector. + +Using the key-value cache has two advantages: +- Significant increase in computational efficiency as less computations are performed compared to computing the full \\( \mathbf{QK}^T \\) matrix. This leads to an increase in inference speed +- The maximum required memory is not increased quadratically with the number of generated tokens, but only increases linearly. + +> One should *always* make use of the key-value cache as it leads to identical results and a significant speed-up for longer input sequences. Transformers has the key-value cache enabled by default when making use of the text pipeline or the [`generate` method](https://huggingface.co/docs/transformers/main_classes/text_generation). We have an entire guide dedicated to caches [here](./kv_cache). + + + +Note that, despite our advice to use key-value caches, your LLM output may be slightly different when you use them. This is a property of the matrix multiplication kernels themselves -- you can read more about it [here](https://github.com/huggingface/transformers/issues/25420#issuecomment-1775317535). + + + +#### 3.2.1 Multi-round conversation + +The key-value cache is especially useful for applications such as chat where multiple passes of auto-regressive decoding are required. Let's look at an example. + +``` +User: How many people live in France? +Assistant: Roughly 75 million people live in France +User: And how many are in Germany? +Assistant: Germany has ca. 81 million inhabitants +``` + +In this chat, the LLM runs auto-regressive decoding twice: + 1. The first time, the key-value cache is empty and the input prompt is `"User: How many people live in France?"` and the model auto-regressively generates the text `"Roughly 75 million people live in France"` while increasing the key-value cache at every decoding step. + 2. The second time the input prompt is `"User: How many people live in France? \n Assistant: Roughly 75 million people live in France \n User: And how many in Germany?"`. Thanks to the cache, all key-value vectors for the first two sentences are already computed. Therefore the input prompt only consists of `"User: And how many in Germany?"`. While processing the shortened input prompt, its computed key-value vectors are concatenated to the key-value cache of the first decoding. The second Assistant's answer `"Germany has ca. 81 million inhabitants"` is then auto-regressively generated with the key-value cache consisting of encoded key-value vectors of `"User: How many people live in France? \n Assistant: Roughly 75 million people live in France \n User: And how many are in Germany?"`. + +Two things should be noted here: + 1. Keeping all the context is crucial for LLMs deployed in chat so that the LLM understands all the previous context of the conversation. E.g. for the example above the LLM needs to understand that the user refers to the population when asking `"And how many are in Germany"`. + 2. The key-value cache is extremely useful for chat as it allows us to continuously grow the encoded chat history instead of having to re-encode the chat history again from scratch (as e.g. would be the case when using an encoder-decoder architecture). + +In `transformers`, a `generate` call will return `past_key_values` when `return_dict_in_generate=True` is passed, in addition to the default `use_cache=True`. Note that it is not yet available through the `pipeline` interface. + +```python +# Generation as usual +prompt = system_prompt + "Question: Please write a function in Python that transforms bytes to Giga bytes.\n\nAnswer: Here" +model_inputs = tokenizer(prompt, return_tensors='pt') +generation_output = model.generate(**model_inputs, max_new_tokens=60, return_dict_in_generate=True) +decoded_output = tokenizer.batch_decode(generation_output.sequences)[0] + +# Piping the returned `past_key_values` to speed up the next conversation round +prompt = decoded_output + "\nQuestion: How can I modify the function above to return Mega bytes instead?\n\nAnswer: Here" +model_inputs = tokenizer(prompt, return_tensors='pt') +generation_output = model.generate( + **model_inputs, + past_key_values=generation_output.past_key_values, + max_new_tokens=60, + return_dict_in_generate=True +) +tokenizer.batch_decode(generation_output.sequences)[0][len(prompt):] +``` + +**Output**: +``` + is a modified version of the function that returns Mega bytes instead. + +def bytes_to_megabytes(bytes): + return bytes / 1024 / 1024 + +Answer: The function takes a number of bytes as input and returns the number of +``` + +Great, no additional time is spent recomputing the same key and values for the attention layer! There is however one catch. While the required peak memory for the \\( \mathbf{QK}^T \\) matrix is significantly reduced, holding the key-value cache in memory can become very memory expensive for long input sequences or multi-turn chat. Remember that the key-value cache needs to store the key-value vectors for all previous input vectors \\( \mathbf{x}_i \text{, for } i \in \{1, \ldots, c - 1\} \\) for all self-attention layers and for all attention heads. + +Let's compute the number of float values that need to be stored in the key-value cache for the LLM `bigcode/octocoder` that we used before. +The number of float values amounts to two times the sequence length times the number of attention heads times the attention head dimension and times the number of layers. +Computing this for our LLM at a hypothetical input sequence length of 16000 gives: + +```python +config = model.config +2 * 16_000 * config.n_layer * config.n_head * config.n_embd // config.n_head +``` + +**Output**: +``` +7864320000 +``` + +Roughly 8 billion float values! Storing 8 billion float values in `float16` precision requires around 15 GB of RAM which is circa half as much as the model weights themselves! +Researchers have proposed two methods that allow to significantly reduce the memory cost of storing the key-value cache, which are explored in the next subsections. + +#### 3.2.2 Multi-Query-Attention (MQA) + +[Multi-Query-Attention](https://huggingface.co/papers/1911.02150) was proposed in Noam Shazeer's *Fast Transformer Decoding: One Write-Head is All You Need* paper. As the title says, Noam found out that instead of using `n_head` key-value projections weights, one can use a single head-value projection weight pair that is shared across all attention heads without that the model's performance significantly degrades. + +> By using a single head-value projection weight pair, the key value vectors \\( \mathbf{k}_i, \mathbf{v}_i \\) have to be identical across all attention heads which in turn means that we only need to store 1 key-value projection pair in the cache instead of `n_head` ones. + +As most LLMs use between 20 and 100 attention heads, MQA significantly reduces the memory consumption of the key-value cache. For the LLM used in this notebook we could therefore reduce the required memory consumption from 15 GB to less than 400 MB at an input sequence length of 16000. + +In addition to memory savings, MQA also leads to improved computational efficiency as explained in the following. +In auto-regressive decoding, large key-value vectors need to be reloaded, concatenated with the current key-value vector pair to be then fed into the \\( \mathbf{q}_c\mathbf{K}^T \\) computation at every step. For auto-regressive decoding, the required memory bandwidth for the constant reloading can become a serious time bottleneck. By reducing the size of the key-value vectors less memory needs to be accessed, thus reducing the memory bandwidth bottleneck. For more detail, please have a look at [Noam's paper](https://huggingface.co/papers/1911.02150). + +The important part to understand here is that reducing the number of key-value attention heads to 1 only makes sense if a key-value cache is used. The peak memory consumption of the model for a single forward pass without key-value cache stays unchanged as every attention head still has a unique query vector so that each attention head still has a different \\( \mathbf{QK}^T \\) matrix. + +MQA has seen wide adoption by the community and is now used by many of the most popular LLMs: + +- [**Falcon**](https://huggingface.co/tiiuae/falcon-40b) +- [**PaLM**](https://huggingface.co/papers/2204.02311) +- [**MPT**](https://huggingface.co/mosaicml/mpt-30b) +- [**BLOOM**](https://huggingface.co/bigscience/bloom) + +Also, the checkpoint used in this notebook - `bigcode/octocoder` - makes use of MQA. + +#### 3.2.3 Grouped-Query-Attention (GQA) + +[Grouped-Query-Attention](https://huggingface.co/papers/2305.13245), as proposed by Ainslie et al. from Google, found that using MQA can often lead to quality degradation compared to using vanilla multi-key-value head projections. The paper argues that more model performance can be kept by less drastically reducing the number of query head projection weights. Instead of using just a single key-value projection weight, `n < n_head` key-value projection weights should be used. By choosing `n` to a significantly smaller value than `n_head`, such as 2,4 or 8 almost all of the memory and speed gains from MQA can be kept while sacrificing less model capacity and thus arguably less performance. + +Moreover, the authors of GQA found out that existing model checkpoints can be *uptrained* to have a GQA architecture with as little as 5% of the original pre-training compute. While 5% of the original pre-training compute can still be a massive amount, GQA *uptraining* allows existing checkpoints to be useful for longer input sequences. + +GQA was only recently proposed which is why there is less adoption at the time of writing this notebook. +The most notable application of GQA is [Llama-v2](https://huggingface.co/meta-llama/Llama-2-70b-hf). + +> As a conclusion, it is strongly recommended to make use of either GQA or MQA if the LLM is deployed with auto-regressive decoding and is required to handle large input sequences as is the case for example for chat. + + +## Conclusion + +The research community is constantly coming up with new, nifty ways to speed up inference time for ever-larger LLMs. As an example, one such promising research direction is [speculative decoding](https://huggingface.co/papers/2211.17192) where "easy tokens" are generated by smaller, faster language models and only "hard tokens" are generated by the LLM itself. Going into more detail is out of the scope of this notebook, but can be read upon in this [nice blog post](https://huggingface.co/blog/assisted-generation). + +The reason massive LLMs such as GPT3/4, Llama-2-70b, Claude, PaLM can run so quickly in chat-interfaces such as [Hugging Face Chat](https://huggingface.co/chat/) or ChatGPT is to a big part thanks to the above-mentioned improvements in precision, algorithms, and architecture. +Going forward, accelerators such as GPUs, TPUs, etc... will only get faster and allow for more memory, but one should nevertheless always make sure to use the best available algorithms and architectures to get the most bang for your buck 🤗 diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/backbones.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/backbones.md new file mode 100644 index 0000000000000000000000000000000000000000..5f1fc1dcbe1f202d9527441a6f625e5049054e9a --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/backbones.md @@ -0,0 +1,60 @@ + + +# Backbone + +A backbone is a model used for feature extraction for higher level computer vision tasks such as object detection and image classification. Transformers provides an [`AutoBackbone`] class for initializing a Transformers backbone from pretrained model weights, and two utility classes: + +* [`~utils.BackboneMixin`] enables initializing a backbone from Transformers or [timm](https://hf.co/docs/timm/index) and includes functions for returning the output features and indices. +* [`~utils.BackboneConfigMixin`] sets the output features and indices of the backbone configuration. + +[timm](https://hf.co/docs/timm/index) models are loaded with the [`TimmBackbone`] and [`TimmBackboneConfig`] classes. + +Backbones are supported for the following models: + +* [BEiT](../model_doc/beit) +* [BiT](../model_doc/bit) +* [ConvNext](../model_doc/convnext) +* [ConvNextV2](../model_doc/convnextv2) +* [DiNAT](../model_doc/dinat) +* [DINOV2](../model_doc/dinov2) +* [FocalNet](../model_doc/focalnet) +* [MaskFormer](../model_doc/maskformer) +* [NAT](../model_doc/nat) +* [ResNet](../model_doc/resnet) +* [Swin Transformer](../model_doc/swin) +* [Swin Transformer v2](../model_doc/swinv2) +* [ViTDet](../model_doc/vitdet) + +## AutoBackbone + +[[autodoc]] AutoBackbone + +## BackboneMixin + +[[autodoc]] utils.BackboneMixin + +## BackboneConfigMixin + +[[autodoc]] utils.BackboneConfigMixin + +## TimmBackbone + +[[autodoc]] models.timm_backbone.TimmBackbone + +## TimmBackboneConfig + +[[autodoc]] models.timm_backbone.TimmBackboneConfig diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/callback.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/callback.md new file mode 100644 index 0000000000000000000000000000000000000000..0a7c73c667542da390e02ed5ccb3d7f4d7b569fc --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/callback.md @@ -0,0 +1,141 @@ + + +# Callbacks + +Callbacks are objects that can customize the behavior of the training loop in the PyTorch +[`Trainer`] (this feature is not yet implemented in TensorFlow) that can inspect the training loop +state (for progress reporting, logging on TensorBoard or other ML platforms...) and take decisions (like early +stopping). + +Callbacks are "read only" pieces of code, apart from the [`TrainerControl`] object they return, they +cannot change anything in the training loop. For customizations that require changes in the training loop, you should +subclass [`Trainer`] and override the methods you need (see [trainer](trainer) for examples). + +By default, `TrainingArguments.report_to` is set to `"all"`, so a [`Trainer`] will use the following callbacks. + +- [`DefaultFlowCallback`] which handles the default behavior for logging, saving and evaluation. +- [`PrinterCallback`] or [`ProgressCallback`] to display progress and print the + logs (the first one is used if you deactivate tqdm through the [`TrainingArguments`], otherwise + it's the second one). +- [`~integrations.TensorBoardCallback`] if tensorboard is accessible (either through PyTorch >= 1.4 + or tensorboardX). +- [`~integrations.TrackioCallback`] if [trackio](https://github.com/gradio-app/trackio) is installed. +- [`~integrations.WandbCallback`] if [wandb](https://www.wandb.com/) is installed. +- [`~integrations.CometCallback`] if [comet_ml](https://www.comet.com/site/) is installed. +- [`~integrations.MLflowCallback`] if [mlflow](https://www.mlflow.org/) is installed. +- [`~integrations.NeptuneCallback`] if [neptune](https://neptune.ai/) is installed. +- [`~integrations.AzureMLCallback`] if [azureml-sdk](https://pypi.org/project/azureml-sdk/) is + installed. +- [`~integrations.CodeCarbonCallback`] if [codecarbon](https://pypi.org/project/codecarbon/) is + installed. +- [`~integrations.ClearMLCallback`] if [clearml](https://github.com/allegroai/clearml) is installed. +- [`~integrations.DagsHubCallback`] if [dagshub](https://dagshub.com/) is installed. +- [`~integrations.FlyteCallback`] if [flyte](https://flyte.org/) is installed. +- [`~integrations.DVCLiveCallback`] if [dvclive](https://dvc.org/doc/dvclive) is installed. +- [`~integrations.SwanLabCallback`] if [swanlab](http://swanlab.cn/) is installed. + +If a package is installed but you don't wish to use the accompanying integration, you can change `TrainingArguments.report_to` to a list of just those integrations you want to use (e.g. `["azure_ml", "wandb"]`). + +The main class that implements callbacks is [`TrainerCallback`]. It gets the +[`TrainingArguments`] used to instantiate the [`Trainer`], can access that +Trainer's internal state via [`TrainerState`], and can take some actions on the training loop via +[`TrainerControl`]. + + +## Available Callbacks + +Here is the list of the available [`TrainerCallback`] in the library: + +[[autodoc]] integrations.CometCallback + - setup + +[[autodoc]] DefaultFlowCallback + +[[autodoc]] PrinterCallback + +[[autodoc]] ProgressCallback + +[[autodoc]] EarlyStoppingCallback + +[[autodoc]] integrations.TensorBoardCallback + +[[autodoc]] integrations.TrackioCallback + - setup + +[[autodoc]] integrations.WandbCallback + - setup + +[[autodoc]] integrations.MLflowCallback + - setup + +[[autodoc]] integrations.AzureMLCallback + +[[autodoc]] integrations.CodeCarbonCallback + +[[autodoc]] integrations.NeptuneCallback + +[[autodoc]] integrations.ClearMLCallback + +[[autodoc]] integrations.DagsHubCallback + +[[autodoc]] integrations.FlyteCallback + +[[autodoc]] integrations.DVCLiveCallback + - setup + +[[autodoc]] integrations.SwanLabCallback + - setup + +## TrainerCallback + +[[autodoc]] TrainerCallback + +Here is an example of how to register a custom callback with the PyTorch [`Trainer`]: + +```python +class MyCallback(TrainerCallback): + "A callback that prints a message at the beginning of training" + + def on_train_begin(self, args, state, control, **kwargs): + print("Starting training") + + +trainer = Trainer( + model, + args, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + callbacks=[MyCallback], # We can either pass the callback class this way or an instance of it (MyCallback()) +) +``` + +Another way to register a callback is to call `trainer.add_callback()` as follows: + +```python +trainer = Trainer(...) +trainer.add_callback(MyCallback) +# Alternatively, we can pass an instance of the callback class +trainer.add_callback(MyCallback()) +``` + +## TrainerState + +[[autodoc]] TrainerState + +## TrainerControl + +[[autodoc]] TrainerControl diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/configuration.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..0cfef06d3ce9caba4b91ed57e99124ba7c32122a --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/configuration.md @@ -0,0 +1,32 @@ + + +# Configuration + +The base class [`PretrainedConfig`] implements the common methods for loading/saving a configuration +either from a local file or directory, or from a pretrained model configuration provided by the library (downloaded +from HuggingFace's AWS S3 repository). + +Each derived config class implements model specific attributes. Common attributes present in all config classes are: +`hidden_size`, `num_attention_heads`, and `num_hidden_layers`. Text models further implement: +`vocab_size`. + + +## PretrainedConfig + +[[autodoc]] PretrainedConfig + - push_to_hub + - all diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/data_collator.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/data_collator.md new file mode 100644 index 0000000000000000000000000000000000000000..0da904f1131a9ecdc7adaead8bbbef0b87393678 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/data_collator.md @@ -0,0 +1,76 @@ + + +# Data Collator + +Data collators are objects that will form a batch by using a list of dataset elements as input. These elements are of +the same type as the elements of `train_dataset` or `eval_dataset`. + +To be able to build batches, data collators may apply some processing (like padding). Some of them (like +[`DataCollatorForLanguageModeling`]) also apply some random data augmentation (like random masking) +on the formed batch. + +Examples of use can be found in the [example scripts](../examples) or [example notebooks](../notebooks). + + +## Default data collator + +[[autodoc]] data.data_collator.default_data_collator + +## DefaultDataCollator + +[[autodoc]] data.data_collator.DefaultDataCollator + +## DataCollatorWithPadding + +[[autodoc]] data.data_collator.DataCollatorWithPadding + +## DataCollatorForTokenClassification + +[[autodoc]] data.data_collator.DataCollatorForTokenClassification + +## DataCollatorForSeq2Seq + +[[autodoc]] data.data_collator.DataCollatorForSeq2Seq + +## DataCollatorForLanguageModeling + +[[autodoc]] data.data_collator.DataCollatorForLanguageModeling + - numpy_mask_tokens + - tf_mask_tokens + - torch_mask_tokens + +## DataCollatorForWholeWordMask + +[[autodoc]] data.data_collator.DataCollatorForWholeWordMask + - numpy_mask_tokens + - tf_mask_tokens + - torch_mask_tokens + +## DataCollatorForPermutationLanguageModeling + +[[autodoc]] data.data_collator.DataCollatorForPermutationLanguageModeling + - numpy_mask_tokens + - tf_mask_tokens + - torch_mask_tokens + +## DataCollatorWithFlattening + +[[autodoc]] data.data_collator.DataCollatorWithFlattening + +# DataCollatorForMultipleChoice + +[[autodoc]] data.data_collator.DataCollatorForMultipleChoice diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/deepspeed.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/deepspeed.md new file mode 100644 index 0000000000000000000000000000000000000000..0b9e28656c0938be4264ae945e999b728a8e0fe7 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/deepspeed.md @@ -0,0 +1,32 @@ + + +# DeepSpeed + +[DeepSpeed](https://github.com/deepspeedai/DeepSpeed), powered by Zero Redundancy Optimizer (ZeRO), is an optimization library for training and fitting very large models onto a GPU. It is available in several ZeRO stages, where each stage progressively saves more GPU memory by partitioning the optimizer state, gradients, parameters, and enabling offloading to a CPU or NVMe. DeepSpeed is integrated with the [`Trainer`] class and most of the setup is automatically taken care of for you. + +However, if you want to use DeepSpeed without the [`Trainer`], Transformers provides a [`HfDeepSpeedConfig`] class. + + + +Learn more about using DeepSpeed with [`Trainer`] in the [DeepSpeed](../deepspeed) guide. + + + +## HfDeepSpeedConfig + +[[autodoc]] integrations.HfDeepSpeedConfig + - all diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/executorch.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/executorch.md new file mode 100644 index 0000000000000000000000000000000000000000..3178085c9135be8a9721d2f24dfd3b427dbe5259 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/executorch.md @@ -0,0 +1,33 @@ + + + +# ExecuTorch + +[`ExecuTorch`](https://github.com/pytorch/executorch) is an end-to-end solution for enabling on-device inference capabilities across mobile and edge devices including wearables, embedded devices and microcontrollers. It is part of the PyTorch ecosystem and supports the deployment of PyTorch models with a focus on portability, productivity, and performance. + +ExecuTorch introduces well defined entry points to perform model, device, and/or use-case specific optimizations such as backend delegation, user-defined compiler transformations, memory planning, and more. The first step in preparing a PyTorch model for execution on an edge device using ExecuTorch is to export the model. This is achieved through the use of a PyTorch API called [`torch.export`](https://pytorch.org/docs/stable/export.html). + + +## ExecuTorch Integration + +An integration point is being developed to ensure that 🤗 Transformers can be exported using `torch.export`. The goal of this integration is not only to enable export but also to ensure that the exported artifact can be further lowered and optimized to run efficiently in `ExecuTorch`, particularly for mobile and edge use cases. + +[[autodoc]] TorchExportableModuleWithStaticCache + - forward + +[[autodoc]] convert_and_export_with_cache diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/feature_extractor.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/feature_extractor.md new file mode 100644 index 0000000000000000000000000000000000000000..d79c531be6df0dd4802aa7b8eddf9f6ecfe916ea --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/feature_extractor.md @@ -0,0 +1,39 @@ + + +# Feature Extractor + +A feature extractor is in charge of preparing input features for audio or vision models. This includes feature extraction from sequences, e.g., pre-processing audio files to generate Log-Mel Spectrogram features, feature extraction from images, e.g., cropping image files, but also padding, normalization, and conversion to NumPy, PyTorch, and TensorFlow tensors. + + +## FeatureExtractionMixin + +[[autodoc]] feature_extraction_utils.FeatureExtractionMixin + - from_pretrained + - save_pretrained + +## SequenceFeatureExtractor + +[[autodoc]] SequenceFeatureExtractor + - pad + +## BatchFeature + +[[autodoc]] BatchFeature + +## ImageFeatureExtractionMixin + +[[autodoc]] image_utils.ImageFeatureExtractionMixin diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/image_processor.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/image_processor.md new file mode 100644 index 0000000000000000000000000000000000000000..cbf6ae95577f70ab2c58785874484368bd4629fc --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/image_processor.md @@ -0,0 +1,79 @@ + + +# Image Processor + +An image processor is in charge of preparing input features for vision models and post processing their outputs. This includes transformations such as resizing, normalization, and conversion to PyTorch, TensorFlow, Flax and Numpy tensors. It may also include model specific post-processing such as converting logits to segmentation masks. + +Fast image processors are available for a few models and more will be added in the future. They are based on the [torchvision](https://pytorch.org/vision/stable/index.html) library and provide a significant speed-up, especially when processing on GPU. +They have the same API as the base image processors and can be used as drop-in replacements. +To use a fast image processor, you need to install the `torchvision` library, and set the `use_fast` argument to `True` when instantiating the image processor: + +```python +from transformers import AutoImageProcessor + +processor = AutoImageProcessor.from_pretrained("facebook/detr-resnet-50", use_fast=True) +``` +Note that `use_fast` will be set to `True` by default in a future release. + +When using a fast image processor, you can also set the `device` argument to specify the device on which the processing should be done. By default, the processing is done on the same device as the inputs if the inputs are tensors, or on the CPU otherwise. + +```python +from torchvision.io import read_image +from transformers import DetrImageProcessorFast + +images = read_image("image.jpg") +processor = DetrImageProcessorFast.from_pretrained("facebook/detr-resnet-50") +images_processed = processor(images, return_tensors="pt", device="cuda") +``` + +Here are some speed comparisons between the base and fast image processors for the `DETR` and `RT-DETR` models, and how they impact overall inference time: + +
+ +
+
+ +
+ +
+ +
+
+ +
+ +These benchmarks were run on an [AWS EC2 g5.2xlarge instance](https://aws.amazon.com/ec2/instance-types/g5/), utilizing an NVIDIA A10G Tensor Core GPU. + + +## ImageProcessingMixin + +[[autodoc]] image_processing_utils.ImageProcessingMixin + - from_pretrained + - save_pretrained + +## BatchFeature + +[[autodoc]] BatchFeature + +## BaseImageProcessor + +[[autodoc]] image_processing_utils.BaseImageProcessor + + +## BaseImageProcessorFast + +[[autodoc]] image_processing_utils_fast.BaseImageProcessorFast diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/keras_callbacks.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/keras_callbacks.md new file mode 100644 index 0000000000000000000000000000000000000000..c9932300dbc56986f107650a474a03233dcc3ae6 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/keras_callbacks.md @@ -0,0 +1,28 @@ + + +# Keras callbacks + +When training a Transformers model with Keras, there are some library-specific callbacks available to automate common +tasks: + +## KerasMetricCallback + +[[autodoc]] KerasMetricCallback + +## PushToHubCallback + +[[autodoc]] PushToHubCallback diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/logging.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/logging.md new file mode 100644 index 0000000000000000000000000000000000000000..5cbdf9ae27ed1ce61b1a45556c569c7b9eb4b628 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/logging.md @@ -0,0 +1,119 @@ + + +# Logging + +🤗 Transformers has a centralized logging system, so that you can setup the verbosity of the library easily. + +Currently the default verbosity of the library is `WARNING`. + +To change the level of verbosity, just use one of the direct setters. For instance, here is how to change the verbosity +to the INFO level. + +```python +import transformers + +transformers.logging.set_verbosity_info() +``` + +You can also use the environment variable `TRANSFORMERS_VERBOSITY` to override the default verbosity. You can set it +to one of the following: `debug`, `info`, `warning`, `error`, `critical`, `fatal`. For example: + +```bash +TRANSFORMERS_VERBOSITY=error ./myprogram.py +``` + +Additionally, some `warnings` can be disabled by setting the environment variable +`TRANSFORMERS_NO_ADVISORY_WARNINGS` to a true value, like *1*. This will disable any warning that is logged using +[`logger.warning_advice`]. For example: + +```bash +TRANSFORMERS_NO_ADVISORY_WARNINGS=1 ./myprogram.py +``` + +Here is an example of how to use the same logger as the library in your own module or script: + +```python +from transformers.utils import logging + +logging.set_verbosity_info() +logger = logging.get_logger("transformers") +logger.info("INFO") +logger.warning("WARN") +``` + + +All the methods of this logging module are documented below, the main ones are +[`logging.get_verbosity`] to get the current level of verbosity in the logger and +[`logging.set_verbosity`] to set the verbosity to the level of your choice. In order (from the least +verbose to the most verbose), those levels (with their corresponding int values in parenthesis) are: + +- `transformers.logging.CRITICAL` or `transformers.logging.FATAL` (int value, 50): only report the most + critical errors. +- `transformers.logging.ERROR` (int value, 40): only report errors. +- `transformers.logging.WARNING` or `transformers.logging.WARN` (int value, 30): only reports error and + warnings. This is the default level used by the library. +- `transformers.logging.INFO` (int value, 20): reports error, warnings and basic information. +- `transformers.logging.DEBUG` (int value, 10): report all information. + +By default, `tqdm` progress bars will be displayed during model download. [`logging.disable_progress_bar`] and [`logging.enable_progress_bar`] can be used to suppress or unsuppress this behavior. + +## `logging` vs `warnings` + +Python has two logging systems that are often used in conjunction: `logging`, which is explained above, and `warnings`, +which allows further classification of warnings in specific buckets, e.g., `FutureWarning` for a feature or path +that has already been deprecated and `DeprecationWarning` to indicate an upcoming deprecation. + +We use both in the `transformers` library. We leverage and adapt `logging`'s `captureWarnings` method to allow +management of these warning messages by the verbosity setters above. + +What does that mean for developers of the library? We should respect the following heuristics: +- `warnings` should be favored for developers of the library and libraries dependent on `transformers` +- `logging` should be used for end-users of the library using it in every-day projects + +See reference of the `captureWarnings` method below. + +[[autodoc]] logging.captureWarnings + +## Base setters + +[[autodoc]] logging.set_verbosity_error + +[[autodoc]] logging.set_verbosity_warning + +[[autodoc]] logging.set_verbosity_info + +[[autodoc]] logging.set_verbosity_debug + +## Other functions + +[[autodoc]] logging.get_verbosity + +[[autodoc]] logging.set_verbosity + +[[autodoc]] logging.get_logger + +[[autodoc]] logging.enable_default_handler + +[[autodoc]] logging.disable_default_handler + +[[autodoc]] logging.enable_explicit_format + +[[autodoc]] logging.reset_format + +[[autodoc]] logging.enable_progress_bar + +[[autodoc]] logging.disable_progress_bar diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/model.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/model.md new file mode 100644 index 0000000000000000000000000000000000000000..15345a7b2af3fb0db28358e9904bf83df4aff272 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/model.md @@ -0,0 +1,73 @@ + + +# Models + +The base classes [`PreTrainedModel`], [`TFPreTrainedModel`], and +[`FlaxPreTrainedModel`] implement the common methods for loading/saving a model either from a local +file or directory, or from a pretrained model configuration provided by the library (downloaded from HuggingFace's AWS +S3 repository). + +[`PreTrainedModel`] and [`TFPreTrainedModel`] also implement a few methods which +are common among all the models to: + +- resize the input token embeddings when new tokens are added to the vocabulary +- prune the attention heads of the model. + +The other methods that are common to each model are defined in [`~modeling_utils.ModuleUtilsMixin`] +(for the PyTorch models) and [`~modeling_tf_utils.TFModuleUtilsMixin`] (for the TensorFlow models) or +for text generation, [`~generation.GenerationMixin`] (for the PyTorch models), +[`~generation.TFGenerationMixin`] (for the TensorFlow models) and +[`~generation.FlaxGenerationMixin`] (for the Flax/JAX models). + + +## PreTrainedModel + +[[autodoc]] PreTrainedModel + - push_to_hub + - all + +Custom models should also include a `_supports_assign_param_buffer`, which determines if superfast init can apply +on the particular model. Signs that your model needs this are if `test_save_and_load_from_pretrained` fails. If so, +set this to `False`. + +## ModuleUtilsMixin + +[[autodoc]] modeling_utils.ModuleUtilsMixin + +## TFPreTrainedModel + +[[autodoc]] TFPreTrainedModel + - push_to_hub + - all + +## TFModelUtilsMixin + +[[autodoc]] modeling_tf_utils.TFModelUtilsMixin + +## FlaxPreTrainedModel + +[[autodoc]] FlaxPreTrainedModel + - push_to_hub + - all + +## Pushing to the Hub + +[[autodoc]] utils.PushToHubMixin + +## Sharded checkpoints + +[[autodoc]] modeling_utils.load_sharded_checkpoint diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/onnx.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/onnx.md new file mode 100644 index 0000000000000000000000000000000000000000..81d31c97e88dde23f3807cbcbc05820c3f06a48d --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/onnx.md @@ -0,0 +1,54 @@ + + +# Exporting 🤗 Transformers models to ONNX + +🤗 Transformers provides a `transformers.onnx` package that enables you to +convert model checkpoints to an ONNX graph by leveraging configuration objects. + +See the [guide](../serialization) on exporting 🤗 Transformers models for more +details. + +## ONNX Configurations + +We provide three abstract classes that you should inherit from, depending on the +type of model architecture you wish to export: + +* Encoder-based models inherit from [`~onnx.config.OnnxConfig`] +* Decoder-based models inherit from [`~onnx.config.OnnxConfigWithPast`] +* Encoder-decoder models inherit from [`~onnx.config.OnnxSeq2SeqConfigWithPast`] + +### OnnxConfig + +[[autodoc]] onnx.config.OnnxConfig + +### OnnxConfigWithPast + +[[autodoc]] onnx.config.OnnxConfigWithPast + +### OnnxSeq2SeqConfigWithPast + +[[autodoc]] onnx.config.OnnxSeq2SeqConfigWithPast + +## ONNX Features + +Each ONNX configuration is associated with a set of _features_ that enable you +to export models for different types of topologies or tasks. + +### FeaturesManager + +[[autodoc]] onnx.features.FeaturesManager + diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/optimizer_schedules.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/optimizer_schedules.md new file mode 100644 index 0000000000000000000000000000000000000000..24c978e6fe3ced5eb39e1e3f0e1f956f36c83247 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/optimizer_schedules.md @@ -0,0 +1,76 @@ + + +# Optimization + +The `.optimization` module provides: + +- an optimizer with weight decay fixed that can be used to fine-tuned models, and +- several schedules in the form of schedule objects that inherit from `_LRSchedule`: +- a gradient accumulation class to accumulate the gradients of multiple batches + + +## AdaFactor (PyTorch) + +[[autodoc]] Adafactor + +## AdamWeightDecay (TensorFlow) + +[[autodoc]] AdamWeightDecay + +[[autodoc]] create_optimizer + +## Schedules + +### Learning Rate Schedules (PyTorch) + +[[autodoc]] SchedulerType + +[[autodoc]] get_scheduler + +[[autodoc]] get_constant_schedule + +[[autodoc]] get_constant_schedule_with_warmup + + + +[[autodoc]] get_cosine_schedule_with_warmup + + + +[[autodoc]] get_cosine_with_hard_restarts_schedule_with_warmup + + + +[[autodoc]] get_linear_schedule_with_warmup + + + +[[autodoc]] get_polynomial_decay_schedule_with_warmup + +[[autodoc]] get_inverse_sqrt_schedule + +[[autodoc]] get_wsd_schedule + +### Warmup (TensorFlow) + +[[autodoc]] WarmUp + +## Gradient Strategies + +### GradientAccumulator (TensorFlow) + +[[autodoc]] GradientAccumulator diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/output.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/output.md new file mode 100644 index 0000000000000000000000000000000000000000..300213d4513ebbf832e22828ac8be3164d5b95e6 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/output.md @@ -0,0 +1,321 @@ + + +# Model outputs + +All models have outputs that are instances of subclasses of [`~utils.ModelOutput`]. Those are +data structures containing all the information returned by the model, but that can also be used as tuples or +dictionaries. + +Let's see how this looks in an example: + +```python +from transformers import BertTokenizer, BertForSequenceClassification +import torch + +tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-uncased") +model = BertForSequenceClassification.from_pretrained("google-bert/bert-base-uncased") + +inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") +labels = torch.tensor([1]).unsqueeze(0) # Batch size 1 +outputs = model(**inputs, labels=labels) +``` + +The `outputs` object is a [`~modeling_outputs.SequenceClassifierOutput`], as we can see in the +documentation of that class below, it means it has an optional `loss`, a `logits`, an optional `hidden_states` and +an optional `attentions` attribute. Here we have the `loss` since we passed along `labels`, but we don't have +`hidden_states` and `attentions` because we didn't pass `output_hidden_states=True` or +`output_attentions=True`. + + + +When passing `output_hidden_states=True` you may expect the `outputs.hidden_states[-1]` to match `outputs.last_hidden_state` exactly. +However, this is not always the case. Some models apply normalization or subsequent process to the last hidden state when it's returned. + + + + +You can access each attribute as you would usually do, and if that attribute has not been returned by the model, you +will get `None`. Here for instance `outputs.loss` is the loss computed by the model, and `outputs.attentions` is +`None`. + +When considering our `outputs` object as tuple, it only considers the attributes that don't have `None` values. +Here for instance, it has two elements, `loss` then `logits`, so + +```python +outputs[:2] +``` + +will return the tuple `(outputs.loss, outputs.logits)` for instance. + +When considering our `outputs` object as dictionary, it only considers the attributes that don't have `None` +values. Here for instance, it has two keys that are `loss` and `logits`. + +We document here the generic model outputs that are used by more than one model type. Specific output types are +documented on their corresponding model page. + +## ModelOutput + +[[autodoc]] utils.ModelOutput + - to_tuple + +## BaseModelOutput + +[[autodoc]] modeling_outputs.BaseModelOutput + +## BaseModelOutputWithPooling + +[[autodoc]] modeling_outputs.BaseModelOutputWithPooling + +## BaseModelOutputWithCrossAttentions + +[[autodoc]] modeling_outputs.BaseModelOutputWithCrossAttentions + +## BaseModelOutputWithPoolingAndCrossAttentions + +[[autodoc]] modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions + +## BaseModelOutputWithPast + +[[autodoc]] modeling_outputs.BaseModelOutputWithPast + +## BaseModelOutputWithPastAndCrossAttentions + +[[autodoc]] modeling_outputs.BaseModelOutputWithPastAndCrossAttentions + +## Seq2SeqModelOutput + +[[autodoc]] modeling_outputs.Seq2SeqModelOutput + +## CausalLMOutput + +[[autodoc]] modeling_outputs.CausalLMOutput + +## CausalLMOutputWithCrossAttentions + +[[autodoc]] modeling_outputs.CausalLMOutputWithCrossAttentions + +## CausalLMOutputWithPast + +[[autodoc]] modeling_outputs.CausalLMOutputWithPast + +## MaskedLMOutput + +[[autodoc]] modeling_outputs.MaskedLMOutput + +## Seq2SeqLMOutput + +[[autodoc]] modeling_outputs.Seq2SeqLMOutput + +## NextSentencePredictorOutput + +[[autodoc]] modeling_outputs.NextSentencePredictorOutput + +## SequenceClassifierOutput + +[[autodoc]] modeling_outputs.SequenceClassifierOutput + +## Seq2SeqSequenceClassifierOutput + +[[autodoc]] modeling_outputs.Seq2SeqSequenceClassifierOutput + +## MultipleChoiceModelOutput + +[[autodoc]] modeling_outputs.MultipleChoiceModelOutput + +## TokenClassifierOutput + +[[autodoc]] modeling_outputs.TokenClassifierOutput + +## QuestionAnsweringModelOutput + +[[autodoc]] modeling_outputs.QuestionAnsweringModelOutput + +## Seq2SeqQuestionAnsweringModelOutput + +[[autodoc]] modeling_outputs.Seq2SeqQuestionAnsweringModelOutput + +## Seq2SeqSpectrogramOutput + +[[autodoc]] modeling_outputs.Seq2SeqSpectrogramOutput + +## SemanticSegmenterOutput + +[[autodoc]] modeling_outputs.SemanticSegmenterOutput + +## ImageClassifierOutput + +[[autodoc]] modeling_outputs.ImageClassifierOutput + +## ImageClassifierOutputWithNoAttention + +[[autodoc]] modeling_outputs.ImageClassifierOutputWithNoAttention + +## DepthEstimatorOutput + +[[autodoc]] modeling_outputs.DepthEstimatorOutput + +## Wav2Vec2BaseModelOutput + +[[autodoc]] modeling_outputs.Wav2Vec2BaseModelOutput + +## XVectorOutput + +[[autodoc]] modeling_outputs.XVectorOutput + +## Seq2SeqTSModelOutput + +[[autodoc]] modeling_outputs.Seq2SeqTSModelOutput + +## Seq2SeqTSPredictionOutput + +[[autodoc]] modeling_outputs.Seq2SeqTSPredictionOutput + +## SampleTSPredictionOutput + +[[autodoc]] modeling_outputs.SampleTSPredictionOutput + +## TFBaseModelOutput + +[[autodoc]] modeling_tf_outputs.TFBaseModelOutput + +## TFBaseModelOutputWithPooling + +[[autodoc]] modeling_tf_outputs.TFBaseModelOutputWithPooling + +## TFBaseModelOutputWithPoolingAndCrossAttentions + +[[autodoc]] modeling_tf_outputs.TFBaseModelOutputWithPoolingAndCrossAttentions + +## TFBaseModelOutputWithPast + +[[autodoc]] modeling_tf_outputs.TFBaseModelOutputWithPast + +## TFBaseModelOutputWithPastAndCrossAttentions + +[[autodoc]] modeling_tf_outputs.TFBaseModelOutputWithPastAndCrossAttentions + +## TFSeq2SeqModelOutput + +[[autodoc]] modeling_tf_outputs.TFSeq2SeqModelOutput + +## TFCausalLMOutput + +[[autodoc]] modeling_tf_outputs.TFCausalLMOutput + +## TFCausalLMOutputWithCrossAttentions + +[[autodoc]] modeling_tf_outputs.TFCausalLMOutputWithCrossAttentions + +## TFCausalLMOutputWithPast + +[[autodoc]] modeling_tf_outputs.TFCausalLMOutputWithPast + +## TFMaskedLMOutput + +[[autodoc]] modeling_tf_outputs.TFMaskedLMOutput + +## TFSeq2SeqLMOutput + +[[autodoc]] modeling_tf_outputs.TFSeq2SeqLMOutput + +## TFNextSentencePredictorOutput + +[[autodoc]] modeling_tf_outputs.TFNextSentencePredictorOutput + +## TFSequenceClassifierOutput + +[[autodoc]] modeling_tf_outputs.TFSequenceClassifierOutput + +## TFSeq2SeqSequenceClassifierOutput + +[[autodoc]] modeling_tf_outputs.TFSeq2SeqSequenceClassifierOutput + +## TFMultipleChoiceModelOutput + +[[autodoc]] modeling_tf_outputs.TFMultipleChoiceModelOutput + +## TFTokenClassifierOutput + +[[autodoc]] modeling_tf_outputs.TFTokenClassifierOutput + +## TFQuestionAnsweringModelOutput + +[[autodoc]] modeling_tf_outputs.TFQuestionAnsweringModelOutput + +## TFSeq2SeqQuestionAnsweringModelOutput + +[[autodoc]] modeling_tf_outputs.TFSeq2SeqQuestionAnsweringModelOutput + +## FlaxBaseModelOutput + +[[autodoc]] modeling_flax_outputs.FlaxBaseModelOutput + +## FlaxBaseModelOutputWithPast + +[[autodoc]] modeling_flax_outputs.FlaxBaseModelOutputWithPast + +## FlaxBaseModelOutputWithPooling + +[[autodoc]] modeling_flax_outputs.FlaxBaseModelOutputWithPooling + +## FlaxBaseModelOutputWithPastAndCrossAttentions + +[[autodoc]] modeling_flax_outputs.FlaxBaseModelOutputWithPastAndCrossAttentions + +## FlaxSeq2SeqModelOutput + +[[autodoc]] modeling_flax_outputs.FlaxSeq2SeqModelOutput + +## FlaxCausalLMOutputWithCrossAttentions + +[[autodoc]] modeling_flax_outputs.FlaxCausalLMOutputWithCrossAttentions + +## FlaxMaskedLMOutput + +[[autodoc]] modeling_flax_outputs.FlaxMaskedLMOutput + +## FlaxSeq2SeqLMOutput + +[[autodoc]] modeling_flax_outputs.FlaxSeq2SeqLMOutput + +## FlaxNextSentencePredictorOutput + +[[autodoc]] modeling_flax_outputs.FlaxNextSentencePredictorOutput + +## FlaxSequenceClassifierOutput + +[[autodoc]] modeling_flax_outputs.FlaxSequenceClassifierOutput + +## FlaxSeq2SeqSequenceClassifierOutput + +[[autodoc]] modeling_flax_outputs.FlaxSeq2SeqSequenceClassifierOutput + +## FlaxMultipleChoiceModelOutput + +[[autodoc]] modeling_flax_outputs.FlaxMultipleChoiceModelOutput + +## FlaxTokenClassifierOutput + +[[autodoc]] modeling_flax_outputs.FlaxTokenClassifierOutput + +## FlaxQuestionAnsweringModelOutput + +[[autodoc]] modeling_flax_outputs.FlaxQuestionAnsweringModelOutput + +## FlaxSeq2SeqQuestionAnsweringModelOutput + +[[autodoc]] modeling_flax_outputs.FlaxSeq2SeqQuestionAnsweringModelOutput diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/peft.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/peft.md new file mode 100644 index 0000000000000000000000000000000000000000..85790f120ebf41a249bd0776ee2d45bfa3c92a41 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/peft.md @@ -0,0 +1,23 @@ + + +# PEFT + +The [`~integrations.PeftAdapterMixin`] provides functions from the [PEFT](https://huggingface.co/docs/peft/index) library for managing adapters with Transformers. This mixin currently supports LoRA, IA3, and AdaLora. Prefix tuning methods (prompt tuning, prompt learning) aren't supported because they can't be injected into a torch module. + +[[autodoc]] integrations.PeftAdapterMixin + - load_adapter + - add_adapter + - set_adapter + - disable_adapters + - enable_adapters + - active_adapters + - get_adapter_state_dict diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/pipelines.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/pipelines.md new file mode 100644 index 0000000000000000000000000000000000000000..59e474fcc49f7523f74a44cf761738e4aea9fcea --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/pipelines.md @@ -0,0 +1,501 @@ + + +# Pipelines + +The pipelines are a great and easy way to use models for inference. These pipelines are objects that abstract most of +the complex code from the library, offering a simple API dedicated to several tasks, including Named Entity +Recognition, Masked Language Modeling, Sentiment Analysis, Feature Extraction and Question Answering. See the +[task summary](../task_summary) for examples of use. + +There are two categories of pipeline abstractions to be aware about: + +- The [`pipeline`] which is the most powerful object encapsulating all other pipelines. +- Task-specific pipelines are available for [audio](#audio), [computer vision](#computer-vision), [natural language processing](#natural-language-processing), and [multimodal](#multimodal) tasks. + +## The pipeline abstraction + +The *pipeline* abstraction is a wrapper around all the other available pipelines. It is instantiated as any other +pipeline but can provide additional quality of life. + +Simple call on one item: + +```python +>>> pipe = pipeline("text-classification") +>>> pipe("This restaurant is awesome") +[{'label': 'POSITIVE', 'score': 0.9998743534088135}] +``` + +If you want to use a specific model from the [hub](https://huggingface.co) you can ignore the task if the model on +the hub already defines it: + +```python +>>> pipe = pipeline(model="FacebookAI/roberta-large-mnli") +>>> pipe("This restaurant is awesome") +[{'label': 'NEUTRAL', 'score': 0.7313136458396912}] +``` + +To call a pipeline on many items, you can call it with a *list*. + +```python +>>> pipe = pipeline("text-classification") +>>> pipe(["This restaurant is awesome", "This restaurant is awful"]) +[{'label': 'POSITIVE', 'score': 0.9998743534088135}, + {'label': 'NEGATIVE', 'score': 0.9996669292449951}] +``` + +To iterate over full datasets it is recommended to use a `dataset` directly. This means you don't need to allocate +the whole dataset at once, nor do you need to do batching yourself. This should work just as fast as custom loops on +GPU. If it doesn't don't hesitate to create an issue. + +```python +import datasets +from transformers import pipeline +from transformers.pipelines.pt_utils import KeyDataset +from tqdm.auto import tqdm + +pipe = pipeline("automatic-speech-recognition", model="facebook/wav2vec2-base-960h", device=0) +dataset = datasets.load_dataset("superb", name="asr", split="test") + +# KeyDataset (only *pt*) will simply return the item in the dict returned by the dataset item +# as we're not interested in the *target* part of the dataset. For sentence pair use KeyPairDataset +for out in tqdm(pipe(KeyDataset(dataset, "file"))): + print(out) + # {"text": "NUMBER TEN FRESH NELLY IS WAITING ON YOU GOOD NIGHT HUSBAND"} + # {"text": ....} + # .... +``` + +For ease of use, a generator is also possible: + + +```python +from transformers import pipeline + +pipe = pipeline("text-classification") + + +def data(): + while True: + # This could come from a dataset, a database, a queue or HTTP request + # in a server + # Caveat: because this is iterative, you cannot use `num_workers > 1` variable + # to use multiple threads to preprocess data. You can still have 1 thread that + # does the preprocessing while the main runs the big inference + yield "This is a test" + + +for out in pipe(data()): + print(out) + # {"text": "NUMBER TEN FRESH NELLY IS WAITING ON YOU GOOD NIGHT HUSBAND"} + # {"text": ....} + # .... +``` + +[[autodoc]] pipeline + +## Pipeline batching + +All pipelines can use batching. This will work +whenever the pipeline uses its streaming ability (so when passing lists or `Dataset` or `generator`). + +```python +from transformers import pipeline +from transformers.pipelines.pt_utils import KeyDataset +import datasets + +dataset = datasets.load_dataset("imdb", name="plain_text", split="unsupervised") +pipe = pipeline("text-classification", device=0) +for out in pipe(KeyDataset(dataset, "text"), batch_size=8, truncation="only_first"): + print(out) + # [{'label': 'POSITIVE', 'score': 0.9998743534088135}] + # Exactly the same output as before, but the content are passed + # as batches to the model +``` + + + +However, this is not automatically a win for performance. It can be either a 10x speedup or 5x slowdown depending +on hardware, data and the actual model being used. + +Example where it's mostly a speedup: + + + +```python +from transformers import pipeline +from torch.utils.data import Dataset +from tqdm.auto import tqdm + +pipe = pipeline("text-classification", device=0) + + +class MyDataset(Dataset): + def __len__(self): + return 5000 + + def __getitem__(self, i): + return "This is a test" + + +dataset = MyDataset() + +for batch_size in [1, 8, 64, 256]: + print("-" * 30) + print(f"Streaming batch_size={batch_size}") + for out in tqdm(pipe(dataset, batch_size=batch_size), total=len(dataset)): + pass +``` + +``` +# On GTX 970 +------------------------------ +Streaming no batching +100%|██████████████████████████████████████████████████████████████████████| 5000/5000 [00:26<00:00, 187.52it/s] +------------------------------ +Streaming batch_size=8 +100%|█████████████████████████████████████████████████████████████████████| 5000/5000 [00:04<00:00, 1205.95it/s] +------------------------------ +Streaming batch_size=64 +100%|█████████████████████████████████████████████████████████████████████| 5000/5000 [00:02<00:00, 2478.24it/s] +------------------------------ +Streaming batch_size=256 +100%|█████████████████████████████████████████████████████████████████████| 5000/5000 [00:01<00:00, 2554.43it/s] +(diminishing returns, saturated the GPU) +``` + +Example where it's most a slowdown: + +```python +class MyDataset(Dataset): + def __len__(self): + return 5000 + + def __getitem__(self, i): + if i % 64 == 0: + n = 100 + else: + n = 1 + return "This is a test" * n +``` + +This is a occasional very long sentence compared to the other. In that case, the **whole** batch will need to be 400 +tokens long, so the whole batch will be [64, 400] instead of [64, 4], leading to the high slowdown. Even worse, on +bigger batches, the program simply crashes. + + +``` +------------------------------ +Streaming no batching +100%|█████████████████████████████████████████████████████████████████████| 1000/1000 [00:05<00:00, 183.69it/s] +------------------------------ +Streaming batch_size=8 +100%|█████████████████████████████████████████████████████████████████████| 1000/1000 [00:03<00:00, 265.74it/s] +------------------------------ +Streaming batch_size=64 +100%|██████████████████████████████████████████████████████████████████████| 1000/1000 [00:26<00:00, 37.80it/s] +------------------------------ +Streaming batch_size=256 + 0%| | 0/1000 [00:00 + for out in tqdm(pipe(dataset, batch_size=256), total=len(dataset)): +.... + q = q / math.sqrt(dim_per_head) # (bs, n_heads, q_length, dim_per_head) +RuntimeError: CUDA out of memory. Tried to allocate 376.00 MiB (GPU 0; 3.95 GiB total capacity; 1.72 GiB already allocated; 354.88 MiB free; 2.46 GiB reserved in total by PyTorch) +``` + +There are no good (general) solutions for this problem, and your mileage may vary depending on your use cases. Rule of +thumb: + +For users, a rule of thumb is: + +- **Measure performance on your load, with your hardware. Measure, measure, and keep measuring. Real numbers are the + only way to go.** +- If you are latency constrained (live product doing inference), don't batch. +- If you are using CPU, don't batch. +- If you are using throughput (you want to run your model on a bunch of static data), on GPU, then: + + - If you have no clue about the size of the sequence_length ("natural" data), by default don't batch, measure and + try tentatively to add it, add OOM checks to recover when it will fail (and it will at some point if you don't + control the sequence_length.) + - If your sequence_length is super regular, then batching is more likely to be VERY interesting, measure and push + it until you get OOMs. + - The larger the GPU the more likely batching is going to be more interesting +- As soon as you enable batching, make sure you can handle OOMs nicely. + +## Pipeline chunk batching + +`zero-shot-classification` and `question-answering` are slightly specific in the sense, that a single input might yield +multiple forward pass of a model. Under normal circumstances, this would yield issues with `batch_size` argument. + +In order to circumvent this issue, both of these pipelines are a bit specific, they are `ChunkPipeline` instead of +regular `Pipeline`. In short: + + +```python +preprocessed = pipe.preprocess(inputs) +model_outputs = pipe.forward(preprocessed) +outputs = pipe.postprocess(model_outputs) +``` + +Now becomes: + + +```python +all_model_outputs = [] +for preprocessed in pipe.preprocess(inputs): + model_outputs = pipe.forward(preprocessed) + all_model_outputs.append(model_outputs) +outputs = pipe.postprocess(all_model_outputs) +``` + +This should be very transparent to your code because the pipelines are used in +the same way. + +This is a simplified view, since the pipeline can handle automatically the batch to ! Meaning you don't have to care +about how many forward passes you inputs are actually going to trigger, you can optimize the `batch_size` +independently of the inputs. The caveats from the previous section still apply. + +## Pipeline FP16 inference +Models can be run in FP16 which can be significantly faster on GPU while saving memory. Most models will not suffer noticeable performance loss from this. The larger the model, the less likely that it will. + +To enable FP16 inference, you can simply pass `torch_dtype=torch.float16` or `torch_dtype='float16'` to the pipeline constructor. Note that this only works for models with a PyTorch backend. Your inputs will be converted to FP16 internally. + +## Pipeline custom code + +If you want to override a specific pipeline. + +Don't hesitate to create an issue for your task at hand, the goal of the pipeline is to be easy to use and support most +cases, so `transformers` could maybe support your use case. + + +If you want to try simply you can: + +- Subclass your pipeline of choice + +```python +class MyPipeline(TextClassificationPipeline): + def postprocess(): + # Your code goes here + scores = scores * 100 + # And here + + +my_pipeline = MyPipeline(model=model, tokenizer=tokenizer, ...) +# or if you use *pipeline* function, then: +my_pipeline = pipeline(model="xxxx", pipeline_class=MyPipeline) +``` + +That should enable you to do all the custom code you want. + + +## Implementing a pipeline + +[Implementing a new pipeline](../add_new_pipeline) + +## Audio + +Pipelines available for audio tasks include the following. + +### AudioClassificationPipeline + +[[autodoc]] AudioClassificationPipeline + - __call__ + - all + +### AutomaticSpeechRecognitionPipeline + +[[autodoc]] AutomaticSpeechRecognitionPipeline + - __call__ + - all + +### TextToAudioPipeline + +[[autodoc]] TextToAudioPipeline + - __call__ + - all + + +### ZeroShotAudioClassificationPipeline + +[[autodoc]] ZeroShotAudioClassificationPipeline + - __call__ + - all + +## Computer vision + +Pipelines available for computer vision tasks include the following. + +### DepthEstimationPipeline +[[autodoc]] DepthEstimationPipeline + - __call__ + - all + +### ImageClassificationPipeline + +[[autodoc]] ImageClassificationPipeline + - __call__ + - all + +### ImageSegmentationPipeline + +[[autodoc]] ImageSegmentationPipeline + - __call__ + - all + +### ImageToImagePipeline + +[[autodoc]] ImageToImagePipeline + - __call__ + - all + +### ObjectDetectionPipeline + +[[autodoc]] ObjectDetectionPipeline + - __call__ + - all + +### VideoClassificationPipeline + +[[autodoc]] VideoClassificationPipeline + - __call__ + - all + +### ZeroShotImageClassificationPipeline + +[[autodoc]] ZeroShotImageClassificationPipeline + - __call__ + - all + +### ZeroShotObjectDetectionPipeline + +[[autodoc]] ZeroShotObjectDetectionPipeline + - __call__ + - all + +## Natural Language Processing + +Pipelines available for natural language processing tasks include the following. + +### FillMaskPipeline + +[[autodoc]] FillMaskPipeline + - __call__ + - all + +### QuestionAnsweringPipeline + +[[autodoc]] QuestionAnsweringPipeline + - __call__ + - all + +### SummarizationPipeline + +[[autodoc]] SummarizationPipeline + - __call__ + - all + +### TableQuestionAnsweringPipeline + +[[autodoc]] TableQuestionAnsweringPipeline + - __call__ + +### TextClassificationPipeline + +[[autodoc]] TextClassificationPipeline + - __call__ + - all + +### TextGenerationPipeline + +[[autodoc]] TextGenerationPipeline + - __call__ + - all + +### Text2TextGenerationPipeline + +[[autodoc]] Text2TextGenerationPipeline + - __call__ + - all + +### TokenClassificationPipeline + +[[autodoc]] TokenClassificationPipeline + - __call__ + - all + +### TranslationPipeline + +[[autodoc]] TranslationPipeline + - __call__ + - all + +### ZeroShotClassificationPipeline + +[[autodoc]] ZeroShotClassificationPipeline + - __call__ + - all + +## Multimodal + +Pipelines available for multimodal tasks include the following. + +### DocumentQuestionAnsweringPipeline + +[[autodoc]] DocumentQuestionAnsweringPipeline + - __call__ + - all + +### FeatureExtractionPipeline + +[[autodoc]] FeatureExtractionPipeline + - __call__ + - all + +### ImageFeatureExtractionPipeline + +[[autodoc]] ImageFeatureExtractionPipeline + - __call__ + - all + +### ImageToTextPipeline + +[[autodoc]] ImageToTextPipeline + - __call__ + - all + +### ImageTextToTextPipeline + +[[autodoc]] ImageTextToTextPipeline + - __call__ + - all + +### MaskGenerationPipeline + +[[autodoc]] MaskGenerationPipeline + - __call__ + - all + +### VisualQuestionAnsweringPipeline + +[[autodoc]] VisualQuestionAnsweringPipeline + - __call__ + - all + +## Parent class: `Pipeline` + +[[autodoc]] Pipeline diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/processors.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/processors.md new file mode 100644 index 0000000000000000000000000000000000000000..2c2e0cd31b72eeb2c17d6695474fedcbac2346a1 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/processors.md @@ -0,0 +1,163 @@ + + +# Processors + +Processors can mean two different things in the Transformers library: +- the objects that pre-process inputs for multi-modal models such as [Wav2Vec2](../model_doc/wav2vec2) (speech and text) + or [CLIP](../model_doc/clip) (text and vision) +- deprecated objects that were used in older versions of the library to preprocess data for GLUE or SQUAD. + +## Multi-modal processors + +Any multi-modal model will require an object to encode or decode the data that groups several modalities (among text, +vision and audio). This is handled by objects called processors, which group together two or more processing objects +such as tokenizers (for the text modality), image processors (for vision) and feature extractors (for audio). + +Those processors inherit from the following base class that implements the saving and loading functionality: + +[[autodoc]] ProcessorMixin + +## Deprecated processors + +All processors follow the same architecture which is that of the +[`~data.processors.utils.DataProcessor`]. The processor returns a list of +[`~data.processors.utils.InputExample`]. These +[`~data.processors.utils.InputExample`] can be converted to +[`~data.processors.utils.InputFeatures`] in order to be fed to the model. + +[[autodoc]] data.processors.utils.DataProcessor + +[[autodoc]] data.processors.utils.InputExample + +[[autodoc]] data.processors.utils.InputFeatures + +## GLUE + +[General Language Understanding Evaluation (GLUE)](https://gluebenchmark.com/) is a benchmark that evaluates the +performance of models across a diverse set of existing NLU tasks. It was released together with the paper [GLUE: A +multi-task benchmark and analysis platform for natural language understanding](https://openreview.net/pdf?id=rJ4km2R5t7) + +This library hosts a total of 10 processors for the following tasks: MRPC, MNLI, MNLI (mismatched), CoLA, SST2, STSB, +QQP, QNLI, RTE and WNLI. + +Those processors are: + +- [`~data.processors.utils.MrpcProcessor`] +- [`~data.processors.utils.MnliProcessor`] +- [`~data.processors.utils.MnliMismatchedProcessor`] +- [`~data.processors.utils.Sst2Processor`] +- [`~data.processors.utils.StsbProcessor`] +- [`~data.processors.utils.QqpProcessor`] +- [`~data.processors.utils.QnliProcessor`] +- [`~data.processors.utils.RteProcessor`] +- [`~data.processors.utils.WnliProcessor`] + +Additionally, the following method can be used to load values from a data file and convert them to a list of +[`~data.processors.utils.InputExample`]. + +[[autodoc]] data.processors.glue.glue_convert_examples_to_features + + +## XNLI + +[The Cross-Lingual NLI Corpus (XNLI)](https://www.nyu.edu/projects/bowman/xnli/) is a benchmark that evaluates the +quality of cross-lingual text representations. XNLI is crowd-sourced dataset based on [*MultiNLI*](http://www.nyu.edu/projects/bowman/multinli/): pairs of text are labeled with textual entailment annotations for 15 +different languages (including both high-resource language such as English and low-resource languages such as Swahili). + +It was released together with the paper [XNLI: Evaluating Cross-lingual Sentence Representations](https://huggingface.co/papers/1809.05053) + +This library hosts the processor to load the XNLI data: + +- [`~data.processors.utils.XnliProcessor`] + +Please note that since the gold labels are available on the test set, evaluation is performed on the test set. + +An example using these processors is given in the [run_xnli.py](https://github.com/huggingface/transformers/tree/main/examples/pytorch/text-classification/run_xnli.py) script. + + +## SQuAD + +[The Stanford Question Answering Dataset (SQuAD)](https://rajpurkar.github.io/SQuAD-explorer//) is a benchmark that +evaluates the performance of models on question answering. Two versions are available, v1.1 and v2.0. The first version +(v1.1) was released together with the paper [SQuAD: 100,000+ Questions for Machine Comprehension of Text](https://huggingface.co/papers/1606.05250). The second version (v2.0) was released alongside the paper [Know What You Don't +Know: Unanswerable Questions for SQuAD](https://huggingface.co/papers/1806.03822). + +This library hosts a processor for each of the two versions: + +### Processors + +Those processors are: + +- [`~data.processors.utils.SquadV1Processor`] +- [`~data.processors.utils.SquadV2Processor`] + +They both inherit from the abstract class [`~data.processors.utils.SquadProcessor`] + +[[autodoc]] data.processors.squad.SquadProcessor + - all + +Additionally, the following method can be used to convert SQuAD examples into +[`~data.processors.utils.SquadFeatures`] that can be used as model inputs. + +[[autodoc]] data.processors.squad.squad_convert_examples_to_features + + +These processors as well as the aforementioned method can be used with files containing the data as well as with the +*tensorflow_datasets* package. Examples are given below. + + +### Example usage + +Here is an example using the processors as well as the conversion method using data files: + +```python +# Loading a V2 processor +processor = SquadV2Processor() +examples = processor.get_dev_examples(squad_v2_data_dir) + +# Loading a V1 processor +processor = SquadV1Processor() +examples = processor.get_dev_examples(squad_v1_data_dir) + +features = squad_convert_examples_to_features( + examples=examples, + tokenizer=tokenizer, + max_seq_length=max_seq_length, + doc_stride=args.doc_stride, + max_query_length=max_query_length, + is_training=not evaluate, +) +``` + +Using *tensorflow_datasets* is as easy as using a data file: + +```python +# tensorflow_datasets only handle Squad V1. +tfds_examples = tfds.load("squad") +examples = SquadV1Processor().get_examples_from_dataset(tfds_examples, evaluate=evaluate) + +features = squad_convert_examples_to_features( + examples=examples, + tokenizer=tokenizer, + max_seq_length=max_seq_length, + doc_stride=args.doc_stride, + max_query_length=max_query_length, + is_training=not evaluate, +) +``` + +Another example using these processors is given in the [run_squad.py](https://github.com/huggingface/transformers/tree/main/examples/legacy/question-answering/run_squad.py) script. diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/quantization.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/quantization.md new file mode 100644 index 0000000000000000000000000000000000000000..e1f4940103c20a1ae3ed34fb8882246711b408e1 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/quantization.md @@ -0,0 +1,106 @@ + + +# Quantization + +Quantization techniques reduce memory and computational costs by representing weights and activations with lower-precision data types like 8-bit integers (int8). This enables loading larger models you normally wouldn't be able to fit into memory, and speeding up inference. Transformers supports the AWQ and GPTQ quantization algorithms and it supports 8-bit and 4-bit quantization with bitsandbytes. + +Quantization techniques that aren't supported in Transformers can be added with the [`HfQuantizer`] class. + + + +Learn how to quantize models in the [Quantization](../quantization) guide. + + + +## QuantoConfig + +[[autodoc]] QuantoConfig + +## AqlmConfig + +[[autodoc]] AqlmConfig + +## VptqConfig + +[[autodoc]] VptqConfig + +## AwqConfig + +[[autodoc]] AwqConfig + +## EetqConfig +[[autodoc]] EetqConfig + +## GPTQConfig + +[[autodoc]] GPTQConfig + +## BitsAndBytesConfig + +[[autodoc]] BitsAndBytesConfig + +## HfQuantizer + +[[autodoc]] quantizers.base.HfQuantizer + +## HiggsConfig + +[[autodoc]] HiggsConfig + +## HqqConfig + +[[autodoc]] HqqConfig + +## Mxfp4Config + +[[autodoc]] Mxfp4Config + +## FbgemmFp8Config + +[[autodoc]] FbgemmFp8Config + +## CompressedTensorsConfig + +[[autodoc]] CompressedTensorsConfig + +## TorchAoConfig + +[[autodoc]] TorchAoConfig + +## BitNetQuantConfig + +[[autodoc]] BitNetQuantConfig + +## SpQRConfig + +[[autodoc]] SpQRConfig + +## FineGrainedFP8Config + +[[autodoc]] FineGrainedFP8Config + +## QuarkConfig + +[[autodoc]] QuarkConfig + +## FPQuantConfig + +[[autodoc]] FPQuantConfig + +## AutoRoundConfig + +[[autodoc]] AutoRoundConfig diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/text_generation.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/text_generation.md new file mode 100644 index 0000000000000000000000000000000000000000..76a0f1381cd6bc413d575c80ec974fe26682bb75 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/text_generation.md @@ -0,0 +1,59 @@ + + +# Generation + +Each framework has a generate method for text generation implemented in their respective `GenerationMixin` class: + +- PyTorch [`~generation.GenerationMixin.generate`] is implemented in [`~generation.GenerationMixin`]. +- TensorFlow [`~generation.TFGenerationMixin.generate`] is implemented in [`~generation.TFGenerationMixin`]. +- Flax/JAX [`~generation.FlaxGenerationMixin.generate`] is implemented in [`~generation.FlaxGenerationMixin`]. + +Regardless of your framework of choice, you can parameterize the generate method with a [`~generation.GenerationConfig`] +class instance. Please refer to this class for the complete list of generation parameters, which control the behavior +of the generation method. + +To learn how to inspect a model's generation configuration, what are the defaults, how to change the parameters ad hoc, +and how to create and save a customized generation configuration, refer to the +[text generation strategies guide](../generation_strategies). The guide also explains how to use related features, +like token streaming. + +## GenerationConfig + +[[autodoc]] generation.GenerationConfig + - from_pretrained + - from_model_config + - save_pretrained + - update + - validate + - get_generation_mode + +## GenerationMixin + +[[autodoc]] GenerationMixin + - generate + - compute_transition_scores + +## TFGenerationMixin + +[[autodoc]] TFGenerationMixin + - generate + - compute_transition_scores + +## FlaxGenerationMixin + +[[autodoc]] FlaxGenerationMixin + - generate diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/tokenizer.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/tokenizer.md new file mode 100644 index 0000000000000000000000000000000000000000..83d2ae5df6a7fb1179edb400ff6ee8b616680db8 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/tokenizer.md @@ -0,0 +1,104 @@ + + +# Tokenizer + +A tokenizer is in charge of preparing the inputs for a model. The library contains tokenizers for all the models. Most +of the tokenizers are available in two flavors: a full python implementation and a "Fast" implementation based on the +Rust library [🤗 Tokenizers](https://github.com/huggingface/tokenizers). The "Fast" implementations allows: + +1. a significant speed-up in particular when doing batched tokenization and +2. additional methods to map between the original string (character and words) and the token space (e.g. getting the + index of the token comprising a given character or the span of characters corresponding to a given token). + +The base classes [`PreTrainedTokenizer`] and [`PreTrainedTokenizerFast`] +implement the common methods for encoding string inputs in model inputs (see below) and instantiating/saving python and +"Fast" tokenizers either from a local file or directory or from a pretrained tokenizer provided by the library +(downloaded from HuggingFace's AWS S3 repository). They both rely on +[`~tokenization_utils_base.PreTrainedTokenizerBase`] that contains the common methods, and +[`~tokenization_utils_base.SpecialTokensMixin`]. + +[`PreTrainedTokenizer`] and [`PreTrainedTokenizerFast`] thus implement the main +methods for using all the tokenizers: + +- Tokenizing (splitting strings in sub-word token strings), converting tokens strings to ids and back, and + encoding/decoding (i.e., tokenizing and converting to integers). +- Adding new tokens to the vocabulary in a way that is independent of the underlying structure (BPE, SentencePiece...). +- Managing special tokens (like mask, beginning-of-sentence, etc.): adding them, assigning them to attributes in the + tokenizer for easy access and making sure they are not split during tokenization. + +[`BatchEncoding`] holds the output of the +[`~tokenization_utils_base.PreTrainedTokenizerBase`]'s encoding methods (`__call__`, +`encode_plus` and `batch_encode_plus`) and is derived from a Python dictionary. When the tokenizer is a pure python +tokenizer, this class behaves just like a standard python dictionary and holds the various model inputs computed by +these methods (`input_ids`, `attention_mask`...). When the tokenizer is a "Fast" tokenizer (i.e., backed by +HuggingFace [tokenizers library](https://github.com/huggingface/tokenizers)), this class provides in addition +several advanced alignment methods which can be used to map between the original string (character and words) and the +token space (e.g., getting the index of the token comprising a given character or the span of characters corresponding +to a given token). + + +# Multimodal Tokenizer + +Apart from that each tokenizer can be a "multimodal" tokenizer which means that the tokenizer will hold all relevant special tokens +as part of tokenizer attributes for easier access. For example, if the tokenizer is loaded from a vision-language model like LLaVA, you will +be able to access `tokenizer.image_token_id` to obtain the special image token used as a placeholder. + +To enable extra special tokens for any type of tokenizer, you have to add the following lines and save the tokenizer. Extra special tokens do not +have to be modality related and can ne anything that the model often needs access to. In the below code, tokenizer at `output_dir` will have direct access +to three more special tokens. + +```python +vision_tokenizer = AutoTokenizer.from_pretrained( + "llava-hf/llava-1.5-7b-hf", + extra_special_tokens={"image_token": "", "boi_token": "", "eoi_token": ""} +) +print(vision_tokenizer.image_token, vision_tokenizer.image_token_id) +("", 32000) +``` + +## PreTrainedTokenizer + +[[autodoc]] PreTrainedTokenizer + - __call__ + - add_tokens + - add_special_tokens + - apply_chat_template + - batch_decode + - decode + - encode + - push_to_hub + - all + +## PreTrainedTokenizerFast + +The [`PreTrainedTokenizerFast`] depend on the [tokenizers](https://huggingface.co/docs/tokenizers) library. The tokenizers obtained from the 🤗 tokenizers library can be +loaded very simply into 🤗 transformers. Take a look at the [Using tokenizers from 🤗 tokenizers](../fast_tokenizers) page to understand how this is done. + +[[autodoc]] PreTrainedTokenizerFast + - __call__ + - add_tokens + - add_special_tokens + - apply_chat_template + - batch_decode + - decode + - encode + - push_to_hub + - all + +## BatchEncoding + +[[autodoc]] BatchEncoding diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/trainer.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/trainer.md new file mode 100644 index 0000000000000000000000000000000000000000..21ba9ed935e2731e9872d767295b13b2d11df50f --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/trainer.md @@ -0,0 +1,54 @@ + + +# Trainer + +The [`Trainer`] class provides an API for feature-complete training in PyTorch, and it supports distributed training on multiple GPUs/TPUs, mixed precision for [NVIDIA GPUs](https://nvidia.github.io/apex/), [AMD GPUs](https://rocm.docs.amd.com/en/latest/rocm.html), and [`torch.amp`](https://pytorch.org/docs/stable/amp.html) for PyTorch. [`Trainer`] goes hand-in-hand with the [`TrainingArguments`] class, which offers a wide range of options to customize how a model is trained. Together, these two classes provide a complete training API. + +[`Seq2SeqTrainer`] and [`Seq2SeqTrainingArguments`] inherit from the [`Trainer`] and [`TrainingArguments`] classes and they're adapted for training models for sequence-to-sequence tasks such as summarization or translation. + + + +The [`Trainer`] class is optimized for 🤗 Transformers models and can have surprising behaviors +when used with other models. When using it with your own model, make sure: + +- your model always return tuples or subclasses of [`~utils.ModelOutput`] +- your model can compute the loss if a `labels` argument is provided and that loss is returned as the first + element of the tuple (if your model returns tuples) +- your model can accept multiple label arguments (use `label_names` in [`TrainingArguments`] to indicate their name to the [`Trainer`]) but none of them should be named `"label"` + + + +## Trainer[[api-reference]] + +[[autodoc]] Trainer + - all + +## Seq2SeqTrainer + +[[autodoc]] Seq2SeqTrainer + - evaluate + - predict + +## TrainingArguments + +[[autodoc]] TrainingArguments + - all + +## Seq2SeqTrainingArguments + +[[autodoc]] Seq2SeqTrainingArguments + - all diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/video_processor.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/video_processor.md new file mode 100644 index 0000000000000000000000000000000000000000..4ff973d2ed29c41fbdd03a2cd14380ad4cdff31f --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/main_classes/video_processor.md @@ -0,0 +1,55 @@ + + + +# Video Processor + +A **Video Processor** is a utility responsible for preparing input features for video models, as well as handling the post-processing of their outputs. It provides transformations such as resizing, normalization, and conversion into PyTorch. + +The video processor extends the functionality of image processors by allowing Vision Large Language Models (VLMs) to handle videos with a distinct set of arguments compared to images. It serves as the bridge between raw video data and the model, ensuring that input features are optimized for the VLM. + +When adding a new VLM or updating an existing one to enable distinct video preprocessing, saving and reloading the processor configuration will store the video related arguments in a dedicated file named `video_preprocessing_config.json`. Don't worry if you haven't updated your VLM, the processor will try to load video related configurations from a file named `preprocessing_config.json`. + + +### Usage Example +Here's an example of how to load a video processor with [`llava-hf/llava-onevision-qwen2-0.5b-ov-hf`](https://huggingface.co/llava-hf/llava-onevision-qwen2-0.5b-ov-hf) model: + +```python +from transformers import AutoVideoProcessor + +processor = AutoVideoProcessor.from_pretrained("llava-hf/llava-onevision-qwen2-0.5b-ov-hf") +``` + +Currently, if using base image processor for videos, it processes video data by treating each frame as an individual image and applying transformations frame-by-frame. While functional, this approach is not highly efficient. Using `AutoVideoProcessor` allows us to take advantage of **fast video processors**, leveraging the [torchvision](https://pytorch.org/vision/stable/index.html) library. Fast processors handle the whole batch of videos at once, without iterating over each video or frame. These updates introduce GPU acceleration and significantly enhance processing speed, especially for tasks requiring high throughput. + +Fast video processors are available for all models and are loaded by default when an `AutoVideoProcessor` is initialized. When using a fast video processor, you can also set the `device` argument to specify the device on which the processing should be done. By default, the processing is done on the same device as the inputs if the inputs are tensors, or on the CPU otherwise. For even more speed improvement, we can compile the processor when using 'cuda' as device. + +```python +import torch +from transformers.video_utils import load_video +from transformers import AutoVideoProcessor + +video = load_video("video.mp4") +processor = AutoVideoProcessor.from_pretrained("llava-hf/llava-onevision-qwen2-0.5b-ov-hf", device="cuda") +processor = torch.compile(processor) +processed_video = processor(video, return_tensors="pt") +``` + + +## BaseVideoProcessor + +[[autodoc]] video_processing_utils.BaseVideoProcessor + diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/aimv2.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/aimv2.md new file mode 100644 index 0000000000000000000000000000000000000000..d5cac85e0a66449e97732946fa41a08adc792b5b --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/aimv2.md @@ -0,0 +1,105 @@ + +*This model was released on 2024-11-21 and added to Hugging Face Transformers on 2025-07-08.* + +# AIMv2 + +## Overview + +The AIMv2 model was proposed in [Multimodal Autoregressive Pre-training of Large Vision Encoders](https://huggingface.co/papers/2411.14402) by Enrico Fini, Mustafa Shukor, Xiujun Li, Philipp Dufter, Michal Klein, David Haldimann, Sai Aitharaju, Victor Guilherme Turrisi da Costa, Louis Béthune, Zhe Gan, Alexander T Toshev, Marcin Eichner, Moin Nabi, Yinfei Yang, Joshua M. Susskind, Alaaeldin El-Nouby. + +The abstract from the paper is the following: + +*We introduce a novel method for pre-training of large-scale vision encoders. Building on recent advancements in autoregressive pre-training of vision models, we extend this framework to a multimodal setting, i.e., images and text. In this paper, we present AIMV2, a family of generalist vision encoders characterized by a straightforward pre-training process, scalability, and remarkable performance across a range of downstream tasks. This is achieved by pairing the vision encoder with a multimodal decoder that autoregressively generates raw image patches and text tokens. Our encoders excel not only in multimodal evaluations but also in vision benchmarks such as localization, grounding, and classification. Notably, our AIMV2-3B encoder achieves 89.5% accuracy on ImageNet-1k with a frozen trunk. Furthermore, AIMV2 consistently outperforms state-of-the-art contrastive models (e.g., CLIP, SigLIP) in multimodal image understanding across diverse settings.* + + +This model was contributed by [Yaswanth Gali](https://huggingface.co/yaswanthgali). +The original code can be found [here](https://github.com/apple/ml-aim). + +## Usage Example + +Here is an example of Image Feature Extraction using specific checkpoints on resized images and native resolution images: + +```python +import requests +from PIL import Image +from transformers import AutoImageProcessor, AutoModel + +url = "http://images.cocodataset.org/val2017/000000039769.jpg" +image = Image.open(requests.get(url, stream=True).raw) + +processor = AutoImageProcessor.from_pretrained("apple/aimv2-large-patch14-native") +model = AutoModel.from_pretrained("apple/aimv2-large-patch14-native") + +inputs = processor(images=image, return_tensors="pt") +outputs = model(**inputs) +``` + +Here is an example of a checkpoint performing zero-shot classification: + +```python +import requests +from PIL import Image +from transformers import AutoProcessor, AutoModel + +url = "http://images.cocodataset.org/val2017/000000039769.jpg" +image = Image.open(requests.get(url, stream=True).raw) +text = ["Picture of a dog.", "Picture of a cat.", "Picture of a horse."] + +processor = AutoProcessor.from_pretrained("apple/aimv2-large-patch14-224-lit") +model = AutoModel.from_pretrained("apple/aimv2-large-patch14-224-lit") + +inputs = processor( + images=image, + text=text, + add_special_tokens=True, + truncation=True, + padding=True, + return_tensors="pt", +) +outputs = model(**inputs) +probs = outputs.logits_per_image.softmax(dim=-1) +``` + +## Aimv2Config + +[[autodoc]] Aimv2Config + +## Aimv2TextConfig + +[[autodoc]] Aimv2TextConfig + +## Aimv2VisionConfig + +[[autodoc]] Aimv2VisionConfig + +## Aimv2Model + +[[autodoc]] Aimv2Model + - forward + +## Aimv2VisionModel + +[[autodoc]] Aimv2VisionModel + - forward + +## Aimv2TextModel + +[[autodoc]] Aimv2TextModel + - forward + + + diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/albert.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/albert.md new file mode 100644 index 0000000000000000000000000000000000000000..2c8b7722c56538b5a52016e49e75a0c1a613cb09 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/albert.md @@ -0,0 +1,264 @@ + +*This model was released on 2019-09-26 and added to Hugging Face Transformers on 2020-11-16.* + +
+
+ PyTorch + TensorFlow + Flax + SDPA +
+
+ +# ALBERT + +[ALBERT](https://huggingface.co/papers/1909.11942) is designed to address memory limitations of scaling and training of [BERT](./bert). It adds two parameter reduction techniques. The first, factorized embedding parametrization, splits the larger vocabulary embedding matrix into two smaller matrices so you can grow the hidden size without adding a lot more parameters. The second, cross-layer parameter sharing, allows layer to share parameters which keeps the number of learnable parameters lower. + +ALBERT was created to address problems like -- GPU/TPU memory limitations, longer training times, and unexpected model degradation in BERT. ALBERT uses two parameter-reduction techniques to lower memory consumption and increase the training speed of BERT: + +- **Factorized embedding parameterization:** The large vocabulary embedding matrix is decomposed into two smaller matrices, reducing memory consumption. +- **Cross-layer parameter sharing:** Instead of learning separate parameters for each transformer layer, ALBERT shares parameters across layers, further reducing the number of learnable weights. + +ALBERT uses absolute position embeddings (like BERT) so padding is applied at right. Size of embeddings is 128 While BERT uses 768. ALBERT can processes maximum 512 token at a time. + +You can find all the original ALBERT checkpoints under the [ALBERT community](https://huggingface.co/albert) organization. + +> [!TIP] +> Click on the ALBERT models in the right sidebar for more examples of how to apply ALBERT to different language tasks. + +The example below demonstrates how to predict the `[MASK]` token with [`Pipeline`], [`AutoModel`], and from the command line. + + + + +```py +import torch +from transformers import pipeline + +pipeline = pipeline( + task="fill-mask", + model="albert-base-v2", + torch_dtype=torch.float16, + device=0 +) +pipeline("Plants create [MASK] through a process known as photosynthesis.", top_k=5) +``` + + + + +```py +import torch +from transformers import AutoModelForMaskedLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("albert/albert-base-v2") +model = AutoModelForMaskedLM.from_pretrained( + "albert/albert-base-v2", + torch_dtype=torch.float16, + attn_implementation="sdpa", + device_map="auto" +) + +prompt = "Plants create energy through a process known as [MASK]." +inputs = tokenizer(prompt, return_tensors="pt").to(model.device) + +with torch.no_grad(): + outputs = model(**inputs) + mask_token_index = torch.where(inputs["input_ids"] == tokenizer.mask_token_id)[1] + predictions = outputs.logits[0, mask_token_index] + +top_k = torch.topk(predictions, k=5).indices.tolist() +for token_id in top_k[0]: + print(f"Prediction: {tokenizer.decode([token_id])}") +``` + + + + +```bash +echo -e "Plants create [MASK] through a process known as photosynthesis." | transformers run --task fill-mask --model albert-base-v2 --device 0 +``` + + + + + +## Notes + +- Inputs should be padded on the right because BERT uses absolute position embeddings. +- The embedding size `E` is different from the hidden size `H` because the embeddings are context independent (one embedding vector represents one token) and the hidden states are context dependent (one hidden state represents a sequence of tokens). The embedding matrix is also larger because `V x E` where `V` is the vocabulary size. As a result, it's more logical if `H >> E`. If `E < H`, the model has less parameters. + +## Resources + +The resources provided in the following sections consist of a list of official Hugging Face and community (indicated by 🌎) resources to help you get started with AlBERT. If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + + + +- [`AlbertForSequenceClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/text-classification). + +- [`TFAlbertForSequenceClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/text-classification). + +- [`FlaxAlbertForSequenceClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/flax/text-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification_flax.ipynb). +- Check the [Text classification task guide](../tasks/sequence_classification) on how to use the model. + + + +- [`AlbertForTokenClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/token-classification). + +- [`TFAlbertForTokenClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/token-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification-tf.ipynb). + +- [`FlaxAlbertForTokenClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/flax/token-classification). +- [Token classification](https://huggingface.co/course/chapter7/2?fw=pt) chapter of the 🤗 Hugging Face Course. +- Check the [Token classification task guide](../tasks/token_classification) on how to use the model. + + + +- [`AlbertForMaskedLM`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/language-modeling#robertabertdistilbert-and-masked-language-modeling) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling.ipynb). +- [`TFAlbertForMaskedLM`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/language-modeling#run_mlmpy) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling-tf.ipynb). +- [`FlaxAlbertForMaskedLM`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/flax/language-modeling#masked-language-modeling) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/masked_language_modeling_flax.ipynb). +- [Masked language modeling](https://huggingface.co/course/chapter7/3?fw=pt) chapter of the 🤗 Hugging Face Course. +- Check the [Masked language modeling task guide](../tasks/masked_language_modeling) on how to use the model. + + + +- [`AlbertForQuestionAnswering`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/question-answering) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/question_answering.ipynb). +- [`TFAlbertForQuestionAnswering`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/question-answering) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/question_answering-tf.ipynb). +- [`FlaxAlbertForQuestionAnswering`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/flax/question-answering). +- [Question answering](https://huggingface.co/course/chapter7/7?fw=pt) chapter of the 🤗 Hugging Face Course. +- Check the [Question answering task guide](../tasks/question_answering) on how to use the model. + +**Multiple choice** + +- [`AlbertForMultipleChoice`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/multiple-choice) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/multiple_choice.ipynb). +- [`TFAlbertForMultipleChoice`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/multiple-choice) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/multiple_choice-tf.ipynb). + +- Check the [Multiple choice task guide](../tasks/multiple_choice) on how to use the model. + +## AlbertConfig + +[[autodoc]] AlbertConfig + +## AlbertTokenizer + +[[autodoc]] AlbertTokenizer - build_inputs_with_special_tokens - get_special_tokens_mask - create_token_type_ids_from_sequences - save_vocabulary + +## AlbertTokenizerFast + +[[autodoc]] AlbertTokenizerFast + +## Albert specific outputs + +[[autodoc]] models.albert.modeling_albert.AlbertForPreTrainingOutput + +[[autodoc]] models.albert.modeling_tf_albert.TFAlbertForPreTrainingOutput + + + + +## AlbertModel + +[[autodoc]] AlbertModel - forward + +## AlbertForPreTraining + +[[autodoc]] AlbertForPreTraining - forward + +## AlbertForMaskedLM + +[[autodoc]] AlbertForMaskedLM - forward + +## AlbertForSequenceClassification + +[[autodoc]] AlbertForSequenceClassification - forward + +## AlbertForMultipleChoice + +[[autodoc]] AlbertForMultipleChoice + +## AlbertForTokenClassification + +[[autodoc]] AlbertForTokenClassification - forward + +## AlbertForQuestionAnswering + +[[autodoc]] AlbertForQuestionAnswering - forward + + + + + +## TFAlbertModel + +[[autodoc]] TFAlbertModel - call + +## TFAlbertForPreTraining + +[[autodoc]] TFAlbertForPreTraining - call + +## TFAlbertForMaskedLM + +[[autodoc]] TFAlbertForMaskedLM - call + +## TFAlbertForSequenceClassification + +[[autodoc]] TFAlbertForSequenceClassification - call + +## TFAlbertForMultipleChoice + +[[autodoc]] TFAlbertForMultipleChoice - call + +## TFAlbertForTokenClassification + +[[autodoc]] TFAlbertForTokenClassification - call + +## TFAlbertForQuestionAnswering + +[[autodoc]] TFAlbertForQuestionAnswering - call + + + + +## FlaxAlbertModel + +[[autodoc]] FlaxAlbertModel - **call** + +## FlaxAlbertForPreTraining + +[[autodoc]] FlaxAlbertForPreTraining - **call** + +## FlaxAlbertForMaskedLM + +[[autodoc]] FlaxAlbertForMaskedLM - **call** + +## FlaxAlbertForSequenceClassification + +[[autodoc]] FlaxAlbertForSequenceClassification - **call** + +## FlaxAlbertForMultipleChoice + +[[autodoc]] FlaxAlbertForMultipleChoice - **call** + +## FlaxAlbertForTokenClassification + +[[autodoc]] FlaxAlbertForTokenClassification - **call** + +## FlaxAlbertForQuestionAnswering + +[[autodoc]] FlaxAlbertForQuestionAnswering - **call** + + + diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/align.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/align.md new file mode 100644 index 0000000000000000000000000000000000000000..07a1ce8b423c44f26095e44bb09f7de75b89f508 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/align.md @@ -0,0 +1,185 @@ + +*This model was released on 2021-02-11 and added to Hugging Face Transformers on 2023-03-01.* +
+
+ PyTorch + Transformers +
+
+ +# ALIGN + +[ALIGN](https://huggingface.co/papers/2102.05918) is pretrained on a noisy 1.8 billion alt‑text and image pair dataset to show that scale can make up for the noise. It uses a dual‑encoder architecture, [EfficientNet](./efficientnet) for images and [BERT](./bert) for text, and a contrastive loss to align similar image–text embeddings together while pushing different embeddings apart. Once trained, ALIGN can encode any image and candidate captions into a shared vector space for zero‑shot retrieval or classification without requiring extra labels. This scale‑first approach reduces dataset curation costs and powers state‑of‑the‑art image–text retrieval and zero‑shot ImageNet classification. + +You can find all the original ALIGN checkpoints under the [Kakao Brain](https://huggingface.co/kakaobrain?search_models=align) organization. + +> [!TIP] +> Click on the ALIGN models in the right sidebar for more examples of how to apply ALIGN to different vision and text related tasks. + +The example below demonstrates zero-shot image classification with [`Pipeline`] or the [`AutoModel`] class. + + + + + +```py +import torch +from transformers import pipeline + +pipeline = pipeline( + task="zero-shot-image-classification", + model="kakaobrain/align-base", + device=0, + torch_dtype=torch.bfloat16 +) + +candidate_labels = [ + "a photo of a dog", + "a photo of a cat", + "a photo of a person" +] + +pipeline("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg", candidate_labels=candidate_labels) +``` + + + + +```py +import torch +import requests +from PIL import Image +from transformers import AutoProcessor, AutoModelForZeroShotImageClassification + +processor = AutoProcessor.from_pretrained("kakaobrain/align-base") +model = AutoModelForZeroShotImageClassification.from_pretrained("kakaobrain/align-base", device_map="auto") + +url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg" +image = requests.get(url, stream=True) +inputs = Image.open(image.raw).convert("RGB") + +image_inputs = processor(images=inputs, return_tensors="pt").to(model.device) +with torch.no_grad(): + image_embeds = model.get_image_features(**image_inputs) + +candidate_labels = ["a photo of a dog", "a photo of a cat", "a photo of a person"] +text_inputs = processor(text=candidate_labels, padding=True, return_tensors="pt").to(model.device) +with torch.no_grad(): + text_embeds = model.get_text_features(**text_inputs) + +image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True) +text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True) + +logits = (image_embeds @ text_embeds.T) * 100.0 +probs = logits.softmax(dim=-1).cpu().squeeze() + +for label, score in zip(candidate_labels, probs): + print(f"{label:20s} → {score.item():.4f}") +``` + + + + + +## Notes + +- ALIGN projects the text and visual features into latent space and the dot product between the projected image and text features is used as the similarity score. The example below demonstrates how to calculate the image-text similarity score with [`AlignProcessor`] and [`AlignModel`]. + + ```py + # Example of using ALIGN for image-text similarity + from transformers import AlignProcessor, AlignModel + import torch + from PIL import Image + import requests + from io import BytesIO + + # Load processor and model + processor = AlignProcessor.from_pretrained("kakaobrain/align-base") + model = AlignModel.from_pretrained("kakaobrain/align-base") + + # Download image from URL + url = "https://huggingface.co/roschmid/dog-races/resolve/main/images/Golden_Retriever.jpg" + response = requests.get(url) + image = Image.open(BytesIO(response.content)) # Convert the downloaded bytes to a PIL Image + + texts = ["a photo of a cat", "a photo of a dog"] + + # Process image and text inputs + inputs = processor(images=image, text=texts, return_tensors="pt") + + # Get the embeddings + with torch.no_grad(): + outputs = model(**inputs) + + image_embeds = outputs.image_embeds + text_embeds = outputs.text_embeds + + # Normalize embeddings for cosine similarity + image_embeds = image_embeds / image_embeds.norm(dim=1, keepdim=True) + text_embeds = text_embeds / text_embeds.norm(dim=1, keepdim=True) + + # Calculate similarity scores + similarity_scores = torch.matmul(text_embeds, image_embeds.T) + + # Print raw scores + print("Similarity scores:", similarity_scores) + + # Convert to probabilities + probs = torch.nn.functional.softmax(similarity_scores, dim=0) + print("Probabilities:", probs) + + # Get the most similar text + most_similar_idx = similarity_scores.argmax().item() + print(f"Most similar text: '{texts[most_similar_idx]}'") + ``` + +## Resources +- Refer to the [Kakao Brain’s Open Source ViT, ALIGN, and the New COYO Text-Image Dataset](https://huggingface.co/blog/vit-align) blog post for more details. + +## AlignConfig + +[[autodoc]] AlignConfig + - from_text_vision_configs + +## AlignTextConfig + +[[autodoc]] AlignTextConfig + +## AlignVisionConfig + +[[autodoc]] AlignVisionConfig + +## AlignProcessor + +[[autodoc]] AlignProcessor + +## AlignModel + +[[autodoc]] AlignModel + - forward + - get_text_features + - get_image_features + +## AlignTextModel + +[[autodoc]] AlignTextModel + - forward + +## AlignVisionModel + +[[autodoc]] AlignVisionModel + - forward diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/altclip.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/altclip.md new file mode 100644 index 0000000000000000000000000000000000000000..2da9f5a78196350980eadb07d99dea3281c29ec4 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/altclip.md @@ -0,0 +1,121 @@ + +*This model was released on 2022-11-12 and added to Hugging Face Transformers on 2023-01-04.* + +
+
+ PyTorch +
+ +# AltCLIP + +[AltCLIP](https://huggingface.co/papers/2211.06679) replaces the [CLIP](./clip) text encoder with a multilingual XLM-R encoder and aligns image and text representations with teacher learning and contrastive learning. + +You can find all the original AltCLIP checkpoints under the [AltClip](https://huggingface.co/collections/BAAI/alt-clip-diffusion-66987a97de8525205f1221bf) collection. + +> [!TIP] +> Click on the AltCLIP models in the right sidebar for more examples of how to apply AltCLIP to different tasks. + +The examples below demonstrates how to calculate similarity scores between an image and one or more captions with the [`AutoModel`] class. + + + + +```python +import torch +import requests +from PIL import Image +from transformers import AltCLIPModel, AltCLIPProcessor + +model = AltCLIPModel.from_pretrained("BAAI/AltCLIP", torch_dtype=torch.bfloat16) +processor = AltCLIPProcessor.from_pretrained("BAAI/AltCLIP") + +url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg" +image = Image.open(requests.get(url, stream=True).raw) + +inputs = processor(text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True) + +outputs = model(**inputs) +logits_per_image = outputs.logits_per_image # this is the image-text similarity score +probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities + +labels = ["a photo of a cat", "a photo of a dog"] +for label, prob in zip(labels, probs[0]): + print(f"{label}: {prob.item():.4f}") +``` + + + + +Quantization reduces the memory burden of large models by representing the weights in a lower precision. Refer to the [Quantization](../quantization/overview) overview for more available quantization backends. + +The example below uses [torchao](../quantization/torchao) to only quantize the weights to int4. + +```python +# !pip install torchao +import torch +import requests +from PIL import Image +from transformers import AltCLIPModel, AltCLIPProcessor, TorchAoConfig + +model = AltCLIPModel.from_pretrained( + "BAAI/AltCLIP", + quantization_config=TorchAoConfig("int4_weight_only", group_size=128), + torch_dtype=torch.bfloat16, +) + +processor = AltCLIPProcessor.from_pretrained("BAAI/AltCLIP") + +url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg" +image = Image.open(requests.get(url, stream=True).raw) + +inputs = processor(text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True) + +outputs = model(**inputs) +logits_per_image = outputs.logits_per_image # this is the image-text similarity score +probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities + +labels = ["a photo of a cat", "a photo of a dog"] +for label, prob in zip(labels, probs[0]): + print(f"{label}: {prob.item():.4f}") +``` + +## Notes + +- AltCLIP uses bidirectional attention instead of causal attention and it uses the `[CLS]` token in XLM-R to represent a text embedding. +- Use [`CLIPImageProcessor`] to resize (or rescale) and normalize images for the model. +- [`AltCLIPProcessor`] combines [`CLIPImageProcessor`] and [`XLMRobertaTokenizer`] into a single instance to encode text and prepare images. + +## AltCLIPConfig +[[autodoc]] AltCLIPConfig + +## AltCLIPTextConfig +[[autodoc]] AltCLIPTextConfig + +## AltCLIPVisionConfig +[[autodoc]] AltCLIPVisionConfig + +## AltCLIPModel +[[autodoc]] AltCLIPModel + +## AltCLIPTextModel +[[autodoc]] AltCLIPTextModel + +## AltCLIPVisionModel +[[autodoc]] AltCLIPVisionModel + +## AltCLIPProcessor +[[autodoc]] AltCLIPProcessor diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/arcee.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/arcee.md new file mode 100644 index 0000000000000000000000000000000000000000..3df4c382fc9411c8f009900ddd331e8085121b2b --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/arcee.md @@ -0,0 +1,105 @@ + +*This model was released on 2025-06-18 and added to Hugging Face Transformers on 2025-06-24.* + +
+
+ PyTorch + FlashAttention + SDPA +
+
+ +# Arcee + +[Arcee](https://www.arcee.ai/blog/deep-dive-afm-4-5b-the-first-arcee-foundational-model) is a decoder-only transformer model based on the Llama architecture with a key modification: it uses ReLU² (ReLU-squared) activation in the MLP blocks instead of SiLU, following recent research showing improved training efficiency with squared activations. This architecture is designed for efficient training and inference while maintaining the proven stability of the Llama design. + +The Arcee model is architecturally similar to Llama but uses `x * relu(x)` in MLP layers for improved gradient flow and is optimized for efficiency in both training and inference scenarios. + +> [!TIP] +> The Arcee model supports extended context with RoPE scaling and all standard transformers features including Flash Attention 2, SDPA, gradient checkpointing, and quantization support. + +The example below demonstrates how to generate text with Arcee using [`Pipeline`] or the [`AutoModel`]. + + + + +```py +import torch +from transformers import pipeline + +pipeline = pipeline( + task="text-generation", + model="arcee-ai/AFM-4.5B", + torch_dtype=torch.float16, + device=0 +) + +output = pipeline("The key innovation in Arcee is") +print(output[0]["generated_text"]) +``` + + + + +```py +import torch +from transformers import AutoTokenizer, ArceeForCausalLM + +tokenizer = AutoTokenizer.from_pretrained("arcee-ai/AFM-4.5B") +model = ArceeForCausalLM.from_pretrained( + "arcee-ai/AFM-4.5B", + torch_dtype=torch.float16, + device_map="auto" +) + +inputs = tokenizer("The key innovation in Arcee is", return_tensors="pt") +with torch.no_grad(): + outputs = model.generate(**inputs, max_new_tokens=50) +print(tokenizer.decode(outputs[0], skip_special_tokens=True)) +``` + + + + +## ArceeConfig + +[[autodoc]] ArceeConfig + +## ArceeModel + +[[autodoc]] ArceeModel + - forward + +## ArceeForCausalLM + +[[autodoc]] ArceeForCausalLM + - forward + +## ArceeForSequenceClassification + +[[autodoc]] ArceeForSequenceClassification + - forward + +## ArceeForQuestionAnswering + +[[autodoc]] ArceeForQuestionAnswering + - forward + +## ArceeForTokenClassification + +[[autodoc]] ArceeForTokenClassification + - forward \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/aria.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/aria.md new file mode 100644 index 0000000000000000000000000000000000000000..bb86257f225d1c11479ed0d6713d2bc079c0e458 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/aria.md @@ -0,0 +1,177 @@ + +*This model was released on 2024-10-08 and added to Hugging Face Transformers on 2024-12-06.* + +
+
+ PyTorch + FlashAttention + SDPA +
+
+ +# Aria + +[Aria](https://huggingface.co/papers/2410.05993) is a multimodal mixture-of-experts (MoE) model. The goal of this model is to open-source a training recipe for creating a multimodal native model from scratch. Aria has 3.9B and 3.5B activated parameters per visual and text token respectively. Text is handled by a MoE decoder and visual inputs are handled by a lightweight visual encoder. It is trained in 4 stages, language pretraining, multimodal pretraining, multimodal long-context pretraining, and multimodal post-training. + +You can find all the original Aria checkpoints under the [Aria](https://huggingface.co/rhymes-ai?search_models=aria) organization. + +> [!TIP] +> Click on the Aria models in the right sidebar for more examples of how to apply Aria to different multimodal tasks. + +The example below demonstrates how to generate text based on an image with [`Pipeline`] or the [`AutoModel`] class. + + + + +```python +import torch +from transformers import pipeline + +pipeline = pipeline( + "image-to-text", + model="rhymes-ai/Aria", + device=0, + torch_dtype=torch.bfloat16 +) +pipeline( + "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg", + text="What is shown in this image?" +) +``` + + + + +```python +import torch +from transformers import AutoModelForCausalLM, AutoProcessor + +model = AutoModelForCausalLM.from_pretrained( + "rhymes-ai/Aria", + device_map="auto", + torch_dtype=torch.bfloat16, + attn_implementation="sdpa" +) + +processor = AutoProcessor.from_pretrained("rhymes-ai/Aria") + +messages = [ + { + "role": "user", "content": [ + {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"}, + {"type": "text", "text": "What is shown in this image?"}, + ] + }, +] + +inputs = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt") +ipnuts = inputs.to(model.device, torch.bfloat16) + +output = model.generate( + **inputs, + max_new_tokens=15, + stop_strings=["<|im_end|>"], + tokenizer=processor.tokenizer, + do_sample=True, + temperature=0.9, +) +output_ids = output[0][inputs["input_ids"].shape[1]:] +response = processor.decode(output_ids, skip_special_tokens=True) +print(response) +``` + + + + +Quantization reduces the memory burden of large models by representing the weights in a lower precision. Refer to the [Quantization](../quantization/overview) overview for more available quantization backends. + +The example below uses [torchao](../quantization/torchao) to only quantize the weights to int4 and the [rhymes-ai/Aria-sequential_mlp](https://huggingface.co/rhymes-ai/Aria-sequential_mlp) checkpoint. This checkpoint replaces grouped GEMM with `torch.nn.Linear` layers for easier quantization. + +```py +# pip install torchao +import torch +from transformers import TorchAoConfig, AutoModelForCausalLM, AutoProcessor + +quantization_config = TorchAoConfig("int4_weight_only", group_size=128) +model = AutoModelForCausalLM.from_pretrained( + "rhymes-ai/Aria-sequential_mlp", + torch_dtype=torch.bfloat16, + device_map="auto", + quantization_config=quantization_config +) +processor = AutoProcessor.from_pretrained( + "rhymes-ai/Aria-sequential_mlp", +) + +messages = [ + { + "role": "user", "content": [ + {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"}, + {"type": "text", "text": "What is shown in this image?"}, + ] + }, +] + +inputs = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt") +inputs = inputs.to(model.device, torch.bfloat16) + +output = model.generate( + **inputs, + max_new_tokens=15, + stop_strings=["<|im_end|>"], + tokenizer=processor.tokenizer, + do_sample=True, + temperature=0.9, +) +output_ids = output[0][inputs["input_ids"].shape[1]:] +response = processor.decode(output_ids, skip_special_tokens=True) +print(response) +``` + + +## AriaImageProcessor + +[[autodoc]] AriaImageProcessor + +## AriaProcessor + +[[autodoc]] AriaProcessor + +## AriaTextConfig + +[[autodoc]] AriaTextConfig + +## AriaConfig + +[[autodoc]] AriaConfig + +## AriaTextModel + +[[autodoc]] AriaTextModel + +## AriaModel + +[[autodoc]] AriaModel + +## AriaTextForCausalLM + +[[autodoc]] AriaTextForCausalLM + +## AriaForConditionalGeneration + +[[autodoc]] AriaForConditionalGeneration + - forward diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/audio-spectrogram-transformer.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/audio-spectrogram-transformer.md new file mode 100644 index 0000000000000000000000000000000000000000..93d7416a41838b6cc3fe82e76122b118503fcc72 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/audio-spectrogram-transformer.md @@ -0,0 +1,110 @@ + +*This model was released on 2021-04-05 and added to Hugging Face Transformers on 2022-11-21.* + +# Audio Spectrogram Transformer + +
+PyTorch +FlashAttention +SDPA +
+ +## Overview + +The Audio Spectrogram Transformer model was proposed in [AST: Audio Spectrogram Transformer](https://huggingface.co/papers/2104.01778) by Yuan Gong, Yu-An Chung, James Glass. +The Audio Spectrogram Transformer applies a [Vision Transformer](vit) to audio, by turning audio into an image (spectrogram). The model obtains state-of-the-art results +for audio classification. + +The abstract from the paper is the following: + +*In the past decade, convolutional neural networks (CNNs) have been widely adopted as the main building block for end-to-end audio classification models, which aim to learn a direct mapping from audio spectrograms to corresponding labels. To better capture long-range global context, a recent trend is to add a self-attention mechanism on top of the CNN, forming a CNN-attention hybrid model. However, it is unclear whether the reliance on a CNN is necessary, and if neural networks purely based on attention are sufficient to obtain good performance in audio classification. In this paper, we answer the question by introducing the Audio Spectrogram Transformer (AST), the first convolution-free, purely attention-based model for audio classification. We evaluate AST on various audio classification benchmarks, where it achieves new state-of-the-art results of 0.485 mAP on AudioSet, 95.6% accuracy on ESC-50, and 98.1% accuracy on Speech Commands V2.* + + + + Audio Spectrogram Transformer architecture. Taken from the original paper. + +This model was contributed by [nielsr](https://huggingface.co/nielsr). +The original code can be found [here](https://github.com/YuanGongND/ast). + +## Usage tips + +- When fine-tuning the Audio Spectrogram Transformer (AST) on your own dataset, it's recommended to take care of the input normalization (to make +sure the input has mean of 0 and std of 0.5). [`ASTFeatureExtractor`] takes care of this. Note that it uses the AudioSet +mean and std by default. You can check [`ast/src/get_norm_stats.py`](https://github.com/YuanGongND/ast/blob/master/src/get_norm_stats.py) to see how +the authors compute the stats for a downstream dataset. +- Note that the AST needs a low learning rate (the authors use a 10 times smaller learning rate compared to their CNN model proposed in the +[PSLA paper](https://huggingface.co/papers/2102.01243)) and converges quickly, so please search for a suitable learning rate and learning rate scheduler for your task. + +### Using Scaled Dot Product Attention (SDPA) + +PyTorch includes a native scaled dot-product attention (SDPA) operator as part of `torch.nn.functional`. This function +encompasses several implementations that can be applied depending on the inputs and the hardware in use. See the +[official documentation](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html) +or the [GPU Inference](https://huggingface.co/docs/transformers/main/en/perf_infer_gpu_one#pytorch-scaled-dot-product-attention) +page for more information. + +SDPA is used by default for `torch>=2.1.1` when an implementation is available, but you may also set +`attn_implementation="sdpa"` in `from_pretrained()` to explicitly request SDPA to be used. + +``` +from transformers import ASTForAudioClassification +model = ASTForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593", attn_implementation="sdpa", torch_dtype=torch.float16) +... +``` + +For the best speedups, we recommend loading the model in half-precision (e.g. `torch.float16` or `torch.bfloat16`). + +On a local benchmark (A100-40GB, PyTorch 2.3.0, OS Ubuntu 22.04) with `float32` and `MIT/ast-finetuned-audioset-10-10-0.4593` model, we saw the following speedups during inference. + +| Batch size | Average inference time (ms), eager mode | Average inference time (ms), sdpa model | Speed up, Sdpa / Eager (x) | +|--------------|-------------------------------------------|-------------------------------------------|------------------------------| +| 1 | 27 | 6 | 4.5 | +| 2 | 12 | 6 | 2 | +| 4 | 21 | 8 | 2.62 | +| 8 | 40 | 14 | 2.86 | + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with the Audio Spectrogram Transformer. + + + +- A notebook illustrating inference with AST for audio classification can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/AST). +- [`ASTForAudioClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/audio-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/audio_classification.ipynb). +- See also: [Audio classification](../tasks/audio_classification). + +If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + +## ASTConfig + +[[autodoc]] ASTConfig + +## ASTFeatureExtractor + +[[autodoc]] ASTFeatureExtractor + - __call__ + +## ASTModel + +[[autodoc]] ASTModel + - forward + +## ASTForAudioClassification + +[[autodoc]] ASTForAudioClassification + - forward diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/auto.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/auto.md new file mode 100644 index 0000000000000000000000000000000000000000..326d8e2d2d3517ef538356c9d550673828920e7f --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/auto.md @@ -0,0 +1,405 @@ + + +# Auto Classes + +In many cases, the architecture you want to use can be guessed from the name or the path of the pretrained model you +are supplying to the `from_pretrained()` method. AutoClasses are here to do this job for you so that you +automatically retrieve the relevant model given the name/path to the pretrained weights/config/vocabulary. + +Instantiating one of [`AutoConfig`], [`AutoModel`], and +[`AutoTokenizer`] will directly create a class of the relevant architecture. For instance + + +```python +model = AutoModel.from_pretrained("google-bert/bert-base-cased") +``` + +will create a model that is an instance of [`BertModel`]. + +There is one class of `AutoModel` for each task, and for each backend (PyTorch, TensorFlow, or Flax). + +## Extending the Auto Classes + +Each of the auto classes has a method to be extended with your custom classes. For instance, if you have defined a +custom class of model `NewModel`, make sure you have a `NewModelConfig` then you can add those to the auto +classes like this: + +```python +from transformers import AutoConfig, AutoModel + +AutoConfig.register("new-model", NewModelConfig) +AutoModel.register(NewModelConfig, NewModel) +``` + +You will then be able to use the auto classes like you would usually do! + + + +If your `NewModelConfig` is a subclass of [`~transformers.PretrainedConfig`], make sure its +`model_type` attribute is set to the same key you use when registering the config (here `"new-model"`). + +Likewise, if your `NewModel` is a subclass of [`PreTrainedModel`], make sure its +`config_class` attribute is set to the same class you use when registering the model (here +`NewModelConfig`). + + + +## AutoConfig + +[[autodoc]] AutoConfig + +## AutoTokenizer + +[[autodoc]] AutoTokenizer + +## AutoFeatureExtractor + +[[autodoc]] AutoFeatureExtractor + +## AutoImageProcessor + +[[autodoc]] AutoImageProcessor + +## AutoVideoProcessor + +[[autodoc]] AutoVideoProcessor + +## AutoProcessor + +[[autodoc]] AutoProcessor + +## Generic model classes + +The following auto classes are available for instantiating a base model class without a specific head. + +### AutoModel + +[[autodoc]] AutoModel + +### TFAutoModel + +[[autodoc]] TFAutoModel + +### FlaxAutoModel + +[[autodoc]] FlaxAutoModel + +## Generic pretraining classes + +The following auto classes are available for instantiating a model with a pretraining head. + +### AutoModelForPreTraining + +[[autodoc]] AutoModelForPreTraining + +### TFAutoModelForPreTraining + +[[autodoc]] TFAutoModelForPreTraining + +### FlaxAutoModelForPreTraining + +[[autodoc]] FlaxAutoModelForPreTraining + +## Natural Language Processing + +The following auto classes are available for the following natural language processing tasks. + +### AutoModelForCausalLM + +[[autodoc]] AutoModelForCausalLM + +### TFAutoModelForCausalLM + +[[autodoc]] TFAutoModelForCausalLM + +### FlaxAutoModelForCausalLM + +[[autodoc]] FlaxAutoModelForCausalLM + +### AutoModelForMaskedLM + +[[autodoc]] AutoModelForMaskedLM + +### TFAutoModelForMaskedLM + +[[autodoc]] TFAutoModelForMaskedLM + +### FlaxAutoModelForMaskedLM + +[[autodoc]] FlaxAutoModelForMaskedLM + +### AutoModelForMaskGeneration + +[[autodoc]] AutoModelForMaskGeneration + +### TFAutoModelForMaskGeneration + +[[autodoc]] TFAutoModelForMaskGeneration + +### AutoModelForSeq2SeqLM + +[[autodoc]] AutoModelForSeq2SeqLM + +### TFAutoModelForSeq2SeqLM + +[[autodoc]] TFAutoModelForSeq2SeqLM + +### FlaxAutoModelForSeq2SeqLM + +[[autodoc]] FlaxAutoModelForSeq2SeqLM + +### AutoModelForSequenceClassification + +[[autodoc]] AutoModelForSequenceClassification + +### TFAutoModelForSequenceClassification + +[[autodoc]] TFAutoModelForSequenceClassification + +### FlaxAutoModelForSequenceClassification + +[[autodoc]] FlaxAutoModelForSequenceClassification + +### AutoModelForMultipleChoice + +[[autodoc]] AutoModelForMultipleChoice + +### TFAutoModelForMultipleChoice + +[[autodoc]] TFAutoModelForMultipleChoice + +### FlaxAutoModelForMultipleChoice + +[[autodoc]] FlaxAutoModelForMultipleChoice + +### AutoModelForNextSentencePrediction + +[[autodoc]] AutoModelForNextSentencePrediction + +### TFAutoModelForNextSentencePrediction + +[[autodoc]] TFAutoModelForNextSentencePrediction + +### FlaxAutoModelForNextSentencePrediction + +[[autodoc]] FlaxAutoModelForNextSentencePrediction + +### AutoModelForTokenClassification + +[[autodoc]] AutoModelForTokenClassification + +### TFAutoModelForTokenClassification + +[[autodoc]] TFAutoModelForTokenClassification + +### FlaxAutoModelForTokenClassification + +[[autodoc]] FlaxAutoModelForTokenClassification + +### AutoModelForQuestionAnswering + +[[autodoc]] AutoModelForQuestionAnswering + +### TFAutoModelForQuestionAnswering + +[[autodoc]] TFAutoModelForQuestionAnswering + +### FlaxAutoModelForQuestionAnswering + +[[autodoc]] FlaxAutoModelForQuestionAnswering + +### AutoModelForTextEncoding + +[[autodoc]] AutoModelForTextEncoding + +### TFAutoModelForTextEncoding + +[[autodoc]] TFAutoModelForTextEncoding + +## Computer vision + +The following auto classes are available for the following computer vision tasks. + +### AutoModelForDepthEstimation + +[[autodoc]] AutoModelForDepthEstimation + +### AutoModelForImageClassification + +[[autodoc]] AutoModelForImageClassification + +### TFAutoModelForImageClassification + +[[autodoc]] TFAutoModelForImageClassification + +### FlaxAutoModelForImageClassification + +[[autodoc]] FlaxAutoModelForImageClassification + +### AutoModelForVideoClassification + +[[autodoc]] AutoModelForVideoClassification + +### AutoModelForKeypointDetection + +[[autodoc]] AutoModelForKeypointDetection + +### AutoModelForKeypointMatching + +[[autodoc]] AutoModelForKeypointMatching + +### AutoModelForMaskedImageModeling + +[[autodoc]] AutoModelForMaskedImageModeling + +### TFAutoModelForMaskedImageModeling + +[[autodoc]] TFAutoModelForMaskedImageModeling + +### AutoModelForObjectDetection + +[[autodoc]] AutoModelForObjectDetection + +### AutoModelForImageSegmentation + +[[autodoc]] AutoModelForImageSegmentation + +### AutoModelForImageToImage + +[[autodoc]] AutoModelForImageToImage + +### AutoModelForSemanticSegmentation + +[[autodoc]] AutoModelForSemanticSegmentation + +### TFAutoModelForSemanticSegmentation + +[[autodoc]] TFAutoModelForSemanticSegmentation + +### AutoModelForInstanceSegmentation + +[[autodoc]] AutoModelForInstanceSegmentation + +### AutoModelForUniversalSegmentation + +[[autodoc]] AutoModelForUniversalSegmentation + +### AutoModelForZeroShotImageClassification + +[[autodoc]] AutoModelForZeroShotImageClassification + +### TFAutoModelForZeroShotImageClassification + +[[autodoc]] TFAutoModelForZeroShotImageClassification + +### AutoModelForZeroShotObjectDetection + +[[autodoc]] AutoModelForZeroShotObjectDetection + +## Audio + +The following auto classes are available for the following audio tasks. + +### AutoModelForAudioClassification + +[[autodoc]] AutoModelForAudioClassification + +### AutoModelForAudioFrameClassification + +[[autodoc]] TFAutoModelForAudioClassification + +### TFAutoModelForAudioFrameClassification + +[[autodoc]] AutoModelForAudioFrameClassification + +### AutoModelForCTC + +[[autodoc]] AutoModelForCTC + +### AutoModelForSpeechSeq2Seq + +[[autodoc]] AutoModelForSpeechSeq2Seq + +### TFAutoModelForSpeechSeq2Seq + +[[autodoc]] TFAutoModelForSpeechSeq2Seq + +### FlaxAutoModelForSpeechSeq2Seq + +[[autodoc]] FlaxAutoModelForSpeechSeq2Seq + +### AutoModelForAudioXVector + +[[autodoc]] AutoModelForAudioXVector + +### AutoModelForTextToSpectrogram + +[[autodoc]] AutoModelForTextToSpectrogram + +### AutoModelForTextToWaveform + +[[autodoc]] AutoModelForTextToWaveform + +### AutoModelForAudioTokenization + +[[autodoc]] AutoModelForAudioTokenization + +## Multimodal + +The following auto classes are available for the following multimodal tasks. + +### AutoModelForTableQuestionAnswering + +[[autodoc]] AutoModelForTableQuestionAnswering + +### TFAutoModelForTableQuestionAnswering + +[[autodoc]] TFAutoModelForTableQuestionAnswering + +### AutoModelForDocumentQuestionAnswering + +[[autodoc]] AutoModelForDocumentQuestionAnswering + +### TFAutoModelForDocumentQuestionAnswering + +[[autodoc]] TFAutoModelForDocumentQuestionAnswering + +### AutoModelForVisualQuestionAnswering + +[[autodoc]] AutoModelForVisualQuestionAnswering + +### AutoModelForVision2Seq + +[[autodoc]] AutoModelForVision2Seq + +### TFAutoModelForVision2Seq + +[[autodoc]] TFAutoModelForVision2Seq + +### FlaxAutoModelForVision2Seq + +[[autodoc]] FlaxAutoModelForVision2Seq + +### AutoModelForImageTextToText + +[[autodoc]] AutoModelForImageTextToText + +## Time Series + +### AutoModelForTimeSeriesPrediction + +[[autodoc]] AutoModelForTimeSeriesPrediction diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/autoformer.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/autoformer.md new file mode 100644 index 0000000000000000000000000000000000000000..af7087d3757cbd7cc5ee20a5e7f59909a4d7fa78 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/autoformer.md @@ -0,0 +1,55 @@ + +*This model was released on 2021-06-24 and added to Hugging Face Transformers on 2023-05-30.* + +# Autoformer + +
+PyTorch +
+ +## Overview + +The Autoformer model was proposed in [Autoformer: Decomposition Transformers with Auto-Correlation for Long-Term Series Forecasting](https://huggingface.co/papers/2106.13008) by Haixu Wu, Jiehui Xu, Jianmin Wang, Mingsheng Long. + +This model augments the Transformer as a deep decomposition architecture, which can progressively decompose the trend and seasonal components during the forecasting process. + +The abstract from the paper is the following: + +*Extending the forecasting time is a critical demand for real applications, such as extreme weather early warning and long-term energy consumption planning. This paper studies the long-term forecasting problem of time series. Prior Transformer-based models adopt various self-attention mechanisms to discover the long-range dependencies. However, intricate temporal patterns of the long-term future prohibit the model from finding reliable dependencies. Also, Transformers have to adopt the sparse versions of point-wise self-attentions for long series efficiency, resulting in the information utilization bottleneck. Going beyond Transformers, we design Autoformer as a novel decomposition architecture with an Auto-Correlation mechanism. We break with the pre-processing convention of series decomposition and renovate it as a basic inner block of deep models. This design empowers Autoformer with progressive decomposition capacities for complex time series. Further, inspired by the stochastic process theory, we design the Auto-Correlation mechanism based on the series periodicity, which conducts the dependencies discovery and representation aggregation at the sub-series level. Auto-Correlation outperforms self-attention in both efficiency and accuracy. In long-term forecasting, Autoformer yields state-of-the-art accuracy, with a 38% relative improvement on six benchmarks, covering five practical applications: energy, traffic, economics, weather and disease.* + +This model was contributed by [elisim](https://huggingface.co/elisim) and [kashif](https://huggingface.co/kashif). +The original code can be found [here](https://github.com/thuml/Autoformer). + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started. If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + +- Check out the Autoformer blog-post in HuggingFace blog: [Yes, Transformers are Effective for Time Series Forecasting (+ Autoformer)](https://huggingface.co/blog/autoformer) + +## AutoformerConfig + +[[autodoc]] AutoformerConfig + +## AutoformerModel + +[[autodoc]] AutoformerModel + - forward + +## AutoformerForPrediction + +[[autodoc]] AutoformerForPrediction + - forward diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/aya_vision.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/aya_vision.md new file mode 100644 index 0000000000000000000000000000000000000000..dfdfea7b4739263ab0b41998944fd62288ec6c11 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/aya_vision.md @@ -0,0 +1,275 @@ + +*This model was released on 2025-05-13 and added to Hugging Face Transformers on 2025-03-04.* + +
+
+ PyTorch +
+
+ +# Aya Vision + +[Aya Vision](https://huggingface.co/papers/2505.08751) is a family of open-weight multimodal vision-language models from Cohere Labs. It is trained with a synthetic annotation framework that generates high-quality multilingual image captions, improving Aya Vision's generated responses. In addition, a cross-modal model merging technique is used to prevent the model from losing its text capabilities after adding vision capabilities. The model combines a CommandR-7B language model with a SigLIP vision encoder. + +You can find all the original Aya Vision checkpoints under the [Aya Vision](https://huggingface.co/collections/CohereLabs/cohere-labs-aya-vision-67c4ccd395ca064308ee1484) collection. + +> [!TIP] +> This model was contributed by [saurabhdash](https://huggingface.co/saurabhdash) and [yonigozlan](https://huggingface.co/yonigozlan). +> +> Click on the Aya Vision models in the right sidebar for more examples of how to apply Aya Vision to different image-to-text tasks. + +The example below demonstrates how to generate text based on an image with [`Pipeline`] or the [`AutoModel`] class. + + + + +```python +from transformers import pipeline + +pipe = pipeline(model="CohereLabs/aya-vision-8b", task="image-text-to-text", device_map="auto") + +# Format message with the aya-vision chat template +messages = [ + {"role": "user", + "content": [ + {"type": "image", "url": "https://media.istockphoto.com/id/458012057/photo/istanbul-turkey.jpg?s=612x612&w=0&k=20&c=qogAOVvkpfUyqLUMr_XJQyq-HkACXyYUSZbKhBlPrxo="}, + {"type": "text", "text": "Bu resimde hangi anıt gösterilmektedir?"}, + ]}, + ] +outputs = pipe(text=messages, max_new_tokens=300, return_full_text=False) + +print(outputs) +``` + + + + +```python +# pip install 'git+https://github.com/huggingface/transformers.git@v4.49.0-Aya Vision' +import torch +from transformers import AutoProcessor, AutoModelForImageTextToText + +model_id = "CohereLabs/aya-vision-8b" + +processor = AutoProcessor.from_pretrained(model_id) +model = AutoModelForImageTextToText.from_pretrained( + model_id, device_map="auto", torch_dtype=torch.float16 +) + +# Format message with the aya-vision chat template +messages = [ + {"role": "user", + "content": [ + {"type": "image", "url": "https://pbs.twimg.com/media/Fx7YvfQWYAIp6rZ?format=jpg&name=medium"}, + {"type": "text", "text": "चित्र में लिखा पाठ क्या कहता है?"}, + ]}, + ] + +inputs = processor.apply_chat_template( + messages, padding=True, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt" +).to(model.device) + +gen_tokens = model.generate( + **inputs, + max_new_tokens=300, + do_sample=True, + temperature=0.3, +) + +print(processor.tokenizer.decode(gen_tokens[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)) +``` + + + + +Quantization reduces the memory footprint of large models by representing weights at lower precision. Refer to the [Quantization](../quantization/overview) overview for supported backends. + +The example below uses [bitsandbytes](../quantization/bitsandbytes) to only quantize the weights to 4-bits. + +```python +import torch +from transformers import ( + AutoProcessor, + AutoModelForImageTextToText, + BitsAndBytesConfig +) + +bnb_config = BitsAndBytesConfig( + load_in_4bit=True, + bnb_4bit_quant_type="nf4", + bnb_4bit_compute_dtype=torch.bfloat16, + bnb_4bit_use_double_quant=True +) + +processor = AutoProcessor.from_pretrained("CohereLabs/aya-vision-32b", use_fast=True) +model = AutoModelForImageTextToText.from_pretrained( + "CohereLabs/aya-vision-32b", + quantization_config=bnb_config, + device_map="auto" +) + +inputs = processor.apply_chat_template( + [ + {"role": "user", "content": [ + {"type": "image", "url": "https://huggingface.co/roschmid/dog-races/resolve/main/images/Border_Collie.jpg"}, + {"type": "text", "text":"Describe what you see."} + ]} + ], + padding=True, + add_generation_prompt=True, + tokenize=True, + return_tensors="pt" +).to(model.device) + +generated = model.generate(**inputs, max_new_tokens=50) +print(processor.tokenizer.decode(generated[0], skip_special_tokens=True)) +``` + +## Notes + +- Images are represented with the `` tag in the chat template. + +- Use the [`~ProcessorMixin.apply_chat_template`] method to correctly format inputs. + +- The example below demonstrates inference with multiple images. + + ```py + import torch + from transformers import AutoProcessor, AutoModelForImageTextToText + + processor = AutoProcessor.from_pretrained("CohereForAI/aya-vision-8b") + model = AutoModelForImageTextToText.from_pretrained( + "CohereForAI/aya-vision-8b", device_map="auto", torch_dtype=torch.float16 + ) + + messages = [ + { + "role": "user", + "content": [ + { + "type": "image", + "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg", + }, + { + "type": "image", + "url": "https://thumbs.dreamstime.com/b/golden-gate-bridge-san-francisco-purple-flowers-california-echium-candicans-36805947.jpg", + }, + { + "type": "text", + "text": "These images depict two different landmarks. Can you identify them?", + }, + ], + }, + ] + + inputs = processor.apply_chat_template( + messages, padding=True, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt" + ).to(model.device) + + gen_tokens = model.generate( + **inputs, + max_new_tokens=300, + do_sample=True, + temperature=0.3, + ) + + gen_text = processor.tokenizer.decode(gen_tokens[0][inputs.input_ids.shape[1]:], skip_special_tokens=True) + print(gen_text) + ``` + +- The example below demonstrates inference with batched inputs. + + ```py + import torch + from transformers import AutoProcessor, AutoModelForImageTextToText + + processor = AutoProcessor.from_pretrained(model_id) + model = AutoModelForImageTextToText.from_pretrained( + "CohereForAI/aya-vision-8b", device_map="auto", torch_dtype=torch.float16 + ) + + batch_messages = [ + [ + { + "role": "user", + "content": [ + {"type": "image", "url": "https://llava-vl.github.io/static/images/view.jpg"}, + {"type": "text", "text": "Write a haiku for this image"}, + ], + }, + ], + [ + { + "role": "user", + "content": [ + { + "type": "image", + "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg", + }, + { + "type": "image", + "url": "https://thumbs.dreamstime.com/b/golden-gate-bridge-san-francisco-purple-flowers-california-echium-candicans-36805947.jpg", + }, + { + "type": "text", + "text": "These images depict two different landmarks. Can you identify them?", + }, + ], + }, + ], + ] + + batch_inputs = processor.apply_chat_template( + batch_messages, + padding=True, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + return_tensors="pt" + ).to(model.device) + + batch_outputs = model.generate( + **batch_inputs, + max_new_tokens=300, + do_sample=True, + temperature=0.3, + ) + + for i, output in enumerate(batch_outputs): + response = processor.tokenizer.decode( + output[batch_inputs.input_ids.shape[1]:], + skip_special_tokens=True + ) + print(f"Response {i+1}:\n{response}\n") + ``` + +## AyaVisionProcessor + +[[autodoc]] AyaVisionProcessor + +## AyaVisionConfig + +[[autodoc]] AyaVisionConfig + +## AyaVisionModel + +[[autodoc]] AyaVisionModel + +## AyaVisionForConditionalGeneration + +[[autodoc]] AyaVisionForConditionalGeneration + - forward diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bamba.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bamba.md new file mode 100644 index 0000000000000000000000000000000000000000..ee54ad221d08417eec38658f4219effc0734550a --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bamba.md @@ -0,0 +1,141 @@ + +*This model was released on 2024-12-18 and added to Hugging Face Transformers on 2024-12-19.* + +
+
+ PyTorch + FlashAttention + SDPA +
+
+ +# Bamba + +[Bamba](https://huggingface.co/blog/bamba) is a 9B parameter decoder-only language model built on the [Mamba-2](./mamba2) architecture. It is pretrained in two stages - it starts by training on 2T tokens from the [Dolma v1.7](https://huggingface.co/datasets/allenai/dolma) dataset and then trained on an additional 200B tokens from [FineWeb](https://huggingface.co/datasets/HuggingFaceFW/fineweb) and [Cosmopedia](https://huggingface.co/datasets/HuggingFaceTB/cosmopedia). + +You can find all the original Bamba checkpoints under the [Bamba](https://huggingface.co/collections/ibm-ai-platform/bamba-674f1388b9bbc98b413c7bab) collection. + +> [!TIP] +> This model was contributed by [ani300](https://github.com/ani300) and [fabianlim](https://github.com/fabianlim). +> +> Click on the Bamba models in the right sidebar for more examples of how to apply Bamba to different text generation tasks. + +The example below demonstrates how to generate text with [`Pipeline`], [`AutoModel`], and from the command line. + + + + +```python +import torch +from transformers import pipeline + +pipeline = pipeline( + task="text-generation", + model="ibm-ai-platform/Bamba-9B-v2", + torch_dtype=torch.bfloat16, + device=0 +) +pipeline("Plants create energy through a process known as") +``` + + + + + +```python +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("ibm-ai-platform/Bamba-9B-v2") +model = AutoModelForCausalLM.from_pretrained("ibm-ai-platform/Bamba-9B-v2", torch_dtype=torch.bfloat16, device_map="auto", attn_implementation="sdpa") +input_ids = tokenizer("Plants create energy through a process known as", return_tensors="pt").to(model.device) + +output = model.generate(**input_ids) +print(tokenizer.decode(output[0], skip_special_tokens=True)) +``` + + + + +```bash +echo "Plants create energy through a process known as" | transformers-cli run --task text-generation --model ibm-ai-platform/Bamba-9B-v2 --device 0 +``` + + + +Quantization reduces the memory burden of large models by representing the weights in a lower precision. Refer to the [Quantization](../quantization/overview) overview for more available quantization backends. + +The example below uses [torchao](../quantization/torchao) to only quantize the weights to int4. + +```python +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer, TorchAoConfig + +quantization_config = TorchAoConfig("int4_weight_only", group_size=128) +tokenizer = AutoTokenizer.from_pretrained("ibm-ai-platform/Bamba-9B-v2") +model = AutoModelForCausalLM.from_pretrained( + "ibm-ai-platform/Bamba-9B-v2", + quantization_config=quantization_config, + device_map="auto", + attn_implementation="sdpa" +) + +inputs = tokenizer("Plants create energy through a process known as", return_tensors="pt").to(model.device) +output = model.generate(**inputs) +print(tokenizer.decode(output[0], skip_special_tokens=True)) +``` + +## Notes + +- Bamba supports padding-free training which concatenates distinct training examples while still processing inputs as separate batches. It can significantly accelerate inference by [~2x](https://github.com/huggingface/transformers/pull/35861#issue-2807873129) (depending on model and data distribution) and reduce memory-usage if there are examples of varying lengths by avoiding unnecessary compute and memory overhead from padding tokens. + + Padding-free training requires the `flash-attn`, `mamba-ssm`, and `causal-conv1d` packages and the following arguments must be passed to the model in addition to `input_ids` and `labels`. + + - `position_ids: torch.LongTensor`: the position index of each token in each sequence. + - `seq_idx: torch.IntTensor`: the index of each sequence in the batch. + - Each of the [`FlashAttentionKwargs`] + - `cu_seq_lens_q: torch.LongTensor`: the cumulative sequence lengths of all queries. + - `cu_seq_lens_k: torch.LongTensor`: the cumulative sequence lengths of all keys. + - `max_length_q: int`: the longest query length in the batch. + - `max_length_k: int`: the longest key length in the batch. + + The `attention_mask` inputs should not be provided. The [`DataCollatorWithFlattening`] programmatically generates the set of additional arguments above using `return_seq_idx=True` and `return_flash_attn_kwargs=True`. See the [Improving Hugging Face Training Efficiency Through Packing with Flash Attention](https://huggingface.co/blog/packing-with-FA2) blog post for additional information. + + ```python + from transformers import DataCollatorWithFlattening + + # Example of using padding-free training + data_collator = DataCollatorWithFlattening( + tokenizer=tokenizer, + return_seq_idx=True, + return_flash_attn_kwargs=True + ) + ``` + +## BambaConfig + +[[autodoc]] BambaConfig + +## BambaModel + +[[autodoc]] BambaModel + - forward + +## BambaForCausalLM + +[[autodoc]] BambaForCausalLM + - forward diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bark.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bark.md new file mode 100644 index 0000000000000000000000000000000000000000..641835bbe54b0bf024a06cfc04e11c0e38dd073c --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bark.md @@ -0,0 +1,238 @@ + +*This model was released on 2023-04-09 and added to Hugging Face Transformers on 2023-07-17.* + +# Bark + +
+PyTorch +FlashAttention +
+ +## Overview + +[Bark](https://huggingface.co/suno/bark) is a transformer-based text-to-speech model proposed by Suno AI in [suno-ai/bark](https://github.com/suno-ai/bark). + +Bark is made of 4 main models: + +- [`BarkSemanticModel`] (also referred to as the 'text' model): a causal auto-regressive transformer model that takes as input tokenized text, and predicts semantic text tokens that capture the meaning of the text. +- [`BarkCoarseModel`] (also referred to as the 'coarse acoustics' model): a causal autoregressive transformer, that takes as input the results of the [`BarkSemanticModel`] model. It aims at predicting the first two audio codebooks necessary for EnCodec. +- [`BarkFineModel`] (the 'fine acoustics' model), this time a non-causal autoencoder transformer, which iteratively predicts the last codebooks based on the sum of the previous codebooks embeddings. +- having predicted all the codebook channels from the [`EncodecModel`], Bark uses it to decode the output audio array. + +It should be noted that each of the first three modules can support conditional speaker embeddings to condition the output sound according to specific predefined voice. + +This model was contributed by [Yoach Lacombe (ylacombe)](https://huggingface.co/ylacombe) and [Sanchit Gandhi (sanchit-gandhi)](https://github.com/sanchit-gandhi). +The original code can be found [here](https://github.com/suno-ai/bark). + +### Optimizing Bark + +Bark can be optimized with just a few extra lines of code, which **significantly reduces its memory footprint** and **accelerates inference**. + +#### Using half-precision + +You can speed up inference and reduce memory footprint by 50% simply by loading the model in half-precision. + +```python +from transformers import BarkModel, infer_device +import torch + +device = infer_device() +model = BarkModel.from_pretrained("suno/bark-small", torch_dtype=torch.float16).to(device) +``` + +#### Using CPU offload + +As mentioned above, Bark is made up of 4 sub-models, which are called up sequentially during audio generation. In other words, while one sub-model is in use, the other sub-models are idle. + +If you're using a CUDA GPU or Intel XPU, a simple solution to benefit from an 80% reduction in memory footprint is to offload the submodels from device to CPU when they're idle. This operation is called *CPU offloading*. You can use it with one line of code as follows: + +```python +model.enable_cpu_offload() +``` + +Note that 🤗 Accelerate must be installed before using this feature. [Here's how to install it.](https://huggingface.co/docs/accelerate/basic_tutorials/install) + +#### Using Better Transformer + +Better Transformer is an 🤗 Optimum feature that performs kernel fusion under the hood. You can gain 20% to 30% in speed with zero performance degradation. It only requires one line of code to export the model to 🤗 Better Transformer: + +```python +model = model.to_bettertransformer() +``` + +Note that 🤗 Optimum must be installed before using this feature. [Here's how to install it.](https://huggingface.co/docs/optimum/installation) + +#### Using Flash Attention 2 + +Flash Attention 2 is an even faster, optimized version of the previous optimization. + +##### Installation + +First, check whether your hardware is compatible with Flash Attention 2. The latest list of compatible hardware can be found in the [official documentation](https://github.com/Dao-AILab/flash-attention#installation-and-features). If your hardware is not compatible with Flash Attention 2, you can still benefit from attention kernel optimisations through Better Transformer support covered [above](https://huggingface.co/docs/transformers/main/en/model_doc/bark#using-better-transformer). + +Next, [install](https://github.com/Dao-AILab/flash-attention#installation-and-features) the latest version of Flash Attention 2: + +```bash +pip install -U flash-attn --no-build-isolation +``` + + +##### Usage + +To load a model using Flash Attention 2, we can pass the `attn_implementation="flash_attention_2"` flag to [`.from_pretrained`](https://huggingface.co/docs/transformers/main/en/main_classes/model#transformers.PreTrainedModel.from_pretrained). We'll also load the model in half-precision (e.g. `torch.float16`), since it results in almost no degradation to audio quality but significantly lower memory usage and faster inference: + +```python +model = BarkModel.from_pretrained("suno/bark-small", torch_dtype=torch.float16, attn_implementation="flash_attention_2").to(device) +``` + +##### Performance comparison + + +The following diagram shows the latency for the native attention implementation (no optimisation) against Better Transformer and Flash Attention 2. In all cases, we generate 400 semantic tokens on a 40GB A100 GPU with PyTorch 2.1. Flash Attention 2 is also consistently faster than Better Transformer, and its performance improves even more as batch sizes increase: + +
+ +
+ +To put this into perspective, on an NVIDIA A100 and when generating 400 semantic tokens with a batch size of 16, you can get 17 times the [throughput](https://huggingface.co/blog/optimizing-bark#throughput) and still be 2 seconds faster than generating sentences one by one with the native model implementation. In other words, all the samples will be generated 17 times faster. + +At batch size 8, on an NVIDIA A100, Flash Attention 2 is also 10% faster than Better Transformer, and at batch size 16, 25%. + + +#### Combining optimization techniques + +You can combine optimization techniques, and use CPU offload, half-precision and Flash Attention 2 (or 🤗 Better Transformer) all at once. + +```python +from transformers import BarkModel, infer_device +import torch + +device = infer_device() + +# load in fp16 and use Flash Attention 2 +model = BarkModel.from_pretrained("suno/bark-small", torch_dtype=torch.float16, attn_implementation="flash_attention_2").to(device) + +# enable CPU offload +model.enable_cpu_offload() +``` + +Find out more on inference optimization techniques [here](https://huggingface.co/docs/transformers/perf_infer_gpu_one). + +### Usage tips + +Suno offers a library of voice presets in a number of languages [here](https://suno-ai.notion.site/8b8e8749ed514b0cbf3f699013548683?v=bc67cff786b04b50b3ceb756fd05f68c). +These presets are also uploaded in the hub [here](https://huggingface.co/suno/bark-small/tree/main/speaker_embeddings) or [here](https://huggingface.co/suno/bark/tree/main/speaker_embeddings). + +```python +>>> from transformers import AutoProcessor, BarkModel + +>>> processor = AutoProcessor.from_pretrained("suno/bark") +>>> model = BarkModel.from_pretrained("suno/bark") + +>>> voice_preset = "v2/en_speaker_6" + +>>> inputs = processor("Hello, my dog is cute", voice_preset=voice_preset) + +>>> audio_array = model.generate(**inputs) +>>> audio_array = audio_array.cpu().numpy().squeeze() +``` + +Bark can generate highly realistic, **multilingual** speech as well as other audio - including music, background noise and simple sound effects. + +```python +>>> # Multilingual speech - simplified Chinese +>>> inputs = processor("惊人的!我会说中文") + +>>> # Multilingual speech - French - let's use a voice_preset as well +>>> inputs = processor("Incroyable! Je peux générer du son.", voice_preset="fr_speaker_5") + +>>> # Bark can also generate music. You can help it out by adding music notes around your lyrics. +>>> inputs = processor("♪ Hello, my dog is cute ♪") + +>>> audio_array = model.generate(**inputs) +>>> audio_array = audio_array.cpu().numpy().squeeze() +``` + +The model can also produce **nonverbal communications** like laughing, sighing and crying. + + +```python +>>> # Adding non-speech cues to the input text +>>> inputs = processor("Hello uh ... [clears throat], my dog is cute [laughter]") + +>>> audio_array = model.generate(**inputs) +>>> audio_array = audio_array.cpu().numpy().squeeze() +``` + +To save the audio, simply take the sample rate from the model config and some scipy utility: + +```python +>>> from scipy.io.wavfile import write as write_wav + +>>> # save audio to disk, but first take the sample rate from the model config +>>> sample_rate = model.generation_config.sample_rate +>>> write_wav("bark_generation.wav", sample_rate, audio_array) +``` + +## BarkConfig + +[[autodoc]] BarkConfig + - all + +## BarkProcessor + +[[autodoc]] BarkProcessor + - all + - __call__ + +## BarkModel + +[[autodoc]] BarkModel + - generate + - enable_cpu_offload + +## BarkSemanticModel + +[[autodoc]] BarkSemanticModel + - forward + +## BarkCoarseModel + +[[autodoc]] BarkCoarseModel + - forward + +## BarkFineModel + +[[autodoc]] BarkFineModel + - forward + +## BarkCausalModel + +[[autodoc]] BarkCausalModel + - forward + +## BarkCoarseConfig + +[[autodoc]] BarkCoarseConfig + - all + +## BarkFineConfig + +[[autodoc]] BarkFineConfig + - all + +## BarkSemanticConfig + +[[autodoc]] BarkSemanticConfig + - all + diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bart.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bart.md new file mode 100644 index 0000000000000000000000000000000000000000..0a4850499d9dfe01c1e064c53f64ad3d16656734 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bart.md @@ -0,0 +1,201 @@ + +*This model was released on 2019-10-29 and added to Hugging Face Transformers on 2020-11-16.* + + +
+
+ PyTorch + TensorFlow + Flax + FlashAttention + SDPA +
+ +# BART +[BART](https://huggingface.co/papers/1910.13461) is a sequence-to-sequence model that combines the pretraining objectives from BERT and GPT. It’s pretrained by corrupting text in different ways like deleting words, shuffling sentences, or masking tokens and learning how to fix it. The encoder encodes the corrupted document and the corrupted text is fixed by the decoder. As it learns to recover the original text, BART gets really good at both understanding and generating language. + +You can find all the original BART checkpoints under the [AI at Meta](https://huggingface.co/facebook?search_models=bart) organization. + +The example below demonstrates how to predict the `[MASK]` token with [`Pipeline`], [`AutoModel`], and from the command line. + + + + +```py +import torch +from transformers import pipeline + +pipeline = pipeline( + task="fill-mask", + model="facebook/bart-large", + torch_dtype=torch.float16, + device=0 +) +pipeline("Plants create through a process known as photosynthesis.") + +``` + + + +```py +import torch +from transformers import AutoModelForMaskedLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained( + "facebook/bart-large", +) +model = AutoModelForMaskedLM.from_pretrained( + "facebook/bart-large", + torch_dtype=torch.float16, + device_map="auto", + attn_implementation="sdpa" +) +inputs = tokenizer("Plants create through a process known as photosynthesis.", return_tensors="pt").to(model.device) + +with torch.no_grad(): + outputs = model(**inputs) + predictions = outputs.logits + +masked_index = torch.where(inputs['input_ids'] == tokenizer.mask_token_id)[1] +predicted_token_id = predictions[0, masked_index].argmax(dim=-1) +predicted_token = tokenizer.decode(predicted_token_id) + +print(f"The predicted token is: {predicted_token}") +``` + + + + +```bash +echo -e "Plants create through a process known as photosynthesis." | transformers-cli run --task fill-mask --model facebook/bart-large --device 0 +``` + + + + +## Notes + +- Inputs should be padded on the right because BERT uses absolute position embeddings. +- The [facebook/bart-large-cnn](https://huggingface.co/facebook/bart-large-cnn) checkpoint doesn't include `mask_token_id` which means it can't perform mask-filling tasks. +- BART doesn’t use `token_type_ids` for sequence classification. Use [`BartTokenizer`] or [`~PreTrainedTokenizerBase.encode`] to get the proper splitting. +- The forward pass of [`BartModel`] creates the `decoder_input_ids` if they're not passed. This can be different from other model APIs, but it is a useful feature for mask-filling tasks. +- Model predictions are intended to be identical to the original implementation when `forced_bos_token_id=0`. This only works if the text passed to `fairseq.encode` begins with a space. +- [`~GenerationMixin.generate`] should be used for conditional generation tasks like summarization. + +## BartConfig + +[[autodoc]] BartConfig + - all + +## BartTokenizer + +[[autodoc]] BartTokenizer + - all + +## BartTokenizerFast + +[[autodoc]] BartTokenizerFast + - all + + + + + +## BartModel + +[[autodoc]] BartModel + - forward + +## BartForConditionalGeneration + +[[autodoc]] BartForConditionalGeneration + - forward + +## BartForSequenceClassification + +[[autodoc]] BartForSequenceClassification + - forward + +## BartForQuestionAnswering + +[[autodoc]] BartForQuestionAnswering + - forward + +## BartForCausalLM + +[[autodoc]] BartForCausalLM + - forward + + + + +## TFBartModel + +[[autodoc]] TFBartModel + - call + +## TFBartForConditionalGeneration + +[[autodoc]] TFBartForConditionalGeneration + - call + +## TFBartForSequenceClassification + +[[autodoc]] TFBartForSequenceClassification + - call + + + + +## FlaxBartModel + +[[autodoc]] FlaxBartModel + - __call__ + - encode + - decode + +## FlaxBartForConditionalGeneration + +[[autodoc]] FlaxBartForConditionalGeneration + - __call__ + - encode + - decode + +## FlaxBartForSequenceClassification + +[[autodoc]] FlaxBartForSequenceClassification + - __call__ + - encode + - decode + +## FlaxBartForQuestionAnswering + +[[autodoc]] FlaxBartForQuestionAnswering + - __call__ + - encode + - decode + +## FlaxBartForCausalLM + +[[autodoc]] FlaxBartForCausalLM + - __call__ + + + + + diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/barthez.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/barthez.md new file mode 100644 index 0000000000000000000000000000000000000000..2193c9d6ffc89cad2d26271a7c9f76df00040607 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/barthez.md @@ -0,0 +1,100 @@ + +*This model was released on 2020-10-23 and added to Hugging Face Transformers on 2020-11-27.* + +
+
+ PyTorch + TensorFlow + Flax +
+
+ +# BARThez + +[BARThez](https://huggingface.co/papers/2010.12321) is a [BART](./bart) model designed for French language tasks. Unlike existing French BERT models, BARThez includes a pretrained encoder-decoder, allowing it to generate text as well. This model is also available as a multilingual variant, mBARThez, by continuing pretraining multilingual BART on a French corpus. + +You can find all of the original BARThez checkpoints under the [BARThez](https://huggingface.co/collections/dascim/barthez-670920b569a07aa53e3b6887) collection. + +> [!TIP] +> This model was contributed by [moussakam](https://huggingface.co/moussakam). +> Refer to the [BART](./bart) docs for more usage examples. + + +The example below demonstrates how to predict the `` token with [`Pipeline`], [`AutoModel`], and from the command line. + + + + +```py +import torch +from transformers import pipeline + +pipeline = pipeline( + task="fill-mask", + model="moussaKam/barthez", + torch_dtype=torch.float16, + device=0 +) +pipeline("Les plantes produisent grâce à un processus appelé photosynthèse.") +``` + + + + +```py +import torch +from transformers import AutoModelForMaskedLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained( + "moussaKam/barthez", +) +model = AutoModelForMaskedLM.from_pretrained( + "moussaKam/barthez", + torch_dtype=torch.float16, + device_map="auto", +) +inputs = tokenizer("Les plantes produisent grâce à un processus appelé photosynthèse.", return_tensors="pt").to(model.device) + +with torch.no_grad(): + outputs = model(**inputs) + predictions = outputs.logits + +masked_index = torch.where(inputs['input_ids'] == tokenizer.mask_token_id)[1] +predicted_token_id = predictions[0, masked_index].argmax(dim=-1) +predicted_token = tokenizer.decode(predicted_token_id) + +print(f"The predicted token is: {predicted_token}") +``` + + + + +```bash +echo -e "Les plantes produisent grâce à un processus appelé photosynthèse." | transformers run --task fill-mask --model moussaKam/barthez --device 0 +``` + + + + +## BarthezTokenizer + +[[autodoc]] BarthezTokenizer + +## BarthezTokenizerFast + +[[autodoc]] BarthezTokenizerFast diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bartpho.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bartpho.md new file mode 100644 index 0000000000000000000000000000000000000000..14fed2b4aae866853f3395aeff025fb0584ebd16 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bartpho.md @@ -0,0 +1,113 @@ + +*This model was released on 2021-09-20 and added to Hugging Face Transformers on 2021-10-18.* + +
+
+ PyTorch + TensorFlow + Flax +
+
+ +# BARTpho + +[BARTpho](https://huggingface.co/papers/2109.09701) is a large-scale Vietnamese sequence-to-sequence model. It offers a word-based and syllable-based version. This model is built on the [BART](./bart) large architecture with its denoising pretraining. + +You can find all the original checkpoints under the [VinAI](https://huggingface.co/vinai/models?search=bartpho) organization. + +> [!TIP] +> This model was contributed by [dqnguyen](https://huggingface.co/dqnguyen). +> Check out the right sidebar for examples of how to apply BARTpho to different language tasks. + +The example below demonstrates how to summarize text with [`Pipeline`] or the [`AutoModel`] class. + + + + + + + +```python +import torch +from transformers import pipeline + +pipeline = pipeline( + task="summarization", + model="vinai/bartpho-word", + torch_dtype=torch.float16, + device=0 +) + +text = """ +Quang tổng hợp hay gọi tắt là quang hợp là quá trình thu nhận và chuyển hóa năng lượng ánh sáng Mặt trời của thực vật, +tảo và một số vi khuẩn để tạo ra hợp chất hữu cơ phục vụ bản thân cũng như làm nguồn thức ăn cho hầu hết các sinh vật +trên Trái Đất. Quang hợp trong thực vật thường liên quan đến chất tố diệp lục màu xanh lá cây và tạo ra oxy như một sản phẩm phụ +""" +pipeline(text) +``` + + + + +```python +import torch +from transformers import BartForConditionalGeneration, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained( + "vinai/bartpho-word", +) +model = BartForConditionalGeneration.from_pretrained( + "vinai/bartpho-word", + torch_dtype=torch.float16, + device_map="auto", +) + +text = """ +Quang tổng hợp hay gọi tắt là quang hợp là quá trình thu nhận và chuyển hóa năng lượng ánh sáng Mặt trời của thực vật, +tảo và một số vi khuẩn để tạo ra hợp chất hữu cơ phục vụ bản thân cũng như làm nguồn thức ăn cho hầu hết các sinh vật +trên Trái Đất. Quang hợp trong thực vật thường liên quan đến chất tố diệp lục màu xanh lá cây và tạo ra oxy như một sản phẩm phụ +""" +inputs = tokenizer(text, return_tensors="pt").to(model.device) + +outputs = model.generate(inputs["input_ids"], num_beams=2, min_length=0, max_length=20) +tokenizer.batch_decode(outputs, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] +``` + + + + +```bash +echo -e "Quang tổng hợp hay gọi tắt là quang hợp là quá trình thu nhận và chuyển hóa năng lượng ánh sáng Mặt trời của thực vật, +tảo và một số vi khuẩn để tạo ra hợp chất hữu cơ phục vụ bản thân cũng như làm nguồn thức ăn cho hầu hết các sinh vật +trên Trái Đất. Quang hợp trong thực vật thường liên quan đến chất tố diệp lục màu xanh lá cây và tạo ra oxy như một sản phẩm phụ" | \ +transformers run --task summarization --model vinai/bartpho-word --device 0 +``` + + + + + + +## Notes + +- BARTpho uses the large architecture of BART with an additional layer-normalization layer on top of the encoder and decoder. The BART-specific classes should be replaced with the mBART-specific classes. +- This implementation only handles tokenization through the `monolingual_vocab_file` file. This is a Vietnamese-specific subset of token types taken from that multilingual vocabulary. If you want to use this tokenizer for another language, replace the `monolingual_vocab_file` with one specialized for your target language. + +## BartphoTokenizer + +[[autodoc]] BartphoTokenizer diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/beit.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/beit.md new file mode 100644 index 0000000000000000000000000000000000000000..6bcd70c0fd69bea6c690adcbe23dfacec42bc90b --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/beit.md @@ -0,0 +1,203 @@ + +*This model was released on 2021-06-15 and added to Hugging Face Transformers on 2021-08-04.* + +# BEiT + +
+PyTorch +Flax +SDPA +
+ +## Overview + +The BEiT model was proposed in [BEiT: BERT Pre-Training of Image Transformers](https://huggingface.co/papers/2106.08254) by +Hangbo Bao, Li Dong and Furu Wei. Inspired by BERT, BEiT is the first paper that makes self-supervised pre-training of +Vision Transformers (ViTs) outperform supervised pre-training. Rather than pre-training the model to predict the class +of an image (as done in the [original ViT paper](https://huggingface.co/papers/2010.11929)), BEiT models are pre-trained to +predict visual tokens from the codebook of OpenAI's [DALL-E model](https://huggingface.co/papers/2102.12092) given masked +patches. + +The abstract from the paper is the following: + +*We introduce a self-supervised vision representation model BEiT, which stands for Bidirectional Encoder representation +from Image Transformers. Following BERT developed in the natural language processing area, we propose a masked image +modeling task to pretrain vision Transformers. Specifically, each image has two views in our pre-training, i.e, image +patches (such as 16x16 pixels), and visual tokens (i.e., discrete tokens). We first "tokenize" the original image into +visual tokens. Then we randomly mask some image patches and fed them into the backbone Transformer. The pre-training +objective is to recover the original visual tokens based on the corrupted image patches. After pre-training BEiT, we +directly fine-tune the model parameters on downstream tasks by appending task layers upon the pretrained encoder. +Experimental results on image classification and semantic segmentation show that our model achieves competitive results +with previous pre-training methods. For example, base-size BEiT achieves 83.2% top-1 accuracy on ImageNet-1K, +significantly outperforming from-scratch DeiT training (81.8%) with the same setup. Moreover, large-size BEiT obtains +86.3% only using ImageNet-1K, even outperforming ViT-L with supervised pre-training on ImageNet-22K (85.2%).* + +This model was contributed by [nielsr](https://huggingface.co/nielsr). The JAX/FLAX version of this model was +contributed by [kamalkraj](https://huggingface.co/kamalkraj). The original code can be found [here](https://github.com/microsoft/unilm/tree/master/beit). + +## Usage tips + +- BEiT models are regular Vision Transformers, but pre-trained in a self-supervised way rather than supervised. They + outperform both the [original model (ViT)](vit) as well as [Data-efficient Image Transformers (DeiT)](deit) when fine-tuned on ImageNet-1K and CIFAR-100. You can check out demo notebooks regarding inference as well as + fine-tuning on custom data [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/VisionTransformer) (you can just replace + [`ViTFeatureExtractor`] by [`BeitImageProcessor`] and + [`ViTForImageClassification`] by [`BeitForImageClassification`]). +- There's also a demo notebook available which showcases how to combine DALL-E's image tokenizer with BEiT for + performing masked image modeling. You can find it [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/BEiT). +- As the BEiT models expect each image to be of the same size (resolution), one can use + [`BeitImageProcessor`] to resize (or rescale) and normalize images for the model. +- Both the patch resolution and image resolution used during pre-training or fine-tuning are reflected in the name of + each checkpoint. For example, `microsoft/beit-base-patch16-224` refers to a base-sized architecture with patch + resolution of 16x16 and fine-tuning resolution of 224x224. All checkpoints can be found on the [hub](https://huggingface.co/models?search=microsoft/beit). +- The available checkpoints are either (1) pre-trained on [ImageNet-22k](http://www.image-net.org/) (a collection of + 14 million images and 22k classes) only, (2) also fine-tuned on ImageNet-22k or (3) also fine-tuned on [ImageNet-1k](http://www.image-net.org/challenges/LSVRC/2012/) (also referred to as ILSVRC 2012, a collection of 1.3 million + images and 1,000 classes). +- BEiT uses relative position embeddings, inspired by the T5 model. During pre-training, the authors shared the + relative position bias among the several self-attention layers. During fine-tuning, each layer's relative position + bias is initialized with the shared relative position bias obtained after pre-training. Note that, if one wants to + pre-train a model from scratch, one needs to either set the `use_relative_position_bias` or the + `use_relative_position_bias` attribute of [`BeitConfig`] to `True` in order to add + position embeddings. + + + + BEiT pre-training. Taken from the original paper. + +### Using Scaled Dot Product Attention (SDPA) + +PyTorch includes a native scaled dot-product attention (SDPA) operator as part of `torch.nn.functional`. This function +encompasses several implementations that can be applied depending on the inputs and the hardware in use. See the +[official documentation](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html) +or the [GPU Inference](https://huggingface.co/docs/transformers/main/en/perf_infer_gpu_one#pytorch-scaled-dot-product-attention) +page for more information. + +SDPA is used by default for `torch>=2.1.1` when an implementation is available, but you may also set +`attn_implementation="sdpa"` in `from_pretrained()` to explicitly request SDPA to be used. + +``` +from transformers import BeitForImageClassification +model = BeitForImageClassification.from_pretrained("microsoft/beit-base-patch16-224", attn_implementation="sdpa", torch_dtype=torch.float16) +... +``` + +For the best speedups, we recommend loading the model in half-precision (e.g. `torch.float16` or `torch.bfloat16`). + +On a local benchmark (NVIDIA GeForce RTX 2060-8GB, PyTorch 2.5.1, OS Ubuntu 20.04) with `float16` and +`microsoft/beit-base-patch16-224` model, we saw the following improvements during training and inference: + +#### Training + +| num_training_steps | batch_size | image_size | is_cuda | Time per batch (eager - s) | Time per batch (sdpa - s) | Speedup (%) | Eager peak mem (MB) | SDPA peak mem (MB) | Mem saving (%) | +|--------------------|------------|--------------|---------|----------------------------|---------------------------|-------------|----------------------|--------------------|----------------| +| 50 | 2 | (1048, 640) | True | 0.984 | 0.746 | 31.975 | 6738.915 | 4319.886 | 55.998 | + +#### Inference + +| Image batch size | Eager (s/iter) | Eager CI, % | Eager memory (MB) | SDPA (s/iter) | SDPA CI, % | SDPA memory (MB) | SDPA speedup | SDPA memory saved (%) | +|-------------------:|-----------------:|:--------------|--------------------:|----------------:|:-------------|-------------------:|---------------:|----------------------:| +| 1 | 0.012 | ±0.3% | 3.76657e+08 | 0.011 | ±0.5% | 3.75739e+08 | 1.05 | 0.244 | +| 4 | 0.013 | ±0.1% | 4.03147e+08 | 0.011 | ±0.2% | 3.90554e+08 | 1.178 | 3.225 | +| 16 | 0.045 | ±0.1% | 4.96697e+08 | 0.035 | ±0.1% | 4.51232e+08 | 1.304 | 10.076 | +| 32 | 0.088 | ±0.1% | 6.24417e+08 | 0.066 | ±0.1% | 5.33488e+08 | 1.325 | 17.044 | + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with BEiT. + + + +- [`BeitForImageClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb). +- See also: [Image classification task guide](../tasks/image_classification) + +**Semantic segmentation** +- [Semantic segmentation task guide](../tasks/semantic_segmentation) + +If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + +## BEiT specific outputs + +[[autodoc]] models.beit.modeling_beit.BeitModelOutputWithPooling + +[[autodoc]] models.beit.modeling_flax_beit.FlaxBeitModelOutputWithPooling + +## BeitConfig + +[[autodoc]] BeitConfig + +## BeitFeatureExtractor + +[[autodoc]] BeitFeatureExtractor + - __call__ + - post_process_semantic_segmentation + +## BeitImageProcessor + +[[autodoc]] BeitImageProcessor + - preprocess + - post_process_semantic_segmentation + +## BeitImageProcessorFast + +[[autodoc]] BeitImageProcessorFast + - preprocess + - post_process_semantic_segmentation + + + + +## BeitModel + +[[autodoc]] BeitModel + - forward + +## BeitForMaskedImageModeling + +[[autodoc]] BeitForMaskedImageModeling + - forward + +## BeitForImageClassification + +[[autodoc]] BeitForImageClassification + - forward + +## BeitForSemanticSegmentation + +[[autodoc]] BeitForSemanticSegmentation + - forward + + + + +## FlaxBeitModel + +[[autodoc]] FlaxBeitModel + - __call__ + +## FlaxBeitForMaskedImageModeling + +[[autodoc]] FlaxBeitForMaskedImageModeling + - __call__ + +## FlaxBeitForImageClassification + +[[autodoc]] FlaxBeitForImageClassification + - __call__ + + + \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bert-generation.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bert-generation.md new file mode 100644 index 0000000000000000000000000000000000000000..e5f7fbf69ddc20a71ef36272f5a3508f946bad60 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bert-generation.md @@ -0,0 +1,158 @@ + + +
+
+ PyTorch +
+
+ +# BertGeneration + +[BertGeneration](https://huggingface.co/papers/1907.12461) leverages pretrained BERT checkpoints for sequence-to-sequence tasks with the [`EncoderDecoderModel`] architecture. BertGeneration adapts the [`BERT`] for generative tasks. + +You can find all the original BERT checkpoints under the [BERT](https://huggingface.co/collections/google/bert-release-64ff5e7a4be99045d1896dbc) collection. + +> [!TIP] +> This model was contributed by [patrickvonplaten](https://huggingface.co/patrickvonplaten). +> +> Click on the BertGeneration models in the right sidebar for more examples of how to apply BertGeneration to different sequence generation tasks. + +The example below demonstrates how to use BertGeneration with [`EncoderDecoderModel`] for sequence-to-sequence tasks. + + + + +```python +import torch +from transformers import pipeline + +pipeline = pipeline( + task="text2text-generation", + model="google/roberta2roberta_L-24_discofuse", + torch_dtype=torch.float16, + device=0 +) +pipeline("Plants create energy through ") +``` + + + + +```python +import torch +from transformers import EncoderDecoderModel, AutoTokenizer + +model = EncoderDecoderModel.from_pretrained("google/roberta2roberta_L-24_discofuse", torch_dtype="auto") +tokenizer = AutoTokenizer.from_pretrained("google/roberta2roberta_L-24_discofuse") + +input_ids = tokenizer( + "Plants create energy through ", add_special_tokens=False, return_tensors="pt" +).input_ids + +outputs = model.generate(input_ids) +print(tokenizer.decode(outputs[0])) +``` + + + + +```bash +echo -e "Plants create energy through " | transformers run --task text2text-generation --model "google/roberta2roberta_L-24_discofuse" --device 0 +``` + + + + +Quantization reduces the memory burden of large models by representing the weights in a lower precision. Refer to the [Quantization](../quantization/overview) overview for more available quantization backends. + +The example below uses [BitsAndBytesConfig](../quantizationbitsandbytes) to quantize the weights to 4-bit. + +```python +import torch +from transformers import EncoderDecoderModel, AutoTokenizer, BitsAndBytesConfig + +# Configure 4-bit quantization +quantization_config = BitsAndBytesConfig( + load_in_4bit=True, + bnb_4bit_compute_dtype=torch.float16 +) + +model = EncoderDecoderModel.from_pretrained( + "google/roberta2roberta_L-24_discofuse", + quantization_config=quantization_config, + torch_dtype="auto" +) +tokenizer = AutoTokenizer.from_pretrained("google/roberta2roberta_L-24_discofuse") + +input_ids = tokenizer( + "Plants create energy through ", add_special_tokens=False, return_tensors="pt" +).input_ids + +outputs = model.generate(input_ids) +print(tokenizer.decode(outputs[0])) +``` + +## Notes + +- [`BertGenerationEncoder`] and [`BertGenerationDecoder`] should be used in combination with [`EncoderDecoderModel`] for sequence-to-sequence tasks. + + ```python + from transformers import BertGenerationEncoder, BertGenerationDecoder, BertTokenizer, EncoderDecoderModel + + # leverage checkpoints for Bert2Bert model + # use BERT's cls token as BOS token and sep token as EOS token + encoder = BertGenerationEncoder.from_pretrained("google-bert/bert-large-uncased", bos_token_id=101, eos_token_id=102) + # add cross attention layers and use BERT's cls token as BOS token and sep token as EOS token + decoder = BertGenerationDecoder.from_pretrained( + "google-bert/bert-large-uncased", add_cross_attention=True, is_decoder=True, bos_token_id=101, eos_token_id=102 + ) + bert2bert = EncoderDecoderModel(encoder=encoder, decoder=decoder) + + # create tokenizer + tokenizer = BertTokenizer.from_pretrained("google-bert/bert-large-uncased") + + input_ids = tokenizer( + "This is a long article to summarize", add_special_tokens=False, return_tensors="pt" + ).input_ids + labels = tokenizer("This is a short summary", return_tensors="pt").input_ids + + # train + loss = bert2bert(input_ids=input_ids, decoder_input_ids=labels, labels=labels).loss + loss.backward() + ``` + +- For summarization, sentence splitting, sentence fusion and translation, no special tokens are required for the input. +- No EOS token should be added to the end of the input for most generation tasks. + +## BertGenerationConfig + +[[autodoc]] BertGenerationConfig + +## BertGenerationTokenizer + +[[autodoc]] BertGenerationTokenizer + - save_vocabulary + +## BertGenerationEncoder + +[[autodoc]] BertGenerationEncoder + - forward + +## BertGenerationDecoder + +[[autodoc]] BertGenerationDecoder + - forward \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bert-japanese.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bert-japanese.md new file mode 100644 index 0000000000000000000000000000000000000000..380d9e3e2bb86957890c5e92980478cb7885ae27 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bert-japanese.md @@ -0,0 +1,90 @@ + +*This model was released on 2019-03-24 and added to Hugging Face Transformers on 2020-11-16.* + +# BertJapanese + +
+PyTorch +TensorFlow +Flax +
+ +## Overview + +The BERT models trained on Japanese text. + +There are models with two different tokenization methods: + +- Tokenize with MeCab and WordPiece. This requires some extra dependencies, [fugashi](https://github.com/polm/fugashi) which is a wrapper around [MeCab](https://taku910.github.io/mecab/). +- Tokenize into characters. + +To use *MecabTokenizer*, you should `pip install transformers["ja"]` (or `pip install -e .["ja"]` if you install +from source) to install dependencies. + +See [details on cl-tohoku repository](https://github.com/cl-tohoku/bert-japanese). + +Example of using a model with MeCab and WordPiece tokenization: + +```python +>>> import torch +>>> from transformers import AutoModel, AutoTokenizer + +>>> bertjapanese = AutoModel.from_pretrained("cl-tohoku/bert-base-japanese") +>>> tokenizer = AutoTokenizer.from_pretrained("cl-tohoku/bert-base-japanese") + +>>> ## Input Japanese Text +>>> line = "吾輩は猫である。" + +>>> inputs = tokenizer(line, return_tensors="pt") + +>>> print(tokenizer.decode(inputs["input_ids"][0])) +[CLS] 吾輩 は 猫 で ある 。 [SEP] + +>>> outputs = bertjapanese(**inputs) +``` + +Example of using a model with Character tokenization: + +```python +>>> bertjapanese = AutoModel.from_pretrained("cl-tohoku/bert-base-japanese-char") +>>> tokenizer = AutoTokenizer.from_pretrained("cl-tohoku/bert-base-japanese-char") + +>>> ## Input Japanese Text +>>> line = "吾輩は猫である。" + +>>> inputs = tokenizer(line, return_tensors="pt") + +>>> print(tokenizer.decode(inputs["input_ids"][0])) +[CLS] 吾 輩 は 猫 で あ る 。 [SEP] + +>>> outputs = bertjapanese(**inputs) +``` + +This model was contributed by [cl-tohoku](https://huggingface.co/cl-tohoku). + + + +This implementation is the same as BERT, except for tokenization method. Refer to [BERT documentation](bert) for +API reference information. + + + + +## BertJapaneseTokenizer + +[[autodoc]] BertJapaneseTokenizer diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bert.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bert.md new file mode 100644 index 0000000000000000000000000000000000000000..2185c6bdcdffa48494fc0c654475c479584ad4e0 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bert.md @@ -0,0 +1,260 @@ + +*This model was released on 2018-10-11 and added to Hugging Face Transformers on 2020-11-16.* + +
+
+ PyTorch + TensorFlow + Flax + SDPA +
+
+ +# BERT + +[BERT](https://huggingface.co/papers/1810.04805) is a bidirectional transformer pretrained on unlabeled text to predict masked tokens in a sentence and to predict whether one sentence follows another. The main idea is that by randomly masking some tokens, the model can train on text to the left and right, giving it a more thorough understanding. BERT is also very versatile because its learned language representations can be adapted for other NLP tasks by fine-tuning an additional layer or head. + +You can find all the original BERT checkpoints under the [BERT](https://huggingface.co/collections/google/bert-release-64ff5e7a4be99045d1896dbc) collection. + +> [!TIP] +> Click on the BERT models in the right sidebar for more examples of how to apply BERT to different language tasks. + +The example below demonstrates how to predict the `[MASK]` token with [`Pipeline`], [`AutoModel`], and from the command line. + + + + +```py +import torch +from transformers import pipeline + +pipeline = pipeline( + task="fill-mask", + model="google-bert/bert-base-uncased", + torch_dtype=torch.float16, + device=0 +) +pipeline("Plants create [MASK] through a process known as photosynthesis.") +``` + + + + +```py +import torch +from transformers import AutoModelForMaskedLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained( + "google-bert/bert-base-uncased", +) +model = AutoModelForMaskedLM.from_pretrained( + "google-bert/bert-base-uncased", + torch_dtype=torch.float16, + device_map="auto", + attn_implementation="sdpa" +) +inputs = tokenizer("Plants create [MASK] through a process known as photosynthesis.", return_tensors="pt").to("cuda") + +with torch.no_grad(): + outputs = model(**inputs) + predictions = outputs.logits + +masked_index = torch.where(inputs['input_ids'] == tokenizer.mask_token_id)[1] +predicted_token_id = predictions[0, masked_index].argmax(dim=-1) +predicted_token = tokenizer.decode(predicted_token_id) + +print(f"The predicted token is: {predicted_token}") +``` + + + + +```bash +echo -e "Plants create [MASK] through a process known as photosynthesis." | transformers run --task fill-mask --model google-bert/bert-base-uncased --device 0 +``` + + + + +## Notes + +- Inputs should be padded on the right because BERT uses absolute position embeddings. + +## BertConfig + +[[autodoc]] BertConfig + - all + +## BertTokenizer + +[[autodoc]] BertTokenizer + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - save_vocabulary + +## BertTokenizerFast + +[[autodoc]] BertTokenizerFast + +## BertModel + +[[autodoc]] BertModel + - forward + +## BertForPreTraining + +[[autodoc]] BertForPreTraining + - forward + +## BertLMHeadModel + +[[autodoc]] BertLMHeadModel + - forward + +## BertForMaskedLM + +[[autodoc]] BertForMaskedLM + - forward + +## BertForNextSentencePrediction + +[[autodoc]] BertForNextSentencePrediction + - forward + +## BertForSequenceClassification + +[[autodoc]] BertForSequenceClassification + - forward + +## BertForMultipleChoice + +[[autodoc]] BertForMultipleChoice + - forward + +## BertForTokenClassification + +[[autodoc]] BertForTokenClassification + - forward + +## BertForQuestionAnswering + +[[autodoc]] BertForQuestionAnswering + - forward + +## TFBertTokenizer + +[[autodoc]] TFBertTokenizer + +## TFBertModel + +[[autodoc]] TFBertModel + - call + +## TFBertForPreTraining + +[[autodoc]] TFBertForPreTraining + - call + +## TFBertModelLMHeadModel + +[[autodoc]] TFBertLMHeadModel + - call + +## TFBertForMaskedLM + +[[autodoc]] TFBertForMaskedLM + - call + +## TFBertForNextSentencePrediction + +[[autodoc]] TFBertForNextSentencePrediction + - call + +## TFBertForSequenceClassification + +[[autodoc]] TFBertForSequenceClassification + - call + +## TFBertForMultipleChoice + +[[autodoc]] TFBertForMultipleChoice + - call + +## TFBertForTokenClassification + +[[autodoc]] TFBertForTokenClassification + - call + +## TFBertForQuestionAnswering + +[[autodoc]] TFBertForQuestionAnswering + - call + +## FlaxBertModel + +[[autodoc]] FlaxBertModel + - __call__ + +## FlaxBertForPreTraining + +[[autodoc]] FlaxBertForPreTraining + - __call__ + +## FlaxBertForCausalLM + +[[autodoc]] FlaxBertForCausalLM + - __call__ + +## FlaxBertForMaskedLM + +[[autodoc]] FlaxBertForMaskedLM + - __call__ + +## FlaxBertForNextSentencePrediction + +[[autodoc]] FlaxBertForNextSentencePrediction + - __call__ + +## FlaxBertForSequenceClassification + +[[autodoc]] FlaxBertForSequenceClassification + - __call__ + +## FlaxBertForMultipleChoice + +[[autodoc]] FlaxBertForMultipleChoice + - __call__ + +## FlaxBertForTokenClassification + +[[autodoc]] FlaxBertForTokenClassification + - __call__ + +## FlaxBertForQuestionAnswering + +[[autodoc]] FlaxBertForQuestionAnswering + - __call__ + +## Bert specific outputs + +[[autodoc]] models.bert.modeling_bert.BertForPreTrainingOutput + +[[autodoc]] models.bert.modeling_tf_bert.TFBertForPreTrainingOutput + +[[autodoc]] models.bert.modeling_flax_bert.FlaxBertForPreTrainingOutput diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bertweet.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bertweet.md new file mode 100644 index 0000000000000000000000000000000000000000..164c2859cd76e913698c24de8b5d10926e662e95 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bertweet.md @@ -0,0 +1,99 @@ + +*This model was released on 2020-05-20 and added to Hugging Face Transformers on 2020-11-16.* + +# BERTweet + +
+
+ PyTorch + TensorFlow + Flax +
+ +## BERTweet + +[BERTweet](https://huggingface.co/papers/2005.10200) shares the same architecture as [BERT-base](./bert), but it’s pretrained like [RoBERTa](./roberta) on English Tweets. It performs really well on Tweet-related tasks like part-of-speech tagging, named entity recognition, and text classification. + + +You can find all the original BERTweet checkpoints under the [VinAI Research](https://huggingface.co/vinai?search_models=BERTweet) organization. + +> [!TIP] +> Refer to the [BERT](./bert) docs for more examples of how to apply BERTweet to different language tasks. + +The example below demonstrates how to predict the `` token with [`Pipeline`], [`AutoModel`], and from the command line. + + + + +```py +import torch +from transformers import pipeline + +pipeline = pipeline( + task="fill-mask", + model="vinai/bertweet-base", + torch_dtype=torch.float16, + device=0 +) +pipeline("Plants create through a process known as photosynthesis.") +``` + + + +```py +import torch +from transformers import AutoModelForMaskedLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained( + "vinai/bertweet-base", +) +model = AutoModelForMaskedLM.from_pretrained( + "vinai/bertweet-base", + torch_dtype=torch.float16, + device_map="auto" +) +inputs = tokenizer("Plants create through a process known as photosynthesis.", return_tensors="pt").to(model.device) + +with torch.no_grad(): + outputs = model(**inputs) + predictions = outputs.logits + +masked_index = torch.where(inputs['input_ids'] == tokenizer.mask_token_id)[1] +predicted_token_id = predictions[0, masked_index].argmax(dim=-1) +predicted_token = tokenizer.decode(predicted_token_id) + +print(f"The predicted token is: {predicted_token}") +``` + + + + +```bash +echo -e "Plants create through a process known as photosynthesis." | transformers-cli run --task fill-mask --model vinai/bertweet-base --device 0 +``` + + + + +## Notes +- Use the [`AutoTokenizer`] or [`BertweetTokenizer`] because it’s preloaded with a custom vocabulary adapted to tweet-specific tokens like hashtags (#), mentions (@), emojis, and common abbreviations. Make sure to also install the [emoji](https://pypi.org/project/emoji/) library. +- Inputs should be padded on the right (`padding="max_length"`) because BERT uses absolute position embeddings. + +## BertweetTokenizer + +[[autodoc]] BertweetTokenizer diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/big_bird.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/big_bird.md new file mode 100644 index 0000000000000000000000000000000000000000..0a8b00bab84f8a3aa1c13560a024f24038025878 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/big_bird.md @@ -0,0 +1,208 @@ + +*This model was released on 2020-07-28 and added to Hugging Face Transformers on 2021-03-30.* + +
+
+ PyTorch + Flax +
+
+ +# BigBird + +[BigBird](https://huggingface.co/papers/2007.14062) is a transformer model built to handle sequence lengths up to 4096 compared to 512 for [BERT](./bert). Traditional transformers struggle with long inputs because attention gets really expensive as the sequence length grows. BigBird fixes this by using a sparse attention mechanism, which means it doesn’t try to look at everything at once. Instead, it mixes in local attention, random attention, and a few global tokens to process the whole input. This combination gives it the best of both worlds. It keeps the computation efficient while still capturing enough of the sequence to understand it well. Because of this, BigBird is great at tasks involving long documents, like question answering, summarization, and genomic applications. + +You can find all the original BigBird checkpoints under the [Google](https://huggingface.co/google?search_models=bigbird) organization. + +> [!TIP] +> Click on the BigBird models in the right sidebar for more examples of how to apply BigBird to different language tasks. + +The example below demonstrates how to predict the `[MASK]` token with [`Pipeline`], [`AutoModel`], and from the command line. + + + + +```py +import torch +from transformers import pipeline + +pipeline = pipeline( + task="fill-mask", + model="google/bigbird-roberta-base", + torch_dtype=torch.float16, + device=0 +) +pipeline("Plants create [MASK] through a process known as photosynthesis.") +``` + + + +```py +import torch +from transformers import AutoModelForMaskedLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained( + "google/bigbird-roberta-base", +) +model = AutoModelForMaskedLM.from_pretrained( + "google/bigbird-roberta-base", + torch_dtype=torch.float16, + device_map="auto", +) +inputs = tokenizer("Plants create [MASK] through a process known as photosynthesis.", return_tensors="pt").to(model.device) + +with torch.no_grad(): + outputs = model(**inputs) + predictions = outputs.logits + +masked_index = torch.where(inputs['input_ids'] == tokenizer.mask_token_id)[1] +predicted_token_id = predictions[0, masked_index].argmax(dim=-1) +predicted_token = tokenizer.decode(predicted_token_id) + +print(f"The predicted token is: {predicted_token}") +``` + + + + +```bash +!echo -e "Plants create [MASK] through a process known as photosynthesis." | transformers-cli run --task fill-mask --model google/bigbird-roberta-base --device 0 +``` + + + +## Notes +- Inputs should be padded on the right because BigBird uses absolute position embeddings. +- BigBird supports `original_full` and `block_sparse` attention. If the input sequence length is less than 1024, it is recommended to use `original_full` since sparse patterns don't offer much benefit for smaller inputs. +- The current implementation uses window size of 3 blocks and 2 global blocks, only supports the ITC-implementation, and doesn't support `num_random_blocks=0`. +- The sequence length must be divisible by the block size. + +## Resources + +- Read the [BigBird](https://huggingface.co/blog/big-bird) blog post for more details about how its attention works. + +## BigBirdConfig + +[[autodoc]] BigBirdConfig + +## BigBirdTokenizer + +[[autodoc]] BigBirdTokenizer + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - save_vocabulary + +## BigBirdTokenizerFast + +[[autodoc]] BigBirdTokenizerFast + +## BigBird specific outputs + +[[autodoc]] models.big_bird.modeling_big_bird.BigBirdForPreTrainingOutput + + + + +## BigBirdModel + +[[autodoc]] BigBirdModel + - forward + +## BigBirdForPreTraining + +[[autodoc]] BigBirdForPreTraining + - forward + +## BigBirdForCausalLM + +[[autodoc]] BigBirdForCausalLM + - forward + +## BigBirdForMaskedLM + +[[autodoc]] BigBirdForMaskedLM + - forward + +## BigBirdForSequenceClassification + +[[autodoc]] BigBirdForSequenceClassification + - forward + +## BigBirdForMultipleChoice + +[[autodoc]] BigBirdForMultipleChoice + - forward + +## BigBirdForTokenClassification + +[[autodoc]] BigBirdForTokenClassification + - forward + +## BigBirdForQuestionAnswering + +[[autodoc]] BigBirdForQuestionAnswering + - forward + + + + +## FlaxBigBirdModel + +[[autodoc]] FlaxBigBirdModel + - __call__ + +## FlaxBigBirdForPreTraining + +[[autodoc]] FlaxBigBirdForPreTraining + - __call__ + +## FlaxBigBirdForCausalLM + +[[autodoc]] FlaxBigBirdForCausalLM + - __call__ + +## FlaxBigBirdForMaskedLM + +[[autodoc]] FlaxBigBirdForMaskedLM + - __call__ + +## FlaxBigBirdForSequenceClassification + +[[autodoc]] FlaxBigBirdForSequenceClassification + - __call__ + +## FlaxBigBirdForMultipleChoice + +[[autodoc]] FlaxBigBirdForMultipleChoice + - __call__ + +## FlaxBigBirdForTokenClassification + +[[autodoc]] FlaxBigBirdForTokenClassification + - __call__ + +## FlaxBigBirdForQuestionAnswering + +[[autodoc]] FlaxBigBirdForQuestionAnswering + - __call__ + + + + + diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bigbird_pegasus.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bigbird_pegasus.md new file mode 100644 index 0000000000000000000000000000000000000000..a629c0367fec67824bc40dcc57985a5c62e8197a --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bigbird_pegasus.md @@ -0,0 +1,164 @@ + +*This model was released on 2020-07-28 and added to Hugging Face Transformers on 2021-05-07.* + +
+
+ PyTorch +
+
+ +# BigBirdPegasus + +[BigBirdPegasus](https://huggingface.co/papers/2007.14062) is an encoder-decoder (sequence-to-sequence) transformer model for long-input summarization. It extends the [BigBird](./big_bird) architecture with an additional pretraining objective borrowed from [Pegasus](./pegasus) called gap sequence generation (GSG). Whole sentences are masked and the model has to fill in the gaps in the document. BigBirdPegasus's ability to keep track of long contexts makes it effective at summarizing lengthy inputs, surpassing the performance of base Pegasus models. + +You can find all the original BigBirdPegasus checkpoints under the [Google](https://huggingface.co/google/models?search=bigbird-pegasus) organization. + +> [!TIP] +> This model was contributed by [vasudevgupta](https://huggingface.co/vasudevgupta). +> +> Click on the BigBirdPegasus models in the right sidebar for more examples of how to apply BigBirdPegasus to different language tasks. + +The example below demonstrates how to summarize text with [`Pipeline`], [`AutoModel`], and from the command line. + + + + +```py +import torch +from transformers import pipeline + +pipeline = pipeline( + task="summarization", + model="google/bigbird-pegasus-large-arxiv", + torch_dtype=torch.float32, + device=0 +) +pipeline("""Plants are among the most remarkable and essential life forms on Earth, possessing a unique ability to produce their own food through a process known as photosynthesis. This complex biochemical process is fundamental not only to plant life but to virtually all life on the planet. +Through photosynthesis, plants capture energy from sunlight using a green pigment called chlorophyll, which is located in specialized cell structures called chloroplasts. In the presence of light, plants absorb carbon dioxide from the atmosphere through small pores in their leaves called stomata, and take in water from the soil through their root systems. +These ingredients are then transformed into glucose, a type of sugar that serves as a source of chemical energy, and oxygen, which is released as a byproduct into the atmosphere. The glucose produced during photosynthesis is not just used immediately; plants also store it as starch or convert it into other organic compounds like cellulose, which is essential for building their cellular structure. +This energy reserve allows them to grow, develop leaves, produce flowers, bear fruit, and carry out various physiological processes throughout their lifecycle.""") +``` + + + +```py +import torch +from transformers import AutoTokenizer, AutoModelForSeq2SeqLM + +tokenizer = AutoTokenizer.from_pretrained( + "google/bigbird-pegasus-large-arxiv" +) +model = AutoModelForSeq2SeqLM.from_pretrained( + "google/bigbird-pegasus-large-arxiv", + torch_dtype=torch.bfloat16, + device_map="auto", +) + +input_text = """Plants are among the most remarkable and essential life forms on Earth, possessing a unique ability to produce their own food through a process known as photosynthesis. This complex biochemical process is fundamental not only to plant life but to virtually all life on the planet. +Through photosynthesis, plants capture energy from sunlight using a green pigment called chlorophyll, which is located in specialized cell structures called chloroplasts. In the presence of light, plants absorb carbon dioxide from the atmosphere through small pores in their leaves called stomata, and take in water from the soil through their root systems. +These ingredients are then transformed into glucose, a type of sugar that serves as a source of chemical energy, and oxygen, which is released as a byproduct into the atmosphere. The glucose produced during photosynthesis is not just used immediately; plants also store it as starch or convert it into other organic compounds like cellulose, which is essential for building their cellular structure. +This energy reserve allows them to grow, develop leaves, produce flowers, bear fruit, and carry out various physiological processes throughout their lifecycle.""" +input_ids = tokenizer(input_text, return_tensors="pt").to(model.device) + +output = model.generate(**input_ids, cache_implementation="static") +print(tokenizer.decode(output[0], skip_special_tokens=True)) +``` + + + +```bash +echo -e "Plants are among the most remarkable and essential life forms on Earth, possessing a unique ability to produce their own food through a process known as photosynthesis. This complex biochemical process is fundamental not only to plant life but to virtually all life on the planet. Through photosynthesis, plants capture energy from sunlight using a green pigment called chlorophyll, which is located in specialized cell structures called chloroplasts." | transformers-cli run --task summarization --model google/bigbird-pegasus-large-arxiv --device 0 +``` + + + + +Quantization reduces the memory burden of large models by representing the weights in a lower precision. Refer to the [Quantization](../quantization/overview) overview for more available quantization backends. + +The example below uses [bitsandbytes](../quantization/bitsandbytes) to only quantize the weights to int4. + +```py +import torch +from transformers import BitsAndBytesConfig, AutoModelForSeq2SeqLM, AutoTokenizer + +quantization_config = BitsAndBytesConfig( + load_in_4bit=True, + bnb_4bit_compute_dtype=torch.bfloat16, + bnb_4bit_quant_type="nf4" +) +model = AutoModelForSeq2SeqLM.from_pretrained( + "google/bigbird-pegasus-large-arxiv", + torch_dtype=torch.bfloat16, + device_map="auto", + quantization_config=quantization_config +) + +tokenizer = AutoTokenizer.from_pretrained( + "google/bigbird-pegasus-large-arxiv" +) + +input_text = """Plants are among the most remarkable and essential life forms on Earth, possessing a unique ability to produce their own food through a process known as photosynthesis. This complex biochemical process is fundamental not only to plant life but to virtually all life on the planet. +Through photosynthesis, plants capture energy from sunlight using a green pigment called chlorophyll, which is located in specialized cell structures called chloroplasts. In the presence of light, plants absorb carbon dioxide from the atmosphere through small pores in their leaves called stomata, and take in water from the soil through their root systems. +These ingredients are then transformed into glucose, a type of sugar that serves as a source of chemical energy, and oxygen, which is released as a byproduct into the atmosphere. The glucose produced during photosynthesis is not just used immediately; plants also store it as starch or convert it into other organic compounds like cellulose, which is essential for building their cellular structure. +This energy reserve allows them to grow, develop leaves, produce flowers, bear fruit, and carry out various physiological processes throughout their lifecycle.""" +input_ids = tokenizer(input_text, return_tensors="pt").to(model.device) + +output = model.generate(**input_ids, cache_implementation="static") +print(tokenizer.decode(output[0], skip_special_tokens=True)) +``` + +## Notes + +- BigBirdPegasus also uses the [`PegasusTokenizer`]. +- Inputs should be padded on the right because BigBird uses absolute position embeddings. +- BigBirdPegasus supports `original_full` and `block_sparse` attention. If the input sequence length is less than 1024, it is recommended to use `original_full` since sparse patterns don't offer much benefit for smaller inputs. +- The current implementation uses window size of 3 blocks and 2 global blocks, only supports the ITC-implementation, and doesn't support `num_random_blocks=0`. +- The sequence length must be divisible by the block size. + +## Resources + +Read the [Understanding BigBird's Block Sparse Attention](https://huggingface.co/blog/big-bird) blog post for more details about how BigBird's attention works. + +## BigBirdPegasusConfig + +[[autodoc]] BigBirdPegasusConfig + - all + +## BigBirdPegasusModel + +[[autodoc]] BigBirdPegasusModel + - forward + +## BigBirdPegasusForConditionalGeneration + +[[autodoc]] BigBirdPegasusForConditionalGeneration + - forward + +## BigBirdPegasusForSequenceClassification + +[[autodoc]] BigBirdPegasusForSequenceClassification + - forward + +## BigBirdPegasusForQuestionAnswering + +[[autodoc]] BigBirdPegasusForQuestionAnswering + - forward + +## BigBirdPegasusForCausalLM + +[[autodoc]] BigBirdPegasusForCausalLM + - forward diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/biogpt.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/biogpt.md new file mode 100644 index 0000000000000000000000000000000000000000..8da62d60b3c51a809efba9e05f64673db358199b --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/biogpt.md @@ -0,0 +1,166 @@ + +*This model was released on 2022-10-19 and added to Hugging Face Transformers on 2022-12-05.* + +
+
+ PyTorch + FlashAttention + SDPA +
+
+ +# BioGPT + +[BioGPT](https://huggingface.co/papers/2210.10341) is a generative Transformer model based on [GPT-2](./gpt2) and pretrained on 15 million PubMed abstracts. It is designed for biomedical language tasks. + +You can find all the original BioGPT checkpoints under the [Microsoft](https://huggingface.co/microsoft?search_models=biogpt) organization. + +> [!TIP] +> Click on the BioGPT models in the right sidebar for more examples of how to apply BioGPT to different language tasks. + +The example below demonstrates how to generate biomedical text with [`Pipeline`], [`AutoModel`], and also from the command line. + + + + +```py +import torch +from transformers import pipeline + +generator = pipeline( + task="text-generation", + model="microsoft/biogpt", + torch_dtype=torch.float16, + device=0, +) +result = generator("Ibuprofen is best used for", truncation=True, max_length=50, do_sample=True)[0]["generated_text"] +print(result) +``` + + + + +```py +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("microsoft/biogpt") +model = AutoModelForCausalLM.from_pretrained( + "microsoft/biogpt", + torch_dtype=torch.float16, + device_map="auto", + attn_implementation="sdpa" +) + +input_text = "Ibuprofen is best used for" +inputs = tokenizer(input_text, return_tensors="pt").to(model.device) + +with torch.no_grad(): + generated_ids = model.generate(**inputs, max_length=50) + +output = tokenizer.decode(generated_ids[0], skip_special_tokens=True) +print(output) +``` + + + + +```bash +echo -e "Ibuprofen is best used for" | transformers-cli run --task text-generation --model microsoft/biogpt --device 0 +``` + + + + +Quantization reduces the memory burden of large models by representing the weights in a lower precision. Refer to the [Quantization](../quantization/overview) overview for more available quantization backends. + +The example below uses [bitsandbytes](../quantization/bitsandbytes) to only quantize the weights to 4-bit precision. + +```py +import torch +from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig + +bnb_config = BitsAndBytesConfig( + load_in_4bit=True, + bnb_4bit_quant_type="nf4", + bnb_4bit_compute_dtype=torch.bfloat16, + bnb_4bit_use_double_quant=True +) + +tokenizer = AutoTokenizer.from_pretrained("microsoft/BioGPT-Large") +model = AutoModelForCausalLM.from_pretrained( + "microsoft/BioGPT-Large", + quantization_config=bnb_config, + torch_dtype=torch.bfloat16, + device_map="auto" +) + +input_text = "Ibuprofen is best used for" +inputs = tokenizer(input_text, return_tensors="pt").to(model.device) +with torch.no_grad(): + generated_ids = model.generate(**inputs, max_length=50) +output = tokenizer.decode(generated_ids[0], skip_special_tokens=True) +print(output) +``` + +## Notes + +- Pad inputs on the right because BioGPT uses absolute position embeddings. +- BioGPT can reuse previously computed key-value attention pairs. Access this feature with the [past_key_values](https://huggingface.co/docs/transformers/main/en/model_doc/biogpt#transformers.BioGptModel.forward.past_key_values) parameter in [`BioGPTModel.forward`]. +- The `head_mask` argument is ignored when using an attention implementation other than "eager". If you want to use `head_mask`, make sure `attn_implementation="eager"`). + + ```py + from transformers import AutoModelForCausalLM + + model = AutoModelForCausalLM.from_pretrained( + "microsoft/biogpt", + attn_implementation="eager" + ) + +## BioGptConfig + +[[autodoc]] BioGptConfig + + +## BioGptTokenizer + +[[autodoc]] BioGptTokenizer + - save_vocabulary + + +## BioGptModel + +[[autodoc]] BioGptModel + - forward + + +## BioGptForCausalLM + +[[autodoc]] BioGptForCausalLM + - forward + + +## BioGptForTokenClassification + +[[autodoc]] BioGptForTokenClassification + - forward + + +## BioGptForSequenceClassification + +[[autodoc]] BioGptForSequenceClassification + - forward \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bit.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bit.md new file mode 100644 index 0000000000000000000000000000000000000000..5a6630566fca26d03f00c6ce4518a64294bbdc3e --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bit.md @@ -0,0 +1,75 @@ + +*This model was released on 2019-12-24 and added to Hugging Face Transformers on 2022-12-07.* + +# Big Transfer (BiT) + +
+PyTorch +
+ +## Overview + +The BiT model was proposed in [Big Transfer (BiT): General Visual Representation Learning](https://huggingface.co/papers/1912.11370) by Alexander Kolesnikov, Lucas Beyer, Xiaohua Zhai, Joan Puigcerver, Jessica Yung, Sylvain Gelly, Neil Houlsby. +BiT is a simple recipe for scaling up pre-training of [ResNet](resnet)-like architectures (specifically, ResNetv2). The method results in significant improvements for transfer learning. + +The abstract from the paper is the following: + +*Transfer of pre-trained representations improves sample efficiency and simplifies hyperparameter tuning when training deep neural networks for vision. We revisit the paradigm of pre-training on large supervised datasets and fine-tuning the model on a target task. We scale up pre-training, and propose a simple recipe that we call Big Transfer (BiT). By combining a few carefully selected components, and transferring using a simple heuristic, we achieve strong performance on over 20 datasets. BiT performs well across a surprisingly wide range of data regimes -- from 1 example per class to 1M total examples. BiT achieves 87.5% top-1 accuracy on ILSVRC-2012, 99.4% on CIFAR-10, and 76.3% on the 19 task Visual Task Adaptation Benchmark (VTAB). On small datasets, BiT attains 76.8% on ILSVRC-2012 with 10 examples per class, and 97.0% on CIFAR-10 with 10 examples per class. We conduct detailed analysis of the main components that lead to high transfer performance.* + +This model was contributed by [nielsr](https://huggingface.co/nielsr). +The original code can be found [here](https://github.com/google-research/big_transfer). + +## Usage tips + +- BiT models are equivalent to ResNetv2 in terms of architecture, except that: 1) all batch normalization layers are replaced by [group normalization](https://huggingface.co/papers/1803.08494), +2) [weight standardization](https://huggingface.co/papers/1903.10520) is used for convolutional layers. The authors show that the combination of both is useful for training with large batch sizes, and has a significant +impact on transfer learning. + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with BiT. + + + +- [`BitForImageClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb). +- See also: [Image classification task guide](../tasks/image_classification) + +If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + +## BitConfig + +[[autodoc]] BitConfig + +## BitImageProcessor + +[[autodoc]] BitImageProcessor + - preprocess + +## BitImageProcessorFast + +[[autodoc]] BitImageProcessorFast + - preprocess + +## BitModel + +[[autodoc]] BitModel + - forward + +## BitForImageClassification + +[[autodoc]] BitForImageClassification + - forward \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bitnet.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bitnet.md new file mode 100644 index 0000000000000000000000000000000000000000..992bb0b7d807eff65972858d372403682b8802cd --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bitnet.md @@ -0,0 +1,122 @@ + +*This model was released on 2025-04-16 and added to Hugging Face Transformers on 2025-04-28.* + +# BitNet + +## Overview + +Trained on a corpus of 4 trillion tokens, this model demonstrates that native 1-bit LLMs can achieve performance comparable to leading open-weight, full-precision models of similar size, while offering substantial advantages in computational efficiency (memory, energy, latency). + +➡️ **Technical Report:** [BitNet b1.58 2B4T Technical Report](https://huggingface.co/papers/2504.12285) + +➡️ **Official Inference Code:** [microsoft/BitNet (bitnet.cpp)](https://github.com/microsoft/BitNet) + +## Model Variants + +Several versions of the model weights are available on Hugging Face: + +* [**`microsoft/bitnet-b1.58-2B-4T`**](https://huggingface.co/microsoft/bitnet-b1.58-2B-4T): Contains the packed 1.58-bit weights optimized for efficient inference. **Use this for deployment.** + +* [**`microsoft/bitnet-b1.58-2B-4T-bf16`**](https://huggingface.co/microsoft/bitnet-b1.58-2B-4T-bf16): Contains the master weights in BF16 format. **Use this only for training or fine-tuning purposes.** + +* [**`microsoft/bitnet-b1.58-2B-4T-gguf`**](https://huggingface.co/microsoft/bitnet-b1.58-2B-4T-gguf): Contains the model weights in GGUF format, compatible with the `bitnet.cpp` library for CPU inference. + + +### Model Details + + +* **Architecture:** Transformer-based, modified with `BitLinear` layers (BitNet framework). + * Uses Rotary Position Embeddings (RoPE). + * Uses squared ReLU (ReLU²) activation in FFN layers. + * Employs [`subln`](https://proceedings.mlr.press/v202/wang23u.html) normalization. + * No bias terms in linear or normalization layers. +* **Quantization:** Native 1.58-bit weights and 8-bit activations (W1.58A8). + * Weights are quantized to ternary values {-1, 0, +1} using absmean quantization during the forward pass. + * Activations are quantized to 8-bit integers using absmax quantization (per-token). + * **Crucially, the model was *trained from scratch* with this quantization scheme, not post-training quantized.** +* **Parameters:** ~2 Billion +* **Training Tokens:** 4 Trillion +* **Context Length:** Maximum sequence length of **4096 tokens**. + * *Recommendation:* For optimal performance on tasks requiring very long contexts (beyond the pre-training length or for specialized long-reasoning tasks), we recommend performing intermediate long-sequence adaptation/training before the final fine-tuning stage. +* **Training Stages:** + 1. **Pre-training:** Large-scale training on public text/code and synthetic math data using a two-stage learning rate and weight decay schedule. + 2. **Supervised Fine-tuning (SFT):** Fine-tuned on instruction-following and conversational datasets using sum loss aggregation and specific hyperparameter tuning. + 3. **Direct Preference Optimization (DPO):** Aligned with human preferences using preference pairs. +* **Tokenizer:** LLaMA 3 Tokenizer (vocab size: 128,256). + + +## Usage tips + + +**VERY IMPORTANT NOTE ON EFFICIENCY** + +> Please do NOT expect performance efficiency gains (in terms of speed, latency, or energy consumption) when using this model with the standard transformers library. +> +> The current execution paths within transformers do not contain the specialized, highly optimized computational kernels required to leverage the advantages of the BitNet architecture. Running the model via transformers will likely result in inference speeds and energy usage comparable to, or potentially worse than, standard full-precision models within this framework on both CPU and GPU. +> +> While you might observe reduced memory usage due to the quantized weights, the primary computational efficiency benefits are not accessible through this standard transformers usage path. +> +> For achieving the efficiency benefits demonstrated in the technical paper, you MUST use the dedicated C++ implementation: [bitnet.cpp](https://github.com/microsoft/BitNet). + +### Requirements + +```bash +pip install transformers +``` + +### Example + +```python +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +model_id = "microsoft/bitnet-b1.58-2B-4T" + +# Load tokenizer and model +tokenizer = AutoTokenizer.from_pretrained(model_id) +model = AutoModelForCausalLM.from_pretrained( + model_id, + torch_dtype=torch.bfloat16 +) + +# Apply the chat template +messages = [ + {"role": "system", "content": "You are a helpful AI assistant."}, + {"role": "user", "content": "How are you?"}, +] +chat_input = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt").to(model.device) + +# Generate response +chat_outputs = model.generate(chat_input, max_new_tokens=50) +response = tokenizer.decode(chat_outputs[0][chat_input.shape[-1]:], skip_special_tokens=True) # Decode only the response part +print("\nAssistant Response:", response) +``` + + +## BitNetConfig + +[[autodoc]] BitNetConfig + +## BitNetModel + +[[autodoc]] BitNetModel + - forward + +## BitNetForCausalLM + +[[autodoc]] BitNetForCausalLM + - forward diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/blenderbot-small.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/blenderbot-small.md new file mode 100644 index 0000000000000000000000000000000000000000..8cfb47f643844eb834f260eb3b2bf667bf1f4528 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/blenderbot-small.md @@ -0,0 +1,133 @@ + +*This model was released on 2020-04-28 and added to Hugging Face Transformers on 2021-01-05.* + +# Blenderbot Small + +
+PyTorch +TensorFlow +Flax +FlashAttention +SDPA +
+ +Note that [`BlenderbotSmallModel`] and +[`BlenderbotSmallForConditionalGeneration`] are only used in combination with the checkpoint +[facebook/blenderbot-90M](https://huggingface.co/facebook/blenderbot-90M). Larger Blenderbot checkpoints should +instead be used with [`BlenderbotModel`] and +[`BlenderbotForConditionalGeneration`] + +## Overview + +The Blender chatbot model was proposed in [Recipes for building an open-domain chatbot](https://huggingface.co/papers/2004.13637) Stephen Roller, Emily Dinan, Naman Goyal, Da Ju, Mary Williamson, Yinhan Liu, +Jing Xu, Myle Ott, Kurt Shuster, Eric M. Smith, Y-Lan Boureau, Jason Weston on 30 Apr 2020. + +The abstract of the paper is the following: + +*Building open-domain chatbots is a challenging area for machine learning research. While prior work has shown that +scaling neural models in the number of parameters and the size of the data they are trained on gives improved results, +we show that other ingredients are important for a high-performing chatbot. Good conversation requires a number of +skills that an expert conversationalist blends in a seamless way: providing engaging talking points and listening to +their partners, and displaying knowledge, empathy and personality appropriately, while maintaining a consistent +persona. We show that large scale models can learn these skills when given appropriate training data and choice of +generation strategy. We build variants of these recipes with 90M, 2.7B and 9.4B parameter models, and make our models +and code publicly available. Human evaluations show our best models are superior to existing approaches in multi-turn +dialogue in terms of engagingness and humanness measurements. We then discuss the limitations of this work by analyzing +failure cases of our models.* + +This model was contributed by [patrickvonplaten](https://huggingface.co/patrickvonplaten). The authors' code can be +found [here](https://github.com/facebookresearch/ParlAI). + +## Usage tips + +Blenderbot Small is a model with absolute position embeddings so it's usually advised to pad the inputs on the right rather than +the left. + + +## Resources + +- [Causal language modeling task guide](../tasks/language_modeling) +- [Translation task guide](../tasks/translation) +- [Summarization task guide](../tasks/summarization) + +## BlenderbotSmallConfig + +[[autodoc]] BlenderbotSmallConfig + +## BlenderbotSmallTokenizer + +[[autodoc]] BlenderbotSmallTokenizer + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - save_vocabulary + +## BlenderbotSmallTokenizerFast + +[[autodoc]] BlenderbotSmallTokenizerFast + + + + +## BlenderbotSmallModel + +[[autodoc]] BlenderbotSmallModel + - forward + +## BlenderbotSmallForConditionalGeneration + +[[autodoc]] BlenderbotSmallForConditionalGeneration + - forward + +## BlenderbotSmallForCausalLM + +[[autodoc]] BlenderbotSmallForCausalLM + - forward + + + + +## TFBlenderbotSmallModel + +[[autodoc]] TFBlenderbotSmallModel + - call + +## TFBlenderbotSmallForConditionalGeneration + +[[autodoc]] TFBlenderbotSmallForConditionalGeneration + - call + + + + +## FlaxBlenderbotSmallModel + +[[autodoc]] FlaxBlenderbotSmallModel + - __call__ + - encode + - decode + +## FlaxBlenderbotForConditionalGeneration + +[[autodoc]] FlaxBlenderbotSmallForConditionalGeneration + - __call__ + - encode + - decode + + + diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/blenderbot.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/blenderbot.md new file mode 100644 index 0000000000000000000000000000000000000000..d4aad114c84394e29d0d042255c040f506b09471 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/blenderbot.md @@ -0,0 +1,154 @@ + +*This model was released on 2020-04-28 and added to Hugging Face Transformers on 2020-11-16.* + +# Blenderbot + +
+PyTorch +TensorFlow +Flax +FlashAttention +SDPA +
+ +## Overview + +The Blender chatbot model was proposed in [Recipes for building an open-domain chatbot](https://huggingface.co/papers/2004.13637) Stephen Roller, Emily Dinan, Naman Goyal, Da Ju, Mary Williamson, Yinhan Liu, +Jing Xu, Myle Ott, Kurt Shuster, Eric M. Smith, Y-Lan Boureau, Jason Weston on 30 Apr 2020. + +The abstract of the paper is the following: + +*Building open-domain chatbots is a challenging area for machine learning research. While prior work has shown that +scaling neural models in the number of parameters and the size of the data they are trained on gives improved results, +we show that other ingredients are important for a high-performing chatbot. Good conversation requires a number of +skills that an expert conversationalist blends in a seamless way: providing engaging talking points and listening to +their partners, and displaying knowledge, empathy and personality appropriately, while maintaining a consistent +persona. We show that large scale models can learn these skills when given appropriate training data and choice of +generation strategy. We build variants of these recipes with 90M, 2.7B and 9.4B parameter models, and make our models +and code publicly available. Human evaluations show our best models are superior to existing approaches in multi-turn +dialogue in terms of engagingness and humanness measurements. We then discuss the limitations of this work by analyzing +failure cases of our models.* + +This model was contributed by [sshleifer](https://huggingface.co/sshleifer). The authors' code can be found [here](https://github.com/facebookresearch/ParlAI) . + +## Usage tips and example + +Blenderbot is a model with absolute position embeddings so it's usually advised to pad the inputs on the right +rather than the left. + +An example: + +```python +>>> from transformers import BlenderbotTokenizer, BlenderbotForConditionalGeneration + +>>> mname = "facebook/blenderbot-400M-distill" +>>> model = BlenderbotForConditionalGeneration.from_pretrained(mname) +>>> tokenizer = BlenderbotTokenizer.from_pretrained(mname) +>>> UTTERANCE = "My friends are cool but they eat too many carbs." +>>> inputs = tokenizer([UTTERANCE], return_tensors="pt") +>>> reply_ids = model.generate(**inputs) +>>> print(tokenizer.batch_decode(reply_ids)) +[" That's unfortunate. Are they trying to lose weight or are they just trying to be healthier?"] +``` + +## Implementation Notes + +- Blenderbot uses a standard [seq2seq model transformer](https://huggingface.co/papers/1706.03762) based architecture. +- Available checkpoints can be found in the [model hub](https://huggingface.co/models?search=blenderbot). +- This is the *default* Blenderbot model class. However, some smaller checkpoints, such as + `facebook/blenderbot_small_90M`, have a different architecture and consequently should be used with + [BlenderbotSmall](blenderbot-small). + + +## Resources + +- [Causal language modeling task guide](../tasks/language_modeling) +- [Translation task guide](../tasks/translation) +- [Summarization task guide](../tasks/summarization) + +## BlenderbotConfig + +[[autodoc]] BlenderbotConfig + +## BlenderbotTokenizer + +[[autodoc]] BlenderbotTokenizer + - build_inputs_with_special_tokens + +## BlenderbotTokenizerFast + +[[autodoc]] BlenderbotTokenizerFast + - build_inputs_with_special_tokens + + + + + +## BlenderbotModel + +See [`~transformers.BartModel`] for arguments to *forward* and *generate* + +[[autodoc]] BlenderbotModel + - forward + +## BlenderbotForConditionalGeneration + +See [`~transformers.BartForConditionalGeneration`] for arguments to *forward* and *generate* + +[[autodoc]] BlenderbotForConditionalGeneration + - forward + +## BlenderbotForCausalLM + +[[autodoc]] BlenderbotForCausalLM + - forward + + + + +## TFBlenderbotModel + +[[autodoc]] TFBlenderbotModel + - call + +## TFBlenderbotForConditionalGeneration + +[[autodoc]] TFBlenderbotForConditionalGeneration + - call + + + + +## FlaxBlenderbotModel + +[[autodoc]] FlaxBlenderbotModel + - __call__ + - encode + - decode + +## FlaxBlenderbotForConditionalGeneration + +[[autodoc]] FlaxBlenderbotForConditionalGeneration + - __call__ + - encode + - decode + + + + + diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/blip-2.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/blip-2.md new file mode 100644 index 0000000000000000000000000000000000000000..fe4e939c2dc8610b31c6085af6de9b48cb3ed624 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/blip-2.md @@ -0,0 +1,112 @@ + +*This model was released on 2023-01-30 and added to Hugging Face Transformers on 2023-02-09.* + +# BLIP-2 + +
+PyTorch +
+ +## Overview + +The BLIP-2 model was proposed in [BLIP-2: Bootstrapping Language-Image Pre-training with Frozen Image Encoders and Large Language Models](https://huggingface.co/papers/2301.12597) by +Junnan Li, Dongxu Li, Silvio Savarese, Steven Hoi. BLIP-2 leverages frozen pre-trained image encoders and large language models (LLMs) by training a lightweight, 12-layer Transformer +encoder in between them, achieving state-of-the-art performance on various vision-language tasks. Most notably, BLIP-2 improves upon [Flamingo](https://huggingface.co/papers/2204.14198), an 80 billion parameter model, by 8.7% +on zero-shot VQAv2 with 54x fewer trainable parameters. + +The abstract from the paper is the following: + +*The cost of vision-and-language pre-training has become increasingly prohibitive due to end-to-end training of large-scale models. This paper proposes BLIP-2, a generic and efficient pre-training strategy that bootstraps vision-language pre-training from off-the-shelf frozen pre-trained image encoders and frozen large language models. BLIP-2 bridges the modality gap with a lightweight Querying Transformer, which is pre-trained in two stages. The first stage bootstraps vision-language representation learning from a frozen image encoder. The second stage bootstraps vision-to-language generative learning from a frozen language model. BLIP-2 achieves state-of-the-art performance on various vision-language tasks, despite having significantly fewer trainable parameters than existing methods. For example, our model outperforms Flamingo80B by 8.7% on zero-shot VQAv2 with 54x fewer trainable parameters. We also demonstrate the model's emerging capabilities of zero-shot image-to-text generation that can follow natural language instructions.* + + + + BLIP-2 architecture. Taken from the original paper. + +This model was contributed by [nielsr](https://huggingface.co/nielsr). +The original code can be found [here](https://github.com/salesforce/LAVIS/tree/5ee63d688ba4cebff63acee04adaef2dee9af207). + +## Usage tips + +- BLIP-2 can be used for conditional text generation given an image and an optional text prompt. At inference time, it's recommended to use the [`generate`] method. +- One can use [`Blip2Processor`] to prepare images for the model, and decode the predicted tokens ID's back to text. + +> [!NOTE] +> BLIP models after release v4.46 will raise warnings about adding `processor.num_query_tokens = {{num_query_tokens}}` and expand model embeddings layer to add special `` token. It is strongly recommended to add the attributes to the processor if you own the model checkpoint, or open a PR if it is not owned by you. Adding these attributes means that BLIP will add the number of query tokens required per image and expand the text with as many `` placeholders as there will be query tokens. Usually it is around 500 tokens per image, so make sure that the text is not truncated as otherwise there will be failure when merging the embeddings. +The attributes can be obtained from model config, as `model.config.num_query_tokens` and model embeddings expansion can be done by following [this link](https://gist.github.com/zucchini-nlp/e9f20b054fa322f84ac9311d9ab67042). + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with BLIP-2. + +- Demo notebooks for BLIP-2 for image captioning, visual question answering (VQA) and chat-like conversations can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/BLIP-2). + +If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + +## Blip2Config + +[[autodoc]] Blip2Config + - from_vision_qformer_text_configs + +## Blip2VisionConfig + +[[autodoc]] Blip2VisionConfig + +## Blip2QFormerConfig + +[[autodoc]] Blip2QFormerConfig + +## Blip2Processor + +[[autodoc]] Blip2Processor + +## Blip2VisionModel + +[[autodoc]] Blip2VisionModel + - forward + +## Blip2QFormerModel + +[[autodoc]] Blip2QFormerModel + - forward + +## Blip2Model + +[[autodoc]] Blip2Model + - forward + - get_text_features + - get_image_features + - get_qformer_features + +## Blip2ForConditionalGeneration + +[[autodoc]] Blip2ForConditionalGeneration + - forward + - generate + +## Blip2ForImageTextRetrieval + +[[autodoc]] Blip2ForImageTextRetrieval + - forward + +## Blip2TextModelWithProjection + +[[autodoc]] Blip2TextModelWithProjection + +## Blip2VisionModelWithProjection + +[[autodoc]] Blip2VisionModelWithProjection diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/blip.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/blip.md new file mode 100644 index 0000000000000000000000000000000000000000..5273589a1454c0a31017651f59d06dbe6be907f8 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/blip.md @@ -0,0 +1,198 @@ + +*This model was released on 2022-01-28 and added to Hugging Face Transformers on 2022-12-21.* + +
+
+ PyTorch + TensorFlow +
+
+ +# BLIP + +[BLIP](https://huggingface.co/papers/2201.12086) (Bootstrapped Language-Image Pretraining) is a vision-language pretraining (VLP) framework designed for *both* understanding and generation tasks. Most existing pretrained models are only good at one or the other. It uses a captioner to generate captions and a filter to remove the noisy captions. This increases training data quality and more effectively uses the messy web data. + + +You can find all the original BLIP checkpoints under the [BLIP](https://huggingface.co/collections/Salesforce/blip-models-65242f40f1491fbf6a9e9472) collection. + +> [!TIP] +> This model was contributed by [ybelkada](https://huggingface.co/ybelkada). +> +> Click on the BLIP models in the right sidebar for more examples of how to apply BLIP to different vision language tasks. + +The example below demonstrates how to visual question answering with [`Pipeline`] or the [`AutoModel`] class. + + + + +```python +import torch +from transformers import pipeline + +pipeline = pipeline( + task="visual-question-answering", + model="Salesforce/blip-vqa-base", + torch_dtype=torch.float16, + device=0 +) +url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg" +pipeline(question="What is the weather in this image?", image=url) +``` + + + + +```python +import requests +import torch +from PIL import Image +from transformers import AutoProcessor, AutoModelForVisualQuestionAnswering + +processor = AutoProcessor.from_pretrained("Salesforce/blip-vqa-base") +model = AutoModelForVisualQuestionAnswering.from_pretrained( + "Salesforce/blip-vqa-base", + torch_dtype=torch.float16, + device_map="auto" +) + +url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg" +image = Image.open(requests.get(url, stream=True).raw) + +question = "What is the weather in this image?" +inputs = processor(images=image, text=question, return_tensors="pt").to(model.device, torch.float16) + +output = model.generate(**inputs) +processor.batch_decode(output, skip_special_tokens=True)[0] +``` + + + + +## Resources + +Refer to this [notebook](https://github.com/huggingface/notebooks/blob/main/examples/image_captioning_blip.ipynb) to learn how to fine-tune BLIP for image captioning on a custom dataset. + +## BlipConfig + +[[autodoc]] BlipConfig + - from_text_vision_configs + +## BlipTextConfig + +[[autodoc]] BlipTextConfig + +## BlipVisionConfig + +[[autodoc]] BlipVisionConfig + +## BlipProcessor + +[[autodoc]] BlipProcessor + +## BlipImageProcessor + +[[autodoc]] BlipImageProcessor + - preprocess + +## BlipImageProcessorFast + +[[autodoc]] BlipImageProcessorFast + - preprocess + + + + +## BlipModel + +`BlipModel` is going to be deprecated in future versions, please use `BlipForConditionalGeneration`, `BlipForImageTextRetrieval` or `BlipForQuestionAnswering` depending on your usecase. + +[[autodoc]] BlipModel + - forward + - get_text_features + - get_image_features + +## BlipTextModel + +[[autodoc]] BlipTextModel + - forward + +## BlipTextLMHeadModel + +[[autodoc]] BlipTextLMHeadModel +- forward + +## BlipVisionModel + +[[autodoc]] BlipVisionModel + - forward + +## BlipForConditionalGeneration + +[[autodoc]] BlipForConditionalGeneration + - forward + +## BlipForImageTextRetrieval + +[[autodoc]] BlipForImageTextRetrieval + - forward + +## BlipForQuestionAnswering + +[[autodoc]] BlipForQuestionAnswering + - forward + + + + +## TFBlipModel + +[[autodoc]] TFBlipModel + - call + - get_text_features + - get_image_features + +## TFBlipTextModel + +[[autodoc]] TFBlipTextModel + - call + +## TFBlipTextLMHeadModel + +[[autodoc]] TFBlipTextLMHeadModel +- forward + +## TFBlipVisionModel + +[[autodoc]] TFBlipVisionModel + - call + +## TFBlipForConditionalGeneration + +[[autodoc]] TFBlipForConditionalGeneration + - call + +## TFBlipForImageTextRetrieval + +[[autodoc]] TFBlipForImageTextRetrieval + - call + +## TFBlipForQuestionAnswering + +[[autodoc]] TFBlipForQuestionAnswering + - call + + diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bloom.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bloom.md new file mode 100644 index 0000000000000000000000000000000000000000..a5cce1a7e81732d6f48205b7979d8ee78f913db9 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bloom.md @@ -0,0 +1,116 @@ + +*This model was released on 2022-11-09 and added to Hugging Face Transformers on 2022-06-09.* + +# BLOOM + +
+PyTorch +Flax +
+ +## Overview + +The [BLOOM](https://huggingface.co/papers/2211.05100) model has been proposed with its various versions through the [BigScience Workshop](https://bigscience.huggingface.co/). BigScience is inspired by other open science initiatives where researchers have pooled their time and resources to collectively achieve a higher impact. +The architecture of BLOOM is essentially similar to GPT3 (auto-regressive model for next token prediction), but has been trained on 46 different languages and 13 programming languages. +Several smaller versions of the models have been trained on the same dataset. BLOOM is available in the following versions: + +- [bloom-560m](https://huggingface.co/bigscience/bloom-560m) +- [bloom-1b1](https://huggingface.co/bigscience/bloom-1b1) +- [bloom-1b7](https://huggingface.co/bigscience/bloom-1b7) +- [bloom-3b](https://huggingface.co/bigscience/bloom-3b) +- [bloom-7b1](https://huggingface.co/bigscience/bloom-7b1) +- [bloom](https://huggingface.co/bigscience/bloom) (176B parameters) + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with BLOOM. If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + + + +- [`BloomForCausalLM`] is supported by this [causal language modeling example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/language-modeling#gpt-2gpt-and-causal-language-modeling) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling.ipynb). + +See also: +- [Causal language modeling task guide](../tasks/language_modeling) +- [Text classification task guide](../tasks/sequence_classification) +- [Token classification task guide](../tasks/token_classification) +- [Question answering task guide](../tasks/question_answering) + + +⚡️ Inference +- A blog on [Optimization story: Bloom inference](https://huggingface.co/blog/bloom-inference-optimization). +- A blog on [Incredibly Fast BLOOM Inference with DeepSpeed and Accelerate](https://huggingface.co/blog/bloom-inference-pytorch-scripts). + +⚙️ Training +- A blog on [The Technology Behind BLOOM Training](https://huggingface.co/blog/bloom-megatron-deepspeed). + +## BloomConfig + +[[autodoc]] BloomConfig + - all + +## BloomTokenizerFast + +[[autodoc]] BloomTokenizerFast + - all + + + + + +## BloomModel + +[[autodoc]] BloomModel + - forward + +## BloomForCausalLM + +[[autodoc]] BloomForCausalLM + - forward + +## BloomForSequenceClassification + +[[autodoc]] BloomForSequenceClassification + - forward + +## BloomForTokenClassification + +[[autodoc]] BloomForTokenClassification + - forward + +## BloomForQuestionAnswering + +[[autodoc]] BloomForQuestionAnswering + - forward + + + + +## FlaxBloomModel + +[[autodoc]] FlaxBloomModel + - __call__ + +## FlaxBloomForCausalLM + +[[autodoc]] FlaxBloomForCausalLM + - __call__ + + + + + diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bort.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bort.md new file mode 100644 index 0000000000000000000000000000000000000000..286559227e2fb127653ca94a441b1f2649d139c9 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bort.md @@ -0,0 +1,65 @@ + +*This model was released on 2020-10-20 and added to Hugging Face Transformers on 2023-06-20.* + +# BORT + +
+PyTorch +TensorFlow +Flax +
+ + + +This model is in maintenance mode only, we do not accept any new PRs changing its code. + +If you run into any issues running this model, please reinstall the last version that supported this model: v4.30.0. +You can do so by running the following command: `pip install -U transformers==4.30.0`. + + + +## Overview + +The BORT model was proposed in [Optimal Subarchitecture Extraction for BERT](https://huggingface.co/papers/2010.10499) by +Adrian de Wynter and Daniel J. Perry. It is an optimal subset of architectural parameters for the BERT, which the +authors refer to as "Bort". + +The abstract from the paper is the following: + +*We extract an optimal subset of architectural parameters for the BERT architecture from Devlin et al. (2018) by +applying recent breakthroughs in algorithms for neural architecture search. This optimal subset, which we refer to as +"Bort", is demonstrably smaller, having an effective (that is, not counting the embedding layer) size of 5.5% the +original BERT-large architecture, and 16% of the net size. Bort is also able to be pretrained in 288 GPU hours, which +is 1.2% of the time required to pretrain the highest-performing BERT parametric architectural variant, RoBERTa-large +(Liu et al., 2019), and about 33% of that of the world-record, in GPU hours, required to train BERT-large on the same +hardware. It is also 7.9x faster on a CPU, as well as being better performing than other compressed variants of the +architecture, and some of the non-compressed variants: it obtains performance improvements of between 0.3% and 31%, +absolute, with respect to BERT-large, on multiple public natural language understanding (NLU) benchmarks.* + +This model was contributed by [stefan-it](https://huggingface.co/stefan-it). The original code can be found [here](https://github.com/alexa/bort/). + +## Usage tips + +- BORT's model architecture is based on BERT, refer to [BERT's documentation page](bert) for the + model's API reference as well as usage examples. +- BORT uses the RoBERTa tokenizer instead of the BERT tokenizer, refer to [RoBERTa's documentation page](roberta) for the tokenizer's API reference as well as usage examples. +- BORT requires a specific fine-tuning algorithm, called [Agora](https://adewynter.github.io/notes/bort_algorithms_and_applications.html#fine-tuning-with-algebraic-topology) , + that is sadly not open-sourced yet. It would be very useful for the community, if someone tries to implement the + algorithm to make BORT fine-tuning work. + + diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bridgetower.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bridgetower.md new file mode 100644 index 0000000000000000000000000000000000000000..6a2b09e263ab05721b56bbe502a639a8d846bf44 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bridgetower.md @@ -0,0 +1,180 @@ + +*This model was released on 2022-06-17 and added to Hugging Face Transformers on 2023-01-25.* + +# BridgeTower + +
+PyTorch +
+ +## Overview + +The BridgeTower model was proposed in [BridgeTower: Building Bridges Between Encoders in Vision-Language Representative Learning](https://huggingface.co/papers/2206.08657) by Xiao Xu, Chenfei Wu, Shachar Rosenman, Vasudev Lal, Wanxiang Che, Nan Duan. The goal of this model is to build a +bridge between each uni-modal encoder and the cross-modal encoder to enable comprehensive and detailed interaction at each layer of the cross-modal encoder thus achieving remarkable performance on various downstream tasks with almost negligible additional performance and computational costs. + +This paper has been accepted to the [AAAI'23](https://aaai.org/Conferences/AAAI-23/) conference. + +The abstract from the paper is the following: + +*Vision-Language (VL) models with the TWO-TOWER architecture have dominated visual-language representation learning in recent years. +Current VL models either use lightweight uni-modal encoders and learn to extract, align and fuse both modalities simultaneously in a deep cross-modal encoder, or feed the last-layer uni-modal representations from the deep pre-trained uni-modal encoders into the top cross-modal encoder. +Both approaches potentially restrict vision-language representation learning and limit model performance. In this paper, we propose BRIDGETOWER, which introduces multiple bridge layers that build a connection between the top layers of uni-modal encoders and each layer of the crossmodal encoder. +This enables effective bottom-up cross-modal alignment and fusion between visual and textual representations of different semantic levels of pre-trained uni-modal encoders in the cross-modal encoder. Pre-trained with only 4M images, BRIDGETOWER achieves state-of-the-art performance on various downstream vision-language tasks. +In particular, on the VQAv2 test-std set, BRIDGETOWER achieves an accuracy of 78.73%, outperforming the previous state-of-the-art model METER by 1.09% with the same pre-training data and almost negligible additional parameters and computational costs. +Notably, when further scaling the model, BRIDGETOWER achieves an accuracy of 81.15%, surpassing models that are pre-trained on orders-of-magnitude larger datasets.* + + + + BridgeTower architecture. Taken from the original paper. + +This model was contributed by [Anahita Bhiwandiwalla](https://huggingface.co/anahita-b), [Tiep Le](https://huggingface.co/Tile) and [Shaoyen Tseng](https://huggingface.co/shaoyent). The original code can be found [here](https://github.com/microsoft/BridgeTower). + +## Usage tips and examples + +BridgeTower consists of a visual encoder, a textual encoder and cross-modal encoder with multiple lightweight bridge layers. +The goal of this approach was to build a bridge between each uni-modal encoder and the cross-modal encoder to enable comprehensive and detailed interaction at each layer of the cross-modal encoder. +In principle, one can apply any visual, textual or cross-modal encoder in the proposed architecture. + +The [`BridgeTowerProcessor`] wraps [`RobertaTokenizer`] and [`BridgeTowerImageProcessor`] into a single instance to both +encode the text and prepare the images respectively. + +The following example shows how to run contrastive learning using [`BridgeTowerProcessor`] and [`BridgeTowerForContrastiveLearning`]. +```python +>>> from transformers import BridgeTowerProcessor, BridgeTowerForContrastiveLearning +>>> import requests +>>> from PIL import Image + +>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" +>>> image = Image.open(requests.get(url, stream=True).raw) +>>> texts = ["An image of two cats chilling on a couch", "A football player scoring a goal"] + +>>> processor = BridgeTowerProcessor.from_pretrained("BridgeTower/bridgetower-large-itm-mlm-itc") +>>> model = BridgeTowerForContrastiveLearning.from_pretrained("BridgeTower/bridgetower-large-itm-mlm-itc") + +>>> # forward pass +>>> scores = dict() +>>> for text in texts: +... # prepare inputs +... encoding = processor(image, text, return_tensors="pt") +... outputs = model(**encoding) +... scores[text] = outputs +``` + +The following example shows how to run image-text retrieval using [`BridgeTowerProcessor`] and [`BridgeTowerForImageAndTextRetrieval`]. +```python +>>> from transformers import BridgeTowerProcessor, BridgeTowerForImageAndTextRetrieval +>>> import requests +>>> from PIL import Image + +>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" +>>> image = Image.open(requests.get(url, stream=True).raw) +>>> texts = ["An image of two cats chilling on a couch", "A football player scoring a goal"] + +>>> processor = BridgeTowerProcessor.from_pretrained("BridgeTower/bridgetower-base-itm-mlm") +>>> model = BridgeTowerForImageAndTextRetrieval.from_pretrained("BridgeTower/bridgetower-base-itm-mlm") + +>>> # forward pass +>>> scores = dict() +>>> for text in texts: +... # prepare inputs +... encoding = processor(image, text, return_tensors="pt") +... outputs = model(**encoding) +... scores[text] = outputs.logits[0, 1].item() +``` + +The following example shows how to run masked language modeling using [`BridgeTowerProcessor`] and [`BridgeTowerForMaskedLM`]. + +```python +>>> from transformers import BridgeTowerProcessor, BridgeTowerForMaskedLM +>>> from PIL import Image +>>> import requests + +>>> url = "http://images.cocodataset.org/val2017/000000360943.jpg" +>>> image = Image.open(requests.get(url, stream=True).raw).convert("RGB") +>>> text = "a looking out of the window" + +>>> processor = BridgeTowerProcessor.from_pretrained("BridgeTower/bridgetower-base-itm-mlm") +>>> model = BridgeTowerForMaskedLM.from_pretrained("BridgeTower/bridgetower-base-itm-mlm") + +>>> # prepare inputs +>>> encoding = processor(image, text, return_tensors="pt") + +>>> # forward pass +>>> outputs = model(**encoding) + +>>> results = processor.decode(outputs.logits.argmax(dim=-1).squeeze(0).tolist()) + +>>> print(results) +.a cat looking out of the window. +``` + +Tips: + +- This implementation of BridgeTower uses [`RobertaTokenizer`] to generate text embeddings and OpenAI's CLIP/ViT model to compute visual embeddings. +- Checkpoints for pre-trained [bridgeTower-base](https://huggingface.co/BridgeTower/bridgetower-base) and [bridgetower masked language modeling and image text matching](https://huggingface.co/BridgeTower/bridgetower-base-itm-mlm) are released. +- Please refer to [Table 5](https://huggingface.co/papers/2206.08657) for BridgeTower's performance on Image Retrieval and other down stream tasks. +- The PyTorch version of this model is only available in torch 1.10 and higher. + + +## BridgeTowerConfig + +[[autodoc]] BridgeTowerConfig + +## BridgeTowerTextConfig + +[[autodoc]] BridgeTowerTextConfig + +## BridgeTowerVisionConfig + +[[autodoc]] BridgeTowerVisionConfig + +## BridgeTowerImageProcessor + +[[autodoc]] BridgeTowerImageProcessor + - preprocess + +## BridgeTowerImageProcessorFast + +[[autodoc]] BridgeTowerImageProcessorFast + - preprocess + +## BridgeTowerProcessor + +[[autodoc]] BridgeTowerProcessor + - __call__ + +## BridgeTowerModel + +[[autodoc]] BridgeTowerModel + - forward + +## BridgeTowerForContrastiveLearning + +[[autodoc]] BridgeTowerForContrastiveLearning + - forward + +## BridgeTowerForMaskedLM + +[[autodoc]] BridgeTowerForMaskedLM + - forward + +## BridgeTowerForImageAndTextRetrieval + +[[autodoc]] BridgeTowerForImageAndTextRetrieval + - forward + diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bros.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bros.md new file mode 100644 index 0000000000000000000000000000000000000000..aeb3dd76e52b1f2ca0732df8b57aa8ac8677aacd --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/bros.md @@ -0,0 +1,119 @@ + +*This model was released on 2021-08-10 and added to Hugging Face Transformers on 2023-09-15.* + +# BROS + +
+PyTorch +
+ +## Overview + +The BROS model was proposed in [BROS: A Pre-trained Language Model Focusing on Text and Layout for Better Key Information Extraction from Documents](https://huggingface.co/papers/2108.04539) by Teakgyu Hong, Donghyun Kim, Mingi Ji, Wonseok Hwang, Daehyun Nam, Sungrae Park. + +BROS stands for *BERT Relying On Spatiality*. It is an encoder-only Transformer model that takes a sequence of tokens and their bounding boxes as inputs and outputs a sequence of hidden states. BROS encode relative spatial information instead of using absolute spatial information. + +It is pre-trained with two objectives: a token-masked language modeling objective (TMLM) used in BERT, and a novel area-masked language modeling objective (AMLM) +In TMLM, tokens are randomly masked, and the model predicts the masked tokens using spatial information and other unmasked tokens. +AMLM is a 2D version of TMLM. It randomly masks text tokens and predicts with the same information as TMLM, but it masks text blocks (areas). + +`BrosForTokenClassification` has a simple linear layer on top of BrosModel. It predicts the label of each token. +`BrosSpadeEEForTokenClassification` has an `initial_token_classifier` and `subsequent_token_classifier` on top of BrosModel. `initial_token_classifier` is used to predict the first token of each entity, and `subsequent_token_classifier` is used to predict the next token of within entity. `BrosSpadeELForTokenClassification` has an `entity_linker` on top of BrosModel. `entity_linker` is used to predict the relation between two entities. + +`BrosForTokenClassification` and `BrosSpadeEEForTokenClassification` essentially perform the same job. However, `BrosForTokenClassification` assumes input tokens are perfectly serialized (which is very challenging task since they exist in a 2D space), while `BrosSpadeEEForTokenClassification` allows for more flexibility in handling serialization errors as it predicts next connection tokens from one token. + +`BrosSpadeELForTokenClassification` perform the intra-entity linking task. It predicts relation from one token (of one entity) to another token (of another entity) if these two entities share some relation. + +BROS achieves comparable or better result on Key Information Extraction (KIE) benchmarks such as FUNSD, SROIE, CORD and SciTSR, without relying on explicit visual features. + +The abstract from the paper is the following: + +*Key information extraction (KIE) from document images requires understanding the contextual and spatial semantics of texts in two-dimensional (2D) space. Many recent studies try to solve the task by developing pre-trained language models focusing on combining visual features from document images with texts and their layout. On the other hand, this paper tackles the problem by going back to the basic: effective combination of text and layout. Specifically, we propose a pre-trained language model, named BROS (BERT Relying On Spatiality), that encodes relative positions of texts in 2D space and learns from unlabeled documents with area-masking strategy. With this optimized training scheme for understanding texts in 2D space, BROS shows comparable or better performance compared to previous methods on four KIE benchmarks (FUNSD, SROIE*, CORD, and SciTSR) without relying on visual features. This paper also reveals two real-world challenges in KIE tasks-(1) minimizing the error from incorrect text ordering and (2) efficient learning from fewer downstream examples-and demonstrates the superiority of BROS over previous methods.* + +This model was contributed by [jinho8345](https://huggingface.co/jinho8345). The original code can be found [here](https://github.com/clovaai/bros). + +## Usage tips and examples + +- [`~transformers.BrosModel.forward`] requires `input_ids` and `bbox` (bounding box). Each bounding box should be in (x0, y0, x1, y1) format (top-left corner, bottom-right corner). Obtaining of Bounding boxes depends on external OCR system. The `x` coordinate should be normalized by document image width, and the `y` coordinate should be normalized by document image height. + +```python +def expand_and_normalize_bbox(bboxes, doc_width, doc_height): + # here, bboxes are numpy array + + # Normalize bbox -> 0 ~ 1 + bboxes[:, [0, 2]] = bboxes[:, [0, 2]] / width + bboxes[:, [1, 3]] = bboxes[:, [1, 3]] / height +``` + +- [`~transformers.BrosForTokenClassification.forward`, `~transformers.BrosSpadeEEForTokenClassification.forward`, `~transformers.BrosSpadeEEForTokenClassification.forward`] require not only `input_ids` and `bbox` but also `box_first_token_mask` for loss calculation. It is a mask to filter out non-first tokens of each box. You can obtain this mask by saving start token indices of bounding boxes when creating `input_ids` from words. You can make `box_first_token_mask` with following code, + + +```python +def make_box_first_token_mask(bboxes, words, tokenizer, max_seq_length=512): + + box_first_token_mask = np.zeros(max_seq_length, dtype=np.bool_) + + # encode(tokenize) each word from words (list[str]) + input_ids_list: list[list[int]] = [tokenizer.encode(e, add_special_tokens=False) for e in words] + + # get the length of each box + tokens_length_list: list[int] = [len(l) for l in input_ids_list] + + box_end_token_indices = np.array(list(itertools.accumulate(tokens_length_list))) + box_start_token_indices = box_end_token_indices - np.array(tokens_length_list) + + # filter out the indices that are out of max_seq_length + box_end_token_indices = box_end_token_indices[box_end_token_indices < max_seq_length - 1] + if len(box_start_token_indices) > len(box_end_token_indices): + box_start_token_indices = box_start_token_indices[: len(box_end_token_indices)] + + # set box_start_token_indices to True + box_first_token_mask[box_start_token_indices] = True + + return box_first_token_mask + +``` + +## Resources + +- Demo scripts can be found [here](https://github.com/clovaai/bros). + +## BrosConfig + +[[autodoc]] BrosConfig + +## BrosProcessor + +[[autodoc]] BrosProcessor + - __call__ + +## BrosModel + +[[autodoc]] BrosModel + - forward + + +## BrosForTokenClassification + +[[autodoc]] BrosForTokenClassification + - forward + +## BrosSpadeEEForTokenClassification + +[[autodoc]] BrosSpadeEEForTokenClassification + - forward + +## BrosSpadeELForTokenClassification + +[[autodoc]] BrosSpadeELForTokenClassification + - forward diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/byt5.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/byt5.md new file mode 100644 index 0000000000000000000000000000000000000000..b2fca1939386d96bec28e0517e0368f537d1ea79 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/byt5.md @@ -0,0 +1,141 @@ + +*This model was released on 2021-05-28 and added to Hugging Face Transformers on 2021-06-01.* +
+
+ PyTorch + TensorFlow + Flax +
+
+ +# ByT5 + +[ByT5](https://huggingface.co/papers/2105.13626) is tokenizer-free version of the [T5](./t5) model designed to works directly on raw UTF-8 bytes. This means it can process any language, more robust to noise like typos, and simpler to use because it doesn't require a preprocessing pipeline. + +You can find all the original ByT5 checkpoints under the [Google](https://huggingface.co/google?search_models=byt5) organization. + +> [!TIP] +> Refer to the [T5](./t5) docs for more examples of how to apply ByT5 to different language tasks. + +The example below demonstrates how to generate text with [`Pipeline`], [`AutoModel`] and from the command line. + + + + +```python +import torch +from transformers import pipeline + +pipeline = pipeline( + task="text2text-generation", + model="google/byt5-small", + torch_dtype=torch.float16, + device=0 +) +pipeline("translate English to French: The weather is nice today") +``` + + + + +```python +import torch +from transformers import AutoModelForSeq2SeqLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained( + "google/byt5-small" +) +model = AutoModelForSeq2SeqLM.from_pretrained( + "google/byt5-small", + torch_dtype=torch.float16, + device_map="auto" +) + +input_ids = tokenizer("summarize: Photosynthesis is the process by which plants, algae, and some bacteria convert light energy into chemical energy.", return_tensors="pt").to(model.device) + +output = model.generate(**input_ids) +print(tokenizer.decode(output[0], skip_special_tokens=True)) +``` + + + + +```bash +echo -e "translate English to French: Life is beautiful." | transformers-cli run --task text2text-generation --model google/byt5-small --device 0 +``` + + + + +## Quantization + +Quantization reduces the memory burden of large models by representing the weights in a lower precision. Refer to the [Quantization](../quantization/overview) overview for more available quantization backends. + +The example below uses [torchao](../quantization/torchao) to only quantize the weights to int4. + +```python +# pip install torchao +import torch +from transformers import TorchAoConfig, AutoModelForSeq2SeqLM, AutoTokenizer + +quantization_config = TorchAoConfig("int4_weight_only", group_size=128) + +model = AutoModelForSeq2SeqLM.from_pretrained( + "google/byt5-xl", + torch_dtype=torch.bfloat16, + device_map="auto", + quantization_config=quantization_config +) + +tokenizer = AutoTokenizer.from_pretrained("google/byt5-xl") +input_ids = tokenizer("translate English to French: The weather is nice today.", return_tensors="pt").to(model.device) + +output = model.generate(**input_ids) +print(tokenizer.decode(output[0], skip_special_tokens=True)) +``` + +## Notes + +- It is recommended to use the tokenizer for batched inference and training. +- The example below shows how to use the model without a tokenizer. + + ```python + import torch + from transformers import AutoModelForSeq2SeqLM + + model = AutoModelForSeq2SeqLM.from_pretrained("google/byt5-small") + + num_special_tokens = 3 + + input_ids = torch.tensor([list("Life is like a box of chocolates.".encode("utf-8"))]) + num_special_tokens + labels = torch.tensor([list("La vie est comme une boîte de chocolat.".encode("utf-8"))]) + num_special_tokens + loss = model(input_ids, labels=labels).loss + loss.item() + ``` + +- ByT5 uses the top byte values (258, 257, etc.) for masking instead of sentinel tokens like `{extra_id_0}`. + + ```python + # Example: character-level denoising with mask tokens + input_ids = tokenizer("The dog chases a ball in the park.").input_ids + masked_input = torch.tensor([input_ids[:8] + [258] + input_ids[14:21] + [257] + input_ids[28:]]) + output = model.generate(masked_input, max_length=100) + ``` + +## ByT5Tokenizer + +[[autodoc]] ByT5Tokenizer diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/camembert.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/camembert.md new file mode 100644 index 0000000000000000000000000000000000000000..1b3eeed66f5d511dfd8177cd2cf301527190005f --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/camembert.md @@ -0,0 +1,197 @@ + +*This model was released on 2019-11-10 and added to Hugging Face Transformers on 2020-11-16.* + +
+
+ PyTorch + TensorFlow + SDPA +
+
+ +# CamemBERT + +[CamemBERT](https://huggingface.co/papers/1911.03894) is a language model based on [RoBERTa](./roberta), but trained specifically on French text from the OSCAR dataset, making it more effective for French language tasks. + +What sets CamemBERT apart is that it learned from a huge, high quality collection of French data, as opposed to mixing lots of languages. This helps it really understand French better than many multilingual models. + +Common applications of CamemBERT include masked language modeling (Fill-mask prediction), text classification (sentiment analysis), token classification (entity recognition) and sentence pair classification (entailment tasks). + +You can find all the original CamemBERT checkpoints under the [ALMAnaCH](https://huggingface.co/almanach/models?search=camembert) organization. + +> [!TIP] +> This model was contributed by the [ALMAnaCH (Inria)](https://huggingface.co/almanach) team. +> +> Click on the CamemBERT models in the right sidebar for more examples of how to apply CamemBERT to different NLP tasks. + +The examples below demonstrate how to predict the `` token with [`Pipeline`], [`AutoModel`], and from the command line. + + + + + +```python +import torch +from transformers import pipeline + +pipeline = pipeline("fill-mask", model="camembert-base", torch_dtype=torch.float16, device=0) +pipeline("Le camembert est un délicieux fromage .") +``` + + + + +```python +import torch +from transformers import AutoTokenizer, AutoModelForMaskedLM + +tokenizer = AutoTokenizer.from_pretrained("camembert-base") +model = AutoModelForMaskedLM.from_pretrained("camembert-base", torch_dtype="auto", device_map="auto", attn_implementation="sdpa") +inputs = tokenizer("Le camembert est un délicieux fromage .", return_tensors="pt").to("cuda") + +with torch.no_grad(): + outputs = model(**inputs) + predictions = outputs.logits + +masked_index = torch.where(inputs['input_ids'] == tokenizer.mask_token_id)[1] +predicted_token_id = predictions[0, masked_index].argmax(dim=-1) +predicted_token = tokenizer.decode(predicted_token_id) + +print(f"The predicted token is: {predicted_token}") +``` + + + + +```bash +echo -e "Le camembert est un délicieux fromage ." | transformers run --task fill-mask --model camembert-base --device 0 +``` + + + + + + +Quantization reduces the memory burden of large models by representing weights in lower precision. Refer to the [Quantization](../quantization/overview) overview for available options. + +The example below uses [bitsandbytes](../quantization/bitsandbytes) quantization to quantize the weights to 8-bits. + +```python +from transformers import AutoTokenizer, AutoModelForMaskedLM, BitsAndBytesConfig +import torch + +quant_config = BitsAndBytesConfig(load_in_8bit=True) +model = AutoModelForMaskedLM.from_pretrained( + "almanach/camembert-large", + quantization_config=quant_config, + device_map="auto" +) +tokenizer = AutoTokenizer.from_pretrained("almanach/camembert-large") + +inputs = tokenizer("Le camembert est un délicieux fromage .", return_tensors="pt").to("cuda") + +with torch.no_grad(): + outputs = model(**inputs) + predictions = outputs.logits + +masked_index = torch.where(inputs["input_ids"] == tokenizer.mask_token_id)[1] +predicted_token_id = predictions[0, masked_index].argmax(dim=-1) +predicted_token = tokenizer.decode(predicted_token_id) + +print(f"The predicted token is: {predicted_token}") +``` + +## CamembertConfig + +[[autodoc]] CamembertConfig + +## CamembertTokenizer + +[[autodoc]] CamembertTokenizer + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - save_vocabulary + +## CamembertTokenizerFast + +[[autodoc]] CamembertTokenizerFast + + + + +## CamembertModel + +[[autodoc]] CamembertModel + +## CamembertForCausalLM + +[[autodoc]] CamembertForCausalLM + +## CamembertForMaskedLM + +[[autodoc]] CamembertForMaskedLM + +## CamembertForSequenceClassification + +[[autodoc]] CamembertForSequenceClassification + +## CamembertForMultipleChoice + +[[autodoc]] CamembertForMultipleChoice + +## CamembertForTokenClassification + +[[autodoc]] CamembertForTokenClassification + +## CamembertForQuestionAnswering + +[[autodoc]] CamembertForQuestionAnswering + + + + +## TFCamembertModel + +[[autodoc]] TFCamembertModel + +## TFCamembertForCausalLM + +[[autodoc]] TFCamembertForCausalLM + +## TFCamembertForMaskedLM + +[[autodoc]] TFCamembertForMaskedLM + +## TFCamembertForSequenceClassification + +[[autodoc]] TFCamembertForSequenceClassification + +## TFCamembertForMultipleChoice + +[[autodoc]] TFCamembertForMultipleChoice + +## TFCamembertForTokenClassification + +[[autodoc]] TFCamembertForTokenClassification + +## TFCamembertForQuestionAnswering + +[[autodoc]] TFCamembertForQuestionAnswering + + + \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/canine.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/canine.md new file mode 100644 index 0000000000000000000000000000000000000000..e1d8bb7f7f681b911c5e8c5dc1f1c8e75632030d --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/canine.md @@ -0,0 +1,129 @@ + +*This model was released on 2021-03-11 and added to Hugging Face Transformers on 2021-06-30.* + +
+
+ PyTorch +
+
+ +# CANINE + +[CANINE](https://huggingface.co/papers/2103.06874) is a tokenization-free Transformer. It skips the usual step of splitting text into subwords or wordpieces and processes text character by character. That means it works directly with raw Unicode, making it especially useful for languages with complex or inconsistent tokenization rules and even noisy inputs like typos. Since working with characters means handling longer sequences, CANINE uses a smart trick. The model compresses the input early on (called downsampling) so the transformer doesn’t have to process every character individually. This keeps things fast and efficient. + +You can find all the original CANINE checkpoints under the [Google](https://huggingface.co/google?search_models=canine) organization. + +> [!TIP] +> Click on the CANINE models in the right sidebar for more examples of how to apply CANINE to different language tasks. + +The example below demonstrates how to generate embeddings with [`Pipeline`], [`AutoModel`], and from the command line. + + + + +```py +import torch +from transformers import pipeline + +pipeline = pipeline( + task="feature-extraction", + model="google/canine-c", + device=0, +) + +pipeline("Plant create energy through a process known as photosynthesis.") +``` + + + + +```py +import torch +from transformers import AutoModel + +model = AutoModel.from_pretrained("google/canine-c") + +text = "Plant create energy through a process known as photosynthesis." +input_ids = torch.tensor([[ord(char) for char in text]]) + +outputs = model(input_ids) +pooled_output = outputs.pooler_output +sequence_output = outputs.last_hidden_state +``` + + + + +```bash +echo -e "Plant create energy through a process known as photosynthesis." | transformers-cli run --task feature-extraction --model google/canine-c --device 0 +``` + + + + +## Notes + +- CANINE skips tokenization entirely — it works directly on raw characters, not subwords. You can use it with or without a tokenizer. For batched inference and training, it is recommended to use the tokenizer to pad and truncate all sequences to the same length. + + ```py + from transformers import AutoTokenizer, AutoModel + + tokenizer = AutoTokenizer("google/canine-c") + inputs = ["Life is like a box of chocolates.", "You never know what you gonna get."] + encoding = tokenizer(inputs, padding="longest", truncation=True, return_tensors="pt") + ``` +- CANINE is primarily designed to be fine-tuned on a downstream task. The pretrained model can be used for either masked language modeling or next sentence prediction. + +## CanineConfig + +[[autodoc]] CanineConfig + +## CanineTokenizer + +[[autodoc]] CanineTokenizer + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + +## CANINE specific outputs + +[[autodoc]] models.canine.modeling_canine.CanineModelOutputWithPooling + +## CanineModel + +[[autodoc]] CanineModel + - forward + +## CanineForSequenceClassification + +[[autodoc]] CanineForSequenceClassification + - forward + +## CanineForMultipleChoice + +[[autodoc]] CanineForMultipleChoice + - forward + +## CanineForTokenClassification + +[[autodoc]] CanineForTokenClassification + - forward + +## CanineForQuestionAnswering + +[[autodoc]] CanineForQuestionAnswering + - forward diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/chameleon.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/chameleon.md new file mode 100644 index 0000000000000000000000000000000000000000..6b711995e3421ace28cf4ecc41a47af6c611e222 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/chameleon.md @@ -0,0 +1,213 @@ + +*This model was released on 2024-05-16 and added to Hugging Face Transformers on 2024-07-17.* + +# Chameleon + +
+PyTorch +FlashAttention +SDPA +
+ +## Overview + +The Chameleon model was proposed in [Chameleon: Mixed-Modal Early-Fusion Foundation Models +](https://huggingface.co/papers/2405.09818) by META AI Chameleon Team. Chameleon is a Vision-Language Model that use vector quantization to tokenize images which enables the model to generate multimodal output. The model takes images and texts as input, including an interleaved format, and generates textual response. Image generation module is not released yet. + + +The abstract from the paper is the following: + +*We present Chameleon, a family of early-fusion token-based mixed-modal models capable of understanding and generating images and text in any arbitrary sequence. We outline a stable training +approach from inception, an alignment recipe, and an architectural parameterization tailored for the +early-fusion, token-based, mixed-modal setting. The models are evaluated on a comprehensive range +of tasks, including visual question answering, image captioning, text generation, image generation, and +long-form mixed modal generation. Chameleon demonstrates broad and general capabilities, including +state-of-the-art performance in image captioning tasks, outperforms Llama-2 in text-only tasks while +being competitive with models such as Mixtral 8x7B and Gemini-Pro, and performs non-trivial image +generation, all in a single model. It also matches or exceeds the performance of much larger models, +including Gemini Pro and GPT-4V, according to human judgments on a new long-form mixed-modal +generation evaluation, where either the prompt or outputs contain mixed sequences of both images and +text. Chameleon marks a significant step forward in unified modeling of full multimodal documents* + + + + + Chameleon incorporates a vector quantizer module to transform images into discrete tokens. That also enables image generation using an auto-regressive transformer. Taken from the original paper. + +This model was contributed by [joaogante](https://huggingface.co/joaogante) and [RaushanTurganbay](https://huggingface.co/RaushanTurganbay). +The original code can be found [here](https://github.com/facebookresearch/chameleon). + + +## Usage tips + +- We advise users to use `padding_side="left"` when computing batched generation as it leads to more accurate results. Simply make sure to set `processor.tokenizer.padding_side = "left"` before generating. + +- Note that Chameleon was tuned for safety alignment. If the model is refusing to answer, consider asking a more concrete question, instead of an open question. + +- Chameleon generates in chat format which means that the generated text will always be the "assistant's turn". You can enable a text completion generation by passing `return_for_text_completion=True` when calling the processor. + +> [!NOTE] +> Chameleon implementation in Transformers uses a special image token to indicate where to merge image embeddings. For special image token we didn't add a new one but used one of the reserved tokens: ``. You have to add `` to your prompt in the place where the image should be embedded for correct generation. + +## Usage example + +### Single image inference + +Chameleon is a gated model so make sure to have access and login to Hugging Face Hub using a token. +Here's how to load the model and perform inference in half-precision (`torch.bfloat16`): + +```python +from transformers import ChameleonProcessor, ChameleonForConditionalGeneration +import torch +from PIL import Image +import requests + +processor = ChameleonProcessor.from_pretrained("facebook/chameleon-7b") +model = ChameleonForConditionalGeneration.from_pretrained("facebook/chameleon-7b", torch_dtype=torch.bfloat16, device_map="auto") + +# prepare image and text prompt +url = 'http://images.cocodataset.org/val2017/000000039769.jpg' +image = Image.open(requests.get(url, stream=True).raw) +prompt = "What do you see in this image?" + +inputs = processor(images=image, text=prompt, return_tensors="pt").to(model.device, dtype=torch.bfloat16) + +# autoregressively complete prompt +output = model.generate(**inputs, max_new_tokens=50) +print(processor.decode(output[0], skip_special_tokens=True)) +``` + +### Multi image inference + +Chameleon can perform inference with multiple images as input, where images either belong to the same prompt or different prompts (in batched inference). Here is how you can do it: + +```python +from transformers import ChameleonProcessor, ChameleonForConditionalGeneration +import torch +from PIL import Image +import requests + +processor = ChameleonProcessor.from_pretrained("facebook/chameleon-7b") + +model = ChameleonForConditionalGeneration.from_pretrained("facebook/chameleon-7b", torch_dtype=torch.bfloat16, device_map="auto") + +# Get three different images +url = "https://www.ilankelman.org/stopsigns/australia.jpg" +image_stop = Image.open(requests.get(url, stream=True).raw) + +url = "http://images.cocodataset.org/val2017/000000039769.jpg" +image_cats = Image.open(requests.get(url, stream=True).raw) + +url = "https://huggingface.co/microsoft/kosmos-2-patch14-224/resolve/main/snowman.jpg" +image_snowman = Image.open(requests.get(url, stream=True).raw) + +# Prepare a batched prompt, where the first one is a multi-image prompt and the second is not +prompts = [ + "What do these images have in common?", + "What is shown in this image?" +] + +# We can simply feed images in the order they have to be used in the text prompt +# Each "" token uses one image leaving the next for the subsequent "" tokens +inputs = processor(images=[image_stop, image_cats, image_snowman], text=prompts, padding=True, return_tensors="pt").to(device=model.device, dtype=torch.bfloat16) + +# Generate +generate_ids = model.generate(**inputs, max_new_tokens=50) +processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False) +``` + +## Model optimization + +### Quantization using Bitsandbytes + +The model can be loaded in 8 or 4 bits, greatly reducing the memory requirements while maintaining the performance of the original model. First make sure to install bitsandbytes, `pip install bitsandbytes` and to have access to a GPU/accelerator that is supported by the library. + + + +bitsandbytes is being refactored to support multiple backends beyond CUDA. Currently, ROCm (AMD GPU) and Intel CPU implementations are mature, with Intel XPU in progress and Apple Silicon support expected by Q4/Q1. For installation instructions and the latest backend updates, visit [this link](https://huggingface.co/docs/bitsandbytes/main/en/installation#multi-backend). + +We value your feedback to help identify bugs before the full release! Check out [these docs](https://huggingface.co/docs/bitsandbytes/main/en/non_cuda_backends) for more details and feedback links. + + + +Simply change the snippet above with: + +```python +from transformers import ChameleonForConditionalGeneration, BitsAndBytesConfig + +# specify how to quantize the model +quantization_config = BitsAndBytesConfig( + load_in_4bit=True, + bnb_4bit_quant_type="nf4", + bnb_4bit_compute_dtype=torch.bfloat16, +) + +model = ChameleonForConditionalGeneration.from_pretrained("facebook/chameleon-7b", quantization_config=quantization_config, device_map="auto") +``` + +### Use Flash-Attention 2 and SDPA to further speed-up generation + +The models supports both, Flash-Attention 2 and PyTorch's [`torch.nn.functional.scaled_dot_product_attention`](https://pytorch.org/docs/master/generated/torch.nn.functional.scaled_dot_product_attention.html) which can be enables for optimization. SDPA is the default options when you load the model, If you want to switch for Flash Attention 2, first make sure to install flash-attn. Refer to the [original repository](https://github.com/Dao-AILab/flash-attention) regarding that package installation. Simply change the snippet above with: + +```python +from transformers import ChameleonForConditionalGeneration + +model_id = "facebook/chameleon-7b" +model = ChameleonForConditionalGeneration.from_pretrained( + model_id, + torch_dtype=torch.bfloat16, + attn_implementation="flash_attention_2" +).to(0) +``` + +## ChameleonConfig + +[[autodoc]] ChameleonConfig + +## ChameleonVQVAEConfig + +[[autodoc]] ChameleonVQVAEConfig + +## ChameleonProcessor + +[[autodoc]] ChameleonProcessor + +## ChameleonImageProcessor + +[[autodoc]] ChameleonImageProcessor + - preprocess + +## ChameleonImageProcessorFast + +[[autodoc]] ChameleonImageProcessorFast + - preprocess + +## ChameleonVQVAE + +[[autodoc]] ChameleonVQVAE + - forward + +## ChameleonModel + +[[autodoc]] ChameleonModel + - forward + +## ChameleonForConditionalGeneration + +[[autodoc]] ChameleonForConditionalGeneration + - forward diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/chinese_clip.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/chinese_clip.md new file mode 100644 index 0000000000000000000000000000000000000000..7ed4d503c00fe14b4e05fcf1570ab82ebd3b1e6b --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/chinese_clip.md @@ -0,0 +1,122 @@ + +*This model was released on 2022-11-02 and added to Hugging Face Transformers on 2022-12-01.* + +# Chinese-CLIP + +
+PyTorch +
+ +## Overview + +The Chinese-CLIP model was proposed in [Chinese CLIP: Contrastive Vision-Language Pretraining in Chinese](https://huggingface.co/papers/2211.01335) by An Yang, Junshu Pan, Junyang Lin, Rui Men, Yichang Zhang, Jingren Zhou, Chang Zhou. +Chinese-CLIP is an implementation of CLIP (Radford et al., 2021) on a large-scale dataset of Chinese image-text pairs. It is capable of performing cross-modal retrieval and also playing as a vision backbone for vision tasks like zero-shot image classification, open-domain object detection, etc. The original Chinese-CLIP code is released [at this link](https://github.com/OFA-Sys/Chinese-CLIP). + +The abstract from the paper is the following: + +*The tremendous success of CLIP (Radford et al., 2021) has promoted the research and application of contrastive learning for vision-language pretraining. In this work, we construct a large-scale dataset of image-text pairs in Chinese, where most data are retrieved from publicly available datasets, and we pretrain Chinese CLIP models on the new dataset. We develop 5 Chinese CLIP models of multiple sizes, spanning from 77 to 958 million parameters. Furthermore, we propose a two-stage pretraining method, where the model is first trained with the image encoder frozen and then trained with all parameters being optimized, to achieve enhanced model performance. Our comprehensive experiments demonstrate that Chinese CLIP can achieve the state-of-the-art performance on MUGE, Flickr30K-CN, and COCO-CN in the setups of zero-shot learning and finetuning, and it is able to achieve competitive performance in zero-shot image classification based on the evaluation on the ELEVATER benchmark (Li et al., 2022). Our codes, pretrained models, and demos have been released.* + +The Chinese-CLIP model was contributed by [OFA-Sys](https://huggingface.co/OFA-Sys). + +## Usage example + +The code snippet below shows how to compute image & text features and similarities: + +```python +>>> from PIL import Image +>>> import requests +>>> from transformers import ChineseCLIPProcessor, ChineseCLIPModel + +>>> model = ChineseCLIPModel.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16") +>>> processor = ChineseCLIPProcessor.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16") + +>>> url = "https://clip-cn-beijing.oss-cn-beijing.aliyuncs.com/pokemon.jpeg" +>>> image = Image.open(requests.get(url, stream=True).raw) +>>> # Squirtle, Bulbasaur, Charmander, Pikachu in English +>>> texts = ["杰尼龟", "妙蛙种子", "小火龙", "皮卡丘"] + +>>> # compute image feature +>>> inputs = processor(images=image, return_tensors="pt") +>>> image_features = model.get_image_features(**inputs) +>>> image_features = image_features / image_features.norm(p=2, dim=-1, keepdim=True) # normalize + +>>> # compute text features +>>> inputs = processor(text=texts, padding=True, return_tensors="pt") +>>> text_features = model.get_text_features(**inputs) +>>> text_features = text_features / text_features.norm(p=2, dim=-1, keepdim=True) # normalize + +>>> # compute image-text similarity scores +>>> inputs = processor(text=texts, images=image, return_tensors="pt", padding=True) +>>> outputs = model(**inputs) +>>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score +>>> probs = logits_per_image.softmax(dim=1) # probs: [[1.2686e-03, 5.4499e-02, 6.7968e-04, 9.4355e-01]] +``` + +Currently, following scales of pretrained Chinese-CLIP models are available on 🤗 Hub: + +- [OFA-Sys/chinese-clip-vit-base-patch16](https://huggingface.co/OFA-Sys/chinese-clip-vit-base-patch16) +- [OFA-Sys/chinese-clip-vit-large-patch14](https://huggingface.co/OFA-Sys/chinese-clip-vit-large-patch14) +- [OFA-Sys/chinese-clip-vit-large-patch14-336px](https://huggingface.co/OFA-Sys/chinese-clip-vit-large-patch14-336px) +- [OFA-Sys/chinese-clip-vit-huge-patch14](https://huggingface.co/OFA-Sys/chinese-clip-vit-huge-patch14) + +## ChineseCLIPConfig + +[[autodoc]] ChineseCLIPConfig + - from_text_vision_configs + +## ChineseCLIPTextConfig + +[[autodoc]] ChineseCLIPTextConfig + +## ChineseCLIPVisionConfig + +[[autodoc]] ChineseCLIPVisionConfig + +## ChineseCLIPImageProcessor + +[[autodoc]] ChineseCLIPImageProcessor + - preprocess + +## ChineseCLIPImageProcessorFast + +[[autodoc]] ChineseCLIPImageProcessorFast + - preprocess + +## ChineseCLIPFeatureExtractor + +[[autodoc]] ChineseCLIPFeatureExtractor + +## ChineseCLIPProcessor + +[[autodoc]] ChineseCLIPProcessor + +## ChineseCLIPModel + +[[autodoc]] ChineseCLIPModel + - forward + - get_text_features + - get_image_features + +## ChineseCLIPTextModel + +[[autodoc]] ChineseCLIPTextModel + - forward + +## ChineseCLIPVisionModel + +[[autodoc]] ChineseCLIPVisionModel + - forward \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/clap.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/clap.md new file mode 100644 index 0000000000000000000000000000000000000000..43b12aef1648b2041e43b1703569e49bb4251d0d --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/clap.md @@ -0,0 +1,109 @@ + +*This model was released on 2022-11-12 and added to Hugging Face Transformers on 2023-02-16.* + +
+
+ PyTorch +
+
+ +# CLAP + +[CLAP (Contrastive Language-Audio Pretraining)](https://huggingface.co/papers/2211.06687) is a multimodal model that combines audio data with natural language descriptions through contrastive learning. + +It incorporates feature fusion and keyword-to-caption augmentation to process variable-length audio inputs and to improve performance. CLAP doesn't require task-specific training data and can learn meaningful audio representations through natural language. + +You can find all the original CLAP checkpoints under the [CLAP](https://huggingface.co/collections/laion/clap-contrastive-language-audio-pretraining-65415c0b18373b607262a490) collection. + +> [!TIP] +> This model was contributed by [ybelkada](https://huggingface.co/ybelkada) and [ArthurZ](https://huggingface.co/ArthurZ). +> +> Click on the CLAP models in the right sidebar for more examples of how to apply CLAP to different audio retrieval and classification tasks. + +The example below demonstrates how to extract text embeddings with the [`AutoModel`] class. + + + + +```python +import torch +from transformers import AutoTokenizer, AutoModel + +model = AutoModel.from_pretrained("laion/clap-htsat-unfused", torch_dtype=torch.float16, device_map="auto") +tokenizer = AutoTokenizer.from_pretrained("laion/clap-htsat-unfused") + +texts = ["the sound of a cat", "the sound of a dog", "music playing"] + +inputs = tokenizer(texts, padding=True, return_tensors="pt").to(model.device) + +with torch.no_grad(): + text_features = model.get_text_features(**inputs) + +print(f"Text embeddings shape: {text_features.shape}") +print(f"Text embeddings: {text_features}") +``` + + + + +## ClapConfig + +[[autodoc]] ClapConfig + - from_text_audio_configs + +## ClapTextConfig + +[[autodoc]] ClapTextConfig + +## ClapAudioConfig + +[[autodoc]] ClapAudioConfig + +## ClapFeatureExtractor + +[[autodoc]] ClapFeatureExtractor + +## ClapProcessor + +[[autodoc]] ClapProcessor + +## ClapModel + +[[autodoc]] ClapModel + - forward + - get_text_features + - get_audio_features + +## ClapTextModel + +[[autodoc]] ClapTextModel + - forward + +## ClapTextModelWithProjection + +[[autodoc]] ClapTextModelWithProjection + - forward + +## ClapAudioModel + +[[autodoc]] ClapAudioModel + - forward + +## ClapAudioModelWithProjection + +[[autodoc]] ClapAudioModelWithProjection + - forward diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/clip.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/clip.md new file mode 100644 index 0000000000000000000000000000000000000000..53a0261a177b6b75e63ca231c5f68124400fd034 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/clip.md @@ -0,0 +1,214 @@ + +*This model was released on 2021-02-26 and added to Hugging Face Transformers on 2021-05-12.* + +
+
+ PyTorch + TensorFlow + Flax + FlashAttention + SDPA +
+
+ +# CLIP + +[CLIP](https://huggingface.co/papers/2103.00020) is a is a multimodal vision and language model motivated by overcoming the fixed number of object categories when training a computer vision model. CLIP learns about images directly from raw text by jointly training on 400M (image, text) pairs. Pretraining on this scale enables zero-shot transfer to downstream tasks. CLIP uses an image encoder and text encoder to get visual features and text features. Both features are projected to a latent space with the same number of dimensions and their dot product gives a similarity score. + +You can find all the original CLIP checkpoints under the [OpenAI](https://huggingface.co/openai?search_models=clip) organization. + +> [!TIP] +> Click on the CLIP models in the right sidebar for more examples of how to apply CLIP to different image and language tasks. + +The example below demonstrates how to calculate similarity scores between multiple text descriptions and an image with [`Pipeline`] or the [`AutoModel`] class. + + + + +```py +import torch +from transformers import pipeline + +clip = pipeline( + task="zero-shot-image-classification", + model="openai/clip-vit-base-patch32", + torch_dtype=torch.bfloat16, + device=0 +) +labels = ["a photo of a cat", "a photo of a dog", "a photo of a car"] +clip("http://images.cocodataset.org/val2017/000000039769.jpg", candidate_labels=labels) +``` + + + + +```py +import requests +import torch +from PIL import Image +from transformers import AutoProcessor, AutoModel + +model = AutoModel.from_pretrained("openai/clip-vit-base-patch32", torch_dtype=torch.bfloat16, attn_implementation="sdpa") +processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32") + +url = "http://images.cocodataset.org/val2017/000000039769.jpg" +image = Image.open(requests.get(url, stream=True).raw) +labels = ["a photo of a cat", "a photo of a dog", "a photo of a car"] + +inputs = processor(text=labels, images=image, return_tensors="pt", padding=True) + +outputs = model(**inputs) +logits_per_image = outputs.logits_per_image +probs = logits_per_image.softmax(dim=1) +most_likely_idx = probs.argmax(dim=1).item() +most_likely_label = labels[most_likely_idx] +print(f"Most likely label: {most_likely_label} with probability: {probs[0][most_likely_idx].item():.3f}") +``` + + + + +## Notes + +- Use [`CLIPImageProcessor`] to resize (or rescale) and normalizes images for the model. + +## CLIPConfig + +[[autodoc]] CLIPConfig + - from_text_vision_configs + +## CLIPTextConfig + +[[autodoc]] CLIPTextConfig + +## CLIPVisionConfig + +[[autodoc]] CLIPVisionConfig + +## CLIPTokenizer + +[[autodoc]] CLIPTokenizer + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - save_vocabulary + +## CLIPTokenizerFast + +[[autodoc]] CLIPTokenizerFast + +## CLIPImageProcessor + +[[autodoc]] CLIPImageProcessor + - preprocess + +## CLIPImageProcessorFast + +[[autodoc]] CLIPImageProcessorFast + - preprocess + +## CLIPFeatureExtractor + +[[autodoc]] CLIPFeatureExtractor + +## CLIPProcessor + +[[autodoc]] CLIPProcessor + + + + +## CLIPModel + +[[autodoc]] CLIPModel + - forward + - get_text_features + - get_image_features + +## CLIPTextModel + +[[autodoc]] CLIPTextModel + - forward + +## CLIPTextModelWithProjection + +[[autodoc]] CLIPTextModelWithProjection + - forward + +## CLIPVisionModelWithProjection + +[[autodoc]] CLIPVisionModelWithProjection + - forward + +## CLIPVisionModel + +[[autodoc]] CLIPVisionModel + - forward + +## CLIPForImageClassification + +[[autodoc]] CLIPForImageClassification + - forward + + + + +## TFCLIPModel + +[[autodoc]] TFCLIPModel + - call + - get_text_features + - get_image_features + +## TFCLIPTextModel + +[[autodoc]] TFCLIPTextModel + - call + +## TFCLIPVisionModel + +[[autodoc]] TFCLIPVisionModel + - call + + + + +## FlaxCLIPModel + +[[autodoc]] FlaxCLIPModel + - __call__ + - get_text_features + - get_image_features + +## FlaxCLIPTextModel + +[[autodoc]] FlaxCLIPTextModel + - __call__ + +## FlaxCLIPTextModelWithProjection + +[[autodoc]] FlaxCLIPTextModelWithProjection + - __call__ + +## FlaxCLIPVisionModel + +[[autodoc]] FlaxCLIPVisionModel + - __call__ + + + diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/clipseg.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/clipseg.md new file mode 100644 index 0000000000000000000000000000000000000000..e27d49ffe4849b08b154687be68a4bd1bc146afd --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/clipseg.md @@ -0,0 +1,109 @@ + +*This model was released on 2021-12-18 and added to Hugging Face Transformers on 2022-11-08.* + +# CLIPSeg + +
+PyTorch +
+ +## Overview + +The CLIPSeg model was proposed in [Image Segmentation Using Text and Image Prompts](https://huggingface.co/papers/2112.10003) by Timo Lüddecke +and Alexander Ecker. CLIPSeg adds a minimal decoder on top of a frozen [CLIP](clip) model for zero-shot and one-shot image segmentation. + +The abstract from the paper is the following: + +*Image segmentation is usually addressed by training a +model for a fixed set of object classes. Incorporating additional classes or more complex queries later is expensive +as it requires re-training the model on a dataset that encompasses these expressions. Here we propose a system +that can generate image segmentations based on arbitrary +prompts at test time. A prompt can be either a text or an +image. This approach enables us to create a unified model +(trained once) for three common segmentation tasks, which +come with distinct challenges: referring expression segmentation, zero-shot segmentation and one-shot segmentation. +We build upon the CLIP model as a backbone which we extend with a transformer-based decoder that enables dense +prediction. After training on an extended version of the +PhraseCut dataset, our system generates a binary segmentation map for an image based on a free-text prompt or on +an additional image expressing the query. We analyze different variants of the latter image-based prompts in detail. +This novel hybrid input allows for dynamic adaptation not +only to the three segmentation tasks mentioned above, but +to any binary segmentation task where a text or image query +can be formulated. Finally, we find our system to adapt well +to generalized queries involving affordances or properties* + + + + CLIPSeg overview. Taken from the original paper. + +This model was contributed by [nielsr](https://huggingface.co/nielsr). +The original code can be found [here](https://github.com/timojl/clipseg). + +## Usage tips + +- [`CLIPSegForImageSegmentation`] adds a decoder on top of [`CLIPSegModel`]. The latter is identical to [`CLIPModel`]. +- [`CLIPSegForImageSegmentation`] can generate image segmentations based on arbitrary prompts at test time. A prompt can be either a text +(provided to the model as `input_ids`) or an image (provided to the model as `conditional_pixel_values`). One can also provide custom +conditional embeddings (provided to the model as `conditional_embeddings`). + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with CLIPSeg. If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + + + +- A notebook that illustrates [zero-shot image segmentation with CLIPSeg](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/CLIPSeg/Zero_shot_image_segmentation_with_CLIPSeg.ipynb). + +## CLIPSegConfig + +[[autodoc]] CLIPSegConfig + - from_text_vision_configs + +## CLIPSegTextConfig + +[[autodoc]] CLIPSegTextConfig + +## CLIPSegVisionConfig + +[[autodoc]] CLIPSegVisionConfig + +## CLIPSegProcessor + +[[autodoc]] CLIPSegProcessor + +## CLIPSegModel + +[[autodoc]] CLIPSegModel + - forward + - get_text_features + - get_image_features + +## CLIPSegTextModel + +[[autodoc]] CLIPSegTextModel + - forward + +## CLIPSegVisionModel + +[[autodoc]] CLIPSegVisionModel + - forward + +## CLIPSegForImageSegmentation + +[[autodoc]] CLIPSegForImageSegmentation + - forward \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/clvp.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/clvp.md new file mode 100644 index 0000000000000000000000000000000000000000..926438a3c1f52777c084c24588500e1178d96a30 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/clvp.md @@ -0,0 +1,131 @@ + +*This model was released on 2023-05-12 and added to Hugging Face Transformers on 2023-11-10.* + +# CLVP + +
+PyTorch +
+ +## Overview + +The CLVP (Contrastive Language-Voice Pretrained Transformer) model was proposed in [Better speech synthesis through scaling](https://huggingface.co/papers/2305.07243) by James Betker. + +The abstract from the paper is the following: + +*In recent years, the field of image generation has been revolutionized by the application of autoregressive transformers and DDPMs. These approaches model the process of image generation as a step-wise probabilistic processes and leverage large amounts of compute and data to learn the image distribution. This methodology of improving performance need not be confined to images. This paper describes a way to apply advances in the image generative domain to speech synthesis. The result is TorToise - an expressive, multi-voice text-to-speech system.* + + +This model was contributed by [Susnato Dhar](https://huggingface.co/susnato). +The original code can be found [here](https://github.com/neonbjb/tortoise-tts). + + +## Usage tips + +1. CLVP is an integral part of the Tortoise TTS model. +2. CLVP can be used to compare different generated speech candidates with the provided text, and the best speech tokens are forwarded to the diffusion model. +3. The use of the [`ClvpModelForConditionalGeneration.generate()`] method is strongly recommended for tortoise usage. +4. Note that the CLVP model expects the audio to be sampled at 22.05 kHz contrary to other audio models which expects 16 kHz. + + +## Brief Explanation: + +- The [`ClvpTokenizer`] tokenizes the text input, and the [`ClvpFeatureExtractor`] extracts the log mel-spectrogram from the desired audio. +- [`ClvpConditioningEncoder`] takes those text tokens and audio representations and converts them into embeddings conditioned on the text and audio. +- The [`ClvpForCausalLM`] uses those embeddings to generate multiple speech candidates. +- Each speech candidate is passed through the speech encoder ([`ClvpEncoder`]) which converts them into a vector representation, and the text encoder ([`ClvpEncoder`]) converts the text tokens into the same latent space. +- At the end, we compare each speech vector with the text vector to see which speech vector is most similar to the text vector. +- [`ClvpModelForConditionalGeneration.generate()`] compresses all of the logic described above into a single method. + + +Example : + +```python +>>> import datasets +>>> from transformers import ClvpProcessor, ClvpModelForConditionalGeneration + +>>> # Define the Text and Load the Audio (We are taking an audio example from HuggingFace Hub using `datasets` library). +>>> text = "This is an example text." + +>>> ds = datasets.load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") +>>> ds = ds.cast_column("audio", datasets.Audio(sampling_rate=22050)) +>>> sample = ds[0]["audio"] + +>>> # Define processor and model. +>>> processor = ClvpProcessor.from_pretrained("susnato/clvp_dev") +>>> model = ClvpModelForConditionalGeneration.from_pretrained("susnato/clvp_dev") + +>>> # Generate processor output and model output. +>>> processor_output = processor(raw_speech=sample["array"], sampling_rate=sample["sampling_rate"], text=text, return_tensors="pt") +>>> generated_output = model.generate(**processor_output) +``` + + +## ClvpConfig + +[[autodoc]] ClvpConfig + - from_sub_model_configs + +## ClvpEncoderConfig + +[[autodoc]] ClvpEncoderConfig + +## ClvpDecoderConfig + +[[autodoc]] ClvpDecoderConfig + +## ClvpTokenizer + +[[autodoc]] ClvpTokenizer + - save_vocabulary + +## ClvpFeatureExtractor + +[[autodoc]] ClvpFeatureExtractor + - __call__ + +## ClvpProcessor + +[[autodoc]] ClvpProcessor + - __call__ + - decode + - batch_decode + +## ClvpModelForConditionalGeneration + +[[autodoc]] ClvpModelForConditionalGeneration + - forward + - generate + - get_text_features + - get_speech_features + +## ClvpForCausalLM + +[[autodoc]] ClvpForCausalLM + +## ClvpModel + +[[autodoc]] ClvpModel + +## ClvpEncoder + +[[autodoc]] ClvpEncoder + +## ClvpDecoder + +[[autodoc]] ClvpDecoder + diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/code_llama.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/code_llama.md new file mode 100644 index 0000000000000000000000000000000000000000..9a3a0f522aa03624bcf4abf481f0e872db7dd960 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/code_llama.md @@ -0,0 +1,182 @@ + +*This model was released on 2023-08-24 and added to Hugging Face Transformers on 2023-08-25.* + +
+
+ PyTorch + Flax +
+
+ +# CodeLlama + +[Code Llama](https://huggingface.co/papers/2308.12950) is a specialized family of large language models based on [Llama 2](./llama2) for coding tasks. It comes in different flavors - general code, Python-specific, and instruction-following variant - all available in 7B, 13B, 34B, and 70B parameters. Code Llama models can generate, explain, and even fill in missing parts of your code (called "infilling"). It can also handle very long contexts with stable generation up to 100k tokens, even though it was trained on sequences of 16K tokens. + +You can find all the original Code Llama checkpoints under the [Code Llama](https://huggingface.co/collections/meta-llama/code-llama-family-661da32d0a9d678b6f55b933) collection. + +> [!TIP] +> Click on the Code Llama models in the right sidebar for more examples of how to apply Code Llama to different coding tasks. + +The example below demonstrates how to generate code with [`Pipeline`], or the [`AutoModel`], and from the command line. + + + + +```py +import torch +from transformers import pipeline + +pipe = pipeline( + "text-generation", + model="meta-llama/CodeLlama-7b-hf", + torch_dtype=torch.float16, + device_map=0 +) + +# basic code generation +result = pipe("# Function to calculate the factorial of a number\ndef factorial(n):", max_new_tokens=256) +print(result[0]['generated_text']) + +# infilling +infill_result = pipe("def remove_non_ascii(s: str) -> str:\n \"\"\" \n return result", max_new_tokens=200) +print(infill_result[0]['generated_text']) +``` + + + + +```py +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("meta-llama/CodeLlama-7b-hf") +model = AutoModelForCausalLM.from_pretrained( + "meta-llama/CodeLlama-7b-hf", + torch_dtype=torch.float16, + device_map="auto", + attn_implementation="sdpa" +) + +# basic code generation +prompt = "# Function to calculate the factorial of a number\ndef factorial(n):" +input_ids = tokenizer(prompt, return_tensors="pt").to(model.device) + +output = model.generate( + **input_ids, + max_new_tokens=256, + cache_implementation="static" +) +print(tokenizer.decode(output[0], skip_special_tokens=True)) + +# infilling +infill_prompt = "def remove_non_ascii(s: str) -> str:\n \"\"\" \n return result" +input_ids = tokenizer(infill_prompt, return_tensors="pt").to(model.device) + +filled_output = model.generate(**input_ids, max_new_tokens=200) +filled_text = tokenizer.decode(filled_output[0], skip_special_tokens=True) +print(filled_text) +``` + + + + +```bash +echo -e "# Function to calculate the factorial of a number\ndef factorial(n):" | transformers run --task text-generation --model meta-llama/CodeLlama-7b-hf --device 0 +``` + + + + +Quantization reduces the memory burden of large models by representing the weights in a lower precision. Refer to the [Quantization](../quantization/overview) overview for more available quantization backends. + +The example below uses [bitsandbytes](../quantization/bitsandbytes) to only quantize the weights to 4-bits. + +```py +# pip install bitsandbytes +import torch +from transformers import AutoModelForCausalLM, CodeLlamaTokenizer, BitsAndBytesConfig + +bnb_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True) +tokenizer = CodeLlamaTokenizer.from_pretrained("meta-llama/CodeLlama-34b-hf") +model = AutoModelForCausalLM.from_pretrained( + "meta-llama/CodeLlama-34b-hf", + torch_dtype=torch.bfloat16, + device_map="auto", + quantization_config=bnb_config +) + +prompt = "# Write a Python function to check if a string is a palindrome\ndef is_palindrome(s):" +input_ids = tokenizer(prompt, return_tensors="pt").to(model.device) + +output = model.generate(**input_ids, max_new_tokens=200, cache_implementation="static") +print(tokenizer.decode(output[0], skip_special_tokens=True)) +``` + +Use the [AttentionMaskVisualizer](https://github.com/huggingface/transformers/blob/beb9b5b02246b9b7ee81ddf938f93f44cfeaad19/src/transformers/utils/attention_visualizer.py#L139) to better understand what tokens the model can and cannot attend to. + +```py +from transformers.utils.attention_visualizer import AttentionMaskVisualizer + +visualizer = AttentionMaskVisualizer("meta-llama/CodeLlama-7b-hf") +visualizer("""def func(a, b): + return a + b""") +``` + +
+ +
+ +## Notes + +- Infilling is only available in the 7B and 13B base models, and not in the Python, Instruct, 34B, or 70B models. +- Use the `` token where you want your input to be filled. The tokenizer splits this token to create a formatted input string that follows the [original training pattern](https://github.com/facebookresearch/codellama/blob/cb51c14ec761370ba2e2bc351374a79265d0465e/llama/generation.py#L402). This is more robust than preparing the pattern yourself. + ```py + from transformers import LlamaForCausalLM, CodeLlamaTokenizer + + tokenizer = CodeLlamaTokenizer.from_pretrained("meta-llama/CodeLlama-7b-hf") + model = LlamaForCausalLM.from_pretrained("meta-llama/CodeLlama-7b-hf") + PROMPT = '''def remove_non_ascii(s: str) -> str: + """ + return result + ''' + input_ids = tokenizer(PROMPT, return_tensors="pt")["input_ids"] + generated_ids = model.generate(input_ids, max_new_tokens=128) + + filling = tokenizer.batch_decode(generated_ids[:, input_ids.shape[1]:], skip_special_tokens = True)[0] + print(PROMPT.replace("", filling)) + ``` +- Use `bfloat16` for further training or fine-tuning and `float16` for inference. +- The `BOS` character is not used for infilling when encoding the prefix or suffix, but only at the beginning of each prompt. +- The tokenizer is a byte-pair encoding model based on [SentencePiece](https://github.com/google/sentencepiece). During decoding, if the first token is the start of the word (for example, “Banana”), the tokenizer doesn’t prepend the prefix space to the string. + +## CodeLlamaTokenizer + +[[autodoc]] CodeLlamaTokenizer + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - save_vocabulary + +## CodeLlamaTokenizerFast + +[[autodoc]] CodeLlamaTokenizerFast + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - update_post_processor + - save_vocabulary diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/codegen.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/codegen.md new file mode 100644 index 0000000000000000000000000000000000000000..e5ad3863b67c3cba4d0b3333e7cea15244955fa0 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/codegen.md @@ -0,0 +1,95 @@ + +*This model was released on 2022-03-25 and added to Hugging Face Transformers on 2022-06-24.* + +# CodeGen + +
+PyTorch +
+ +## Overview + +The CodeGen model was proposed in [A Conversational Paradigm for Program Synthesis](https://huggingface.co/papers/2203.13474) by Erik Nijkamp, Bo Pang, Hiroaki Hayashi, Lifu Tu, Huan Wang, Yingbo Zhou, Silvio Savarese, and Caiming Xiong. + +CodeGen is an autoregressive language model for program synthesis trained sequentially on [The Pile](https://pile.eleuther.ai/), BigQuery, and BigPython. + +The abstract from the paper is the following: + +*Program synthesis strives to generate a computer program as a solution to a given problem specification. We propose a conversational program synthesis approach via large language models, which addresses the challenges of searching over a vast program space and user intent specification faced in prior approaches. Our new approach casts the process of writing a specification and program as a multi-turn conversation between a user and a system. It treats program synthesis as a sequence prediction problem, in which the specification is expressed in natural language and the desired program is conditionally sampled. We train a family of large language models, called CodeGen, on natural language and programming language data. With weak supervision in the data and the scaling up of data size and model size, conversational capacities emerge from the simple autoregressive language modeling. To study the model behavior on conversational program synthesis, we develop a multi-turn programming benchmark (MTPB), where solving each problem requires multi-step synthesis via multi-turn conversation between the user and the model. Our findings show the emergence of conversational capabilities and the effectiveness of the proposed conversational program synthesis paradigm. In addition, our model CodeGen (with up to 16B parameters trained on TPU-v4) outperforms OpenAI's Codex on the HumanEval benchmark. We make the training library JaxFormer including checkpoints available as open source contribution: [this https URL](https://github.com/salesforce/codegen).* + +This model was contributed by [Hiroaki Hayashi](https://huggingface.co/rooa). +The original code can be found [here](https://github.com/salesforce/codegen). + +## Checkpoint Naming + +* CodeGen model [checkpoints](https://huggingface.co/models?other=codegen) are available on different pre-training data with variable sizes. +* The format is: `Salesforce/codegen-{size}-{data}`, where + * `size`: `350M`, `2B`, `6B`, `16B` + * `data`: + * `nl`: Pre-trained on the Pile + * `multi`: Initialized with `nl`, then further pre-trained on multiple programming languages data + * `mono`: Initialized with `multi`, then further pre-trained on Python data +* For example, `Salesforce/codegen-350M-mono` offers a 350 million-parameter checkpoint pre-trained sequentially on the Pile, multiple programming languages, and Python. + +## Usage example + +```python +>>> from transformers import AutoModelForCausalLM, AutoTokenizer + +>>> checkpoint = "Salesforce/codegen-350M-mono" +>>> model = AutoModelForCausalLM.from_pretrained(checkpoint) +>>> tokenizer = AutoTokenizer.from_pretrained(checkpoint) + +>>> text = "def hello_world():" + +>>> completion = model.generate(**tokenizer(text, return_tensors="pt")) + +>>> print(tokenizer.decode(completion[0])) +def hello_world(): + print("Hello World") + +hello_world() +``` + +## Resources + +- [Causal language modeling task guide](../tasks/language_modeling) + +## CodeGenConfig + +[[autodoc]] CodeGenConfig + - all + +## CodeGenTokenizer + +[[autodoc]] CodeGenTokenizer + - create_token_type_ids_from_sequences + - save_vocabulary + +## CodeGenTokenizerFast + +[[autodoc]] CodeGenTokenizerFast + +## CodeGenModel + +[[autodoc]] CodeGenModel + - forward + +## CodeGenForCausalLM + +[[autodoc]] CodeGenForCausalLM + - forward diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/cohere.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/cohere.md new file mode 100644 index 0000000000000000000000000000000000000000..c15a2f6f3a28c8cfb27ce2820d72ea76703dcb37 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/cohere.md @@ -0,0 +1,152 @@ + +*This model was released on 2024-03-12 and added to Hugging Face Transformers on 2024-03-15.* + +
+
+ PyTorch + FlashAttention + SDPA + Tensor parallelism +
+
+ + +# Cohere + +Cohere [Command-R](https://cohere.com/blog/command-r) is a 35B parameter multilingual large language model designed for long context tasks like retrieval-augmented generation (RAG) and calling external APIs and tools. The model is specifically trained for grounded generation and supports both single-step and multi-step tool use. It supports a context length of 128K tokens. + +You can find all the original Command-R checkpoints under the [Command Models](https://huggingface.co/collections/CohereForAI/command-models-67652b401665205e17b192ad) collection. + + +> [!TIP] +> Click on the Cohere models in the right sidebar for more examples of how to apply Cohere to different language tasks. + +The example below demonstrates how to generate text with [`Pipeline`] or the [`AutoModel`], and from the command line. + + + + +```python +import torch +from transformers import pipeline + +pipeline = pipeline( + task="text-generation", + model="CohereForAI/c4ai-command-r-v01", + torch_dtype=torch.float16, + device=0 +) +pipeline("Plants create energy through a process known as") +``` + + + + +```python +import torch +from transformers import AutoTokenizer, AutoModelForCausalLM + +tokenizer = AutoTokenizer.from_pretrained("CohereForAI/c4ai-command-r-v01") +model = AutoModelForCausalLM.from_pretrained("CohereForAI/c4ai-command-r-v01", torch_dtype=torch.float16, device_map="auto", attn_implementation="sdpa") + +# format message with the Command-R chat template +messages = [{"role": "user", "content": "How do plants make energy?"}] +input_ids = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt").to(model.device) +output = model.generate( + input_ids, + max_new_tokens=100, + do_sample=True, + temperature=0.3, + cache_implementation="static", +) +print(tokenizer.decode(output[0], skip_special_tokens=True)) +``` + + + + +```bash +# pip install -U flash-attn --no-build-isolation +transformers chat CohereForAI/c4ai-command-r-v01 --torch_dtype auto --attn_implementation flash_attention_2 +``` + + + + +Quantization reduces the memory burden of large models by representing the weights in a lower precision. Refer to the [Quantization](../quantization/overview) overview for more available quantization backends. + +The example below uses [bitsandbytes](../quantization/bitsandbytes) to quantize the weights to 4-bits. + +```python +import torch +from transformers import BitsAndBytesConfig, AutoTokenizer, AutoModelForCausalLM + +bnb_config = BitsAndBytesConfig(load_in_4bit=True) +tokenizer = AutoTokenizer.from_pretrained("CohereForAI/c4ai-command-r-v01") +model = AutoModelForCausalLM.from_pretrained("CohereForAI/c4ai-command-r-v01", torch_dtype=torch.float16, device_map="auto", quantization_config=bnb_config, attn_implementation="sdpa") + +# format message with the Command-R chat template +messages = [{"role": "user", "content": "How do plants make energy?"}] +input_ids = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt").to(model.device) +output = model.generate( + input_ids, + max_new_tokens=100, + do_sample=True, + temperature=0.3, + cache_implementation="static", +) +print(tokenizer.decode(output[0], skip_special_tokens=True)) +``` + +Use the [AttentionMaskVisualizer](https://github.com/huggingface/transformers/blob/beb9b5b02246b9b7ee81ddf938f93f44cfeaad19/src/transformers/utils/attention_visualizer.py#L139) to better understand what tokens the model can and cannot attend to. + +```py +from transformers.utils.attention_visualizer import AttentionMaskVisualizer + +visualizer = AttentionMaskVisualizer("CohereForAI/c4ai-command-r-v01") +visualizer("Plants create energy through a process known as") +``` + +
+ +
+ + +## Notes +- Don’t use the torch_dtype parameter in [`~AutoModel.from_pretrained`] if you’re using FlashAttention-2 because it only supports fp16 or bf16. You should use [Automatic Mixed Precision](https://pytorch.org/tutorials/recipes/recipes/amp_recipe.html), set fp16 or bf16 to True if using [`Trainer`], or use [torch.autocast](https://pytorch.org/docs/stable/amp.html#torch.autocast). + +## CohereConfig + +[[autodoc]] CohereConfig + +## CohereTokenizerFast + +[[autodoc]] CohereTokenizerFast + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - update_post_processor + - save_vocabulary + +## CohereModel + +[[autodoc]] CohereModel + - forward + + +## CohereForCausalLM + +[[autodoc]] CohereForCausalLM + - forward diff --git a/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/cohere2.md b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/cohere2.md new file mode 100644 index 0000000000000000000000000000000000000000..50d4e96b29ba548e848f4003d14055408af8c2e3 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/environment/source/docs/source/en/model_doc/cohere2.md @@ -0,0 +1,145 @@ + +*This model was released on 2024-12-13 and added to Hugging Face Transformers on 2024-12-13.* + +
+
+ PyTorch + FlashAttention + SDPA + Tensor parallelism +
+
+ + +# Cohere 2 + +[Cohere Command R7B](https://cohere.com/blog/command-r7b) is an open weights research release of a 7B billion parameter model. It is a multilingual model trained on 23 languages and has a context window of 128k. The model features three layers with sliding window attention and ROPE for efficient local context modeling and relative positional encoding. A fourth layer uses global attention without positional embeddings, enabling unrestricted token interactions across the entire sequence. + +This model is optimized for speed, cost-performance, and compute resources. + +You can find all the original Command-R checkpoints under the [Command Models](https://huggingface.co/collections/CohereForAI/command-models-67652b401665205e17b192ad) collection. + + +> [!TIP] +> Click on the Cohere models in the right sidebar for more examples of how to apply Cohere to different language tasks. + +The example below demonstrates how to generate text with [`Pipeline`] or the [`AutoModel`] class, and from the command line. + + + + +```python +import torch +from transformers import pipeline + +pipeline = pipeline( + task="text-generation", + model="CohereLabs/c4ai-command-r7b-12-2024", + torch_dtype=torch.float16, + device_map=0 +) + +messages = [ + {"role": "user", "content": "Hello, can you please help me book a hotel in Japan?"}, +] +pipeline(messages) +``` + + + + +```python +import torch +from transformers import AutoTokenizer, AutoModelForCausalLM + +tokenizer = AutoTokenizer.from_pretrained("CohereLabs/c4ai-command-r7b-12-2024") +model = AutoModelForCausalLM.from_pretrained( + "CohereLabs/c4ai-command-r7b-12-2024", + torch_dtype=torch.float16, + device_map="auto", + attn_implementation="sdpa" +) + +# format message with the Command-R chat template +messages = [{"role": "user", "content": "Hello, can you please help me book a hotel in Japan?"}] +input_ids = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt").to(model.device) +output = model.generate( + input_ids, + max_new_tokens=100, + do_sample=True, + temperature=0.3, + cache_implementation="static", +) +print(tokenizer.decode(output[0], skip_special_tokens=True)) +``` + + + + +```bash +# pip install -U flash-attn --no-build-isolation +transformers-cli chat CohereLabs/c4ai-command-r7b-12-2024 --torch_dtype auto --attn_implementation flash_attention_2 +``` + + + + +Quantization reduces the memory burden of large models by representing the weights in a lower precision. Refer to the [Quantization](../quantization/overview.md) overview for more available quantization backends. + +The example below uses [bitsandbytes](../quantization/bitsandbytes.md) to quantize the weights to 4-bits. + +```python +import torch +from transformers import BitsAndBytesConfig, AutoTokenizer, AutoModelForCausalLM + +bnb_config = BitsAndBytesConfig(load_in_4bit=True) +tokenizer = AutoTokenizer.from_pretrained("CohereLabs/c4ai-command-r7b-12-2024") +model = AutoModelForCausalLM.from_pretrained( + "CohereLabs/c4ai-command-r7b-12-2024", + torch_dtype=torch.float16, + device_map="auto", + quantization_config=bnb_config, + attn_implementation="sdpa" +) + +# format message with the Command-R chat template +messages = [{"role": "user", "content": "Hello, can you please help me book a hotel in Japan?"}] +input_ids = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt").to(model.device) +output = model.generate( + input_ids, + max_new_tokens=100, + do_sample=True, + temperature=0.3, + cache_implementation="static", +) +print(tokenizer.decode(output[0], skip_special_tokens=True)) +``` + +## Cohere2Config + +[[autodoc]] Cohere2Config + +## Cohere2Model + +[[autodoc]] Cohere2Model + - forward + + +## Cohere2ForCausalLM + +[[autodoc]] Cohere2ForCausalLM + - forward + +