Source browser
examples/shaders/nn_binary_loss.cpp
Read the complete file below or download its original bytes. Line numbers provide stable links to a declaration or processing step.
File fingerprint
1// Compute mean binary cross-entropy for a small validation batch.
2#ifdef __cplusplus // Expose host declarations only when a C++ compiler reads this shader.
3#include "shdr.h" // Include shdr.h declarations.
4#endif // Finish this conditional compilation branch.
5layout(local_size_x = 1) in; // Group 1 independent invocations along x.
6layout(std430, binding = 0) readonly buffer Predictions { // Read one predicted class probability per sample through buffer binding 0.
7 float predictions[]; // Store one predicted class probability per sample.
8}; // Finish this declaration.
9layout(std430, binding = 1) readonly buffer Targets { // Read one binary training label per sample through buffer binding 1.
10 float targets[]; // Store one binary training label per sample.
11}; // Finish this declaration.
12layout(std430, binding = 2) writeonly buffer Loss { // Write the single mean loss value through buffer binding 2.
13 float loss[]; // Store the single mean loss value.
14}; // Finish this declaration.
15uniform uint batch_count; // Set the number of independent samples in this model batch.
16void main() { // Reduce the batch predictions into their mean binary cross entropy.
17 float total = 0.0; // Start the total negative log likelihood at zero.
18 for (uint row = 0u; row < batch_count; ++row) { // Include every predicted probability and binary label in the batch.
19 float p = clamp(predictions[row], 0.000001, 0.999999); // Keep probabilities away from zero and one before taking logarithms.
20 total -= targets[row] * log(p) + (1.0 - targets[row]) * log(1.0 - p); // Accumulate binary cross entropy for the label and its complement.
21 } // End this block.
22 loss[0] = total / float(batch_count); // Publish the mean sample loss as one scalar result.
23} // End this block.