test_chained_inference.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. ######
  2. # Warning:torch this test is a work in progress. It will be modified soon.
  3. # - if you want more stable tests, see test_block_exact_match
  4. # - if you want to figure out chained inference, ask yozh
  5. import os
  6. import hivemind
  7. import torch
  8. from hivemind.moe.expert_uid import ExpertInfo
  9. from src.bloom.from_pretrained import load_pretrained_block
  10. from src.client.remote_block import RemoteTransformerBlock
  11. from src.dht_utils import get_remote_module
  12. INITIAL_PEERS = os.environ.get("INITIAL_PEERS")
  13. if not INITIAL_PEERS:
  14. raise RuntimeError("Must specify INITIAL_PEERS environment variable with one or more peer ids")
  15. INITIAL_PEERS = INITIAL_PEERS.split()
  16. BLOCK_UID = os.environ.get("BLOCK_UID")
  17. if not BLOCK_UID:
  18. raise RuntimeError("Must specify BLOCK_UID as an index of a transformer block to be tested")
  19. REF_NAME = os.environ.get("REF_NAME", "bigscience/test-bloomd-6b3")
  20. REF_INDEX = int(os.environ.get("REF_INDEX", BLOCK_UID[-1].split(".")[-1]))
  21. def test_remote_block_exact_match(atol_inference=1e-4):
  22. dht = hivemind.DHT(initial_peers=INITIAL_PEERS, client_mode=True, start=True)
  23. remote_block = get_remote_module(dht, BLOCK_UID)
  24. assert remote_block is not None, f"Could not find {BLOCK_UID} in DHT"
  25. assert isinstance(remote_block, RemoteTransformerBlock)
  26. _ = remote_block.info # lazy-init info now, because otherwise we will _break_ info init by chaning _info
  27. remote_block._info = ExpertInfo('bloom6b3.3 bloom6b3.4', remote_block._info.peer_id)
  28. inputs = torch.randn(1, 8, 4096)
  29. outputs_inference = []
  30. with remote_block.begin_inference_session() as sess:
  31. for i in range(inputs.shape[1]):
  32. outputs_inference.append(sess.step(inputs[:, i : i + 1, :]))
  33. outputs_inference = torch.cat(outputs_inference, dim=1)
  34. ref_blocks = [
  35. load_pretrained_block(REF_NAME, 3, torch_dtype=torch.float32),
  36. load_pretrained_block(REF_NAME, 4, torch_dtype=torch.float32)
  37. ]
  38. outputs_ref = []
  39. caches = [None, None]
  40. for i in range(inputs.shape[1]):
  41. new_caches = []
  42. hidden_states = inputs[:, i : i + 1, :]
  43. for ref_block, cache in zip(ref_blocks, caches):
  44. with torch.no_grad():
  45. hidden_states, new_cache = ref_block.forward(hidden_states, use_cache=True, layer_past=cache)
  46. new_caches.append(new_cache)
  47. outputs_ref.append(hidden_states)
  48. caches = new_caches
  49. outputs_ref = torch.cat(outputs_ref, dim=1)
  50. assert torch.allclose(outputs_ref, outputs_inference, rtol=0, atol=atol_inference)