Fix to_numpy() crash on bfloat16 tensors by upcasting to float32#1346
Merged
jlarson4 merged 1 commit intoMay 29, 2026
Merged
Conversation
NumPy has no bfloat16 dtype, so calling .numpy() on a bfloat16 tensor raises TypeError. Detach/move to CPU, upcast bfloat16 to float32, then convert. bfloat16 is common since many pretrained models load in reduced precision. Adds a TestToNumpy class covering bfloat16, float32/float16/int passthrough, numpy/list/tuple/scalar inputs, and the invalid-type error.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
transformer_lens.utilities.tensors.to_numpy(re-exported astransformer_lens.utils.to_numpy) raisesTypeError: Got unsupported ScalarType BFloat16when passed abfloat16tensor, because NumPy has nobfloat16dtype andtorch.Tensor.numpy()cannot convert it directly.bfloat16is common in TransformerLens since many pretrained models load inreduced precision, and
to_numpyis used in several utility paths (e.g.utilities/slice.py), so this is easy to hit.Fix: in the
torch.Tensor/nn.Parameterbranch, detach + move to CPU,then upcast to
float32when the dtype isbfloat16before calling.numpy(). All other dtypes (float32, float16, int, etc.) are unchanged.Tests: added a
TestToNumpyclass covering bfloat16 tensors andnn.Parameter, float32/float16/int passthrough, numpy-array identity,list/tuple, scalars, and the invalid-type
ValueError. Reverting the fixmakes the two bfloat16 tests fail with the original
TypeError, confirmingthey're meaningful.
No existing tracking issue.
Type of change
to not work as expected)
Checklist:
works
backward compatibility