test_modeling_flax_bert.py 1.65 KB
Newer Older
1
2
3
4
import unittest

from numpy import ndarray

Sylvain Gugger's avatar
Sylvain Gugger committed
5
from transformers import BertTokenizerFast, TensorType, is_flax_available, is_torch_available
6
7
8
9
from transformers.testing_utils import require_flax, require_torch


if is_flax_available():
Sylvain Gugger's avatar
Sylvain Gugger committed
10
    from transformers.models.bert.modeling_flax_bert import FlaxBertModel
11
12
13
14

if is_torch_available():
    import torch

Sylvain Gugger's avatar
Sylvain Gugger committed
15
    from transformers.models.bert.modeling_bert import BertModel
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30


@require_flax
@require_torch
class FlaxBertModelTest(unittest.TestCase):
    def test_from_pytorch(self):
        with torch.no_grad():
            with self.subTest("bert-base-cased"):
                tokenizer = BertTokenizerFast.from_pretrained("bert-base-cased")
                fx_model = FlaxBertModel.from_pretrained("bert-base-cased")
                pt_model = BertModel.from_pretrained("bert-base-cased")

                # Check for simple input
                pt_inputs = tokenizer.encode_plus("This is a simple input", return_tensors=TensorType.PYTORCH)
                fx_inputs = tokenizer.encode_plus("This is a simple input", return_tensors=TensorType.JAX)
31
                pt_outputs = pt_model(**pt_inputs).to_tuple()
32
33
34
35
36
37
38
39
40
41
                fx_outputs = fx_model(**fx_inputs)

                self.assertEqual(len(fx_outputs), len(pt_outputs), "Output lengths differ between Flax and PyTorch")

                for fx_output, pt_output in zip(fx_outputs, pt_outputs):
                    self.assert_almost_equals(fx_output, pt_output.numpy(), 5e-4)

    def assert_almost_equals(self, a: ndarray, b: ndarray, tol: float):
        diff = (a - b).sum()
        self.assertLessEqual(diff, tol, "Difference between torch and flax is {} (>= {})".format(diff, tol))