STER / code /ster_constraints.py
eduzrh's picture
feat: NS-D2S GPU pipeline verified (F1=0.859) + multi-city benchmark plan + constraint program
a80391b
Raw
History Blame Contribute Delete
2.82 kB
# Fix: constraint_program — convert all numpy constants to torch tensors
# And CS-SDEdit gradient computation
import torch
import torch.nn.functional as F
import numpy as np
def constraint_program(x):
"""Compute constraint violation C(x).
x: (batch, 25) tensor in log(1+x) space.
Returns: (batch,) tensor of total violation (always differentiable).
"""
b = x.shape[0]
device = x.device
# Property name to index map
idx = {
"compactness_2d": 12, "compactness_3d": 13, "cubeness": 19,
"hemisphericality": 17, "area": 2, "volume": 5,
"height_diff": 9, "num_vertices": 24, "bounding_box_width": 0,
"bounding_box_length": 1, "aligned_bounding_box_height": 23,
"num_floors": 10, "density": 14,
}
c2d = x[:, idx["compactness_2d"]]
c3d = x[:, idx["compactness_3d"]]
cub = x[:, idx["cubeness"]]
hemi = x[:, idx["hemisphericality"]]
area_log = x[:, idx["area"]]
volume_log = x[:, idx["volume"]]
height = x[:, idx["height_diff"]]
n_vert = x[:, idx["num_vertices"]]
bb_w = x[:, idx["bounding_box_width"]]
bb_l = x[:, idx["bounding_box_length"]]
bb_h = x[:, idx["aligned_bounding_box_height"]]
floors = x[:, idx["num_floors"]]
density = x[:, idx["density"]]
# All constants as torch tensors
log2 = torch.tensor(np.log(2.0), device=device)
log4 = torch.tensor(np.log(4.0), device=device)
eps = torch.tensor(1e-6, device=device)
tol = torch.tensor(2.0, device=device)
v_list = []
# H1-H4: Boundedness ∈ (0, 1] → in log space ∈ (0, log(2)]
v_list.append(F.relu(-c2d + eps) + F.relu(c2d - log2)) # H1
v_list.append(F.relu(-c3d + eps) + F.relu(c3d - log2)) # H2
v_list.append(F.relu(-cub + eps) + F.relu(cub - log2)) # H3
v_list.append(F.relu(-hemi + eps) + F.relu(hemi - log2)) # H4
# H5-H9: Positivity
v_list.append(F.relu(-area_log + eps)) # H5
v_list.append(F.relu(-volume_log + eps)) # H6
v_list.append(F.relu(-height + eps)) # H7
v_list.append(F.relu(-n_vert + log4)) # H8: ≥4 vertices
v_list.append(F.relu(-bb_w + eps)) # H9
# S1-S4: Dimensional consistency (soft, tolerance=2.0)
vol_est = area_log + height
v_list.append(F.relu(torch.abs(volume_log - vol_est) - tol)) # S1
v_list.append(F.relu(torch.abs(floors - height / log4) - tol)) # S2
v_list.append(F.relu(density - log2)) # S3
v_list.append(F.relu(cub - log2)) # S4
return sum(v_list) # (batch,) scalar tensor per sample