Skip to content

Commit cce514a

Browse files
committed
Compute entropy for activations
1 parent 9744a4a commit cce514a

File tree

1 file changed

+24
-4
lines changed

1 file changed

+24
-4
lines changed

tools/imatrix/imatrix.cpp

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -173,10 +173,28 @@ static int compute_tensor_statistics(std::vector<tensor_statistics> & tstats, co
173173
const float active_ratio = 1 - static_cast<float>(inactive_count) / activations.size();
174174

175175
float entropy = 0;
176-
if (sum > 0) {
177-
for (const auto act : activations) {
178-
if (const float p = act / sum; p > 0) {
179-
entropy -= p * std::log2(p);
176+
177+
if (calc_mode == 1) {
178+
float div = 0.0;
179+
std::vector<float> weights(activations.size());
180+
for (size_t i = 0; i < activations.size(); ++i) {
181+
const float w = activations[i] * activations[i];
182+
weights[i] = w;
183+
div += w;
184+
}
185+
186+
if (div > 0.0) {
187+
for (float w : weights) {
188+
const float p = w / div;
189+
if (p > 0.0) entropy -= p * std::log2(p);
190+
}
191+
}
192+
} else {
193+
if (sum > 0) {
194+
for (const auto act : activations) {
195+
if (const float p = act / sum; p > 0) {
196+
entropy -= p * std::log2(p);
197+
}
180198
}
181199
}
182200
}
@@ -202,6 +220,8 @@ static int compute_tensor_statistics(std::vector<tensor_statistics> & tstats, co
202220
ts.active = active_ratio;
203221
ts.entropy = entropy;
204222
ts.zd_score = static_cast<float>(z_score) / ts.elements;
223+
224+
return calc_mode;
205225
}
206226

207227
static void compute_cossim(std::vector<tensor_statistics> & tstats) {

0 commit comments

Comments
 (0)