MxFp4Codec: all-zero block zeroes 32 bytes instead of 17 and wipes the next block
What happens
In compression/mxfp4-inl.h (on dev, 8073ef9), the all-zero early-out in MxFp4Codec::QuantizeBlock is:
if (max_abs == 0.0f) {
hwy::ZeroBytes(block_ptr, kBlockSize);
return;
}
kBlockSize is the number of elements per block (32). An encoded block is sizeof(MxFp4Stream) = 17 bytes: 1 e8m0 scale byte plus 16 nibble bytes (types.h). Enc also advances block_ptr by sizeof(MxFp4Stream). The non-zero path writes exactly 17 bytes, so only the zero path is wrong. It writes 15 bytes past its block: the next block's scale byte and 14 of its 16 nibble bytes. A scale byte of 0 decodes to a scale of 0.0f, so the whole next block then decodes to zeros.
When blocks are encoded strictly in order, the next block overwrites the damage, so sequential encoding mostly hides the bug. Two cases are not hidden:
Compress(..., ThreadingContext&)(and theThreadPooloverload) encodes 8192-element batches in parallel viapool.Run. If the last 32-element block of batch k is all zero and batch k+1 has already written its first block, that first block is lost. Whether data is lost depends on thread scheduling. This is the path the Python exporter uses:SbsWriterImpl::InsertT<MxFp4Stream>incompression/python/compression_clif_aux.cccalls thisCompress.- If the all-zero block is the last block of the tensor, the write goes up to 15 bytes past
PackedEnd.MatOwnerpadding may absorb this, but the codec should not rely on it.
The same thing happens with the packed_ofs sub-region compression that compress-inl.h documents, whenever sub-regions are not written in increasing order.
Real-world impact depends on how often whole 32-element blocks are exactly zero in exported weights. That is probably uncommon in trained weights, but it is possible with pruned or zero-initialized tensors. When it happens, the corruption is silent.
Minimal repro
Add the test below to compression/mxfp4_test.cc. It encodes block 1 and then the all-zero block 0, which is the order a parallel batch boundary can produce. All values used are exactly representable in MXFP4, so the round trip should be lossless.
// Encoding an all-zero block must only write the sizeof(MxFp4Stream) bytes of
// that block. `Compress` encodes 8192-element batches in parallel, and callers
// may compress sub-ranges via `packed_ofs`, so blocks can be encoded in any
// order and must not clobber their neighbors.
struct TestMxFp4ZeroBlockStaysInBounds {
template <typename T, class D>
HWY_INLINE void operator()(T /*unused*/, D d) {
constexpr size_t kBlock = MxFp4Stream::kBlockSize;
const size_t total = 2 * kBlock;
const hn::ScalableTag<float> df;
auto in = hwy::AllocateAligned<float>(total);
auto dec = hwy::AllocateAligned<T>(total);
auto packed =
hwy::AllocateAligned<MxFp4Stream>(MxFp4Stream::PackedEnd(total));
HWY_ASSERT(in && dec && packed);
const auto packed_span = MakeSpan(packed.get(), total);
// Block 0 is all zero; block 1 holds exactly representable values.
for (size_t i = 0; i < kBlock; ++i) {
in[i] = 0.0f;
in[kBlock + i] = (i & 1) ? -1.5f : 3.0f;
}
// Encode block 1 first, then the all-zero block 0.
MxFp4Codec::Enc(df, in.get() + kBlock, kBlock, packed_span, kBlock);
MxFp4Codec::Enc(df, in.get(), kBlock, packed_span, 0);
MxFp4Codec::DecompressAndZeroPad(d, MakeConst(packed_span), 0, dec.get(),
total);
size_t num_wrong = 0;
for (size_t i = 0; i < total; ++i) {
num_wrong += in[i] != hwy::ConvertScalarTo<float>(dec[i]);
}
EXPECT_EQ(0u, num_wrong)
<< "block 1 decodes to " << hwy::ConvertScalarTo<float>(dec[kBlock])
<< ", expected " << in[kBlock];
// The bytes after a single all-zero block must remain untouched.
uint8_t* bytes = reinterpret_cast<uint8_t*>(packed.get());
constexpr size_t kBlockBytes = sizeof(MxFp4Stream);
constexpr uint8_t kSentinel = 0xAB;
for (size_t i = 0; i < 2 * kBlockBytes; ++i) bytes[i] = kSentinel;
MxFp4Codec::Enc(df, in.get(), kBlock, packed_span, 0);
size_t num_clobbered = 0;
for (size_t i = kBlockBytes; i < 2 * kBlockBytes; ++i) {
num_clobbered += bytes[i] != kSentinel;
}
EXPECT_EQ(0u, num_clobbered)
<< "bytes written past the " << kBlockBytes << "-byte block";
}
};
Registered next to the existing tests:
void TestAllZeroBlockStaysInBounds() {
hn::ForGEVectors<128, TestMxFp4ZeroBlockStaysInBounds>()(float());
hn::ForGEVectors<128, TestMxFp4ZeroBlockStaysInBounds>()(BF16());
}
// ...
HWY_EXPORT_AND_TEST_P(MxFp4Test, TestAllZeroBlockStaysInBounds);
Then:
cmake -B build -DGEMMA_ENABLE_TESTS=ON -DCMAKE_BUILD_TYPE=Release
cmake --build build -j4 --target mxfp4_test
./build/mxfp4_test --gtest_filter='*ZeroBlock*'
Expected vs actual
Expected: the decode matches the input exactly, and encoding one block writes only its own 17 bytes. A per-block encoder should not write into a neighbouring block. The non-zero path follows this rule, and Q4_0Codec::QuantizeBlock handles an all-zero block in its normal path, writing only its own scale and 16 nibble bytes.
Actual (on every target: NEON_BF16, NEON, NEON_WITHOUT_AES, EMU128):
mxfp4_test.cc: Failure
Expected equality of these values:
0u
num_wrong
Which is: 32
block 1 decodes to 0, expected 3
mxfp4_test.cc: Failure
num_clobbered
Which is: 15
bytes written past the 17-byte block
[ FAILED ] MxFp4TestGroup/MxFp4Test.TestAllZeroBlockStaysInBounds/NEON_BF16
Environment
- gemma.cpp
devat 8073ef9 - macOS 26.5, Apple M4 (arm64), Apple clang 17.0.0, CMake Release build
Suggested fix
Make the early-out zero only its own block:
hwy::ZeroBytes(block_ptr, sizeof(MxFp4Stream));
With this change, the new test and the existing TestAllExact, TestAllRandom and TestAllEncDec pass on all targets (16/16).
AI assistance: drafted with an AI coding assistant (Claude). The reproduction above was run locally against the current default branch.
Thanks for pointing this out, fix coming up shortly.