Skip to content

float8 tensor subclass + export issues #129682

Closed

Description

@bdhirsh

Today, we advertise that you can use torch.export on a model that has a tensor subclasses as model params/buffers as long as you write a custom parametrization that "desugars" your subclass into the state dict. However, doing this still doesn't get you all the way through export. Below is a repro using float8 (you can check this branch of the float8 repro to run it meta-pytorch/float8_experimental#287)

import torch
from torch.export import export

import torch.nn.utils.parametrize as parametrize

import io
import random
import unittest
import pytest
import torch
import torch.nn as nn
import torch.nn.functional as F
from float8_experimental.float8_dynamic_linear import Float8DynamicLinear
from float8_experimental.float8_linear_utils import swap_linear_with_float8_linear
from float8_experimental.float8_tensor import Float8Tensor
from float8_experimental.float8_utils import compute_error
random.seed(0)
torch.manual_seed(0)
is_H100 = torch.cuda.is_available() and torch.cuda.get_device_capability() >= (9, 0)
class UnwrapTensorSubclass(torch.nn.Module):
    def forward(self, *tensors):
        todo = list(tensors)
        for tp, meta, inner_tensors in reversed(self.rebuild_stack):
            nb_tensor = len(inner_tensors)
            inner_tensors = {a: b for a, b in zip(inner_tensors, todo[-nb_tensor:])}
            todo = todo[nb_tensor:]
            rebuilt = tp.__tensor_unflatten__(inner_tensors, meta, None, None)
            todo.append(rebuilt)
        assert len(todo) == 1
        return todo[0]
    def right_inverse(self, tensor):
        assert type(tensor) is not torch.Tensor
        rebuild_stack = []
        plain_tensors = []
        todo = [tensor]
        while todo:
            obj = todo.pop()
            inner_tensors, metadata = obj.__tensor_flatten__()
            rebuild_stack.append((type(obj), metadata, inner_tensors))
            for attr_name in inner_tensors:
                val = getattr(obj, attr_name)
                if type(val) is torch.Tensor:
                    plain_tensors.append(val)
                else:
                    assert isinstance(val, torch.Tensor)
                    todo.append(val)
        self.rebuild_stack = rebuild_stack
        return plain_tensors
def unwrap_tensor_subclass(model, filter_fn=None):
    for name, child in model.named_children():
        if (
            isinstance(child, torch.nn.Linear) and
            hasattr(child, "weight") and
            type(child.weight) is not torch.Tensor and
            isinstance(child.weight, torch.Tensor)
        ):
            parametrize.register_parametrization(child, "weight", UnwrapTensorSubclass())
        unwrap_tensor_subclass(child)
    return model
