tinygrad 퀵스타트 — Tensor와 기본 연산

tinygrad 퀵스타트 — Tensor와 기본 연산

이 가이드는 PyTorch나 다른 딥러닝 프레임워크 지식이 없다고 가정하지만, 신경망의 기본 개념은 알고 있다고 가정해요. tinygrad의 하이레벨 API를 빠르게 훑으면서 끝에는 손글씨 숫자를 분류하는 모델을 만들게 됩니다.

출처: https://docs.tinygrad.org/quickstart

Tensor

Tensor는 tinygrad의 기본 데이터 구조예요. 특정 데이터 타입의 다차원 배열로 생각하면 되고, 하이레벨 연산은 모두 Tensor에서 동작해요.

from tinygrad import Tensor

파이썬 리스트나 numpy ndarray에서 만들 수 있고, 팩토리 메서드로도 만들 수 있어요.

full = Tensor.full(shape=(2, 3), fill_value=5)  # create a tensor of shape (2, 3) filled with 5
zeros = Tensor.zeros(2, 3)  # create a tensor of shape (2, 3) filled with 0
ones = Tensor.ones(2, 3)  # create a tensor of shape (2, 3) filled with 1

eye = Tensor.eye(3)  # create a 3x3 identity matrix
arange = Tensor.arange(start=0, stop=10, step=1)  # create a tensor of shape (10,) filled with values from 0 to 9

rand = Tensor.rand(2, 3)  # uniform distribution
randn = Tensor.randn(2, 3)  # standard normal distribution

모든 생성 메서드는 dtype 인자를 받을 수 있어요.

from tinygrad import dtypes

t3 = Tensor([1, 2, 3, 4, 5], dtype=dtypes.int32)

연산은 lazy

Tensor 연산은 이렇게 합니다. 그리고 이 모든 연산은 lazy 해서, .realize().numpy()로 tensor를 realize할 때까지 실행되지 않습니다.

t4 = Tensor([1, 2, 3, 4, 5])
t5 = (t4 + 1) * 2
t6 = (t5 * t4).relu().log_softmax()

print(t6.numpy())
# [-56. -48. -36. -20.   0.]

신경망 모델

trainable 파라미터가 필요한 레이어는 클래스로 만들고, 필요 없으면 함수만으로 충분해요. nn.Linear가 그 예다.

class Linear:
    def __init__(self, in_features, out_features, bias=True, initialization: str='kaiming_uniform'):
        self.weight = getattr(Tensor, initialization)(out_features, in_features)
        self.bias = Tensor.zeros(out_features) if bias else None

    def __call__(self, x):
        return x.linear(self.weight.transpose(), self.bias)

이어가기

MNIST를 분류하는 2계층 신경망(TinyNet)을 만들어 128개의 은닉 유닛과 Leaky ReLU로 학습시키고, 손실은 sparse categorical cross entropy 를 씁니다. 훈련은 신경망·손실 함수를 정의한 뒤 .backward()를 호출해 그라디언트를 계산하고 옵티마이저로 파라미터를 갱신하면 됩니다.

더 알아보기