Sure! Let's proceed to implement the code as per your instructions. We'll start by loading the data using the provided code, preprocess the grids by padding them to a fixed size, and then define and train a sparse autoencoder without data augmentation.
Below is the step-by-step implementation:
1. Data Loading and Preprocessing
First, we'll load the data using the provided code and preprocess the grids.
import json
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
import torch.nn as nn
import torch.optim as optim
# Define the base path to the dataset
base_path = '/kaggle/input/arc-prize-2024/' # Update this path accordingly
# Loading JSON data
def load_json(file_path):
with open(file_path) as f:
data = json.load(f)
return data
# Reading files
training_challenges = load_json(base_path + 'arc-agi_training_challenges.json')
training_solutions = load_json(base_path + 'arc-agi_training_solutions.json')
evaluation_challenges = load_json(base_path + 'arc-agi_evaluation_challenges.json')
evaluation_solutions = load_json(base_path + 'arc-agi_evaluation_solutions.json')
test_challenges = load_json(base_path + 'arc-agi_test_challenges.json')
# Example exploration
for i in range(5):
t = list(training_challenges)[i]
task = training_challenges[t]
print(f'Set #{i}, {t}')
task = training_challenges['007bbfb7']
print(task.keys())
n_train_pairs = len(task['train'])
n_test_pairs = len(task['test'])
print(f'Task contains {n_train_pairs} training pairs')
print(f'Task contains {n_test_pairs} test pairs')
print(task['train'][0]['input'])
print(task['train'][0]['output'])
2. Preprocessing Grids
We need to pad the grids to a fixed size (e.g., 30x30) and normalize the values.
# Define the maximum grid size
MAX_GRID_SIZE = 30
def pad_grid(grid, max_size=MAX_GRID_SIZE):
"""
Pads the grid to the specified max_size with zeros (background value).
"""
height = len(grid)
width = len(grid[0])
padded_grid = np.zeros((max_size, max_size), dtype=np.int64)
padded_grid[:height, :width] = np.array(grid)
return padded_grid
# Collect all input and output grids from training data
input_grids = []
output_grids = []
for task_id in training_challenges:
task = training_challenges[task_id]
for pair in task['train']:
input_grid = pad_grid(pair['input'])
output_grid = pad_grid(pair['output'])
input_grids.append(input_grid)
output_grids.append(output_grid)
print(f"Total number of training pairs: {len(input_grids)}")
3. Creating a Custom Dataset
We'll create a custom PyTorch Dataset to handle our data.
class ARCDataset(Dataset):
def __init__(self, input_grids, output_grids):
self.inputs = input_grids
self.outputs = output_grids
def __len__(self):
return len(self.inputs)
def __getitem__(self, idx):
input_grid = self.inputs[idx]
output_grid = self.outputs[idx]
# Convert grids to tensors
input_tensor = torch.from_numpy(input_grid).long()
output_tensor = torch.from_numpy(output_grid).long()
return input_tensor, output_tensor
# Create dataset and dataloader
dataset = ARCDataset(input_grids, output_grids)
dataloader = DataLoader(dataset, batch_size=32, shuffle=True)
4. Defining the Sparse Autoencoder
We'll define a simple sparse autoencoder using PyTorch. Since we're dealing with discrete values (integers from 0 to 9), we'll use embedding layers to convert these integers into continuous embeddings before feeding them into the autoencoder.
4.1. Embedding Layer
NUM_COLORS = 10 # Colors are integers from 0 to 9
EMBEDDING_DIM = 16 # Dimension of the embedding vector
embedding = nn.Embedding(NUM_COLORS, EMBEDDING_DIM)
4.2. Autoencoder Model
class SparseAutoencoder(nn.Module):
def __init__(self, embedding_dim=EMBEDDING_DIM, hidden_dim=256, sparse_dim=1024):
super(SparseAutoencoder, self).__init__()
self.embedding = nn.Embedding(NUM_COLORS, embedding_dim)
# Encoder
self.encoder = nn.Sequential(
nn.Conv2d(embedding_dim, 64, kernel_size=3, padding=1),
nn.ReLU(),
nn.Conv2d(64, 128, kernel_size=3, padding=1),
nn.ReLU(),
nn.Flatten(),
nn.Linear(128 * MAX_GRID_SIZE * MAX_GRID_SIZE, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, sparse_dim),
nn.ReLU(),
)
# Decoder
self.decoder = nn.Sequential(
nn.Linear(sparse_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, 128 * MAX_GRID_SIZE * MAX_GRID_SIZE),
nn.ReLU(),
nn.Unflatten(1, (128, MAX_GRID_SIZE, MAX_GRID_SIZE)),
nn.ConvTranspose2d(128, 64, kernel_size=3, padding=1),
nn.ReLU(),
nn.ConvTranspose2d(64, embedding_dim, kernel_size=3, padding=1),
nn.ReLU(),
)
# Output layer
self.output_layer = nn.Conv2d(embedding_dim, NUM_COLORS, kernel_size=1)
def forward(self, x):
# x shape: (batch_size, height, width)
batch_size = x.size(0)
x_embed = self.embedding(x) # Shape: (batch_size, height, width, embedding_dim)
x_embed = x_embed.permute(0, 3, 1, 2) # Shape: (batch_size, embedding_dim, height, width)
# Encoder
encoded = self.encoder(x_embed)
# Decoder
decoded = self.decoder(encoded)
# Output layer
output = self.output_layer(decoded)
return output, encoded
4.3. Sparsity Constraint
We'll implement the sparsity constraint by adding L1 regularization on the encoded representations.
def sparsity_loss(encoded, sparsity_weight=1e-5):
return sparsity_weight * torch.mean(torch.abs(encoded))
5. Training the Sparse Autoencoder
We'll set up the training loop.
# Initialize model, loss function, and optimizer
model = SparseAutoencoder()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=1e-3)
# Move model to GPU if available
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
embedding.to(device)
# Training loop
num_epochs = 10 # Adjust the number of epochs as needed
for epoch in range(num_epochs):
model.train()
total_loss = 0.0
for batch_idx, (inputs, _) in enumerate(dataloader):
inputs = inputs.to(device) # Shape: (batch_size, height, width)
optimizer.zero_grad()
# Forward pass
outputs, encoded = model(inputs)
# outputs shape: (batch_size, NUM_COLORS, height, width)
outputs = outputs.permute(0, 2, 3, 1) # Shape: (batch_size, height, width, NUM_COLORS)
outputs = outputs.reshape(-1, NUM_COLORS) # Reshape for CrossEntropyLoss
targets = inputs.view(-1) # Flatten targets
# Compute losses
reconstruction_loss = criterion(outputs, targets)
sparsity = sparsity_loss(encoded)
loss = reconstruction_loss + sparsity
# Backward pass and optimization
loss.backward()
optimizer.step()
total_loss += loss.item()
avg_loss = total_loss / len(dataloader)
print(f"Epoch [{epoch+1}/{num_epochs}], Loss: {avg_loss:.4f}")
6. Testing the Autoencoder
Let's test the autoencoder on some grids to see how well it reconstructs them.
import matplotlib.pyplot as plt
def plot_grid(grid, title="Grid"):
plt.imshow(grid, cmap='tab10', vmin=0, vmax=9)
plt.title(title)
plt.colorbar(ticks=range(10))
plt.show()
# Get a sample from the dataset
model.eval()
with torch.no_grad():
sample_input, _ = dataset[0]
sample_input = sample_input.unsqueeze(0).to(device)
outputs, encoded = model(sample_input)
outputs = outputs.argmax(dim=1).squeeze(0).cpu().numpy()
original_input = sample_input.squeeze(0).cpu().numpy()
plot_grid(original_input, title="Original Grid")
plot_grid(outputs, title="Reconstructed Grid")
Notes:
- Variable Grid Sizes: Since all grids are padded to
30x30, the autoencoder can handle them in batches.
- Integer Values: The use of the embedding layer allows us to convert integer grid values to continuous embeddings suitable for convolutional layers.
- Loss Function: We use
CrossEntropyLoss because the output is a classification over the possible colors (0 to 9).
- Sparsity Constraint: The sparsity loss encourages the encoded representations to be sparse.
- Hyperparameters: Adjust
EMBEDDING_DIM, hidden_dim, sparse_dim, learning rate, and number of epochs based on performance.
Conclusion
This implementation provides a basic sparse autoencoder trained on the ARC dataset without data augmentation. It serves as a foundation for further development, such as incorporating the custom reasoning architecture and data augmentation as per your proposed solution.
Feel free to adjust the model architecture and training parameters to improve performance. Additionally, you can proceed to implement the Build Algorithm and Run Algorithm blocks following the same development approach.