{"id":13563168,"url":"https://github.com/lucidrains/perfusion-pytorch","last_synced_at":"2025-04-05T21:05:52.300Z","repository":{"id":186539855,"uuid":"675333215","full_name":"lucidrains/perfusion-pytorch","owner":"lucidrains","description":"Implementation of Key-Locked Rank One Editing, from Nvidia AI","archived":false,"fork":false,"pushed_at":"2023-09-07T17:16:18.000Z","size":3288,"stargazers_count":233,"open_issues_count":5,"forks_count":7,"subscribers_count":51,"default_branch":"main","last_synced_at":"2025-04-04T09:07:30.569Z","etag":null,"topics":["artificial-intelligence","deep-learning","memory-editing","text-to-image"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/lucidrains.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2023-08-06T15:20:56.000Z","updated_at":"2025-03-10T02:53:42.000Z","dependencies_parsed_at":null,"dependency_job_id":"8285469a-a8f2-44e1-816c-1c3f4ae28519","html_url":"https://github.com/lucidrains/perfusion-pytorch","commit_stats":null,"previous_names":["lucidrains/perfusion-pytorch"],"tags_count":51,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lucidrains%2Fperfusion-pytorch","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lucidrains%2Fperfusion-pytorch/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lucidrains%2Fperfusion-pytorch/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lucidrains%2Fperfusion-pytorch/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/lucidrains","download_url":"https://codeload.github.com/lucidrains/perfusion-pytorch/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247399871,"owners_count":20932876,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["artificial-intelligence","deep-learning","memory-editing","text-to-image"],"created_at":"2024-08-01T13:01:15.848Z","updated_at":"2025-04-05T21:05:52.276Z","avatar_url":"https://github.com/lucidrains.png","language":"Python","funding_links":[],"categories":["Python"],"sub_categories":[],"readme":"\u003cimg src=\"./key-locked-rank-1-editing.png\" width=\"450px\"\u003e\u003c/img\u003e\n\n## Perfusion - Pytorch\n\nImplementation of \u003ca href=\"https://arxiv.org/abs/2305.01644\"\u003eKey-Locked Rank One Editing\u003c/a\u003e. \u003ca href=\"https://research.nvidia.com/labs/par/Perfusion/\"\u003eProject page\u003c/a\u003e\n\nThe selling point of this paper is extremely low extra parameters per added concept, down to 100kb.\n\nIt seems they successfully applied the Rank-1 editing technique from a \u003ca href=\"https://arxiv.org/abs/2202.05262\"\u003ememory editing paper for LLM\u003c/a\u003e, with a few improvements. They also identified that the keys determine the \"where\" of the new concept, while the values determine the \"what\", and propose local / global-key locking to a superclass concept (while learning the values).\n\nFor researchers out there, if this paper checks out, the tools in this repository should work for any other text-to-`\u003cinsert modality\u003e` network using cross attention conditioning. Just a thought\n\n## Appreciation\n\n- \u003ca href=\"https://stability.ai/\"\u003eStabilityAI\u003c/a\u003e for the generous sponsorship, as well as my other sponsors out there\n\n- Yoad Tewel for the multiple code reviews and clarifying emails\n\n- \u003ca href=\"https://github.com/BradVidler\"\u003eBrad Vidler\u003c/a\u003e for precomputing the covariance matrix for the CLIP used in Stable Diffusion 1.5!\n\n- All the maintainers at \u003ca href=\"https://github.com/mlfoundations/open_clip\"\u003eOpenClip\u003c/a\u003e, for their SOTA open sourced contrastive learning text-image models\n\n## Install\n\n```bash\n$ pip install perfusion-pytorch\n```\n\n## Usage\n\n```python\nimport torch\nfrom torch import nn\n\nfrom perfusion_pytorch import Rank1EditModule\n\nto_keys = nn.Linear(768, 320, bias = False)\nto_values = nn.Linear(768, 320, bias = False)\n\nwrapped_to_keys = Rank1EditModule(\n    to_keys,\n    is_key_proj = True\n)\n\nwrapped_to_values = Rank1EditModule(\n    to_values\n)\n\ntext_enc = torch.randn(4, 77, 768)                  # regular input\ntext_enc_with_superclass = torch.randn(4, 77, 768)  # init_input in algorithm 1, for key-locking\nconcept_indices = torch.randint(0, 77, (4,))        # index where the concept or superclass concept token is in the sequence\nkey_pad_mask = torch.ones(4, 77).bool()\n\nkeys = wrapped_to_keys(\n    text_enc,\n    concept_indices = concept_indices,\n    text_enc_with_superclass = text_enc_with_superclass,\n)\n\nvalues = wrapped_to_values(\n    text_enc,\n    concept_indices = concept_indices,\n    text_enc_with_superclass = text_enc_with_superclass,\n)\n\n# after much training ...\n\nwrapped_to_keys.eval()\nwrapped_to_values.eval()\n\nkeys = wrapped_to_keys(text_enc)\n\nvalues = wrapped_to_values(text_enc)\n\n```\n\nThe repository also contains an `EmbeddingWrapper` that makes it easy to train on a new concept (and for eventual inference with multiple concepts)\n\n```python\nimport torch\nfrom torch import nn\n\nfrom perfusion_pytorch import EmbeddingWrapper\n\nembed = nn.Embedding(49408, 512) # open clip embedding, somewhere in the module tree of stable diffusion\n\n# wrap it, and will automatically create a new concept for learning, based on the superclass embed string\n\nwrapped_embed = EmbeddingWrapper(\n    embed,\n    superclass_string = 'dog'\n)\n\n# now just pass in your prompts with the superclass id\n\nembeds_with_new_concept, embeds_with_superclass, embed_mask, concept_indices = wrapped_embed([\n    'a portrait of dog',\n    'dog running through a green field',\n    'a man walking his dog'\n]) # (3, 77, 512), (3, 77, 512), (3, 77), (3,)\n\n# now pass both embeds through clip text transformer\n# the embed_mask needs to be passed to the cross attention as key padding mask\n```\n\nIf you can identify the `CLIP` instance within the stable diffusion instance, you can also pass it directly to the `OpenClipEmbedWrapper` to gain everything you need on forward for the cross attention layers\n\nex.\n\n```python\nfrom perfusion_pytorch import OpenClipEmbedWrapper\n\ntexts = [\n    'a portrait of dog',\n    'dog running through a green field',\n    'a man walking his dog'\n]\n\nwrapped_clip_with_new_concept = OpenClipEmbedWrapper(\n    stable_diffusion.path.to.clip,\n    superclass_string = 'dog'\n)\n\ntext_enc, superclass_enc, mask, indices = wrapped_clip_with_new_concept(texts)\n\n# (3, 77, 512), (3, 77, 512), (3, 77), (3,)\n```\n\n## Todo\n\n- [ ] wire up with SD 1.5, starting with xiao's dreambooth-sd\n- [ ] show example in readme for inference with multiple concepts\n- [ ] automatically infer where keys and values projection are if not specified for the `make_key_value_proj_rank1_edit_modules_` function\n\n- [x] embedding wrapper should take care of substituting with super class token id and return embedding with super class\n- [x] review multiple concepts - thanks to Yoad\n- [x] offer a function that wires up the cross attention\n- [x] handle multiple concepts in one prompt at inference - summation of the sigmoid term + outputs\n    - [x] accept multiple concept indices\n- [x] offer a way to combine separately learned concepts from multiple `Rank1EditModule` into one for inference\n    - [x] offer function for merging `Rank1EditModule`s\n- [x] add the zero-shot masking of concept proposed in paper\n- [x] take care of the function that takes in the dataset and text encoder and precomputes the covariance matrix needed for the rank-1 update\n- [x] instead of having the researcher worry about different learning rates, offer the fractional gradient trick from other paper (to learn the concept embedding)\n\n## Citations\n\n```bibtex\n@article{Tewel2023KeyLockedRO,\n    title   = {Key-Locked Rank One Editing for Text-to-Image Personalization},\n    author  = {Yoad Tewel and Rinon Gal and Gal Chechik and Yuval Atzmon},\n    journal = {ACM SIGGRAPH 2023 Conference Proceedings},\n    year    = {2023},\n    url     = {https://api.semanticscholar.org/CorpusID:258436985}\n}\n```\n\n```bibtex\n@inproceedings{Meng2022LocatingAE,\n    title   = {Locating and Editing Factual Associations in GPT},\n    author  = {Kevin Meng and David Bau and Alex Andonian and Yonatan Belinkov},\n    booktitle = {Neural Information Processing Systems},\n    year    = {2022},\n    url     = {https://api.semanticscholar.org/CorpusID:255825985}\n}\n```\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flucidrains%2Fperfusion-pytorch","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flucidrains%2Fperfusion-pytorch","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flucidrains%2Fperfusion-pytorch/lists"}