Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
3 changes: 1 addition & 2 deletions nx/lib/nx.ex
Original file line number Diff line number Diff line change
Expand Up @@ -2020,7 +2020,6 @@ defmodule Nx do
Creates a one-dimensional tensor from a `binary` with the given `type`.

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

## Examples

iex> Nx.from_binary(<<1, 2, 3, 4>>, :s8)
Expand Down Expand Up @@ -2049,7 +2048,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