Repository navigation
Conversation
Mostly copying from `src/peft/tuners/lora` and changing names and layers Haven't validated it works.
currently seems to work for creating the model. however, random projs are not shared. I don't think this affects behaviour but isn't as efficient. However, it would be fun to try it out.
This avoids needing to save the random projection matrices, as well as ensuring they are identical across all devices. This involved creating a new kaiming_normal init that supported generators Perhaps they can be computed on the fly to save memory?
|
For convenience, here is the paper link: https://arxiv.org/abs/2310.11454 Thanks for working on adding this method. @pacman100 also took a look at it already, not sure if he can share more insights.
I'm curious to see what you can find out. Regarding this part of the paper:
How did you deal with it? |
With my approach I am getting peak 87% accuracy compared to 89% in the paper on GLUE's MRPC benchmark. It seems relatively sensitive to choice in parameters, so I am assuming the mismatch is down to some small difference between my code and the author's code.
For experimentation, I just store the A B matrices in all VeRA modules. For initialisation, I use a PRNG key I store in a config object. This does not save memory, but just wanted to experiment with the method first. To actually get it working, I would just store the PRNG key in each module, then in the forward pass use the key to generate the matrices as they are needed. Probably generating on CPU then moving to device. I generate the matrices with a modified Not sure if @pacman100 has chatted with the paper author's, but they had some thoughts too:
Finally, an idea from me:
@BenjaminBossan could you link me to a branch where @pacman100 is working on this? |
If possible, could you please check what score you get using normal LoRA? Even if the score from the paper cannot be replicated 1:1 (maybe once the authors release their code), if it is still identical to LoRA scores while using fewer parameters, it would be a win. Regarding the PRNG question, I would be afraid to run into reproducibility issues. Is there a guarantee that a seed is enough to restore the exact weights across all hardware, OS's, PyTorch versions, etc.? Having something like a checksum would help to detect such issues, but still wouldn't help to restore the weights. I wonder if it wouldn't be better to just store the full weights, even if that means that some of the memory savings are lost.
This is an interesting idea and I would like to know how well it works in practice. Since it's a deviation from the paper, it should probably be disabled by default, with an option to enable it via the config. Of course, if this is implemented alongside storage of the weights, it means that even less memory is safed.
I don't think he did.
Not sure if he has pushed anything to a branch yet, I don't see anything. As he's off for a few days, I can't ask him right now. |
I based my example code off
Unsure. I am not an expert on how PyTorch handles PRNG. If we can rely on it (even better if we can rely on it generating on GPU) that would be great. But I can't say.
Yeah, disabled by default makes sense. it just seems so easy to add that we might as well (as an option). |
we are ignoring merging of weighted adapters unsure the best way to do it for VeRA yet.
|
Check out this pull request on See visual diffs & provide feedback on Jupyter Notebooks. Powered by ReviewNB |
currently leads to mismatched results when loading, even when parameters match. needs investigating
According to author, this is no longer needed with kaiming init. With this change, at reported batch size, we reach reported accuracy in GLUE MRPC benchmark 🔥
to be removed before merge
|
@BenjaminBossan with recent changes the GLUE MRPC task now reaches the reported performance. I need to test other tasks, which I have been doing with my @pacman100 when you are back from leave, could we work together on this feature? I've already done the ground work, what is left is the following:
These don't all have to be done in the initial PR, of course. |
this was not used in any tests, just removing to avoid confusion
paper results were computed with this left at default, unlike lora which sets to `sqrt(5)`
BenjaminBossan
left a comment
There was a problem hiding this comment.
Thanks for your extensive work on adding VeRA. I wanted to give some early feedback. For this, I focused mainly on the VeRA method itself, not so much on the general implementation (which has a lot of code duplication for now and can probably be streamlined). I left a few comments in the code, please take a look. Apart from those, I have some more general comments:
- AFAICT, there is no equivalent to LoRA alpha for VeRA. I think that it's important to have and might help replicating the paper results.
- For
init_vera_weights=False, you set b and do to zero. But this would result in an identity transform, which is what we want to avoid for this setting. It's not clear what to use instead though. - For
init_vera_weights=True, you set b to 0 and d to 1. At some point, however, they seem to suggest 1e-7 for d works better (table 7). - We have yet to discuss how A and B are used/shared across layers. One way could be that we store the seed on each layer and create the matrices on the fly when needed (see one of my comments).
- One thing I wondered about: Sharing of A and B only works as long as the layer dimensions are all the same, right? If we had an architecture with different hidden sizes on different layers, this cannot work.
Regarding some of the points you mentioned:
Adapter merging (it isn't clear to me how this would be done here)
Not sure if I understand: You do have merging implemented, don't you? Or do you mean something else?
Tests
Yes, I think that's going to be important. Let me know if you need help with adding tests.
These don't all have to be done in the initial PR, of course.
Yes, we don't need to have everything perfect in place. Something to also think about eventually are docs.
|
Hi Benjamin, thanks for your comments.
Actually, I spoke to the author directly, and he said they did not use scaling via alpha, as they believe the kaiming init to be sufficient. So I removed it in a later commit.
What is the intended behaviour of this parameter in its LoRA equivalent? I was a bit confused when you would choose not to init the weights, so I think I was lazy with the
Yep, but equally for all sentence understanding benchmarks they set this to
I think this is the best way, with the option to instead store the A B matrices to. We could have this as a config option to balance speed against memory. What do you think about this?
It's a fair point. Simplest solution is to do as you said before: store only the seed. Then we will just have a different random projection for each dimensionality. From talking with the author, the model should still train – even if every layer has a different random projection.
I am not too familiar with peft, but it seems there is an option to merge multiple adapters together? See here Let me know if you have any further questions. In particular, I am curious to hear your thoughts on the matter of whether to store or regenerate the AB matrices, or provide the option to do both. I've been putting off implementing this as I was unsure what is preferred by the maintainers. Once we agree, I can implement whatever we decide. |
|
Hi, author of the paper here, I'd be happy to help with any questions you might have:) Regarding the shared matrices for different dimensions - we can generate a single matrix pair with highest dimensions required, and slice accordingly for each layer. As for the regeneration during forward pass/storing a single copy - it's a matter of performance/memory usage trade-off. |
|
Hi @dkopi I like the idea of a single shared matrix pair and just slicing for each layer. It minimises the memory use whilst avoiding the need to regenerate on the fly (which increases latency) and allows us to reliably restore the checkpoint in the event the seed approach fails. The only issue I can think of is making this slicing approach performant, which I think we can do by generating a single flat vector, slicing to the dimension we need, and then taking a view of it (rather than a reshape). This will prevent any additional copies as we ensure the view is always contiguous. To ensure I've understood correctly, we would calculate:
Then take the maximum of all of these as the size of the shared vector. Each layer then stores its VeRA projection parameter count, takes a slice of this size, then takes a view of the slice that matches the expected weight shape of its linear / embedding / convolution operation. @dkopi does that sound about right? @BenjaminBossan would this approach be suitable for |
|
@vvvm23 Yeah, I guess that would work, slicing is technically a view so it shouldn't affect the performance. The only problem now is with initialization - maybe we could init the vectors with uniform[-1, 1] and scale it for each layer separately. |
|
Hmmm I didn't think about that. That adds a lot of complexity, so probably not the best way 🤔 As it is a view, we would also have to unscale after the layer is done (or make a copy). Homogeneous architectures like transformers would work well, but we would struggle to do this approach in general. This indicates that recomputing on the fly is the best way to retain memory savings at the cost of losing some speed. However, I had the realisation yesterday that we probably won't save memory using this approach either. This is because torch's autograd will internally still save the generated A B matrices for use in backprop. To confirm this, I wrote a simple script: import torch
import torch.nn as nn
import torch.nn.functional as F
import torchviz
class Layer(nn.Module):
def __init__(self, key: int = 0xffff, dim: int = 8, r: int = 4):
super().__init__()
self.key = key
self.dim = dim
self.r = r
self.b = nn.Parameter(torch.zeros(dim))
self.d = nn.Parameter(0.1* torch.ones(r))
self.dummy = nn.Parameter(torch.zeros(dim))
def forward(self, x):
generator = torch.Generator().manual_seed(self.key)
# to make A show up in autograd
x = x + self.dummy
A = torch.randn(r, dim, generator=generator)
B = torch.randn(dim, r, generator=generator)
return self.b * F.linear(self.d * F.linear(x, A), B)
if __name__ == '__main__':
dim = 8
r = 2
key = 0xffff
N = 10000
batch_size = 100
device = torch.device('cuda')
model = Layer(key, dim=dim, r=r)
torch.manual_seed(key % 111111)
x = torch.randn(batch_size, dim)
y = torch.zeros(batch_size, dim)
logits = model(x)
loss = F.mse_loss(F.sigmoid(logits), y)
dot = torchviz.make_dot(
loss,
params=dict(model.named_parameters()),
show_attrs=True, show_saved=True
)
dot.format = 'png'
dot.render()which produces the following render: You can see, highlighted in orange, the tensors that will be saved by the autograd engine, which includes the A B (mat1 and mat2) projection matrices. Hence, we obtain no memory savings. So, there is basically no point computing on the fly over simply saving the matrices as frozen parameters in each layer. In conclusion, there are only two approaches worth doing:
For the first, we could have multiple sets of global A B matrices for each layer type. However, in the worst case the memory usage is the same as the second approach 🤔 Apologies for the lengthy analysis, @dkopi and @BenjaminBossan would love your input on how best to continue. I admit, I am unsure what works best for Huggingface and peft 😓 |
|
Thanks for the fruitful discussions and for running the analysis. I think it's better to have a long discussion beforehand than ending up with a bad implementation. I agree that the idea of using a big A/B matrix and taking smaller pieces of that depending on the layer, then rescaling it, sounds too complicated and error prone. Computing on the fly may not reduce peak memory usage, but it sounds easier to implement, especially if the matrices we need to generate have different shapes and/or use different distributions. One disadvantage I see here is that this approach would rely on the seed being sufficient to reproduce exact numbers across platforms/hardware/versions etc. I could not determine with certainty if there is any guarantee for this. In the context of running single experiments, this is no big deal, but if people want to be able to reliably share model weights over time, which is expected of Hugging Face, it would be a deal breaker. Storing the matrices on a per layer basis sounds like the way to go then. I think this is also not going to be as easy as it may sound when we have model architectures that require differently shaped A and B matrices for different layers. We could restrict VeRA to only support architectures where this is not the case, but I think this would be an unfortunate restriction. Also, not sure if PyTorch's Finally, we have the option of just creating different A and B matrices for each layer, at least as an opt in feature. This should be easiest to implement, as it mirrors the current LoRA implementation. However, it would negate a lot of the size savings when it comes to storing the weights. When it comes to memory requirements during training, in the grand scheme of things, the overhead vs using the same weights should be relatively small though, right? From my understanding, there is no evidence yet that having different weights is beneficial or detrimental for the loss. |
Hmm yes, now I am unsure how to interpret the graph. I think your analysis might be correct, so let's change our method in the new year :) |
|
Hi guys, happy new year and thanks for your work. |
|
Hello, was working on other pressing projects, probably come back to this next week :) |
|
Thanks a lot @vvvm23! |
|
I started looking at this again and changing the implementation to use per-layer I think this is an important feature though, so I will keep trying to figure something out. Feel free to take a look at my WIP version. |
passes tests, but pretty rough and needs cleaning up. needs careful review to check for any edge cases. Does achieve the intended purpose of matching the shared API between all tuners. However, makes the implementation within `vera/model.py` more complex and repeats some code.
this involved removing the post_init check for the projection key being not None. This is because certain tests assume the config's defaults are all valid, which is not the case for VeraConfig previously
|
Got a working implementation of this per-layer buffer thing. I have not rigorously tested it (and to be honest, I need to add some vera specific tests still) but the current suite passes. The draft implementation is a bit fragile though so it will need a careful review. In particular, I had to split the regular I also had to change how the shape of the As a random side, I had to remove the Next I'll do some cleanup and tests for the vera specific stuff. Let me know what you think @BenjaminBossan |
|
Did some cleanup that hopefully makes the changes I made more clear. In particular, look at the docstring for a temporary method I made Hope that makes sense, let me know what you think of the proposal in the todo @BenjaminBossan EDIT: if you are wondering why this is so complex even though we did the same thing previously, that was because we were using raw tensors then and not buffers. Without them, we could not add |
|
I started looking at adding tests this morning, however I am unsure where adapter-specific, one-off tests would go in the existing structure. Most tests seem to be formulated in an adapter-agnostic way (with the exception of some LoRA tests, but I feel they are popular enough to be their own thing) so I am hesitant to change the structure without knowing what is best. Any advice @BenjaminBossan ? |
BenjaminBossan
left a comment
There was a problem hiding this comment.
Hi, I'm back in office, sorry for the long wait. I didn't have time yet for an in-depth review, but wanted to give some feedback as quickly as I could.
I started looking at this again and changing the implementation to use per-layer BufferDict again. This is surprisingly quite challenging, mostly due to the model init calling _create_new_module before vera_A has a chance to be created - as the first call of this happens before the main body of VeraModel. However, we can't create vera_A before as the class isn't even a nn.Module yet, so we can't register submodules yet.
I think there has to be a better way. Not sure if this will work, but maybe let's consider something like this:
- Change
BaseTuner.__init__to call a_pre_initmethod before doing the proper initialization. This method is defined by default to justpass. - Inside of
VeraModel, define the_pre_initmethod to do the necessary work to createvera_Aandvera_B.
Would this or a similar approach work so that we can get rid of the __tuner_init__ workaround?
I started looking at adding tests this morning, however I am unsure where adapter-specific, one-off tests would go in the existing structure. Most tests seem to be formulated in an adapter-agnostic way (with the exception of some LoRA tests, but I feel they are popular enough to be their own thing) so I am hesitant to change the structure without knowing what is best.
It is indeed a bit tricky to decide where to put those tests for the reasons you described. I'd say that for now, just create a separate test file, like we have for test_adaption_prompt, and put the tests there. We may later still decide to put them elsewhere if really needed. These tests don't need to run the full gauntlet of real world models (like test_decoder.py etc.) but can use some small toy models instead. Maybe one end-to-end test with a "real" model could be added for good measure.
I think that having those tests, especially when it comes to saving and loading, is super crucial to ensure that the implementation is correct. I could imagine that they can still uncover a few issues, as many things are non-trivial. Therefore, those should have highest priority. After adding those, I'll do another round of in-depth review. In the meantime, please ask if you have questions regarding the tests.
| # non trainable references to vera_A/B buffers | ||
| # use setattr as this happens post `nn.Module.__init__` | ||
| # but should not be issue as these are just references to the normally initialised `vera_A/B` | ||
| setattr(self, "vera_A", vera_A) |
There was a problem hiding this comment.
Calling setattr here and below should not be necessary, self.vera_A = vera_A should be functionally identical, right?
|
@vvvm23 Do you need help with PR? |
|
Hi sorry, just started a new job so I am pretty busy. Not sure how much time I can dedicate to this. The PR is pretty close to completion though, so don't mind if someone continues this for me. |
|
Thanks for giving us an update @vvvm23- I can take a stab at this when I have time, but also would be happy for outside contributions. |
Should now be 95% on par with huggingface#1039, with some minor changes on my part + resolving merge conflicts. Examples have not been included yet.
|
I plan to continue the work in #1564. |
|
Let me know if you want a review there :) |
|
This issue has been automatically marked as stale because it has not had recent activity. If you think this still needs to be addressed please comment on this thread. |
Implements VeRA: https://huggingface.co/papers/2310.11454 VeRA is similar to LoRA but even more parameter efficient, while promising to keep the same performance. In its current implementation, it has a few limitations compared to LoRA: - All targeted parameters must have the same shape. - Only `nn.Linear` layers are supported. - Quantized layers are not supported. This PR is based on, and supersedes, #1039. --------- Co-authored-by: Alex McKinney <alex.f.mckinney@gmail.com> Co-authored-by: Dawid <20214809+dkopi@users.noreply.github.com>
Implements VeRA: https://huggingface.co/papers/2310.11454 VeRA is similar to LoRA but even more parameter efficient, while promising to keep the same performance. In its current implementation, it has a few limitations compared to LoRA: - All targeted parameters must have the same shape. - Only `nn.Linear` layers are supported. - Quantized layers are not supported. This PR is based on, and supersedes, huggingface#1039. --------- Co-authored-by: Alex McKinney <alex.f.mckinney@gmail.com> Co-authored-by: Dawid <20214809+dkopi@users.noreply.github.com>

See #1038 for details.
This is still a WIP and maybe shouldn't be added at all depending on actual performance of the method. Working on verifying this in this branch 🤗