| 24 | |
| 25 | |
| 26 | class TestBertModel(unittest.TestCase): |
| 27 | def init_data(self, use_cuda) -> None: |
| 28 | torch.set_grad_enabled(False) |
| 29 | torch.set_num_threads(4) |
| 30 | turbo_transformers.set_num_threads(4) |
| 31 | self.test_device = torch.device('cuda:0') if use_cuda else \ |
| 32 | torch.device('cpu:0') |
| 33 | |
| 34 | self.cfg = BertConfig() |
| 35 | self.torch_model = BertModel(self.cfg) |
| 36 | self.torch_model.eval() |
| 37 | |
| 38 | if torch.cuda.is_available(): |
| 39 | self.torch_model.to(self.test_device) |
| 40 | |
| 41 | self.turbo_model = turbo_transformers.BertModel.from_torch( |
| 42 | self.torch_model, self.test_device, "turbo") |
| 43 | |
| 44 | def check_torch_and_turbo(self, use_cuda): |
| 45 | self.init_data(use_cuda) |
| 46 | num_iter = 1 |
| 47 | device_name = "GPU" if use_cuda else "CPU" |
| 48 | input_ids = torch.randint(low=0, |
| 49 | high=self.cfg.vocab_size - 1, |
| 50 | size=(1, 10), |
| 51 | dtype=torch.long, |
| 52 | device=self.test_device) |
| 53 | |
| 54 | torch_model = lambda: self.torch_model(input_ids) |
| 55 | torch_result, torch_qps, torch_time = \ |
| 56 | test_helper.run_model(torch_model, use_cuda, num_iter) |
| 57 | print(f'BertModel PyTorch({device_name}) QPS {torch_qps}') |
| 58 | |
| 59 | turbo_model = (lambda: self.turbo_model(input_ids)) |
| 60 | |
| 61 | with turbo_transformers.pref_guard("bert_perf") as perf: |
| 62 | turbo_result, turbo_qps, turbo_time = \ |
| 63 | test_helper.run_model(turbo_model, use_cuda, num_iter) |
| 64 | print(f'BertModel TurboTransformer({device_name}) QPS {turbo_qps}') |
| 65 | |
| 66 | self.assertTrue( |
| 67 | numpy.allclose(torch_result[0].cpu(), |
| 68 | turbo_result[0].cpu(), |
| 69 | atol=1e-3, |
| 70 | rtol=1e-3)) |
| 71 | |
| 72 | def test_bert_model(self): |
| 73 | if torch.cuda.is_available() and \ |
| 74 | turbo_transformers.config.is_compiled_with_cuda(): |
| 75 | self.check_torch_and_turbo(use_cuda=True) |
| 76 | self.check_torch_and_turbo(use_cuda=False) |
| 77 | |
| 78 | |
| 79 | if __name__ == '__main__': |
nothing calls this directly
no outgoing calls
no test coverage detected