Skip to content

Resource Optimizer

Compress an SNN to fit a target FPGA (LUT/BRAM/DSP constraints).

from sc_neurocore.optimizer import ResourceOptimizer

opt = ResourceOptimizer(target_luts=10000, target_bram=36)
compressed = opt.optimize(model)

sc_neurocore.optimizer

Automatically compress an SNN to fit a target FPGA.

OptimizationResult dataclass

Result of the resource optimization process.

Source code in src/sc_neurocore/optimizer/resource_optimizer.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
@dataclass
class OptimizationResult:
    """Result of the resource optimization process."""

    fits: bool
    target: str
    final_luts: int
    target_luts: int
    utilization_pct: float
    final_bitstream_length: int
    final_sparsity: float
    steps: list[OptimizationStep] = field(default_factory=list)
    optimized_weights: list[np.ndarray] = field(default_factory=list, repr=False)

    def summary(self) -> str:
        lines = [
            f"Resource Optimization: {self.target}",
            f"  Fits: {'YES' if self.fits else 'NO'}",
            f"  LUTs: {self.final_luts:,} / {self.target_luts:,} ({self.utilization_pct:.1f}%)",
            f"  Bitstream length: {self.final_bitstream_length}",
            f"  Sparsity: {self.final_sparsity:.1%}",
            f"  Steps taken: {len(self.steps)}",
        ]
        for s in self.steps:
            lines.append(f"    {s.action}: {s.luts_before:,} -> {s.luts_after:,} LUTs")
        return "\n".join(lines)

fit_to_target(layer_sizes, weights, target='ice40', max_iterations=10, min_bitstream_length=32, initial_bitstream_length=256)

Automatically compress an SNN to fit a target FPGA.

Iteratively applies: 1. Bitstream length reduction (halving L) 2. Weight pruning (increasing threshold) 3. Weight quantization (reducing bit width)

Stops when the energy estimator says the network fits on the target.

Parameters

layer_sizes : list of (n_inputs, n_neurons) weights : list of ndarray target : str FPGA target ('ice40', 'ecp5', 'artix7', 'zynq'). max_iterations : int Maximum optimization steps. min_bitstream_length : int Minimum allowed L. initial_bitstream_length : int Starting bitstream length.

Returns

OptimizationResult

Source code in src/sc_neurocore/optimizer/resource_optimizer.py
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def fit_to_target(
    layer_sizes: list[tuple[int, int]],
    weights: list[np.ndarray],
    target: str = "ice40",
    max_iterations: int = 10,
    min_bitstream_length: int = 32,
    initial_bitstream_length: int = 256,
) -> OptimizationResult:
    """Automatically compress an SNN to fit a target FPGA.

    Iteratively applies:
    1. Bitstream length reduction (halving L)
    2. Weight pruning (increasing threshold)
    3. Weight quantization (reducing bit width)

    Stops when the energy estimator says the network fits on the target.

    Parameters
    ----------
    layer_sizes : list of (n_inputs, n_neurons)
    weights : list of ndarray
    target : str
        FPGA target ('ice40', 'ecp5', 'artix7', 'zynq').
    max_iterations : int
        Maximum optimization steps.
    min_bitstream_length : int
        Minimum allowed L.
    initial_bitstream_length : int
        Starting bitstream length.

    Returns
    -------
    OptimizationResult
    """
    from sc_neurocore.energy.fpga_models import TARGETS

    target_info = TARGETS.get(target)
    if target_info is None:
        raise ValueError(f"Unknown target '{target}'")

    current_weights = [w.copy() for w in weights]
    current_L = initial_bitstream_length
    steps = []
    prune_threshold = 0.001
    quant_bits = 16

    for iteration in range(max_iterations):
        report = estimate(layer_sizes, target=target, bitstream_length=current_L)

        if report.fits_on_target:
            break

        luts_before = report.total_luts

        # Strategy 1: Halve bitstream length
        if current_L > min_bitstream_length:
            current_L = max(current_L // 2, min_bitstream_length)
            report_after = estimate(layer_sizes, target=target, bitstream_length=current_L)
            steps.append(
                OptimizationStep(
                    action=f"Reduce L to {current_L}",
                    luts_before=luts_before,
                    luts_after=report_after.total_luts,
                    sparsity=0.0,
                    bitstream_length=current_L,
                )
            )
            if report_after.fits_on_target:  # pragma: no cover
                break
            continue

        # Strategy 2: Prune weights
        prune_threshold *= 3
        current_weights, prune_report = prune_weights(current_weights, threshold=prune_threshold)
        report_after = estimate(layer_sizes, target=target, bitstream_length=current_L)
        steps.append(
            OptimizationStep(
                action=f"Prune threshold={prune_threshold:.3f}",
                luts_before=luts_before,
                luts_after=report_after.total_luts,
                sparsity=prune_report.sparsity,
                bitstream_length=current_L,
            )
        )

        # Strategy 3: Reduce quantization
        if quant_bits > 4:
            quant_bits = max(quant_bits - 2, 4)
            current_weights = quantize_weights(current_weights, bits=quant_bits)
            steps.append(
                OptimizationStep(
                    action=f"Quantize to {quant_bits}-bit",
                    luts_before=report_after.total_luts,
                    luts_after=report_after.total_luts,
                    sparsity=prune_report.sparsity,
                    bitstream_length=current_L,
                )
            )

    # Final estimate
    final_report = estimate(layer_sizes, target=target, bitstream_length=current_L)

    total_params = sum(w.size for w in current_weights)
    nonzero = sum(np.count_nonzero(w) for w in current_weights)
    sparsity = 1.0 - nonzero / max(total_params, 1)

    return OptimizationResult(
        fits=final_report.fits_on_target,
        target=target,
        final_luts=final_report.total_luts,
        target_luts=target_info.total_luts,
        utilization_pct=final_report.utilization_pct,
        final_bitstream_length=current_L,
        final_sparsity=sparsity,
        steps=steps,
        optimized_weights=current_weights,
    )