149 lines
4.7 KiB
Python
149 lines
4.7 KiB
Python
"""HLS-friendly higher-capacity CNN for light-petal recognition.
|
|
|
|
This model is intentionally larger than the old TinyCNN while still keeping a
|
|
regular layer set that can be translated to Vitis HLS later:
|
|
|
|
- RGB input, 128x128, float32 in [0, 1]
|
|
- Conv2d + BatchNorm2d + ReLU + MaxPool blocks
|
|
- Global average pooling
|
|
- Two linear layers for 10 logits
|
|
|
|
It is not a FINN/Brevitas model. The purpose is to train a stronger CNN on
|
|
Windows first, then export fused/fixed-point weights to a hand-written or
|
|
generated HLS accelerator.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import torch
|
|
import torch.nn as nn
|
|
|
|
|
|
DEFAULT_INPUT_SIZE = 128
|
|
DEFAULT_CHANNELS = (16, 32, 64, 96, 128)
|
|
DEFAULT_HIDDEN_FEATURES = 128
|
|
|
|
|
|
class ConvBNReLU(nn.Module):
|
|
def __init__(self, in_channels: int, out_channels: int) -> None:
|
|
super().__init__()
|
|
self.conv = nn.Conv2d(
|
|
in_channels,
|
|
out_channels,
|
|
kernel_size=3,
|
|
stride=1,
|
|
padding=1,
|
|
bias=False,
|
|
)
|
|
self.bn = nn.BatchNorm2d(out_channels)
|
|
self.relu = nn.ReLU(inplace=True)
|
|
|
|
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
return self.relu(self.bn(self.conv(x)))
|
|
|
|
|
|
class HLSQConvNet(nn.Module):
|
|
"""A stronger CNN that avoids exotic ops for later HLS implementation."""
|
|
|
|
def __init__(
|
|
self,
|
|
num_classes: int = 10,
|
|
input_size: int = DEFAULT_INPUT_SIZE,
|
|
channels: tuple[int, ...] = DEFAULT_CHANNELS,
|
|
hidden_features: int = DEFAULT_HIDDEN_FEATURES,
|
|
dropout: float = 0.1,
|
|
) -> None:
|
|
super().__init__()
|
|
if input_size % (2 ** len(channels)) != 0:
|
|
raise ValueError(
|
|
f"input_size={input_size} must be divisible by 2^{len(channels)}"
|
|
)
|
|
self.num_classes = num_classes
|
|
self.input_size = input_size
|
|
self.channels = tuple(channels)
|
|
self.hidden_features = hidden_features
|
|
self.dropout = dropout
|
|
|
|
blocks: list[nn.Module] = []
|
|
in_channels = 3
|
|
for out_channels in channels:
|
|
blocks.extend(
|
|
[
|
|
ConvBNReLU(in_channels, out_channels),
|
|
ConvBNReLU(out_channels, out_channels),
|
|
nn.MaxPool2d(kernel_size=2, stride=2),
|
|
]
|
|
)
|
|
in_channels = out_channels
|
|
|
|
self.features = nn.Sequential(*blocks)
|
|
self.gap = nn.AdaptiveAvgPool2d((1, 1))
|
|
self.classifier = nn.Sequential(
|
|
nn.Flatten(),
|
|
nn.Linear(channels[-1], hidden_features),
|
|
nn.ReLU(inplace=True),
|
|
nn.Dropout(p=dropout),
|
|
nn.Linear(hidden_features, num_classes),
|
|
)
|
|
|
|
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
x = self.features(x)
|
|
x = self.gap(x)
|
|
return self.classifier(x)
|
|
|
|
def config(self) -> dict:
|
|
return {
|
|
"model_name": "HLSQConvNet",
|
|
"num_classes": self.num_classes,
|
|
"input_size": self.input_size,
|
|
"channels": list(self.channels),
|
|
"hidden_features": self.hidden_features,
|
|
"dropout": self.dropout,
|
|
"preprocess": {
|
|
"color": "RGB",
|
|
"scale": "float32_0_1",
|
|
"normalize": "none",
|
|
},
|
|
"hls_notes": {
|
|
"ops": "Conv2d, BatchNorm2d, ReLU, MaxPool2d, GlobalAveragePool, Linear",
|
|
"export": "Fuse Conv+BN before fixed-point HLS weight export.",
|
|
},
|
|
}
|
|
|
|
|
|
def create_hls_qcnn(
|
|
num_classes: int = 10,
|
|
input_size: int = DEFAULT_INPUT_SIZE,
|
|
channels: tuple[int, ...] | list[int] = DEFAULT_CHANNELS,
|
|
hidden_features: int = DEFAULT_HIDDEN_FEATURES,
|
|
dropout: float = 0.1,
|
|
) -> HLSQConvNet:
|
|
return HLSQConvNet(
|
|
num_classes=num_classes,
|
|
input_size=input_size,
|
|
channels=tuple(channels),
|
|
hidden_features=hidden_features,
|
|
dropout=dropout,
|
|
)
|
|
|
|
|
|
def create_hls_qcnn_from_checkpoint(checkpoint: dict) -> HLSQConvNet:
|
|
cfg = checkpoint.get("model_config", {})
|
|
return create_hls_qcnn(
|
|
num_classes=int(cfg.get("num_classes", 10)),
|
|
input_size=int(cfg.get("input_size", DEFAULT_INPUT_SIZE)),
|
|
channels=tuple(cfg.get("channels", DEFAULT_CHANNELS)),
|
|
hidden_features=int(cfg.get("hidden_features", DEFAULT_HIDDEN_FEATURES)),
|
|
dropout=float(cfg.get("dropout", 0.1)),
|
|
)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
model = create_hls_qcnn()
|
|
dummy = torch.rand(1, 3, DEFAULT_INPUT_SIZE, DEFAULT_INPUT_SIZE)
|
|
output = model(dummy)
|
|
params = sum(p.numel() for p in model.parameters())
|
|
print(model)
|
|
print("Output:", tuple(output.shape))
|
|
print("Parameters:", params)
|