trl icon indicating copy to clipboard operation
trl copied to clipboard

If there are any training acceleration techniques?

Open 141forever opened this issue 10 months ago • 10 comments

Reproduction

I would like to ask whether there are any training acceleration techniques for the GOLD algorithm in TRL.

My setup is as follows: ''' training_args = GOLDConfig( output_dir="gold-model-llama", save_strategy="steps", save_steps=500, learning_rate=1e-7, warmup_ratio=0.05, per_device_train_batch_size=16, teacher_model_name_or_path=teacher_name, teacher_tokenizer_name_or_path=teacher_name, bf16=True, use_uld_loss=True, uld_use_hybrid_loss=True, push_to_hub=False, report_to=[], lr_scheduler_type = 'cosine', num_train_epochs=5, max_steps=2000, logging_steps=10, gradient_accumulation_steps=1, lmbda = 0.5, beta = 0.0, uld_crossentropy_weight = 0, uld_distillation_weight = 1.0, ) '' I am currently running on 2*H200 GPUs, with 30k samples for 5 epochs (or 2000 steps), yet it still takes about 15 hours to complete.

System Info

above

Checklist

  • [x] I have checked that my issue isn't already filed (see open issues)
  • [x] I have included my system information
  • [x] Any code provided is minimal, complete, and reproducible (more on MREs)
  • [x] Any code provided is properly formatted in code blocks, (no screenshot, more on code blocks)
  • [x] Any traceback provided is complete

141forever avatar Jan 19 '26 13:01 141forever

thanks for the report @141forever the main slowness is perhaps in the sampling for which one can use the vllm server via the use_vllm flag to speed up that part of the pipeline

kashif avatar Jan 19 '26 16:01 kashif

Additionally, you can also lower the lambda value to 0.25. It will yield similar performance but will be faster to run because it need to sample fewer generations.

cmpatino avatar Jan 19 '26 17:01 cmpatino

Thank you very much to both of you for your replies. I did a timing analysis and found that on-policy generation takes about 2 seconds, while off-policy does not require additional time. However, the loss computation takes around 10–20 seconds. It seems that the loss calculation is also a part worth optimizing.

141forever avatar Jan 20 '26 05:01 141forever

In particular, the ULDLoss computation code scales linearly with the batch size (BSZ), and it is unclear whether there is room for optimization in this part.

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)

            # Get token IDs for mapping (always use actual input_ids)
            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:
                # Build alignment groups directly from token ids using greedy text matching
                student_alignment_groups, teacher_alignment_groups = self._build_alignment_groups_from_ids(
                    student_token_ids, teacher_token_ids
                )

                # Merge student probabilities using student alignment groups
                # Pass student_token_ids to enable corrected conditional probability merging
                student_aligned = self._merge_probabilities_with_alignment_groups(
                    student_probs, student_alignment_groups, student_token_ids
                )

                # Merge teacher probabilities using teacher alignment groups
                # Pass teacher_token_ids to enable corrected conditional probability merging
                teacher_aligned = self._merge_probabilities_with_alignment_groups(
                    teacher_probs, teacher_alignment_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)

141forever avatar Jan 20 '26 06:01 141forever

I know the answers to all the questions now!!!!

In the code at https://github.com/huggingface/trl/blob/main/trl/experimental/gold/gold_trainer.py from line 617 to line 621:

if self._teacher_matched_ids:
    teacher_matched_indices = torch.tensor(sorted(self._teacher_matched_ids), dtype=torch.long, device=device)
    student_matched_indices = torch.tensor(
        [self._vocab_mapping[tid.item()] for tid in teacher_matched_indices], dtype=torch.long, device=device
    )

The .item() here involves transferring data from GPU to CPU. Since teacher_matched_indices can be very large (possibly over 100k), this operation can be extremely time-consuming.

I have updated the code, which speeds up the training time by 6 times:

if self._teacher_matched_ids:
    teacher_matched_indices = torch.tensor(sorted(self._teacher_matched_ids), dtype=torch.long, device=device)
    teacher_indices_cpu = teacher_matched_indices.cpu().tolist()
    student_matched_indices = torch.tensor( 
                [self._vocab_mapping[tid] for tid in teacher_indices_cpu], dtype=torch.long, device=device
            )

Do you need a PR or something?

141forever avatar Jan 20 '26 09:01 141forever

That's a very good catch! Thank you for flagging this.

A PR would be great. But first, I think we may optimize it further. What if we avoid the Python loop altogether?

We can build a mapping tensor

max_teacher_id = max(self_vocab_mapping.keys())
mapping_tensor = torch.full(
    (max_teacher_id + 1,), -1, dtype=torch.long
)  # -1 for unmapped ids
for k, v in vocab_mapping.items():
    mapping_tensor[k] = v
mapping_tensor_device = mapping_tensor.to(device)

and then use it to map the indices

teacher_matched_indices = torch.tensor(
    sorted(self._teacher_matched_ids), dtype=torch.long, device=device
)
student_matched_indices = mapping_tensor_device[teacher_matched_indices]

A ran a quick benchmarking and it is ~2x faster that your suggestion and way faster than our initial approach, but it would be better if you test it on your use case to check it works. What do you think, @141forever?

(Also tagging @kashif for visibility)

cmpatino avatar Jan 20 '26 10:01 cmpatino

That's a very good catch! Thank you for flagging this.

A PR would be great. But first, I think we may optimize it further. What if we avoid the Python loop altogether?

We can build a mapping tensor

max_teacher_id = max(self_vocab_mapping.keys()) mapping_tensor = torch.full( (max_teacher_id + 1,), -1, dtype=torch.long ) # -1 for unmapped ids for k, v in vocab_mapping.items(): mapping_tensor[k] = v mapping_tensor_device = mapping_tensor.to(device) and then use it to map the indices

teacher_matched_indices = torch.tensor( sorted(self._teacher_matched_ids), dtype=torch.long, device=device ) student_matched_indices = mapping_tensor_device[teacher_matched_indices] A ran a quick benchmarking and it is ~2x faster that your suggestion and way faster than our initial approach, but it would be better if you test it on your use case to check it works. What do you think, @141forever?

(Also tagging @kashif for visibility)

I think that is a great idea. What can I do for you?

141forever avatar Jan 20 '26 17:01 141forever

It would be great if you upload a PR with this change and let us know here when you've created it.

If you haven't made a PR to trl before, there is a great guide that walks you through the steps. You can also ask us any questions you have.

cmpatino avatar Jan 21 '26 09:01 cmpatino

It would be great if you upload a PR with this change and let us know here when you've created it.

If you haven't made a PR to trl before, there is a great guide that walks you through the steps. You can also ask us any questions you have.

SURE, I will let you know ASAP.

141forever avatar Jan 21 '26 15:01 141forever

Hi, there! This is my PR: https://github.com/huggingface/trl/pull/4888.

141forever avatar Jan 22 '26 13:01 141forever