First, let's start by importing the necessary libraries, checking if CUDA is available, and defining some utility functions:
import os
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
# Check if CUDA is available and set the device accordingly
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print("Using device:", device)
def tokens_to_tensor(tokens, num_tokens):
token_indices = [hash(token) % num_tokens for token in tokens]
tensor = torch.zeros(num_tokens, device=device)
for idx in token_indices:
tensor[idx] += 1
return tensor
Now, let's define the simple neural network architecture and the function to generate 32x32x32 arrays from tokens:
class SimpleNeuralNet(nn.Module):
def __init__(self, num_tokens):
super(SimpleNeuralNet, self).__init__()
self.fc1 = nn.Linear(num_tokens, 2048)
self.fc2 = nn.Linear(2048, 32 * 32 * 32)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = self.fc2(x)
return x.view(-1, 32, 32, 32)
def generate_from_tokens(model, tokens, num_tokens):
token_tensor = tokens_to_tensor(tokens, num_tokens)
with torch.no_grad():
output = model(token_tensor.unsqueeze(0).float())
return output.squeeze(0).cpu().numpy()
Now, let's define the training function:
def train_model(model, data_loader, criterion, optimizer, epochs, save_path):
for epoch in range(epochs):
for batch_idx, (inputs, targets) in enumerate(data_loader):
inputs, targets = inputs.to(device), targets.to(device)
optimizer.zero_grad()
outputs = model(inputs.float())
loss = criterion(outputs, targets.float())
loss.backward()
optimizer.step()
print(f"Epoch [{epoch + 1}/{epochs}] - Loss: {loss.item()}")
torch.save(model.state_dict(), save_path)
print(f"Model saved to {save_path}")
Finally, let's create the main functions to load the pretrained model, generate 3D arrays from tokens, and train the model:
def get_pretrained_model(path, num_tokens):
model = SimpleNeuralNet(num_tokens).to(device)
if os.path.exists(path):
model.load_state_dict(torch.load(path, map_location=device))
print(f"Loaded pretrained weights from {path}")
return model
def save_model(model, path):
torch.save(model.state_dict(), path)
# Testing tokens function
num_tokens = 1024
test_tokens = ['hello', 'world', 'test']
pretrained_path = 'pretrained_weights.pth'
model = get_pretrained_model(pretrained_path, num_tokens)
output_array = generate_from_tokens(model, test_tokens, num_tokens)
print("Generated array shape:", output_array.shape)
# Training on random data
mock_data = torch.randint(low=0, high=1024, size=(1024, num_tokens))
mock_targets = torch.randint(low=0, high=1024, size=(1024, 32, 32, 32))
data_loader = torch.utils.data.DataLoader(torch.utils.data.TensorDataset(mock_data, mock_targets), batch_size=32)
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
epochs = 10
trained_path = 'trained_weights.pth'
train_model(model, data_loader, criterion, optimizer, epochs, trained_path)