| 158 | return TensorValue{tensor, shape, type}; |
| 159 | } |
| 160 | |
| 161 | TensorValue reshape_tensor(ModuleBuildContext & ctx, const TensorValue & value, const TensorShape & new_shape) { |
| 162 | if (!value.valid()) { |
| 163 | throw std::runtime_error("Cannot reshape an invalid tensor"); |
| 164 | } |
| 165 | if (value.shape.num_elements() != new_shape.num_elements()) { |
| 166 | throw std::runtime_error("Reshape element count mismatch"); |
| 167 | } |
| 168 | if (ctx.ggml == nullptr) { |
| 169 | throw std::runtime_error("ModuleBuildContext.ggml is null"); |
| 170 | } |
| 171 | |
| 172 | const auto ggml_dims = to_ggml_dims(new_shape); |
| 173 | if (ctx.elide_identity_reshapes && ggml_is_contiguous(value.tensor) && |
| 174 | std::equal(ggml_dims.begin(), ggml_dims.end(), value.tensor->ne)) { |
| 175 | return wrap_tensor(value.tensor, new_shape, value.type); |
| 176 | } |
| 177 | ggml_tensor * reshaped = nullptr; |
| 178 | switch (new_shape.rank) { |
| 179 | case 1: |
| 180 | reshaped = ggml_reshape_1d(ctx.ggml, value.tensor, ggml_dims[0]); |
| 181 | break; |
| 182 | case 2: |
| 183 | reshaped = ggml_reshape_2d(ctx.ggml, value.tensor, ggml_dims[0], ggml_dims[1]); |
| 184 | break; |
| 185 | case 3: |
| 186 | reshaped = ggml_reshape_3d(ctx.ggml, value.tensor, ggml_dims[0], ggml_dims[1], ggml_dims[2]); |
| 187 | break; |
| 188 | case 4: |
| 189 | reshaped = ggml_reshape_4d(ctx.ggml, value.tensor, ggml_dims[0], ggml_dims[1], ggml_dims[2], ggml_dims[3]); |
| 190 | break; |
| 191 | default: |
| 192 | throw std::runtime_error("Unsupported reshape rank"); |
| 193 | } |
| 194 | |