beautiful_mnist.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. # model based off https://towardsdatascience.com/going-beyond-99-mnist-handwritten-digits-recognition-cfff96337392
  2. from typing import List, Callable
  3. from tinygrad import Tensor, TinyJit, nn, GlobalCounters
  4. from tinygrad.helpers import getenv, colored, trange
  5. from tinygrad.nn.datasets import mnist
  6. class Model:
  7. def __init__(self):
  8. self.layers: List[Callable[[Tensor], Tensor]] = [
  9. nn.Conv2d(1, 32, 5), Tensor.relu,
  10. nn.Conv2d(32, 32, 5), Tensor.relu,
  11. nn.BatchNorm(32), Tensor.max_pool2d,
  12. nn.Conv2d(32, 64, 3), Tensor.relu,
  13. nn.Conv2d(64, 64, 3), Tensor.relu,
  14. nn.BatchNorm(64), Tensor.max_pool2d,
  15. lambda x: x.flatten(1), nn.Linear(576, 10)]
  16. def __call__(self, x:Tensor) -> Tensor: return x.sequential(self.layers)
  17. if __name__ == "__main__":
  18. X_train, Y_train, X_test, Y_test = mnist()
  19. model = Model()
  20. opt = nn.optim.Adam(nn.state.get_parameters(model))
  21. @TinyJit
  22. def train_step() -> Tensor:
  23. with Tensor.train():
  24. opt.zero_grad()
  25. samples = Tensor.randint(getenv("BS", 512), high=X_train.shape[0])
  26. # TODO: this "gather" of samples is very slow. will be under 5s when this is fixed
  27. loss = model(X_train[samples]).sparse_categorical_crossentropy(Y_train[samples]).backward()
  28. opt.step()
  29. return loss
  30. @TinyJit
  31. def get_test_acc() -> Tensor: return (model(X_test).argmax(axis=1) == Y_test).mean()*100
  32. test_acc = float('nan')
  33. for i in (t:=trange(70)):
  34. GlobalCounters.reset() # NOTE: this makes it nice for DEBUG=2 timing
  35. loss = train_step()
  36. if i%10 == 9: test_acc = get_test_acc().item()
  37. t.set_description(f"loss: {loss.item():6.2f} test_accuracy: {test_acc:5.2f}%")
  38. # verify eval acc
  39. if target := getenv("TARGET_EVAL_ACC_PCT", 0.0):
  40. if test_acc >= target and test_acc != 100.0: print(colored(f"{test_acc=} >= {target}", "green"))
  41. else: raise ValueError(colored(f"{test_acc=} < {target}", "red"))