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

Add bnb.nn.StableEmbedding for quantized training #1770

Merged
merged 2 commits into from
Oct 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion litgpt/finetune/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,9 +172,15 @@ def main(
fabric.print(f"Number of non-trainable parameters: {num_parameters(model, requires_grad=False):,}")

model = fabric.setup_module(model)

if isinstance(fabric.strategy.precision, BitsandbytesPrecision):
optimizer = instantiate_bnb_optimizer(optimizer, model.parameters())

from bitsandbytes.nn import StableEmbedding
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If it doesn't cause any issues, later it should be moved to PTL/Fabric's BitsandbytesPrecision plugin.

In addition, it should be better from a memory usage perspective.
Now the model is materialized on the device, embeddings aren't quantized (only Linear layers are) and only after embeddings weights are replaced with quantized once.

If the code is in the PTL code, then embeddings will be quantized during materialization.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice! Agreed

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Andrei-Aksionov @lantiga I think the idea is not to quantize StableEmbedding during training due to precision issues, but I am not an expert in BitsandBytes tbh.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But I think I maybe understand what you are saying: the modified model will be more inefficient during inference because quantization will not be applied to the StableEmbedding layer after training?

In this case, perhaps we should convert the StableEmbedding layer back into the regular Embedding layer before saving the model at the end of training. Let me investigate what impact that has on performance during inference.

Regarding integration into PTL/Fabric, that's a good point, but I am a bit concerned if we can/should make model architecture modifications like that?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, it was my mistake 😄.
I thought that it's a way to quantize embeddings 🙈.

But it still might be beneficial to upstream the code.
Right now, the model is initialized on a meta device and materialized on a target device via Fabric.
After the model is materialized the code creates StableEmbeddings and after replaces weights of the regular embeddings. So, at the same moment in time, we have two sets of weights: regular embeddings and stable ones.

If we move the code to Fabric, the replacement will happen during materialization.
Or you can try to replace the layer while the model is on meta device.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So, at the same moment in time, we have two sets of weights: regular embeddings and stable ones.

Good point. We could/should explicitly delete and garbage-collect the redundant original weight embedding after initializing the StableEmbedding. Sure, it would be even more efficient to never have 2 sets of weight at the same time during this weight-swapping point, but I don't think this will create a memory bottleneck there because the forward and backward passes in the training afterwards will likely be much higher than having temporarily a second embedding layer in memory.

The one concern is though if we move the code to Fabric, it will apply the Fabric precision settings to StableEmbedding, but if I understand correctly, this is a special layer that should retain float32 bit precision. So we would have to make a special exception for that layer in Fabric.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct. It's in a category of "nice to have".

If we move it to Fabric, it will just mean that whenever you apply BnB prevision plugin, this type of embedding, with the correct precision, will be used. Moving the code to Fabric doesn't require embeddings to be quantized :)

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds good! And it might also be a good first Fabric contribution for me to familiarize myself with the code base.

old_embedding = model.transformer.wte
model.transformer.wte = StableEmbedding(old_embedding.num_embeddings, old_embedding.embedding_dim)
with torch.no_grad():
model.transformer.wte.weight.copy_(old_embedding.weight)
model.transformer.wte = model.transformer.wte.to(device=old_embedding.weight.device, dtype=old_embedding.weight.dtype)
else:
optimizer = instantiate_torch_optimizer(optimizer, model.parameters())

Expand Down
8 changes: 7 additions & 1 deletion litgpt/finetune/adapter_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,9 +172,15 @@ def main(
fabric.print(f"Number of non-trainable parameters: {num_parameters(model, requires_grad=False):,}")

model = fabric.setup_module(model)

if isinstance(fabric.strategy.precision, BitsandbytesPrecision):
optimizer = instantiate_bnb_optimizer(optimizer, model.parameters())

from bitsandbytes.nn import StableEmbedding
old_embedding = model.transformer.wte
model.transformer.wte = StableEmbedding(old_embedding.num_embeddings, old_embedding.embedding_dim)
with torch.no_grad():
model.transformer.wte.weight.copy_(old_embedding.weight)
model.transformer.wte = model.transformer.wte.to(device=old_embedding.weight.device, dtype=old_embedding.weight.dtype)
else:
optimizer = instantiate_torch_optimizer(optimizer, model.parameters())

Expand Down
8 changes: 7 additions & 1 deletion litgpt/finetune/lora.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,9 +202,15 @@ def main(
fabric.print(f"Number of non-trainable parameters: {num_parameters(model, requires_grad=False):,}")

model = fabric.setup_module(model)

if isinstance(fabric.strategy.precision, BitsandbytesPrecision):
optimizer = instantiate_bnb_optimizer(optimizer, model.parameters())

from bitsandbytes.nn import StableEmbedding
old_embedding = model.transformer.wte
model.transformer.wte = StableEmbedding(old_embedding.num_embeddings, old_embedding.embedding_dim)
with torch.no_grad():
model.transformer.wte.weight.copy_(old_embedding.weight)
model.transformer.wte = model.transformer.wte.to(device=old_embedding.weight.device, dtype=old_embedding.weight.dtype)
else:
optimizer = instantiate_torch_optimizer(optimizer, model.parameters())

Expand Down
2 changes: 2 additions & 0 deletions tests/test_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,8 @@ def test_adapter_bitsandbytes(monkeypatch, tmp_path, fake_checkpoint_dir, alpaca
assert dtype_to_name == {
"torch.float16": {
"transformer.wte.weight",
"transformer.wte.norm.weight",
"transformer.wte.norm.bias",
"transformer.h.0.norm_1.weight",
"transformer.h.0.norm_1.bias",
"transformer.h.0.attn.gating_factor",
Expand Down
2 changes: 2 additions & 0 deletions tests/test_adapter_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,8 @@ def test_adapter_v2_bitsandbytes(monkeypatch, tmp_path, fake_checkpoint_dir, alp
"transformer.h.1.mlp.fc.adapter_scale",
"transformer.h.1.attn.attn.linear.bias",
"transformer.wte.weight",
"transformer.wte.norm.weight",
"transformer.wte.norm.bias",
"transformer.h.0.norm_2.weight",
"transformer.h.1.mlp.proj.linear.bias",
"transformer.h.0.attn.gating_factor",
Expand Down
3 changes: 3 additions & 0 deletions tests/test_lora.py
Original file line number Diff line number Diff line change
Expand Up @@ -724,6 +724,7 @@ def test_lora_bitsandbytes(monkeypatch, tmp_path, fake_checkpoint_dir, alpaca_pa

args, kwargs = train_mock.call_args
fabric, model, optimizer, *_ = args
model.transformer.wte = model.transformer.wte.half()
assert isinstance(fabric.strategy.precision, BitsandbytesPrecision)
assert isinstance(optimizer, _FabricOptimizer)
assert isinstance(optimizer._optimizer, PagedAdamW)
Expand All @@ -748,6 +749,8 @@ def test_lora_bitsandbytes(monkeypatch, tmp_path, fake_checkpoint_dir, alpaca_pa
"transformer.h.0.attn.attn.lora_B",
"transformer.h.0.norm_2.weight",
"transformer.wte.weight",
"transformer.wte.norm.weight",
"transformer.wte.norm.bias",
"transformer.h.1.mlp.fc.linear.bias",
"transformer.ln_f.bias",
"transformer.h.1.attn.attn.lora_B",
Expand Down
Loading