ao icon indicating copy to clipboard operation
ao copied to clipboard

Buffer mutation tracking lost after convert_pt2e for index_put_

Open tom-arm opened this issue 8 months ago • 18 comments

Summary

When using prepare_pt2e / convert_pt2e to quantize a module that mutates a registered buffer via index_put_, the resulting exported program loses its buffers_to_mutate mapping. The FP32 exported program correctly records the buffer mutation, but after quantization the buffer is renamed to a frozen parameter (_frozen_param0) and the mutation relationship is silently dropped.

Reproduction

Below is a reproduction script with a simple quantizer for index_put_. Note this annotation behviour is similar to the TOSAQuantizer in ExecuTorch where this issue was found.

import torch
from torch.export import export
from torchao.quantization.pt2e.observer import MinMaxObserver
from torchao.quantization.pt2e.quantize_pt2e import convert_pt2e, prepare_pt2e
from torchao.quantization.pt2e.quantizer import (
    QuantizationAnnotation,
    QuantizationSpec,
    Quantizer,
    SharedQuantizationSpec,
)
from torchao.quantization.pt2e.quantizer.quantizer import Q_ANNOTATION_KEY


class MutatingBufferModule(torch.nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.register_buffer("buf", torch.zeros(4, dtype=torch.float32))

    def forward(self, x: torch.Tensor, idx: torch.Tensor) -> torch.Tensor:
        updated = self.buf.index_put_((idx,), x)
        return updated.clone()


class IndexPutQuantizer(Quantizer):
    def __init__(self) -> None:
        super().__init__()
        self.qspec = QuantizationSpec(
            dtype=torch.int8,
            observer_or_fake_quant_ctr=MinMaxObserver.with_args(eps=2**-12),
            quant_min=-128,
            quant_max=127,
            qscheme=torch.per_tensor_affine,
        )

    def annotate(self, model: torch.fx.GraphModule) -> torch.fx.GraphModule:
        for node in model.graph.nodes:
            if node.op != "call_function":
                continue
            if node.target != torch.ops.aten.index_put_.default:
                continue

            dst = node.args[0]
            value = node.args[2]
            node.meta[Q_ANNOTATION_KEY] = QuantizationAnnotation(
                input_qspec_map={
                    dst: self.qspec,
                    value: SharedQuantizationSpec((dst, node)),
                },
                output_qspec=SharedQuantizationSpec((dst, node)),
                _annotated=True,
            )
        return model

    def transform_for_annotation(self, model: torch.fx.GraphModule) -> torch.fx.GraphModule:
        return model

    def validate(self, model: torch.fx.GraphModule) -> None:
        return None


def main():
    module = MutatingBufferModule().eval()
    inputs = (
        torch.tensor([1.0, 2.0], dtype=torch.float32),
        torch.tensor([1, 3], dtype=torch.int64),
    )

    source_ep = export(module, inputs, strict=True)
    
    # To reproduce running to_edge_transform_and_lower in ExecuTorch
    source_decomp = source_ep.run_decompositions({})

    captured = export(module, inputs, strict=True).module()
    prepared = prepare_pt2e(captured, IndexPutQuantizer())
    prepared(*inputs)
    converted = convert_pt2e(prepared)

    converted_ep = export(converted, inputs, strict=True)
    
    # To reproduce running to_edge_transform_and_lower in ExecuTorch
    converted_decomp = converted_ep.run_decompositions({})

    print("Graph inputs after exporting for FP32")
    print("=========================")
    print("inputs_to_buffers:", source_decomp.graph_signature.inputs_to_buffers)
    print()
    
    print("Graph inputs after exporting for INT8 using PT2E")
    print("=========================")
    print("inputs_to_buffers:", converted_decomp.graph_signature.inputs_to_buffers)
    print()

    print("Graph outputs after exporting for FP32")
    print("=========================")
    print(source_ep.graph_signature.output_specs)
    print("buffers_to_mutate:", source_decomp.graph_signature.buffers_to_mutate)
    print()

    print("Graph outputs after exporting for INT8 using PT2E")
    print("=========================")
    print(converted_ep.graph_signature.output_specs)
    print("buffers_to_mutate:", converted_decomp.graph_signature.buffers_to_mutate)
    print()


if __name__ == "__main__":
    main()

Observed behavior

After the PT2E quantization flow, the exported program's graph signature shows:

  • Input: The original buffer buf is replaced by _frozen_param0, showing that it is has been folded into a constant.
  • Output: buffers_to_mutate is empty — the mutation of the buffer via index_put_ is no longer tracked.

Below are excerpts from the reproduction scripts output:

FP32 (correct):

inputs_to_buffers: {'b_buf': 'buf'}
buffers_to_mutate: {'index_put': 'buf'}

INT8 via PT2E (incorrect):

inputs_to_buffers: {'b__frozen_param0': '_frozen_param0'}
buffers_to_mutate: {}

Expected behavior

The quantized exported program should preserve the buffer mutation relationship. After convert_pt2e and re-export, buffers_to_mutate should still map the index_put_ output node back to the original buffer (or its quantized equivalent), just as it does in the FP32 case. In addition, the input to the graph should not be folded into a constant.

Impact

This causes a downstream ExecuTorch program to drop the mutable buffer output and replaces the mutable input as a constant.

Workarounds

I have been able to workaround the input folding issue by using fold_quantize=False in convert_pt2e, but this is not ideal.

tom-arm avatar Mar 23 '26 10:03 tom-arm

sorry just saw this, I think fold_quantize=False is the correct workaround, why is this not ideal?

Edit: oh I guess it's because other parts of the program will also not be frozen, makes sense

jerryzh168 avatar Apr 02 '26 03:04 jerryzh168

sorry just saw this, I think fold_quantize=False is the correct workaround, why is this not ideal?

Edit: oh I guess it's because other parts of the program will also not be frozen, makes sense

Yep, it would be good to still fold parts of the graph that are constant.

tom-arm avatar Apr 07 '26 12:04 tom-arm

fixed in https://github.com/pytorch/ao/pull/4181?

jerryzh168 avatar Apr 10 '26 00:04 jerryzh168

fixed in #4181?

The issue is partially fixed by this change. There are two sub-issues here:

  • The mutable input is being folded into a constant (this is fixed by #4181, thanks for the review!)
  • The mutable buffer is getting dropped from buffers_to_mutate (still needs fixing)

I'm not sure how to proceed with the second problem, so it would be good to keep this open if that's ok

tom-arm avatar Apr 10 '26 12:04 tom-arm

The mutable buffer is getting dropped from buffers_to_mutate (still needs fixing)

@tom-arm I see, is this a issue only related to quantization flow? or export in general

also cc @JacobSzwejbka

jerryzh168 avatar Apr 17 '26 00:04 jerryzh168

The mutable buffer is getting dropped from buffers_to_mutate (still needs fixing)

@tom-arm I see, is this a issue only related to quantization flow? or export in general

also cc @JacobSzwejbka

Yes this only occurs in the quantization flow

tom-arm avatar Apr 17 '26 07:04 tom-arm

Is there any update on this @jerryzh168? I would really appreciate if the issue of the mutable buffer being dropped from buffers_to_mutate could be looked at. Thanks!

tom-arm avatar May 08 '26 12:05 tom-arm

@vkuzo can you help here?

digantdesai avatar May 21 '26 17:05 digantdesai

I'd be happy to review a PR!

vkuzo avatar May 28 '26 10:05 vkuzo

Thanks for the follow up @vkuzo. I don't have a PR for last remaining issue as mentioned here: https://github.com/pytorch/ao/issues/4138#issuecomment-4223730758 - I was hoping you folks could help with this?

tom-arm avatar Jun 01 '26 14:06 tom-arm

Hi @vkuzo - a PR https://github.com/pytorch/ao/pull/4466 is available for review

mansnils avatar Jun 08 '26 06:06 mansnils

This issue is fixed by #4466 & #4181. Closing this issue

tom-arm avatar Jun 23 '26 13:06 tom-arm

Reopening issue as #4466 was reverted

tom-arm avatar Jun 24 '26 15:06 tom-arm

@liangel-02 and @andrewor14 how can we fix this without breaking any internal tests?

mansnils avatar Jun 24 '26 15:06 mansnils

I looked through #4466 and the revert in #4531. It seems #4466 fixed buffers_to_mutate, but ended up skipping arg0 observers for all buffer-backed schema-write ops.

Would a narrower fix work instead?

  • Only handle aten.index_put_.default
  • Only when arg0 comes from a named buffer
  • Skip the arg0 observer only if the input edge and output share the same observer group
  • Add regression tests for buf.index_put_, buf.select(...).index_put_, and a negative test to ensure other mutable ops still insert observers

Would this still address the internal regression behind #4531?

eshwanthkartitr avatar Jul 08 '26 10:07 eshwanthkartitr

Hi @mansnils @eshwanthkartitr sorry for the delay, I'm looking into a way to fix the broken test internally, but cannot share more details here right now. If there's a quick way to modify this PR and work around the issue I'll let you know. In the meantime do you mind reopening a PR with the exact same changes so I can import and try to fix the internal test there? Thanks.

andrewor14 avatar Jul 10 '26 16:07 andrewor14

Hi @andrewor14,

Thanks for offering to take a look at this! I opened a revert here: https://github.com/pytorch/ao/pull/4564

Also FYI - we have a change being worked on internally which solves this with a different approach. I can submit that next week if that's helpful/needed

tom-arm avatar Jul 10 '26 16:07 tom-arm

To hopefully keep the ball rolling with this issue, I have posted a potential fix: https://github.com/pytorch/ao/pull/4569.

This change adds a pass to add qdq observers, to address @eshwanthkartitr's observation that observers were missing for arg0.

tom-arm avatar Jul 13 '26 17:07 tom-arm