Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[NF4] Add quantize_() API support for NF4 #1216

Merged
merged 1 commit into from
Nov 4, 2024
Merged

Conversation

gau-nernst
Copy link
Collaborator

@gau-nernst gau-nernst commented Nov 2, 2024

Background

When I was working on INT8 training stuff a while back, I realized there was no issue to make NF4 training work with quantize_() API (i.e. swap plain tensor with tensor subclass). This is because autograd+compile still works correctly for __torch_function__ (might not be the case in the past when NF4 was implemented) -> eliminate the need for custom nn.Module for downstream users as well as need for explicitly call to linear_nf4().

Usage

from torchao import quantize_
from torchao.dtypes.nf4 import nf4_weight_only

model = ...
quantize_(model, nf4_weight_only())  # works for both training and inference. NF4 weight is non-trainable

This would also compose nicely with LoRA, making QLoRA implementation more seamless. e.g.

from torch import nn
import torch.nn.functional as F

class LoRALinear(nn.Module):
    ...
    def forward(self, x):
        out = F.linear(x, self.weight)  # self.weight can be NF4Tensor
        out = out + self.lora_b(self.lora_a(x)) * (self.alpha / self.rank)
        return out

lora_layer = LoRALinear(...)
quantize_(
    lora_layer,
    nf4_weight_only(),
    filter_fn=lambda module, name: isinstance(module, LoRALinear),
)  # now this becomes QLoRA

Copy link

pytorch-bot bot commented Nov 2, 2024

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/ao/1216

Note: Links to docs will display an error until the docs builds have been completed.

❌ 1 New Failure

As of commit f9a5f94 with merge base f99b667 (image):

NEW FAILURE - The following job has failed:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@facebook-github-bot facebook-github-bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Nov 2, 2024
@suryanshgupta9933
Copy link

This would be really neat.

@msaroufim msaroufim self-requested a review November 2, 2024 22:53
@msaroufim msaroufim merged commit 1fbf788 into pytorch:main Nov 4, 2024
16 of 17 checks passed
@gau-nernst gau-nernst deleted the nf4 branch November 4, 2024 05:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants