"""Stage A. Two full-resolution side views and the six joint positions.""" import timm import torch from torch import nn from torch.nn import functional as F from .geometry import FIXTURE_SCALE, FIXTURE_XY, ORIGIN, PARTS, SCALE class CoarseNet(nn.Module): def __init__(self, imagenet_path=None): super().__init__() trunk = timm.create_model("resnet18", pretrained=False) if imagenet_path is not None: state = torch.load(imagenet_path, map_location="cpu", weights_only=True) trunk.load_state_dict(state, strict=True) self.encoder = nn.Sequential( trunk.conv1, trunk.bn1, trunk.act1, trunk.maxpool, trunk.layer1, trunk.layer2, trunk.layer3, nn.Conv2d(256, 32, 1), nn.BatchNorm2d(32), nn.ReLU(), nn.AdaptiveAvgPool2d((9, 16))) self.fuse = nn.Sequential(nn.Linear(2 * 32 * 9 * 16 + 6, 512), nn.LayerNorm(512), nn.SiLU(), nn.Dropout(0.1), nn.Linear(512, 384), nn.LayerNorm(384), nn.SiLU()) self.part_head = nn.Linear(384, len(PARTS) * 10) self.fixture_head = nn.Linear(384, 4) self.register_buffer("mean", torch.tensor( [0.485, 0.456, 0.406]).view(1, 3, 1, 1)) self.register_buffer("std", torch.tensor( [0.229, 0.224, 0.225]).view(1, 3, 1, 1)) self.register_buffer("origin", torch.tensor(ORIGIN)) self.register_buffer("scale", torch.tensor(SCALE)) self.register_buffer("fixture_xy", torch.tensor(FIXTURE_XY)) # Bolt offsets follow Part.head_local_x and Part.tip_x, in kit order. self.register_buffer("bolt_offsets", torch.tensor( [[0.025, -0.030], [0.035, -0.0425], [0.050, -0.05935]])) def forward(self, images, joints): """Accept uint8 RGB [B,2,3,360,640] and joint angles in radians.""" batch = joints.shape[0] rgb = images.flatten(0, 1).contiguous(memory_format=torch.channels_last) rgb = (rgb.float() / 255 - self.mean) / self.std features = self.encoder(rgb).reshape(batch, -1) joined = self.fuse(torch.cat((features, joints / torch.pi), dim=1)) raw = self.part_head(joined).float().reshape(batch, len(PARTS), 10) fixture = self.fixture_head(joined).float() centre = raw[:, :, 1:4] * self.scale + self.origin axis = F.normalize(raw[:, :, 4:7], dim=-1) points = (centre[:, :3, None] + axis[:, :3, None] * self.bolt_offsets[..., None]) return dict(presence=raw[:, :, 0], centre=centre, axis=axis, points=points, hex=F.normalize(raw[:, :, 7:9], dim=-1), confidence=raw[:, :, 9], fixture_xy=fixture[:, :2] * FIXTURE_SCALE + self.fixture_xy, fixture_angle=F.normalize(fixture[:, 2:4], dim=-1))