test_training.py 1.2 KB

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