mirror of
https://github.com/ml-explore/mlx.git
synced 2025-08-09 18:56:39 +08:00
Fix reshaping of empty arrays (#791)
This commit is contained in:
parent
14b4e51a7c
commit
e39bebe13e
15
mlx/ops.cpp
15
mlx/ops.cpp
@ -293,26 +293,35 @@ array reshape(
|
||||
for (int i = 0; i < shape.size(); ++i) {
|
||||
if (shape[i] == -1) {
|
||||
if (infer_idx >= 0) {
|
||||
throw std::invalid_argument("Reshape can only infer one dimension.");
|
||||
throw std::invalid_argument(
|
||||
"[reshape] Reshape can only infer one dimension.");
|
||||
}
|
||||
infer_idx = i;
|
||||
} else {
|
||||
size *= shape[i];
|
||||
}
|
||||
}
|
||||
|
||||
// Infer the shape
|
||||
if (size > 0) {
|
||||
auto q_and_r = std::ldiv(a.size(), size);
|
||||
if (infer_idx >= 0) {
|
||||
shape[infer_idx] = q_and_r.quot;
|
||||
size *= q_and_r.quot;
|
||||
}
|
||||
} else if (infer_idx >= 0) {
|
||||
throw std::invalid_argument(
|
||||
"[reshape] Cannot infer the shape of an empty array");
|
||||
}
|
||||
|
||||
// Check the the reshaping is valid
|
||||
if (a.size() != size) {
|
||||
std::ostringstream msg;
|
||||
msg << "Cannot reshape array of size " << a.size() << " into shape "
|
||||
<< shape << ".";
|
||||
msg << "[reshape] Cannot reshape array of size " << a.size()
|
||||
<< " into shape " << shape << ".";
|
||||
throw std::invalid_argument(msg.str());
|
||||
}
|
||||
|
||||
return array(
|
||||
shape, a.dtype(), std::make_unique<Reshape>(to_stream(s), shape), {a});
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user