def merge_view_ops(sorted_graph: List[Tensor], workdir: str = None) -> List[Tensor]:
    """
    Merge consecutive view ops.
    """
    changed = False
    # Find pairs of consecutive view ops and merge them, iterating to a
    # fixpoint.
    # TODO: Instead of merging pairs of view ops, we should look for entire
    # chains of view ops and merge them all at once.
    while True:
        for tensor in sorted_graph:
            src_ops = tensor._attrs["src_ops"]
            if len(src_ops) != 1:
                continue
            src_op = list(src_ops)[0]
            if src_op._attrs["op"] not in _VIEW_OPS:
                continue
            dst_ops = tensor._attrs["dst_ops"]
            if any(op._attrs["op"] in _VIEW_OPS for op in dst_ops):
                # NOTE: _merge_view_ops_for does *not* return a sorted graph
                sorted_graph = _merge_view_ops_for(sorted_graph, tensor)
                changed = True
                break
        else:
            break

    if changed:
        # Prune tensors that may have become unused after view op merging
        sorted_graph = toposort([t for t in sorted_graph if t._attrs["is_output"]])
        return transform_utils.sanitize_sorted_graph(toposort(sorted_graph))
    return sorted_graph
Merge consecutive view ops.
python/aitemplate/compiler/transform/transform_merge_view_ops.py