File size: 1,589 Bytes
afec862 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | """Verify physical row batching independently of CUDA, task rewards, and saved results."""
import torch
from torch import nn
from novel_tokens.model import Canvas, Policy
def test_physical_rows_preserve_logits_and_optimizer_gradient():
class Reader(nn.Module):
logits = Policy.logits
def __init__(self):
super().__init__()
self.scale = nn.Parameter(torch.tensor([0.3, -0.7], dtype=torch.float64))
self.widths = []
def _project(self, canvas, positions, mode):
assert mode == "number"
self.widths.append(len(canvas.ids))
values = (canvas.ids * canvas.visible).gather(1, positions).double()
return (values.unsqueeze(-1) * self.scale).tanh()
model = Reader()
ids = torch.arange(24).reshape(6, 4)
canvas = Canvas(ids, (ids % 5 != 0).long())
positions = torch.tensor([[0, 3], [2, 1], [1, 3]] * 2)
def run(limit):
model.forward_rows = limit
model.widths.clear()
model.zero_grad(set_to_none=True)
with torch.no_grad():
sampled = model.logits(canvas, positions, "number")
replay = model.logits(canvas, positions, "number")
replay.square().sum().backward()
torch.testing.assert_close(sampled, replay)
return sampled, model.scale.grad.clone()
full, full_gradient = run(None)
chunked, chunked_gradient = run(4)
assert max(model.widths) == 4 and 2 in model.widths
torch.testing.assert_close(chunked, full)
torch.testing.assert_close(chunked_gradient, full_gradient)
|