def set_valid_max_seq_length(
    desired=None, model_max_length=512, num_max_tokens_in_seq=510
) -> int:
    """Calculate and set the maximum allowed sequence length."""
    min_length = model_max_length - num_max_tokens_in_seq
    max_length = num_max_tokens_in_seq

    if desired is None or desired > max_length or desired <= min_length:
        desired = max_length
    return desired