code: def sort_batch_by_length(tensor: torch.Tensor, sequence_lengths: torch.Tensor):
      if not isinstance(tensor, torch.Tensor) or not isinstance(sequence_lengths, torch.Tensor):
          raise ConfigurationError("Both the tensor and sequence lengths must be torch.Tensors.")
      sorted_sequence_lengths, permutation_index = sequence_lengths.sort(0, descending=True)
      sorted_tensor = tensor.index_select(0, permutation_index)
      index_range = torch.arange(0, len(sequence_lengths), device=sequence_lengths.device)
      _, reverse_mapping = permutation_index.sort(0, descending=False)
      restoration_indices = index_range.index_select(0, reverse_mapping)
      return sorted_tensor, sorted_sequence_lengths, restoration_indices, permutation_index