5/23
Part 1 of 6 · From NumPy to PyTorchLearn and do

Three things a tensor carries

The numbers aren't the whole story. Every tensor also knows three facts about itself. You need to know they exist, not their details.

What kind of number it holds. Token ids are whole numbers, int64. Weights and activations are decimals, float32. Masks are True and False, bool:

# the cat sat on the mat, as ids
ids = torch.tensor([0, 1, 2, 3, 0, 4])
print(ids.dtype, scores.dtype, (ids > 0).dtype)
torch.int64 torch.float32 torch.bool

The dot in 70. is what made the scores decimals. That tiny dot matters more than it looks. Only decimals can hold minus infinity, and attention uses minus infinity to hide tokens. Build your scores from whole numbers and the masking step stops with an error, so convert them with .float() first.

Where the numbers live. On the CPU or on a GPU. Every tensor in one operation has to be in the same place, and model.to("cuda") moves a whole model in one call.

Whether PyTorch is taking notes. During training, PyTorch records every operation so it can work out the gradients later. When you generate text or run a test, those notes only waste memory, and a with torch.no_grad(): block turns them off. Here nn.Linear(2, 2) is a tiny layer with weights to train. The Layers step covers it.

lin = nn.Linear(2, 2)
with torch.no_grad():
    a = lin(torch.ones(1, 2))
b = lin(torch.ones(1, 2))
print(a.requires_grad, b.requires_grad)
False True

a was made inside the block, so it carries no history. b was made outside it, so it does.

The editor holds the ids from above and raw_scores, a 2 by 2 table of whole numbers. Fill in mask, True where an id is above 0, and scores_f, the same table as decimals.