Repository navigation
Description
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
drisspg commentedon Jun 27, 2024
Should the AOTI issues be separate or folded into here around the striding of not being col_major?
bdhirsh commentedon Jun 27, 2024
The AOTI striding thing seems pretty inductor-specific - we can leave it as a separate issue
bdhirsh commentedon Jun 27, 2024
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:
Update base for Update on "AOTI: dont treat views of buffers as const…
Update on "AOTI: dont treat views of buffers as constants"
AOTI: dont treat views of buffers as constants (#129688)
tugsbayasgalan commentedon Aug 6, 2024
New repro based on float8 API changes:
jerryzh168 commentedon Jan 9, 2025
this is fixed now by #141941 I think, enabled test in pytorch/ao#1531, feel free to close if there are no other issues
bdhirsh commentedon Jan 10, 2025
great :) Let us know if there are any other torchAO + export problems