Layers & STE¶
Trainable binary/ternary layers and the straight-through estimators.
BinaryLinear ¶
Bases: Module
Dense layer with binary weights & binary activations (+ channel scale).
Forward (sim): y = (alpha * sign(W)) @ sign(x)^T ... via F.linear Does NOT accelerate; use packed kernels for inference speed.
Source code in bnn/layers.py
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | |
BinaryConv2d ¶
Bases: Module
3x3 binary conv with binary activations and per-out-channel scale.
Source code in bnn/layers.py
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 | |
TernaryLinear ¶
Bases: Module
BitNet-style ternary weights, full-precision activations (training sim).
Source code in bnn/layers.py
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | |
BiRealBlock ¶
Bases: Module
Binary conv + BN + FP residual (Bi-Real Net idea).
Source code in bnn/layers.py
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 | |
fuse_binary_conv_bn_ ¶
fuse_binary_conv_bn_(block: BiRealBlock) -> BiRealBlock
Fold BatchNorm into BinaryConv2d.alpha (+ bias) for eval throughput.
Safe for inference only — does not change STE training when left unfused.
Call after model.eval() once BN running stats are populated.
Source code in bnn/layers.py
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 | |
fuse_bireal_bn_ ¶
fuse_bireal_bn_(module: Module) -> nn.Module
Recursively fuse BiRealBlock BN into binary conv scales (eval).
Source code in bnn/layers.py
159 160 161 162 163 164 | |
Estimators¶
binary_sign ¶
binary_sign(x: Tensor) -> Tensor
Binarize to {-1, +1} with clipped STE.
Source code in bnn/ste.py
45 46 47 | |
ternary_weight ¶
ternary_weight(w: Tensor) -> Tensor
Source code in bnn/ste.py
244 245 | |
clip_weights_ ¶
clip_weights_(module: Module, max_val: float = 1.0) -> None
Clip latent binary/ternary weights after optimizer step.
Source code in bnn/ste.py
248 249 250 251 252 253 | |
set_approx_sign ¶
set_approx_sign(enabled: bool) -> None
Backward-compatible: True → ApproxSign, False → clipped STE.
Source code in bnn/ste.py
154 155 156 157 | |