test_training.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import argparse
  2. from typing import Optional
  3. import torch
  4. import torch.nn as nn
  5. import torch.nn.functional as F
  6. from hivemind import RemoteExpert, find_open_port, LOCALHOST
  7. from test_utils.run_server import background_server
  8. from sklearn.datasets import load_digits
  9. def test_training(port: Optional[int] = None, max_steps: int = 100, threshold: float = 0.9):
  10. dataset = load_digits()
  11. X_train, y_train = torch.tensor(dataset['data'], dtype=torch.float), torch.tensor(dataset['target'])
  12. with background_server(num_experts=2, device='cpu', hidden_dim=64) as (server_endpoint, _):
  13. expert1 = RemoteExpert('expert.0', server_endpoint)
  14. expert2 = RemoteExpert('expert.1', server_endpoint)
  15. model = nn.Sequential(expert2, nn.Tanh(), expert1, nn.Linear(64, 10))
  16. opt = torch.optim.SGD(model.parameters(), lr=0.05)
  17. for step in range(max_steps):
  18. opt.zero_grad()
  19. outputs = model(X_train)
  20. loss = F.cross_entropy(outputs, y_train)
  21. loss.backward()
  22. opt.step()
  23. accuracy = (outputs.argmax(dim=1) == y_train).numpy().mean()
  24. if accuracy >= threshold:
  25. break
  26. assert accuracy >= threshold, f"too small accuracy: {accuracy}"