202 lines
6.3 KiB
Python
202 lines
6.3 KiB
Python
"""FINN-friendly quantized CNN for the light-petal classifier.
|
|
|
|
The model is intentionally built from FINN/Brevitas-friendly layers:
|
|
QuantIdentity, QuantConv2d, BatchNorm2d, QuantReLU, MaxPool2d, Flatten and
|
|
QuantLinear. Input preprocessing for this route is RGB 128x128 converted to
|
|
float32 in [0, 1], with no ImageNet normalization.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import torch
|
|
import torch.nn as nn
|
|
|
|
try:
|
|
from brevitas.nn import QuantConv2d, QuantIdentity, QuantLinear, QuantReLU
|
|
except Exception: # pragma: no cover - handled at model construction time
|
|
QuantConv2d = None
|
|
QuantIdentity = None
|
|
QuantLinear = None
|
|
QuantReLU = None
|
|
|
|
|
|
DEFAULT_CHANNELS = (16, 32, 64, 96, 128)
|
|
DEFAULT_INPUT_SIZE = 128
|
|
DEFAULT_HIDDEN_FEATURES = 256
|
|
|
|
|
|
def _require_brevitas() -> None:
|
|
if QuantConv2d is None:
|
|
raise ImportError(
|
|
"Brevitas is required for FINN QCNN training/export. "
|
|
"Install it with: pip install brevitas qonnx"
|
|
)
|
|
|
|
|
|
class QuantConvBlock(nn.Module):
|
|
"""Conv-BN-ReLU-Pool block using quantized conv and activation."""
|
|
|
|
def __init__(
|
|
self,
|
|
in_channels: int,
|
|
out_channels: int,
|
|
weight_bit_width: int = 8,
|
|
act_bit_width: int = 8,
|
|
) -> None:
|
|
super().__init__()
|
|
_require_brevitas()
|
|
self.conv = QuantConv2d(
|
|
in_channels,
|
|
out_channels,
|
|
kernel_size=3,
|
|
stride=1,
|
|
padding=1,
|
|
bias=False,
|
|
weight_bit_width=weight_bit_width,
|
|
return_quant_tensor=False,
|
|
)
|
|
self.bn = nn.BatchNorm2d(out_channels)
|
|
self.act = QuantReLU(bit_width=act_bit_width, return_quant_tensor=False)
|
|
self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
|
|
|
|
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
x = self.conv(x)
|
|
x = self.bn(x)
|
|
x = self.act(x)
|
|
x = self.pool(x)
|
|
return x
|
|
|
|
|
|
class FINNQuantCNN(nn.Module):
|
|
"""A wider 128x128 RGB QAT model intended for FINN dataflow builds."""
|
|
|
|
def __init__(
|
|
self,
|
|
num_classes: int = 10,
|
|
input_size: int = DEFAULT_INPUT_SIZE,
|
|
channels: tuple[int, ...] = DEFAULT_CHANNELS,
|
|
hidden_features: int = DEFAULT_HIDDEN_FEATURES,
|
|
weight_bit_width: int = 8,
|
|
act_bit_width: int = 8,
|
|
input_bit_width: int = 8,
|
|
) -> None:
|
|
super().__init__()
|
|
_require_brevitas()
|
|
if input_size % (2 ** len(channels)) != 0:
|
|
raise ValueError(
|
|
f"input_size={input_size} must be divisible by 2^{len(channels)} "
|
|
"because every block contains MaxPool2d(2)."
|
|
)
|
|
|
|
self.num_classes = num_classes
|
|
self.input_size = input_size
|
|
self.channels = tuple(channels)
|
|
self.hidden_features = hidden_features
|
|
self.weight_bit_width = weight_bit_width
|
|
self.act_bit_width = act_bit_width
|
|
self.input_bit_width = input_bit_width
|
|
|
|
self.quant_input = QuantIdentity(
|
|
bit_width=input_bit_width,
|
|
return_quant_tensor=False,
|
|
)
|
|
|
|
blocks = []
|
|
in_channels = 3
|
|
for out_channels in channels:
|
|
blocks.append(
|
|
QuantConvBlock(
|
|
in_channels,
|
|
out_channels,
|
|
weight_bit_width=weight_bit_width,
|
|
act_bit_width=act_bit_width,
|
|
)
|
|
)
|
|
in_channels = out_channels
|
|
self.features = nn.Sequential(*blocks)
|
|
|
|
reduced_size = input_size // (2 ** len(channels))
|
|
flattened_features = channels[-1] * reduced_size * reduced_size
|
|
self.classifier = nn.Sequential(
|
|
QuantLinear(
|
|
flattened_features,
|
|
hidden_features,
|
|
bias=True,
|
|
weight_bit_width=weight_bit_width,
|
|
return_quant_tensor=False,
|
|
),
|
|
QuantReLU(bit_width=act_bit_width, return_quant_tensor=False),
|
|
QuantLinear(
|
|
hidden_features,
|
|
num_classes,
|
|
bias=True,
|
|
weight_bit_width=weight_bit_width,
|
|
return_quant_tensor=False,
|
|
),
|
|
)
|
|
|
|
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
x = self.quant_input(x)
|
|
x = self.features(x)
|
|
x = torch.flatten(x, 1)
|
|
x = self.classifier(x)
|
|
return x
|
|
|
|
def config(self) -> dict:
|
|
return {
|
|
"num_classes": self.num_classes,
|
|
"input_size": self.input_size,
|
|
"channels": list(self.channels),
|
|
"hidden_features": self.hidden_features,
|
|
"weight_bit_width": self.weight_bit_width,
|
|
"act_bit_width": self.act_bit_width,
|
|
"input_bit_width": self.input_bit_width,
|
|
"preprocess": {
|
|
"color": "RGB",
|
|
"scale": "float32_0_1",
|
|
"normalize": "none",
|
|
},
|
|
}
|
|
|
|
|
|
def create_finn_qcnn(
|
|
num_classes: int = 10,
|
|
input_size: int = DEFAULT_INPUT_SIZE,
|
|
channels: tuple[int, ...] | list[int] = DEFAULT_CHANNELS,
|
|
hidden_features: int = DEFAULT_HIDDEN_FEATURES,
|
|
weight_bit_width: int = 8,
|
|
act_bit_width: int = 8,
|
|
input_bit_width: int = 8,
|
|
) -> FINNQuantCNN:
|
|
return FINNQuantCNN(
|
|
num_classes=num_classes,
|
|
input_size=input_size,
|
|
channels=tuple(channels),
|
|
hidden_features=hidden_features,
|
|
weight_bit_width=weight_bit_width,
|
|
act_bit_width=act_bit_width,
|
|
input_bit_width=input_bit_width,
|
|
)
|
|
|
|
|
|
def create_finn_qcnn_from_checkpoint(checkpoint: dict) -> FINNQuantCNN:
|
|
config = checkpoint.get("model_config", {})
|
|
model = create_finn_qcnn(
|
|
num_classes=int(config.get("num_classes", 10)),
|
|
input_size=int(config.get("input_size", DEFAULT_INPUT_SIZE)),
|
|
channels=tuple(config.get("channels", DEFAULT_CHANNELS)),
|
|
hidden_features=int(config.get("hidden_features", DEFAULT_HIDDEN_FEATURES)),
|
|
weight_bit_width=int(config.get("weight_bit_width", 8)),
|
|
act_bit_width=int(config.get("act_bit_width", 8)),
|
|
input_bit_width=int(config.get("input_bit_width", 8)),
|
|
)
|
|
return model
|
|
|
|
|
|
if __name__ == "__main__":
|
|
model = create_finn_qcnn()
|
|
dummy = torch.rand(1, 3, DEFAULT_INPUT_SIZE, DEFAULT_INPUT_SIZE)
|
|
out = model(dummy)
|
|
print(model)
|
|
print("Output shape:", tuple(out.shape))
|