def transform_pattern(pattern):
    """
    Insert instance_norm / layer_norm and delete all ops.
    :param pattern: A pattern object that contains all relevant information.
    """
    out_name = pattern.final_op.outputs[0].name
    axes = pattern.main_reduce.axes.val

    if pattern.requires_rank4_transpose:
        x = mb.transpose(
            x=pattern.main_reduce.x,
            perm=[0, 3, 1, 2],
            name=out_name + "_transpose_nhwc_nchw",
            before_op=pattern.final_op,
        )
    if pattern.is_instancenorm:
        x = mb.instance_norm(
            x=x if pattern.requires_rank4_transpose else pattern.main_reduce.x,
            gamma=np.squeeze(pattern.gamma_var.val),
            beta=np.squeeze(pattern.beta_var.val),
            epsilon=pattern.epsilon_var,
            name=out_name + "_instancenorm" if pattern.requires_rank4_transpose else out_name,
            before_op=pattern.final_op,
        )
    else:  # is_layernorm
        x = mb.layer_norm(
            x=x if pattern.requires_rank4_transpose else pattern.main_reduce.x,
            axes=axes,
            gamma=pattern.gamma_var,
            beta=pattern.beta_var,
            epsilon=pattern.epsilon_var,
            name=out_name + "_layernorm" if pattern.requires_rank4_transpose else out_name,
            before_op=pattern.final_op,
        )
    if pattern.requires_rank4_transpose:
        x = mb.transpose(
            x=x,
            perm=[0, 2, 3, 1],
            name=out_name + "_transpose_nchw_nhwc",
            before_op=pattern.final_op,
        )

    pattern.final_op.enclosing_block.replace_uses_of_var_after_op(
        anchor_op=pattern.final_op, old_var=pattern.final_op.outputs[0], new_var=x
    )
    # Remove all the ops at once
    pattern.block.remove_ops(pattern.op_list())

    Insert instance_norm / layer_norm and delete all ops.
    :param pattern: A pattern object that contains all relevant information.
    
coremltools/converters/mil/experimental/passes/generic_layernorm_instancenorm_pattern_fusion.py