From 1a26a051a50ed8293e8c9edb539a93ef0858ca7a Mon Sep 17 00:00:00 2001 From: erwanvivien <44021072+erwanvivien@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:17:19 +0100 Subject: [PATCH] zml/tensor: return a distinct tensor from toMemory on single-memory platforms (#1087) On cpu, neuron and metal, `toMemory` returned self. Donating a result to a device buffer and its `toMemory` copy to a host buffer then called `reuseBuffer` twice on the same tensor id: the second donation replaced the first, and compilation panicked because both outputs aliased the host buffer. This broke llmd async scheduling on Metal and CPU. Return the same value under a new tensor id instead. --- zml/tensor.zig | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/zml/tensor.zig b/zml/tensor.zig index a09a5d38..ee084835 100644 --- a/zml/tensor.zig +++ b/zml/tensor.zig @@ -282,7 +282,13 @@ pub const Tensor = struct { pub fn toMemory(self: Tensor, kind: Memory.Kind) Tensor { const ctx = Compiler.current(); switch (ctx.platform.target) { - .cpu, .neuron, .metal => return self, + .cpu, .neuron, .metal => { + // A single memory needs no copy, but the result must still be a distinct + // tensor: `reuseBuffer` donations are keyed by tensor id. + var res = _result(self._shape, self.value()); + res._shape._sharding = self._shape._sharding; + return res; + }, .cuda, .rocm, .tpu, .oneapi, .furiosa => {}, }