test_block_exact_match.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import random
  2. import pytest
  3. import torch
  4. from petals import AutoDistributedConfig, RemoteSequential
  5. from petals.server.from_pretrained import load_pretrained_block
  6. from test_utils import *
  7. @pytest.mark.forked
  8. def test_remote_block_exact_match(atol_forward=1e-4, atol_inference=1e-3):
  9. config = AutoDistributedConfig.from_pretrained(MODEL_NAME, initial_peers=INITIAL_PEERS)
  10. remote_sequential = RemoteSequential(config)
  11. for block_index in random.sample(range(config.num_hidden_layers), 3):
  12. remote_block = remote_sequential[block_index]
  13. inputs = torch.randn(1, 8, config.hidden_size)
  14. outputs_forward = remote_block(inputs)
  15. outputs_inference = []
  16. with torch.inference_mode():
  17. with remote_block.inference_session(max_length=inputs.shape[1]) as sess:
  18. for i in range(inputs.shape[1]):
  19. outputs_inference.append(sess.step(inputs[:, i : i + 1, :]))
  20. # test that max length is respected
  21. with pytest.raises(ValueError, match=r"Maximum length exceeded") as exc_info:
  22. sess.step(inputs[:, -1:, :])
  23. assert "Maximum length exceeded" in repr(exc_info.value)
  24. outputs_inference = torch.cat(outputs_inference, dim=1)
  25. ref_block = load_pretrained_block(MODEL_NAME, block_index, torch_dtype=torch.float32)
  26. (outputs_local,) = ref_block(inputs)
  27. assert torch.allclose(outputs_local, outputs_forward, rtol=0, atol=atol_forward)
  28. assert torch.allclose(outputs_local, outputs_inference, rtol=0, atol=atol_inference)