class FeedForward(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.w1 = nn.Linear(4096, 14336, bias=False)
        self.w3 = nn.Linear(4096, 14336, bias=False)
        self.w2 = nn.Linear(14336, 4096, bias=False)
    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.w2(F.silu(self.w1(x)) * self.w3(x))
    def reset_parameters(self):
        for m in self.modules():
            if isinstance(m, nn.Linear):
                m.reset_parameters()
export_model = FeedForward().to("cuda")
swap_linear_with_float8_linear(
    export_model,
    Float8DynamicLinear,
    from_float_kwargs={"pre_quantize_weight": True},
)
export_model = unwrap_tensor_subclass(export_model)
batch_size = 4
num_tokens = 1024
embedding_dim = 4096
input_tensor = torch.randn(
    batch_size, num_tokens, embedding_dim, device="cuda", dtype=torch.float32
)
example_args = (input_tensor,)
exported_program: torch.export.ExportedProgram = export(
    export_model, args=example_args
)
print(exported_program)

After running the repro and making some changes locally, I found 3 problems:

(1) in the end state, we shouldn't require float8 to role its own logic to do the parametrization that I wrote above. Instead, we should upstream this directly into export, so the export API can do this automatically when it detects params/buffers that are subclasses

(2) With the hand-rolled parametrization above, the repro still breaks: export will run in "strict mode" by default. The parametrization above will call __tensor_unflatten__ on the parametrized weights, and we need dynamo to dump that call directly into the graph (it errors today instead)

(3) if you turn off strict mode and run non-strict export, we end up with a similar problem: morally, pre-dispatch tracing will also need to include the tensor_unflatten call in the graph, which requires capturing it as a proxy (this does not work today)

cc @ezyang @albanD @anijain2305 @chauhang @penguinwu @avikchaudhuri @gmagogsfm @zhxchen17 @tugsbayasgalan @angelayi @suo @ydwu4 @zou3519

Activity

  1. drisspg commented on Jun 27, 2024

    @drisspg
    Contributor

    Should the AOTI issues be separate or folded into here around the striding of not being col_major?

  2. bdhirsh commented on Jun 27, 2024

    @bdhirsh
    CollaboratorAuthor

    The AOTI striding thing seems pretty inductor-specific - we can leave it as a separate issue

  3. bdhirsh commented on Jun 27, 2024

    @bdhirsh
    CollaboratorAuthor

    Although fwiw, with this patch: P1450057821 I can run a version of the above repro properly (exporting a float8 model and getting an inductor .so output), as long as I use some private API's to trace out a non-strict, aot-dispatch-only graph:

    import torch
    from torch.export import export
    from torch.export._trace import _export
    # Copyright (c) Meta Platforms, Inc. and affiliates.
    # All rights reserved.
    #
    # This source code is licensed under the BSD 3-Clause license found in the
    # LICENSE file in the root directory of this source tree.
    import copy
    import io
    import random
    import unittest
    import pytest
    import torch
    import torch.nn as nn
    import torch.nn.functional as F
    from float8_experimental.float8_dynamic_linear import Float8DynamicLinear
    from float8_experimental.float8_linear_utils import swap_linear_with_float8_linear
    from float8_experimental.float8_tensor import Float8Tensor
    from float8_experimental.float8_utils import compute_error
    random.seed(0)
    torch.manual_seed(0)
    is_H100 = torch.cuda.is_available() and torch.cuda.get_device_capability() >= (9, 0)
    import torch.nn.utils.parametrize as parametrize
    # NOTE: we should upstream this directly into export and make it more automatic!
    class UnwrapTensorSubclass(torch.nn.Module):
        def forward(self, *tensors):
            todo = list(tensors)
            for tp, meta, inner_tensors in reversed(self.rebuild_stack):
                nb_tensor = len(inner_tensors)
                inner_tensors = {a: b for a, b in zip(inner_tensors, todo[-nb_tensor:])}
                todo = todo[nb_tensor:]
                rebuilt = tp.__tensor_unflatten__(inner_tensors, meta, None, None)
                todo.append(rebuilt)
            assert len(todo) == 1
            return todo[0]
        def right_inverse(self, tensor):
            assert type(tensor) is not torch.Tensor
            rebuild_stack = []
            plain_tensors = []
            todo = [tensor]
            while todo:
                obj = todo.pop()
                inner_tensors, metadata = obj.__tensor_flatten__()
                rebuild_stack.append((type(obj), metadata, inner_tensors))
                for attr_name in inner_tensors:
                    val = getattr(obj, attr_name)
                    if type(val) is torch.Tensor:
                        plain_tensors.append(val)
                    else:
                        assert isinstance(val, torch.Tensor)
                        todo.append(val)
            self.rebuild_stack = rebuild_stack
            return plain_tensors
    def unwrap_tensor_subclass(model, filter_fn=None):
        for name, child in model.named_children():
            if (
                isinstance(child, Float8DynamicLinear) and
                hasattr(child, "weight") and
                type(child.weight) is not torch.Tensor and
                isinstance(child.weight, torch.Tensor)
            ):
                parametrize.register_parametrization(child, "weight", UnwrapTensorSubclass())
            unwrap_tensor_subclass(child)
        return model
    class FeedForward(nn.Module):
        def __init__(self) -> None:
            super().__init__()
            self.w1 = nn.Linear(4096, 14336, bias=False)
            self.w3 = nn.Linear(4096, 14336, bias=False)
            self.w2 = nn.Linear(14336, 4096, bias=False)
        def forward(self, x: torch.Tensor) -> torch.Tensor:
            return self.w2(F.silu(self.w1(x)) * self.w3(x))
        def reset_parameters(self):
            for m in self.modules():
                if isinstance(m, nn.Linear):
                    m.reset_parameters()
    export_model = FeedForward().to("cuda")
    swap_linear_with_float8_linear(
        export_model,
        Float8DynamicLinear,
        from_float_kwargs={"pre_quantize_weight": True},
    )
    export_model = unwrap_tensor_subclass(export_model)
    batch_size = 4
    num_tokens = 1024
    embedding_dim = 4096
    input_tensor = torch.randn(
        batch_size, num_tokens, embedding_dim, device="cuda", dtype=torch.float32
    )
    example_args = (input_tensor,)
    # NOTE: this breaks unless we use strict=False, pre_dispatch=False!
    exported_program: torch.export.ExportedProgram = _export(
        export_model,
        example_args,
        strict=False,
        pre_dispatch=False,
    )
    with torch.no_grad():
        so_path = torch._inductor.aot_compile(exported_program.module(), example_args)
        print(so_path)
    
    
  4. added
    tensor subclass
    module: pt2-dispatcher
    on Jul 1, 2024
  5. added
    triaged
    on Jul 2, 2024
  6. tugsbayasgalan commented on Aug 6, 2024

    @tugsbayasgalan
    Contributor

    New repro based on float8 API changes:

    import torch
    from torch.export import export
    
    import torch.nn.utils.parametrize as parametrize
    
    import io
    import random
    import unittest
    import pytest
    import torch
    import torch.nn as nn
    import torch.nn.functional as F
    from float8_experimental.float8_linear import Float8Linear
    from float8_experimental.float8_linear_utils import convert_to_float8_training
    from float8_experimental.float8_tensor import Float8Tensor
    from float8_experimental.float8_utils import compute_error
    random.seed(0)
    torch.manual_seed(0)
    is_H100 = torch.cuda.is_available() and torch.cuda.get_device_capability() >= (9, 0)
    class UnwrapTensorSubclass(torch.nn.Module):
        def forward(self, *tensors):
            todo = list(tensors)
            for tp, meta, inner_tensors in reversed(self.rebuild_stack):
                nb_tensor = len(inner_tensors)
                inner_tensors = {a: b for a, b in zip(inner_tensors, todo[-nb_tensor:])}
                todo = todo[nb_tensor:]
                rebuilt = tp.__tensor_unflatten__(inner_tensors, meta, None, None)
                todo.append(rebuilt)
            assert len(todo) == 1
            return todo[0]
        def right_inverse(self, tensor):
            assert type(tensor) is not torch.Tensor
            rebuild_stack = []
            plain_tensors = []
            todo = [tensor]
            while todo:
                obj = todo.pop()
                inner_tensors, metadata = obj.__tensor_flatten__()
                rebuild_stack.append((type(obj), metadata, inner_tensors))
                for attr_name in inner_tensors:
                    val = getattr(obj, attr_name)
                    if type(val) is torch.Tensor:
                        plain_tensors.append(val)
                    else:
                        assert isinstance(val, torch.Tensor)
                        todo.append(val)
            self.rebuild_stack = rebuild_stack
            return plain_tensors
    def unwrap_tensor_subclass(model, filter_fn=None):
        for name, child in model.named_children():
            if (
                isinstance(child, torch.nn.Linear) and
                hasattr(child, "weight") and
                type(child.weight) is not torch.Tensor and
                isinstance(child.weight, torch.Tensor)
            ):
                parametrize.register_parametrization(child, "weight", UnwrapTensorSubclass())
            unwrap_tensor_subclass(child)
        return model
    class FeedForward(nn.Module):
        def __init__(self) -> None:
            super().__init__()
            self.w1 = nn.Linear(4096, 14336, bias=False)
            self.w3 = nn.Linear(4096, 14336, bias=False)
            self.w2 = nn.Linear(14336, 4096, bias=False)
        def forward(self, x: torch.Tensor) -> torch.Tensor:
            return self.w2(F.silu(self.w1(x)) * self.w3(x))
        def reset_parameters(self):
            for m in self.modules():
                if isinstance(m, nn.Linear):
                    m.reset_parameters()
    export_model = FeedForward().to("cuda")
    convert_to_float8_training(
        export_model,
        Float8Linear,
        from_float_kwargs={"pre_quantize_weight": True},
    )
    export_model = unwrap_tensor_subclass(export_model)
    batch_size = 4
    num_tokens = 1024
    embedding_dim = 4096
    input_tensor = torch.randn(
        batch_size, num_tokens, embedding_dim, device="cuda", dtype=torch.float32
    )
    example_args = (input_tensor,)
    exported_program: torch.export.ExportedProgram = export(
        export_model, args=example_args
    )
    print(exported_program)
    
    
  7. jerryzh168 commented on Jan 9, 2025

    @jerryzh168
    Contributor

    this is fixed now by #141941 I think, enabled test in pytorch/ao#1531, feel free to close if there are no other issues

  8. bdhirsh commented on Jan 10, 2025

    @bdhirsh
    CollaboratorAuthor

    great :) Let us know if there are any other torchAO + export problems

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    module: pt2-dispatcheroncall: exportoncall: pt2tensor subclasstriaged

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions