test_wo_a_w8.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. """CPU checks for adapter/wo_a_w8.py: twin exactness, rejection of non-representable weights, and
  2. the kernel patch (including the drift guard). The GPU kernel itself is checked on the Spark."""
  3. import os
  4. import types
  5. os.environ["DSV41_WO_A_W8"] = "1"
  6. import torch # noqa: E402
  7. import wo_a_w8 # noqa: E402
  8. def checkpoint_like(seed=0):
  9. g = torch.Generator().manual_seed(seed)
  10. q = (torch.randn(2, 1024, 4096, generator=g) * 60).clamp(-448, 448).to(torch.float8_e4m3fn)
  11. e = torch.randint(-14, -6, (2, 32, 128), generator=g).float()
  12. return (q.float().view(2, 32, 32, 128, 32) * torch.exp2(e)[:, :, None, :, None]).view(2, 1024, 4096).to(torch.bfloat16)
  13. def test_twin_is_exact():
  14. w = checkpoint_like()
  15. q, s = wo_a_w8.make_twin(w)
  16. back = (q.float().view(2, 32, 32, 128, 32) * torch.exp2(s.float() - 127)[:, :, None, :, None]).view(2, 1024, 4096)
  17. assert torch.equal(back.to(torch.bfloat16), w)
  18. def test_view_accepts_tp3_groups():
  19. # Padded TP3 is 4 local o_groups; the twin path must see [4, 1024, 4096].
  20. w = torch.empty(4 * 1024, 4096, dtype=torch.bfloat16)
  21. assert tuple(wo_a_w8._wo_a_view(w).shape) == (4, 1024, 4096)
  22. def test_non_representable_is_rejected():
  23. w = torch.randn(2, 1024, 4096).to(torch.bfloat16) # bf16 mantissas e4m3 cannot hold
  24. assert wo_a_w8.make_twin(w) is None
  25. def test_patch_and_drift_guard():
  26. def small(x, w):
  27. return "stock"
  28. def small_mx(x, w):
  29. return "stock-mx"
  30. kern = types.SimpleNamespace(wo_a_bf16_small_batch=small, wo_a_bf16_small_batch_mxfp8=small_mx,
  31. _wo_a_reduce=None, _quantize_partial=None, __name__="k")
  32. model = types.SimpleNamespace(wo_a_bf16_small_batch=small, wo_a_bf16_small_batch_mxfp8=small_mx)
  33. wo_a_w8._patch_kernels(model, kern)
  34. assert model.wo_a_bf16_small_batch is kern.wo_a_bf16_small_batch is not small
  35. # a weight without a twin still goes to the stock kernel
  36. assert model.wo_a_bf16_small_batch(torch.zeros(6, 2, 4096), torch.zeros(1)) == "stock"
  37. drifted = types.SimpleNamespace(wo_a_bf16_small_batch=small, _wo_a_reduce=None, _quantize_partial=None, __name__="k")
  38. try:
  39. wo_a_w8._patch_kernels(types.SimpleNamespace(), drifted)
  40. except RuntimeError:
  41. return
  42. raise AssertionError("drifted kernel module was accepted")
  43. if __name__ == "__main__":
  44. test_twin_is_exact()
  45. test_view_accepts_tp3_groups()
  46. test_non_representable_is_rejected()
  47. test_patch_and_drift_guard()
  48. print("test_wo_a_w8: ok")