test_training.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536
  1. from functools import partial
  2. from typing import Optional
  3. import torch
  4. import torch.nn as nn
  5. import torch.nn.functional as F
  6. from sklearn.datasets import load_digits
  7. from hivemind import RemoteExpert, background_server
  8. def test_training(port: Optional[int] = None, max_steps: int = 100, threshold: float = 0.9):
  9. dataset = load_digits()
  10. X_train, y_train = torch.tensor(dataset['data'], dtype=torch.float), torch.tensor(dataset['target'])
  11. SGD = partial(torch.optim.SGD, lr=0.05)
  12. with background_server(num_experts=2, device='cpu', Optimzer=SGD, 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).float().mean().item()
  24. if accuracy >= threshold:
  25. break
  26. assert accuracy >= threshold, f"too small accuracy: {accuracy}"