-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBitLinear.cs
More file actions
176 lines (140 loc) · 5.37 KB
/
BitLinear.cs
File metadata and controls
176 lines (140 loc) · 5.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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
using BitNetSharp.Core.Quantization;
namespace BitNetSharp.Core.Layers;
public sealed class BitLinear : Module
{
private const int ActivationQuantizationMaxMagnitude = 127;
private const float WeightQuantizationEpsilon = 1e-6f;
private readonly sbyte[,] _ternaryWeights;
public BitLinear(BitLinearConfig config)
{
ArgumentNullException.ThrowIfNull(config);
Config = config;
_ternaryWeights = new sbyte[config.OutputDimension, config.InputDimension];
}
public BitLinearConfig Config { get; }
public float Gamma { get; private set; }
public bool HasBias => false;
public int ActivationQuantizationBound => ActivationQuantizationMaxMagnitude;
public int ActivationQuantizationBitWidth => 8;
public long EstimateResidentParameterBytes() =>
((long)_ternaryWeights.Length * sizeof(sbyte)) + sizeof(float);
public override float[,] Forward(float[,] input)
{
ArgumentNullException.ThrowIfNull(input);
if (input.GetLength(1) != Config.InputDimension)
{
throw new ArgumentException($"Expected input dimension {Config.InputDimension}, but received {input.GetLength(1)}.", nameof(input));
}
var quantizedInput = QuantizeActivations(input);
var output = new float[input.GetLength(0), Config.OutputDimension];
for (var row = 0; row < quantizedInput.GetLength(0); row++)
{
for (var outputColumn = 0; outputColumn < Config.OutputDimension; outputColumn++)
{
var sum = 0f;
for (var inputColumn = 0; inputColumn < Config.InputDimension; inputColumn++)
{
sum += quantizedInput[row, inputColumn] * _ternaryWeights[outputColumn, inputColumn];
}
output[row, outputColumn] = sum * Gamma;
}
}
return output;
}
public void QuantizeFromFullPrecision(float[,] fullPrecisionWeights)
{
ArgumentNullException.ThrowIfNull(fullPrecisionWeights);
if (fullPrecisionWeights.GetLength(0) != Config.OutputDimension || fullPrecisionWeights.GetLength(1) != Config.InputDimension)
{
throw new ArgumentException(
$"Expected weights with shape [{Config.OutputDimension}, {Config.InputDimension}], but received [{fullPrecisionWeights.GetLength(0)}, {fullPrecisionWeights.GetLength(1)}].",
nameof(fullPrecisionWeights));
}
Gamma = ComputeAbsMean(fullPrecisionWeights);
if (Gamma <= 0f)
{
Array.Clear(_ternaryWeights, 0, _ternaryWeights.Length);
return;
}
for (var row = 0; row < Config.OutputDimension; row++)
{
for (var column = 0; column < Config.InputDimension; column++)
{
var normalized = fullPrecisionWeights[row, column] / Gamma;
normalized += WeightQuantizationEpsilon;
var quantized = Math.Clamp((int)MathF.Round(normalized, MidpointRounding.AwayFromZero), -1, 1);
_ternaryWeights[row, column] = (sbyte)quantized;
}
}
}
public float[,] ToFullPrecision()
{
var result = new float[Config.OutputDimension, Config.InputDimension];
for (var row = 0; row < Config.OutputDimension; row++)
{
for (var column = 0; column < Config.InputDimension; column++)
{
result[row, column] = _ternaryWeights[row, column] * Gamma;
}
}
return result;
}
public TernaryWeightStats GetTernaryStats()
{
var negativeCount = 0;
var zeroCount = 0;
var positiveCount = 0;
foreach (var value in _ternaryWeights)
{
switch (value)
{
case < 0:
negativeCount++;
break;
case > 0:
positiveCount++;
break;
default:
zeroCount++;
break;
}
}
return new TernaryWeightStats(negativeCount, zeroCount, positiveCount);
}
private static float ComputeAbsMean(float[,] weights)
{
if (weights.Length == 0)
{
return 0f;
}
var sum = 0f;
foreach (var weight in weights)
{
sum += MathF.Abs(weight);
}
return sum / weights.Length;
}
private static float[,] QuantizeActivations(float[,] input)
{
var result = new float[input.GetLength(0), input.GetLength(1)];
for (var row = 0; row < input.GetLength(0); row++)
{
var maxAbs = 0f;
for (var column = 0; column < input.GetLength(1); column++)
{
maxAbs = MathF.Max(maxAbs, MathF.Abs(input[row, column]));
}
if (maxAbs <= 0f)
{
continue;
}
var scale = maxAbs / ActivationQuantizationMaxMagnitude;
for (var column = 0; column < input.GetLength(1); column++)
{
var quantized = Math.Clamp((int)MathF.Round(input[row, column] / scale, MidpointRounding.AwayFromZero), -ActivationQuantizationMaxMagnitude, ActivationQuantizationMaxMagnitude);
result[row, column] = quantized * scale;
}
}
return result;
}
}