Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion nx/lib/nx.ex
Original file line number Diff line number Diff line change
Expand Up @@ -2021,6 +2021,10 @@ defmodule Nx do

If the binary size does not match its type, an error is raised.

For sub-byte types (u2/u4/s2/s4), the input may also be a bitstring
whose bit count is not divisible by 8, as produced by `to_binary/2`
for those types.

Comment thread
polvalente marked this conversation as resolved.
Outdated
## Examples

iex> Nx.from_binary(<<1, 2, 3, 4>>, :s8)
Expand Down Expand Up @@ -2049,7 +2053,7 @@ defmodule Nx do
is ignored inside `defn`
"""
@doc type: :creation
def from_binary(binary, type, opts \\ []) when is_binary(binary) do
def from_binary(binary, type, opts \\ []) when is_bitstring(binary) do
opts = keyword!(opts, [:backend])
{_, size} = type = Nx.Type.normalize!(type)
dim = div(Kernel.bit_size(binary), size)
Expand Down
14 changes: 14 additions & 0 deletions nx/test/nx_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -1489,6 +1489,20 @@ defmodule NxTest do
Nx.from_binary("", {:u, 32})
end)
end

test "round-trips sub-byte tensors whose binary is not byte-aligned" do
for {type, values} <- [
{{:u, 2}, [1, 2, 3]},
{{:u, 4}, [5, 10, 15]},
{{:s, 2}, [-1, 0, 1]}
] do
tensor = Nx.tensor(values, type: type)
data = Nx.to_binary(tensor)

refute is_binary(data)
assert Nx.from_binary(data, type) == tensor
end
end
end

describe "to_batched/3" do
Expand Down
Loading