-
Notifications
You must be signed in to change notification settings - Fork 107
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Co-authored-by: Jonatan Kłosko <jonatanklosko@gmail.com>
- Loading branch information
1 parent
b9acb4a
commit 23de64b
Showing
4 changed files
with
238 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,116 @@ | ||
defmodule Bumblebee.Text.TextEmbedding do | ||
@moduledoc false | ||
|
||
alias Bumblebee.Shared | ||
|
||
def text_embedding(model_info, tokenizer, opts \\ []) do | ||
%{model: model, params: params, spec: _spec} = model_info | ||
|
||
opts = | ||
Keyword.validate!(opts, [ | ||
:compile, | ||
output_attribute: :pooled_state, | ||
output_pool: nil, | ||
embedding_processor: nil, | ||
defn_options: [] | ||
]) | ||
|
||
output_attribute = opts[:output_attribute] | ||
output_pool = opts[:output_pool] | ||
embedding_processor = opts[:embedding_processor] | ||
compile = opts[:compile] | ||
defn_options = opts[:defn_options] | ||
|
||
batch_size = compile[:batch_size] | ||
sequence_length = compile[:sequence_length] | ||
|
||
if compile != nil and (batch_size == nil or sequence_length == nil) do | ||
raise ArgumentError, | ||
"expected :compile to be a keyword list specifying :batch_size and :sequence_length, got: #{inspect(compile)}" | ||
end | ||
|
||
{_init_fun, encoder} = Axon.build(model) | ||
|
||
embedding_fun = fn params, inputs -> | ||
output = encoder.(params, inputs) | ||
|
||
output = | ||
if is_map(output) do | ||
output[output_attribute] | ||
else | ||
output | ||
end | ||
|
||
output = | ||
case output_pool do | ||
nil -> | ||
output | ||
|
||
:mean_pooling -> | ||
input_mask_expanded = Nx.new_axis(inputs["attention_mask"], -1) | ||
|
||
output | ||
|> Nx.multiply(input_mask_expanded) | ||
|> Nx.sum(axes: [1]) | ||
|> Nx.divide(Nx.sum(input_mask_expanded, axes: [1])) | ||
|
||
other -> | ||
raise ArgumentError, | ||
"expected :output_pool to be one of nil or :mean_pooling, got: #{inspect(other)}" | ||
end | ||
|
||
output = | ||
case embedding_processor do | ||
nil -> | ||
output | ||
|
||
:l2_norm -> | ||
Bumblebee.Utils.Nx.normalize(output) | ||
|
||
other -> | ||
raise ArgumentError, | ||
"expected :embedding_processor to be one of nil or :l2_norm, got: #{inspect(other)}" | ||
end | ||
|
||
output | ||
end | ||
|
||
Nx.Serving.new( | ||
fn defn_options -> | ||
embedding_fun = | ||
Shared.compile_or_jit(embedding_fun, defn_options, compile != nil, fn -> | ||
inputs = %{ | ||
"input_ids" => Nx.template({batch_size, sequence_length}, :u32), | ||
"attention_mask" => Nx.template({batch_size, sequence_length}, :u32) | ||
} | ||
|
||
[params, inputs] | ||
end) | ||
|
||
fn inputs -> | ||
inputs = Shared.maybe_pad(inputs, batch_size) | ||
embedding_fun.(params, inputs) | ||
end | ||
end, | ||
defn_options | ||
) | ||
|> Nx.Serving.process_options(batch_size: batch_size) | ||
|> Nx.Serving.client_preprocessing(fn input -> | ||
{texts, multi?} = Shared.validate_serving_input!(input, &Shared.validate_string/1) | ||
|
||
inputs = | ||
Bumblebee.apply_tokenizer(tokenizer, texts, | ||
length: sequence_length, | ||
return_token_type_ids: false | ||
) | ||
|
||
{Nx.Batch.concatenate([inputs]), multi?} | ||
end) | ||
|> Nx.Serving.client_postprocessing(fn embeddings, _metadata, multi? -> | ||
for embedding <- Bumblebee.Utils.Nx.batch_to_list(embeddings) do | ||
%{embedding: embedding} | ||
end | ||
|> Shared.normalize_output(multi?) | ||
end) | ||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
defmodule Bumblebee.Text.TextEmbeddingTest do | ||
use ExUnit.Case, async: false | ||
|
||
import Bumblebee.TestHelpers | ||
|
||
@moduletag model_test_tags() | ||
|
||
describe "integration" do | ||
test "returns E5 embedding for a piece of text" do | ||
{:ok, model_info} = Bumblebee.load_model({:hf, "intfloat/e5-large"}) | ||
{:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, "intfloat/e5-large"}) | ||
|
||
serving = Bumblebee.Text.TextEmbedding.text_embedding(model_info, tokenizer) | ||
|
||
text = "query: Cats are cute." | ||
|
||
assert %{embedding: %Nx.Tensor{} = embedding} = Nx.Serving.run(serving, text) | ||
|
||
assert Nx.shape(embedding) == {1024} | ||
|
||
assert_all_close( | ||
embedding[1..3], | ||
Nx.tensor([-0.9815, -0.5015, 0.9868]), | ||
atol: 1.0e-4 | ||
) | ||
end | ||
|
||
test "returns normalized E5 embedding for a piece of text" do | ||
{:ok, model_info} = Bumblebee.load_model({:hf, "intfloat/e5-large"}) | ||
{:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, "intfloat/e5-large"}) | ||
|
||
options = [embedding_processor: :l2_norm] | ||
|
||
serving = Bumblebee.Text.TextEmbedding.text_embedding(model_info, tokenizer, options) | ||
|
||
text = "query: Cats are cute." | ||
|
||
assert %{embedding: %Nx.Tensor{} = embedding} = Nx.Serving.run(serving, text) | ||
|
||
assert Nx.shape(embedding) == {1024} | ||
|
||
assert_all_close( | ||
embedding[1..3], | ||
Nx.tensor([-0.0459, -0.0234, 0.0461]), | ||
atol: 1.0e-4 | ||
) | ||
|
||
assert_equal(Nx.sum(Nx.pow(embedding, 2)), Nx.tensor(1.0)) | ||
end | ||
end | ||
end |