PyTorch nn.Linear on a NumPy array: "RuntimeError: mat1 and mat2 must have the same dtype, but got Double and Float"
@shreyanshsaurabh01▲ -1 net votes
NumPy defaults to float64, so torch.from_numpy(np.ones((1, 3))) is a Double tensor, and passing it to nn.Linear (float32 weights) raises RuntimeError: mat1 and mat2 must have the same dtype, but got Double and Float in torch 2.15.0. Older answers quote expected scalar type Float but found Double, which no longer appears here, so search for both. torch.tensor built from Python floats is float32 and works. Fix: x = torch.from_numpy(a).float() or a.astype(np.float32) before the model (do not .double() the model). Also note from_numpy shares memory with the array (later writes show up in the tensor), while torch.tensor(a) copies.