namespace {
// Macro to embed the default efficiently updatable neural network (NNUE) file
// data in the engine binary (using incbin.h, by Dale Weiler).
// This macro invocation will declare the following three variables
// const unsigned char gEmbeddedNNUEData[]; // a pointer to the embedded data
// const unsigned char const gEmbeddedNNUEEnd; // a marker to the end
// const unsigned int gEmbeddedNNUESize; // the size of the embedded file
// Note that this does not work in Microsoft Visual Studio.
#if !defined(_MSC_VER) && !defined(NNUE_EMBEDDING_OFF)
INCBIN(EmbeddedNNUEBig, EvalFileDefaultNameBig);
INCBIN(EmbeddedNNUESmall, EvalFileDefaultNameSmall);
#else
const unsigned char gEmbeddedNNUEBigData[1] = {0x0};
const unsigned char const gEmbeddedNNUEBigEnd = &gEmbeddedNNUEBigData[1];
const unsigned int gEmbeddedNNUEBigSize = 1;
const unsigned char gEmbeddedNNUESmallData[1] = {0x0};
const unsigned char* const gEmbeddedNNUESmallEnd = &gEmbeddedNNUESmallData[1];
const unsigned int gEmbeddedNNUESmallSize = 1;
#endif
if (filename.has_value())
actualFilename = filename.value();
else
{
if (evalFile.current != evalFile.defaultName)
{
msg = "Failed to export a net. "
"A non-embedded net can only be saved if the filename is specified";
msg = saved ? "Network saved successfully to " + actualFilename : "Failed to export a net";
sync_cout << msg << sync_endl;
return saved;
}
template<typename Arch, typename Transformer>
NetworkOutput
Network<Arch, Transformer>::evaluate(const Position& pos,
AccumulatorCaches::Cache cache) const {
// We manually align the arrays on the stack because with gcc < 9.3
// overaligning stack variables with alignas() doesn't work correctly.
if (evalFile.current != evalfilePath)
{
std::string msg1 =
"Network evaluation parameters compatible with the engine must be available.";
std::string msg2 = "The network file " + evalfilePath + " was not loaded successfully.";
std::string msg3 = "The UCI option EvalFile might need to specify the full path, "
"including the directory name, to the network file.";
std::string msg4 = "The default net can be downloaded from: "
"https://tests.stockfishchess.org/api/nn/"
evalFile.defaultName;
std::string msg5 = "The engine will be terminated now.";
template<typename Arch, typename Transformer>
void Network<Arch, Transformer>::load_internal() {
// C++ way to prepare a buffer for a memory stream
class MemoryBuffer: public std::basic_streambuf {
public:
MemoryBuffer(char* p, size_t n) {
setg(p, p, p + n);
setp(p, p + n);
}
};
template<typename Arch, typename Transformer>
bool Network<Arch, Transformer>::read_parameters(std::istream& stream,
std::string& netDescription) const {
std::uint32_t hashValue;
if (!read_header(stream, &hashValue, &netDescription))
return false;
if (hashValue != Network::hash)
return false;
if (!Detail::read_parameters(stream, *featureTransformer))
return false;
for (std::size_t i = 0; i < LayerStacks; ++i)
{
if (!Detail::read_parameters(stream, network[i]))
return false;
}
return stream && stream.peek() == std::ios::traits_type::eof();
}
template<typename Arch, typename Transformer>
bool Network<Arch, Transformer>::write_parameters(std::ostream& stream,
const std::string& netDescription) const {
if (!write_header(stream, Network::hash, netDescription))
return false;
if (!Detail::write_parameters(stream, *featureTransformer))
return false;
for (std::size_t i = 0; i < LayerStacks; ++i)
{
if (!Detail::write_parameters(stream, network[i]))
return false;
}
return bool(stream);
}
// Explicit template instantiation
template class Network<
NetworkArchitecture<TransformedFeatureDimensionsBig, L2Big, L3Big>,
FeatureTransformer<TransformedFeatureDimensionsBig, &StateInfo::accumulatorBig>>;
template class Network<
NetworkArchitecture<TransformedFeatureDimensionsSmall, L2Small, L3Small>,
FeatureTransformer<TransformedFeatureDimensionsSmall, &StateInfo::accumulatorSmall>>;
} // namespace Stockfish::Eval::NNUE
I would definitely optimize two aspects of the provided code, especially considering that GCC 11 is being used:
Remove Workarounds for Older GCC Versions (Manual Stack Alignment):
The code contains conditional compilation blocks that manually align stack variables due to issues in GCC versions prior to 9.3. Specifically, it addresses the problem where overaligning stack variables with alignas() didn't work correctly. Given that GCC 11 is being used, these workarounds are no longer necessary because the issue has been resolved in GCC 9.3 and later versions.
Optimized Approach:
Eliminate Manual Alignment Code: Remove the #if defined(ALIGNAS_ON_STACK_VARIABLES_BROKEN) blocks along with the manual alignment logic using align_ptr_up and unaligned arrays.
Use alignas() Directly: Rely solely on alignas(alignment) to properly align stack variables.
Simplified Code: The code becomes cleaner and easier to read without the unnecessary conditional blocks and manual alignment calculations.
Performance Improvement: Removing unnecessary code can slightly improve performance, although in this case, the impact might be minimal.
Maintenance Ease: Less code means fewer potential bugs and easier future maintenance.
Reconsider Copy Constructor and Assignment Operator Implementation:
The Network class manually defines the copy constructor and copy assignment operator. However, these implementations might not be handling resource management correctly, especially concerning std::unique_ptr.
Issues in the Current Implementation:
Improper Copying of std::unique_ptr: Copying std::unique_ptr directly leads to compilation errors because std::unique_ptr cannot be copied (copy constructor is deleted). The code attempts to copy featureTransformer and network using make_unique_large_page and make_unique_aligned, possibly with incorrect parameters.
Potential Memory Leaks: The assignment operator doesn't release existing resources before allocating new ones, leading to potential memory leaks.
Optimized Approach:
Delete Copy Operations: If copying a Network isn't necessary for the application's logic, explicitly delete the copy constructor and copy assignment operator. This approach prevents accidental copying and enforces move semantics.
Implement Move Semantics: If moving is acceptable, implement move constructor and move assignment operator to transfer ownership of resources without copying.
Properly Handle Copying: If copying is required, ensure that the objects pointed to by std::unique_ptr are copyable, and perform a deep copy where necessary.
Before Optimization:
cpp
// Copy Constructor
Network(const Network& other) :
evalFile(other.evalFile),
embeddedType(other.embeddedType) {
if (other.featureTransformer)
featureTransformer = make_unique_large_page<Transformer>(other.featureTransformer);
network = make_unique_aligned<Arch[]>(LayerStacks);
if (!other.network)
return;
for (std::size_t i = 0; i < LayerStacks; ++i)
network[i] = other.network[i];
}
// Copy Assignment Operator
Network& operator=(const Network& other) {
evalFile = other.evalFile;
embeddedType = other.embeddedType;
if (other.featureTransformer)
featureTransformer = make_unique_large_page<Transformer>(other.featureTransformer);
network = make_unique_aligned<Arch[]>(LayerStacks);
if (!other.network)
return *this;
for (std::size_t i = 0; i < LayerStacks; ++i)
network[i] = other.network[i];
return *this;
}
Conclusion:
By removing the outdated GCC-specific workarounds and properly handling resource management with move semantics, the code becomes more efficient, maintainable, and aligned with modern C++ best practices. These optimizations take advantage of GCC 11's capabilities and modern C++ language features, leading to cleaner and potentially more performant code.
Prevent Undefined Behavior: By deleting the copy operations, we avoid incorrect copying of std::unique_ptr, which could lead to double deletions or use-after-free errors.
Efficient Resource Management: Move semantics allow for efficient transfer of resources without unnecessary copying.
Code Clarity: The class's intended usage is clearer, and potential future errors are prevented.