code: def truncate_sequences(
      tokens_ls: Sequence[Sequence],
      max_length: int,
      truncate_end: bool = True,
  ):
      """Takes a sequence of sequences and trims the sub-seqs to fit within the max length.
  
      Trims the length of subsequences within a sequence until the total length of the combined sub-
      sequences is within the max_length. While total length exceeds the max_length, trims whichever
      subsequence is longest until the total combined length of the subsequences is under the limit.
  
      Args:
          tokens_ls (Sequence[Sequence]): sequence of subsequences to truncate.
          max_length (int): the maximum length of the combined sub-sequences.
          truncate_end (bool): if True, truncate from the end of the sub-sequence, else from start.
  
      Returns:
          Sequence[Sequence] with subsequences trimmed to fit within the max length when combined.
  
      """
      if len(tokens_ls) == 0:
          return []
      if len(tokens_ls) == 1:
          if truncate_end:
              return [tokens_ls[0][:max_length]]
          else:
              return [tokens_ls[0][-max_length:]]
      lengths = np.array([len(tokens) for tokens in tokens_ls])
      total_length = lengths.sum()
      if total_length < max_length:
          return tokens_ls
      target_lengths = lengths
      while sum(target_lengths) > max_length:
          target_lengths[np.argmax(target_lengths)] -= 1
  
      return [
          tokens[:target_length]
          if truncate_end
          else tokens[-target_length:]
          for tokens, target_length in zip(tokens_ls, target_lengths)
      ]
  
file_path: jiant/jiant/tasks/utils.py
imports: import numpy
  from typing import NamedTuple, Sequence
label_desc: Use image node_id 1 for calling a global function with example usage: truncate_sequences(tokens_ls, max_length, truncate_end) and returns: unknown, list, tokens_ls, list, list