|
| 1 | +# Copyright 2024 NVIDIA CORPORATION |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import pytest |
| 16 | + |
| 17 | +from crossfit.utils.model_adapter import adapt_model_input |
| 18 | + |
| 19 | +torch = pytest.importorskip("torch") |
| 20 | +sentence_transformers = pytest.importorskip("sentence_transformers") |
| 21 | +transformers = pytest.importorskip("transformers") |
| 22 | + |
| 23 | + |
| 24 | +def test_adapt_model_input_hf(): |
| 25 | + from transformers import AutoTokenizer, DistilBertModel |
| 26 | + |
| 27 | + with torch.no_grad(): |
| 28 | + model_hf = DistilBertModel.from_pretrained("distilbert-base-uncased") |
| 29 | + tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased") |
| 30 | + inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") |
| 31 | + |
| 32 | + # Hugging Face model output |
| 33 | + outputs_hf = model_hf(**inputs) |
| 34 | + adapted_inputs_hf = adapt_model_input(model_hf, inputs) |
| 35 | + assert torch.equal(adapted_inputs_hf.last_hidden_state, outputs_hf.last_hidden_state) |
| 36 | + |
| 37 | + |
| 38 | +def test_adapt_model_input_sentence_transformers(): |
| 39 | + from transformers import AutoTokenizer |
| 40 | + |
| 41 | + with torch.no_grad(): |
| 42 | + model_st = sentence_transformers.SentenceTransformer("all-MiniLM-L6-v2").to("cpu") |
| 43 | + tokenizer = AutoTokenizer.from_pretrained("sentence-transformers/all-MiniLM-L6-v2") |
| 44 | + |
| 45 | + inputs = tokenizer( |
| 46 | + ["Hello", "my dog is cute"], return_tensors="pt", padding=True, truncation=True |
| 47 | + ) |
| 48 | + # Sentence Transformers model output |
| 49 | + expected_output = model_st(inputs) |
| 50 | + adapted_output_st = adapt_model_input(model_st, inputs) |
| 51 | + |
| 52 | + assert torch.equal(adapted_output_st.sentence_embedding, expected_output.sentence_embedding) |
0 commit comments