Skip to content

Apply tokenizer truncation before post-processor #307

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 21 additions & 29 deletions lib/bumblebee/utils/tokenizers.ex
Original file line number Diff line number Diff line change
Expand Up @@ -21,55 +21,47 @@ defmodule Bumblebee.Utils.Tokenizers do

input = List.wrap(input)

tokenizer =
if length = opts[:length] do
upper_bound_length = length |> List.wrap() |> Enum.max()

Tokenizer.set_truncation(tokenizer,
max_length: upper_bound_length,
direction: opts[:truncate_direction]
)
Comment on lines +28 to +31
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When we apply the tokenizer it does:

  1. Truncate the sequence if configured (accounting for the number of tokens added by 2.)
  2. Applies post-processor (in particular templating that adds leading trailing tokens)
  3. Applies padding if configured

So for example, lets say we have sequence that tokenizes to [10, 20, 30, 40] and the processor that adds 0 at the beginning and 1 at the end. And let's say we want to enforce length 4. If we tokenize without truncation, it's going to give us [0, 10, 20, 30, 40, 1], and then we manually truncate to [0, 10, 20, 30], which looses the added end token. On the other hand if we configure truncation it's going to compute [10, 20, 30, 40], then first truncate to 4 - 2 addeditional tokens, so [10, 20], and then add the tokens [0, 10, 20, 1].


Now the issue is that Tokenizer.set_truncation copies the underlying tokenizer. It is relatively cheap (bumping some refcounts and copying added_vocabulary, not the full vocabulary). That said ideally we would configure the tokenizer once. So what we can do deprecate options like :length, :truncate_direction, :pad_direction, and instead have a separate function to configure that. @josevalim wdyt?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As you prefer!

else
tokenizer
end

{:ok, encodings} =
Tokenizer.encode_batch(tokenizer, input, add_special_tokens: opts[:add_special_tokens])

length = opts[:length]

{pad_length, truncate_length} =
pad_length =
if is_number(length) do
{length, length}
length
else
max_length =
encodings
|> Enum.map(&Encoding.n_tokens/1)
|> Enum.max()

case length do
nil ->
{max_length, nil}

lengths when is_list(lengths) ->
bounding_length = find_bounding_length(max_length, lengths)
{bounding_length, bounding_length}
nil -> max_length
lengths when is_list(lengths) -> find_bounding_length(max_length, lengths)
end
end

pad_id = Tokenizer.token_to_id(tokenizer, pad_token)

encodings =
Enum.map(encodings, fn encoding ->
transformations = [
Encoding.Transformation.pad(pad_length,
pad_id: pad_id,
pad_token: pad_token,
direction: opts[:pad_direction]
)
]

transformations =
transformations ++
if truncate_length do
[
Encoding.Transformation.truncate(truncate_length,
direction: opts[:truncate_direction]
)
]
else
[]
end

Encoding.transform(encoding, transformations)
Encoding.pad(encoding, pad_length,
pad_id: pad_id,
pad_token: pad_token,
direction: opts[:pad_direction]
)
end)

input_ids = encodings |> Enum.map(&Encoding.get_u32_ids/1) |> u32_binaries_to_tensor()
Expand Down
2 changes: 1 addition & 1 deletion test/bumblebee/text/albert_tokenizer_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ defmodule Bumblebee.Text.AlbertTokenizerTest do
Nx.tensor([
[2, 4310, 111, 3, 0, 0],
[2, 4310, 111, 748, 3, 0],
[2, 4310, 111, 748, 19674, 6582]
[2, 4310, 111, 748, 19674, 3]
])
)

Expand Down
23 changes: 11 additions & 12 deletions test/bumblebee/text/bert_tokenizer_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,7 @@ defmodule Bumblebee.Text.BertTokenizerTest do
assert {:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, "bert-base-cased"})

inputs =
Bumblebee.apply_tokenizer(
tokenizer,
[
"Test sentence with [MASK]."
],
Bumblebee.apply_tokenizer(tokenizer, ["Test sentence with [MASK]."],
return_special_tokens_mask: true
)

Expand All @@ -58,13 +54,7 @@ defmodule Bumblebee.Text.BertTokenizerTest do
assert {:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, "bert-base-cased"})

inputs =
Bumblebee.apply_tokenizer(
tokenizer,
[
"Test sentence with [MASK]."
],
return_offsets: true
)
Bumblebee.apply_tokenizer(tokenizer, ["Test sentence with [MASK]."], return_offsets: true)

assert_equal(inputs["start_offsets"], Nx.tensor([[0, 0, 5, 14, 19, 25, 0]]))
assert_equal(inputs["end_offsets"], Nx.tensor([[0, 4, 13, 18, 25, 26, 0]]))
Expand All @@ -84,4 +74,13 @@ defmodule Bumblebee.Text.BertTokenizerTest do

assert {1, 16} = Nx.shape(inputs["input_ids"])
end

test "adds template tokens when the sequence is truncated" do
assert {:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, "bert-base-cased"})

inputs = Bumblebee.apply_tokenizer(tokenizer, ["This is a long test sentence."], length: 5)

assert_equal(inputs["input_ids"], Nx.tensor([[101, 1188, 1110, 170, 102]]))
assert_equal(inputs["attention_mask"], Nx.tensor([[1, 1, 1, 1, 1]]))
end
end