Skip to content

Commit d6b363a

Browse files
fix: use truncation instead of rounding in ToBF16 (#1244)
1 parent d7a249a commit d6b363a

3 files changed

Lines changed: 5 additions & 6 deletions

File tree

common/floats/floats.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -232,8 +232,7 @@ func ToBF16(values []float32) []uint16 {
232232
encoded := make([]uint16, len(values))
233233
for i, value := range values {
234234
bits := math.Float32bits(value)
235-
roundingBias := uint32(0x7FFF + ((bits >> 16) & 1))
236-
encoded[i] = uint16((bits + roundingBias) >> 16)
235+
encoded[i] = uint16(bits >> 16)
237236
}
238237
return encoded
239238
}

common/floats/floats_test.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,17 +42,17 @@ func TestZero(t *testing.T) {
4242

4343
func TestToBF16(t *testing.T) {
4444
assert.Nil(t, ToBF16(nil))
45-
assert.Equal(t, []uint16{0x0000, 0x3f80, 0xc020, 0x3f8d}, ToBF16([]float32{0, 1, -2.5, 1.1}))
45+
assert.Equal(t, []uint16{0x0000, 0x3f80, 0xc020, 0x3f8c}, ToBF16([]float32{0, 1, -2.5, 1.1}))
4646
}
4747

4848
func TestFromBF16(t *testing.T) {
4949
assert.Nil(t, FromBF16(nil))
50-
decoded := FromBF16([]uint16{0x0000, 0x3f80, 0xc020, 0x3f8d})
50+
decoded := FromBF16([]uint16{0x0000, 0x3f80, 0xc020, 0x3f8c})
5151
assert.Len(t, decoded, 4)
5252
assert.Equal(t, uint32(0x00000000), math.Float32bits(decoded[0]))
5353
assert.Equal(t, uint32(0x3f800000), math.Float32bits(decoded[1]))
5454
assert.Equal(t, uint32(0xc0200000), math.Float32bits(decoded[2]))
55-
assert.Equal(t, uint32(0x3f8d0000), math.Float32bits(decoded[3]))
55+
assert.Equal(t, uint32(0x3f8c0000), math.Float32bits(decoded[3]))
5656
}
5757

5858
func TestAdd(t *testing.T) {

model/ctr/data_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@ func TestDataset_Split(t *testing.T) {
174174
dataSet.Index.CountUsers() + dataSet.Index.CountItems() + dataSet.Index.CountUserLabels() + 8,
175175
0,
176176
}, features)
177-
assert.InDeltaSlice(t, []float32{2, 2.1, 2.2}, floats.FromBF16(embeddings[0]), 0.01)
177+
assert.InDeltaSlice(t, []float32{2, 2.09375, 2.1875}, floats.FromBF16(embeddings[0]), 0.001)
178178
assert.Equal(t, []float32{1, 1, 1, 1, 1, 1, 1, 0.5}, values)
179179
assert.Equal(t, float32(-1), target)
180180

0 commit comments

Comments
 (0)