def filter_input_words(all_counts, allowed_chars, max_input_tokens):
    """Filters out words with unallowed chars and limits words to max_input_tokens.

    Args:
      all_counts: list of (string, int) tuples
      allowed_chars: list of single-character strings
      max_input_tokens: int, maximum number of tokens accepted as input

    Returns:
      list of (string, int) tuples of filtered wordcounts
    """
    # Ensure that the input is sorted so that if `max_input_tokens` is reached
    # the least common tokens are dropped.
    all_counts = sorted(
        all_counts, key=lambda word_and_count: word_and_count[1], reverse=True)
    filtered_counts = []
    for word, count in all_counts:
        if (max_input_tokens != -1 and
                len(filtered_counts) >= max_input_tokens):
            break
        has_unallowed_chars = False
        for char in word:
            if char not in allowed_chars:
                has_unallowed_chars = True
                break
        if has_unallowed_chars:
            continue
        filtered_counts.append((word, count))

    return filtered_counts