Skip to content

Accept sub-byte bitstrings in Nx.from_binary - #1817

Merged
polvalente merged 2 commits into
elixir-nx:mainfrom
blasphemetheus:fix/from-binary-bitstring
Aug 17, 2026
Merged

Accept sub-byte bitstrings in Nx.from_binary#1817
polvalente merged 2 commits into
elixir-nx:mainfrom
blasphemetheus:fix/from-binary-bitstring

Conversation

@blasphemetheus

Copy link
Copy Markdown
Contributor

Nx.to_binary's docs note that sub-byte types (u2/u4/s2/s4) may yield a bitstring whose bit count is not divisible by 8 — but Nx.from_binary's is_binary guard rejected exactly those values, so the documented round trip crashed:

t = Nx.tensor([1, 2, 3], type: {:u, 2})   # 6 bits
t |> Nx.to_binary() |> Nx.from_binary({:u, 2})
# ** (FunctionClauseError) no function clause matching in Nx.from_binary/3

The function body already measures in bits (bit_size + rem check), so the fix is the guard: is_binaryis_bitstring. A doc sentence now notes the bitstring case, mirroring to_binary's existing info box.

Regression test: round trip for u2/u4/s2, asserting the intermediate really is a non-binary bitstring.

🤖 Generated with Claude Code

to_binary's docs note that sub-byte types (u2/u4/s2/s4) may yield a
bitstring whose bit count is not divisible by 8 — but from_binary's
is_binary guard rejected exactly those values, so the documented round
trip crashed. The body already measures in bits (bit_size + rem
check); the guard becomes is_bitstring. Docs now note the bitstring
case, mirroring to_binary's existing info box.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Comment thread nx/lib/nx.ex Outdated
@polvalente
polvalente merged commit 8a58763 into elixir-nx:main Aug 17, 2026
9 checks passed
@blasphemetheus
blasphemetheus deleted the fix/from-binary-bitstring branch August 17, 2026 17:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants