MCPcopy Create free account
hub / github.com/MegEngine/MegEngine / einsum_impl

Function einsum_impl

imperative/python/megengine/functional/einsum.py:276–325  ·  view source on GitHub ↗
(shapes, output_shape, inputs, ctx: EinsumContext)

Source from the content-addressed store, hash-verified

274
275
276def einsum_impl(shapes, output_shape, inputs, ctx: EinsumContext):
277 assert len(shapes) == len(inputs), "input size mismatch"
278 dim2firstop = dict()
279 dim2lastop = dict()
280 dims = set()
281 for i, shape in enumerate(shapes):
282 for dim in shape:
283 if dim not in output_shape:
284 dim2lastop[dim] = i
285 if dim not in dim2firstop:
286 dim2firstop[dim] = i
287 dims.add(dim)
288 result = EinsumOperand(shapes[0], inputs[0], ctx).dedup_dim()
289 for i in range(1, len(inputs)):
290 rhs = EinsumOperand(shapes[i], inputs[i], ctx).dedup_dim()
291 lshape = result.shape
292 batch_dims: Tuple[EinsumDimension, ...] = ()
293 sum_dims: Tuple[EinsumDimension, ...] = ()
294 left_dims: Tuple[EinsumDimension, ...] = ()
295 right_dims: Tuple[EinsumDimension, ...] = ()
296 reduce_dims: Tuple[EinsumDimension, ...] = ()
297 lshape = result.shape
298 rshape = rhs.shape
299 for dim in lshape:
300 lastop = dim2lastop.get(dim, -1)
301 if lastop == i - 1:
302 reduce_dims = reduce_dims + (dim,)
303 elif lastop == i:
304 sum_dims = sum_dims + (dim,)
305 else:
306 if dim in rshape:
307 batch_dims = batch_dims + (dim,)
308 else:
309 left_dims = left_dims + (dim,)
310 for dim in rshape:
311 if dim not in lshape:
312 lastop = dim2lastop.get(dim, -1)
313 if lastop == i:
314 reduce_dims = reduce_dims + (dim,)
315 else:
316 right_dims = right_dims + (dim,)
317 result = result.reduce(
318 tuple(filter(lambda x: x not in reduce_dims, result.shape))
319 )
320 rhs = rhs.reduce(tuple(filter(lambda x: x not in reduce_dims, rhs.shape)))
321 result = einsum_matmul(result, rhs, batch_dims, sum_dims, left_dims, right_dims)
322 result = result.reduce(
323 tuple(filter(lambda x: x in output_shape, result.shape))
324 ).transpose(output_shape)
325 return result._tracer
326
327
328def diag_plane_interpret(inp: Tensor, inp_ndim: int, axes: List[int]) -> Tensor:

Callers 2

einsum_interpretFunction · 0.85
einsumFunction · 0.85

Calls 8

EinsumOperandClass · 0.85
filterFunction · 0.85
einsum_matmulFunction · 0.85
dedup_dimMethod · 0.80
addMethod · 0.45
getMethod · 0.45
reduceMethod · 0.45
transposeMethod · 0.45

Tested by

no test coverage detected