from pathlib import Path
import torch
import torch.nn as nn
test_dir = Path(__file__).parent / "test_data"
class Net(nn.Module):
def __init__(self):
super().__init__()
self.fc = nn.Linear(4, 3)
self.head = nn.Linear(3, 2, bias=False)
self.blocks = nn.Sequential(nn.Linear(2, 2), nn.BatchNorm1d(2))
self.tied = self.fc
self.register_buffer("running_mean", torch.arange(3, dtype=torch.float32))
self.register_buffer("mask", torch.ones(2, dtype=torch.bool), persistent=False)
self.scale = torch.tensor([2.0])
def forward(self, x):
return self.blocks(self.head(self.fc(x)))
def main():
torch.manual_seed(0)
model = Net()
torch.save(model, test_dir / "full_model.pt")
torch.save(model.state_dict(), test_dir / "full_model_state_dict.pt")
torch.save(
{"model": model, "epoch": 3},
test_dir / "full_model_checkpoint.pt",
pickle_protocol=4,
)
for name, tensor in model.state_dict().items():
print(f"{name}: {tuple(tensor.shape)} {tensor.dtype}")
if __name__ == "__main__":
main()