test_block_exact_match.py 3.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import random
  2. from typing import Union
  3. import pytest
  4. import torch
  5. from transformers.models.bloom.configuration_bloom import BloomConfig
  6. from petals.bloom.block import WrappedBloomBlock
  7. from petals.bloom.from_pretrained import DTYPE_MAP, _load_state_dict, load_pretrained_block
  8. from petals.client import DistributedBloomConfig, RemoteSequential
  9. from petals.data_structures import UID_DELIMITER
  10. from test_utils import *
  11. @pytest.mark.forked
  12. def test_remote_block_exact_match(atol_forward=1e-4, atol_inference=1e-3):
  13. config = DistributedBloomConfig.from_pretrained(MODEL_NAME, initial_peers=INITIAL_PEERS)
  14. remote_sequential = RemoteSequential(config)
  15. for block_index in random.sample(range(config.n_layer), 3):
  16. remote_block = remote_sequential[block_index]
  17. inputs = torch.randn(1, 8, config.hidden_size)
  18. outputs_forward = remote_block(inputs)
  19. outputs_inference = []
  20. with remote_block.inference_session(max_length=inputs.shape[1]) as sess:
  21. for i in range(inputs.shape[1]):
  22. outputs_inference.append(sess.step(inputs[:, i : i + 1, :]))
  23. # test that max length is respected
  24. with pytest.raises(ValueError, match=r"Maximum length exceeded") as exc_info:
  25. sess.step(inputs[:, -1:, :])
  26. assert "Maximum length exceeded" in repr(exc_info.value)
  27. outputs_inference = torch.cat(outputs_inference, dim=1)
  28. ref_block = load_pretrained_block(MODEL_NAME, block_index, torch_dtype=torch.float32)
  29. (outputs_local,) = ref_block(inputs)
  30. assert torch.allclose(outputs_local, outputs_forward, rtol=0, atol=atol_forward)
  31. assert torch.allclose(outputs_local, outputs_inference, rtol=0, atol=atol_inference)
  32. def _old_load_pretrained_block(
  33. converted_model_name_or_path: str,
  34. block_index: int,
  35. torch_dtype: Union[torch.dtype, str] = "auto",
  36. ) -> WrappedBloomBlock:
  37. """Load the BLOOM block by directly initializing the weights.
  38. This test is used to check consistency with the previous implementation and can be removed in the future."""
  39. config = BloomConfig.from_pretrained(converted_model_name_or_path)
  40. block = WrappedBloomBlock(config)
  41. state_dict = _load_state_dict(
  42. converted_model_name_or_path,
  43. block_index,
  44. config,
  45. cache_dir=None,
  46. )
  47. if torch_dtype == "auto":
  48. with torch.no_grad():
  49. for name, param in block.named_parameters():
  50. assert name in state_dict, f"{name} not in state dict"
  51. param.data = param.data.to(state_dict[name].dtype)
  52. else:
  53. assert torch_dtype in DTYPE_MAP.values(), f"torch_dtype must be one of {list(DTYPE_MAP.values())}"
  54. block = block.to(dtype=torch_dtype)
  55. block.load_state_dict(state_dict, strict=True)
  56. return block
  57. @pytest.mark.forked
  58. def test_init_pretrained_block(torch_dtype=torch.float32, atol_forward=1e-8):
  59. config = DistributedBloomConfig.from_pretrained(MODEL_NAME)
  60. torch.random.manual_seed(0)
  61. inputs = torch.randn(1, 16, config.hidden_size, dtype=torch_dtype)
  62. block = load_pretrained_block(MODEL_NAME, 3, torch_dtype=torch_dtype)
  63. ref_block = _old_load_pretrained_block(MODEL_NAME, 3, torch_dtype=torch_dtype)
  64. outputs = block.forward(inputs)[0]
  65. outputs_ref = ref_block.forward(inputs)[0]
  66. assert torch.allclose(outputs, outputs_ref, rtol=0, atol=atol_forward)