Avoid host round-trips for same-device backend copies#117
Merged
polvalente merged 2 commits intoJun 18, 2026
Conversation
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.
Summary
This adds a same-device fast path for
Nx.backend_copy/3when copying EMLX tensors back toEMLX.Backend.Previously, same-device EMLX copies went through the generic binary path, which materializes tensor data through the host before rebuilding an EMLX tensor. This already preserved copy independence, but it was unnecessary when the source and target EMLX device were the same.
This PR adds
EMLX.copy/1, backed by MLX'smlx::core::copy, and uses it for same-device EMLX copies. Cross-device copies still useEMLX.to_device/2.It also makes same-device
Nx.backend_transfer/3a no-op, which matches transfer semantics more directly when the tensor is already on the requested backend/device.I exposed
EMLX.copy/1because MLX already exposescopyand EMLX exposes similar low-level tensor primitives directly. If you prefer not to expand the public API in this PR, I can keep the copy helper internal to the backend.Local check
On an M4 Max, copying a
{2048, 2048}f32 tensor from EMLX CPU to the same EMLX CPU device preserved values and independent refs while avoiding the host binary round-trip.Rough local timing for:
upstream/mainFor copy followed by materialization with
Nx.to_binary/1:upstream/mainThis is a small local sanity check, not a full benchmark suite.
Tests
mix test test/emlx/nx_test.exs --include metal