I would like to solve the problem of optimizing the packing N equally-sized squares of maximal size into a larger size with (x,y) in [-L, L] and [-L, L]. I have a function that does the following in a differentiable manner:
Function: get_maximal_expansion(squares, L)
Input: squares is a tensor of shape Nx3, representing the coordinates of each square and angle as (x,y,theta). L is 2.
Output: The maximal size of all equally-sized squares, such that no squares overlap
As a first pass, let's create a neural network that considers the case of N=17. Let's use a transformer architecture. We start off with an empty list. On each pass of the transformer, we can get it to generate the position of the next square position. We run N=17 passes of the transformer and get the final set of coordinates. We can then train the transformer somehow so that it gets us the best packing. Write me python code using Pytorch (2.7.1+cu118) that does this.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
I'll create a PyTorch implementation of an autoregressive transformer that generates square positions sequentially to maximize the packing density. Since you have a differentiable get_maximal_expansion function, we can directly optimize for the maximum square size.
python
import torch
import torch.nn as nn
import torch.optim as optim
import math
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Constants
N = 17
L = 2.0
class PositionalEncoding(nn.Module):
"""Standard sinusoidal positional encoding"""
def __init__(self, d_model, max_len=50):
super(PositionalEncoding, self).__init__()
pe = torch.zeros(max_len, d_model)
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
self.register_buffer('pe', pe.unsqueeze(0).transpose(0, 1))
def forward(self, x):
return x + self.pe[:x.size(0), :]
class AutoregressivePackingTransformer(nn.Module):
def __init__(self, N=17, d_model=256, nhead=8, num_layers=6, dim_feedforward=1024, L=2.0):
super(AutoregressivePackingTransformer, self).__init__()
self.N = N
self.L = L
self.d_model = d_model
self.input_dim = 3 # x, y, theta
# Input embedding
self.input_embedding = nn.Linear(self.input_dim, d_model)
self.pos_encoder = PositionalEncoding(d_model, max_len=N + 1)
# Transformer decoder (no encoder needed for autoregressive generation)
decoder_layer = nn.TransformerDecoderLayer(
d_model=d_model,
nhead=nhead,
dim_feedforward=dim_feedforward,
dropout=0.1,
batch_first=False
)
self.decoder = nn.TransformerDecoder(decoder_layer, num_layers)
# Output head
self.output_head = nn.Sequential(
nn.Linear(d_model, d_model // 2),
nn.ReLU(),
nn.Linear(d_model // 2, 3) # Output: x, y, theta
)
# Learnable start token
self.start_token = nn.Parameter(torch.randn(1, 1, self.input_dim))
# Dummy memory for decoder (required by PyTorch API)
self.register_buffer('dummy_memory', torch.zeros(1, 1, d_model))
def forward(self):
batch_size = 1
device = next(self.parameters()).device
# Initialize with start token
current_sequence = self.start_token # (1, 1, input_dim)
generated_squares = []
for i in range(self.N):
# Embed and add positional encoding
seq_len = current_sequence.size(0)
embedded = self.input_embedding(current_sequence) * math.sqrt(self.d_model)
embedded = self.pos_encoder(embedded)
# Create causal mask
causal_mask = nn.Transformer.generate_square_subsequent_mask(seq_len).to(device)
# Pass through decoder
memory = self.dummy_memory.repeat(1, batch_size, 1)
decoder_output = self.decoder(
tgt=embedded,
memory=memory,
tgt_mask=causal_mask
)
# Get output for the last position
last_hidden = decoder_output[-1, :, :] # (batch_size, d_model)
# Generate next square parameters
raw_output = self.output_head(last_hidden) # (batch_size, 3)
# Process outputs to ensure they're in valid ranges
x = torch.tanh(raw_output[:, 0:1]) * self.L # x in [-L, L]
y = torch.tanh(raw_output[:, 1:2]) * self.L # y in [-L, L]
theta = torch.sigmoid(raw_output[:, 2:3]) * 2 * math.pi # theta in [0, 2π]
next_square = torch.cat([x, y, theta], dim=1) # (batch_size, 3)
generated_squares.append(next_square)
# Append to sequence for next iteration
if i < self.N - 1:
next_square_expanded = next_square.unsqueeze(0) # (1, batch_size, 3)
current_sequence = torch.cat([current_sequence, next_square_expanded], dim=0)
# Stack all generated squares: (N, 3)
final_configuration = torch.cat(generated_squares, dim=0)
return final_configuration
def visualize_packing(squares, square_size, L, epoch, title_suffix=""):
"""Visualize the packing configuration"""
squares_np = squares.detach().cpu().numpy()
square_size_np = square_size.detach().cpu().item()
fig, ax = plt.subplots(figsize=(8, 8))
# Draw the boundary
boundary = patches.Rectangle((-L, -L), 2*L, 2*L,
edgecolor='black', facecolor='lightgray',
linewidth=2, alpha=0.3)
ax.add_patch(boundary)
# Draw each square
for i in range(len(squares_np)):
x, y, theta = squares_np[i]
# Create a square centered at origin, then rotate and translate
square = patches.Rectangle(
(-square_size_np/2, -square_size_np/2),
square_size_np,
square_size_np,
edgecolor='blue',
facecolor='skyblue',
alpha=0.7
)
# Apply rotation and translation
t = patches.transforms.Affine2D().rotate(theta).translate(x, y) + ax.transData
square.set_transform(t)
ax.add_patch(square)
# Add square number at center
ax.text(x, y, str(i), ha='center', va='center', fontsize=8)
ax.set_xlim(-L - 0.5, L + 0.5)
ax.set_ylim(-L - 0.5, L + 0.5)
ax.set_aspect('equal')
ax.grid(True, alpha=0.3)
title = f"N={N} Squares, Size={square_size_np:.4f}, Epoch={epoch}"
if title_suffix:
title += f" - {title_suffix}"
ax.set_title(title)
plt.tight_layout()
plt.show()
def train_packing_transformer(get_maximal_expansion, num_epochs=3000):
"""Train the transformer to maximize square size"""
model = AutoregressivePackingTransformer(N=N, L=L).to(device)
optimizer = optim.Adam(model.parameters(), lr=0.001)
scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=num_epochs)
best_size = 0
best_squares = None
print(f"Training on {device}")
print(f"Packing {N} squares in [{-L}, {L}]²")
for epoch in range(num_epochs):
model.train()
optimizer.zero_grad()
# Generate square configuration
squares = model() # (N, 3)
# Calculate maximal expansion
max_size = get_maximal_expansion(squares, L)
# Loss is negative of square size (we want to maximize size)
loss = -max_size
# Backpropagation
loss.backward()
# Gradient clipping for stability
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
optimizer.step()
scheduler.step()
# Track best configuration
current_size = max_size.item()
if current_size > best_size:
best_size = current_size
best_squares = squares.detach().clone()
print(f"Epoch {epoch}: New best size = {best_size:.6f}")
# Periodic logging and visualization
if epoch % 100 == 0:
print(f"Epoch {epoch}/{num_epochs}: Size = {current_size:.6f}, "
f"Loss = {loss.item():.6f}, LR = {scheduler.get_last_lr()[0]:.6f}")
if epoch % 500 == 0 or epoch == num_epochs - 1:
visualize_packing(squares, max_size, L, epoch)
print(f"\nTraining complete. Best square size achieved: {best_size:.6f}")
if best_squares is not None:
print("Visualizing best configuration...")
best_size_tensor = get_maximal_expansion(best_squares, L)
visualize_packing(best_squares, best_size_tensor, L, "Final", "Best Configuration")
return model, best_squares, best_size
# Example usage with a dummy get_maximal_expansion function
# Replace this with your actual differentiable function
def dummy_get_maximal_expansion(squares, L):
"""
Dummy implementation - replace with your actual function
This just returns a small value that increases with better separation
"""
N = squares.shape[0]
# Simple heuristic: penalize close squares
min_dist = float('inf')
for i in range(N):
for j in range(i + 1, N):
dist = torch.norm(squares[i, :2] - squares[j, :2])
min_dist = min(min_dist, dist)
# Return a size that's larger when squares are well-separated
# This is just a placeholder - use your actual function
return torch.tensor(min_dist / 10, requires_grad=True, device=squares.device)
if __name__ == "__main__":
# Replace dummy_get_maximal_expansion with your actual function
# model, best_config, best_size = train_packing_transformer(get_maximal_expansion)
# For demonstration with dummy function:
print("Note: Using dummy get_maximal_expansion function for demonstration")
print("Replace with your actual differentiable packing function")
model, best_config, best_size = train_packing_transformer(dummy_get_maximal_expansion, num_epochs=1000)
This implementation includes:
AutoregressivePackingTransformer: A transformer decoder that generates square positions sequentially
Uses positional encoding to track the sequence position
Employs causal masking to ensure autoregressive generation
Outputs (x, y, theta) for each square with appropriate constraints
Training Loop:
Maximizes the square size by minimizing the negative size
Uses gradient clipping for stability
Tracks the best configuration found
Includes learning rate scheduling
Visualization: Shows the packing configuration at regular intervals
To use this with your actual get_maximal_expansion function, simply replace the dummy_get_maximal_expansion call in the main block: