import{s as be,o as ye,n as ve}from"../chunks/scheduler.4cd3e004.js";import{S as we,i as $e,e as d,s,c as v,h as Se,a as p,d as a,b as i,f as ee,g as w,j as _,k as te,l as u,m as n,n as $,t as S,o as x,p as C}from"../chunks/index.b664cb2d.js";import{D as _e}from"../chunks/Docstring.9ceb4334.js";import{C as xe}from"../chunks/CodeBlock.8601e34e.js";import{E as Ce}from"../chunks/ExampleCodeBlock.4f57b575.js";import{H as re,E as ke}from"../chunks/MermaidChart.svelte_svelte_type_style_lang.179b63f8.js";function Me(G){let r,k="Example:",h,m,f;return m=new xe({props:{code:"ZnJvbSUyMHRyYW5zZm9ybWVycyUyMGltcG9ydCUyMEF1dG9Nb2RlbEZvckNhdXNhbExNJTBBZnJvbSUyMHBlZnQlMjBpbXBvcnQlMjBTaGlyYUNvbmZpZyUyQyUyMGdldF9wZWZ0X21vZGVsJTBBJTBBYmFzZV9tb2RlbCUyMCUzRCUyMEF1dG9Nb2RlbEZvckNhdXNhbExNLmZyb21fcHJldHJhaW5lZCglMjJmYWNlYm9vayUyRm9wdC0xMjVtJTIyKSUwQWNvbmZpZyUyMCUzRCUyMFNoaXJhQ29uZmlnKHIlM0QzMiklMEFtb2RlbCUyMCUzRCUyMGdldF9wZWZ0X21vZGVsKGJhc2VfbW9kZWwlMkMlMjBjb25maWcp",highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForCausalLM
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> peft <span class="hljs-keyword">import</span> ShiraConfig, get_peft_model

<span class="hljs-meta">&gt;&gt;&gt; </span>base_model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">&quot;facebook/opt-125m&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>config = ShiraConfig(r=<span class="hljs-number">32</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>model = get_peft_model(base_model, config)`,wrap:!1}}),{c(){r=d("p"),r.textContent=k,h=s(),v(m.$$.fragment)},l(o){r=p(o,"P",{"data-svelte-h":!0}),_(r)!=="svelte-11lpom8"&&(r.textContent=k),h=i(o),w(m.$$.fragment,o)},m(o,c){n(o,r,c),n(o,h,c),$(m,o,c),f=!0},p:ve,i(o){f||(S(m.$$.fragment,o),f=!0)},o(o){x(m.$$.fragment,o),f=!1},d(o){o&&(a(r),a(h)),C(m,o)}}}function Te(G){let r,k,h,m,f,o,c,le='Sparse High Rank Adapters or <a href="https://arxiv.org/abs/2406.13175" rel="nofollow">SHiRA</a> is an alternate type of adapter and has been found to have significant advantages over the low rank adapters. Specifically, SHiRA achieves better accuracy than LoRA for a variety of vision and language tasks. It also offers simpler and higher quality multi-adapter fusion by significantly reducing concept loss, a common problem faced by low rank adapters. SHiRA directly finetunes a small number of the base model’s parameters to finetune the model on any adaptation task.',z,M,de="SHiRA currently has the following constraint:",D,T,pe="<li>Only <code>nn.Linear</code> layers are supported.</li>",J,H,me="The abstract from the paper is:",W,R,fe="<p>Low Rank Adaptation (LoRA) has gained massive attention in the recent generative AI research. One of the main advantages of LoRA is its ability to be fused with pretrained models, adding no overhead during inference. However, from a mobile deployment standpoint, we can either avoid inference overhead in the fused mode but lose the ability to switch adapters rapidly, or suffer significant (up to 30% higher) inference latency while enabling rapid switching in the unfused mode. LoRA also exhibits concept-loss when multiple adapters are used concurrently. In this paper, we propose Sparse High Rank Adapters (SHiRA), a new paradigm which incurs no inference overhead, enables rapid switching, and significantly reduces concept-loss. Specifically, SHiRA can be trained by directly tuning only 1-2% of the base model weights while leaving others unchanged. This results in a highly sparse adapter which can be switched directly in the fused mode. We further provide theoretical and empirical insights on how high sparsity in SHiRA can aid multi-adapter fusion by reducing concept loss. Our extensive experiments on LVMs and LLMs demonstrate that finetuning only a small fraction of the parameters in the base model significantly outperforms LoRA while enabling both rapid switching and multi-adapter fusion. Finally, we provide a latency- and memory-efficient SHiRA implementation based on Parameter-Efficient Finetuning (PEFT) Library which trains at nearly the same speed as LoRA while consuming up to 16% lower peak GPU memory, thus making SHiRA easy to adopt for practical use cases. To demonstrate rapid switching benefits during inference, we show that loading SHiRA on a base model can be 5x-16x faster than LoRA fusion on a CPU.</p>",q,A,I,b,L,ae,Z,ce='This is the configuration class to store the configuration of a <a href="/docs/peft/main/en/package_reference/shira#peft.ShiraModel">ShiraModel</a>.',V,U,Q,l,P,ne,F,he="Creates a Sparse High Rank Adapter (SHiRA) Model from a pretrained model.",oe,y,se,j,ge="<strong>Attributes</strong>:",ie,O,ue='<li><strong>model</strong> (<a href="https://huggingface.co/docs/transformers/main/en/main_classes/model#transformers.PreTrainedModel" rel="nofollow">PreTrainedModel</a>) — The model to be adapted.</li> <li><strong>peft_config</strong> (<a href="/docs/peft/main/en/package_reference/shira#peft.ShiraConfig">ShiraConfig</a>): The configuration of the SHiRA model.</li>',X,N,Y,B,K;return f=new re({props:{title:"Sparse High Rank Adapters",local:"sparse-high-rank-adapters",headingTag:"h1"}}),A=new re({props:{title:"ShiraConfig",local:"peft.ShiraConfig",headingTag:"h2"}}),L=new _e({props:{name:"class peft.ShiraConfig",anchor:"peft.ShiraConfig",parameters:[{name:"task_type",val:": Optional[Union[str, TaskType]] = None"},{name:"peft_type",val:": Optional[Union[str, PeftType]] = None"},{name:"auto_mapping",val:": Optional[dict] = None"},{name:"peft_version",val:": Optional[str] = None"},{name:"base_model_name_or_path",val:": Optional[str] = None"},{name:"revision",val:": Optional[str] = None"},{name:"inference_mode",val:": bool = False"},{name:"r",val:": int = 32"},{name:"mask_type",val:": Literal['random'] = 'random'"},{name:"random_seed",val:": Optional[int] = None"},{name:"target_modules",val:": Optional[Union[list[str], str]] = None"},{name:"fan_in_fan_out",val:": bool = False"},{name:"init_weights",val:": bool = True"},{name:"modules_to_save",val:": Optional[list[str]] = None"}],parametersDescription:[{anchor:"peft.ShiraConfig.r",description:`<strong>r</strong> (<code>int</code>, <em>optional</em>, defaults to <code>32</code>) &#x2014;
For a given target module, the number of SHiRA parameters is computed as r(m+n), where the original tensor
dimensions are m x n. This means the number of SHiRA parameters is the same as that for a LoRA adapter.
SHiRA is a high rank adapter. Setting this r parameter does not restrict the rank to this value.`,name:"r"},{anchor:"peft.ShiraConfig.mask_type",description:`<strong>mask_type</strong> (<code>str</code>, defaults to <code>random</code>) &#x2014;
Type of mask function. Defaults to a random sparse mask. An optional user-defined mask_fn to compute the
mask value can also be supplied by instantiating <code>config = ShiraConfig(...)</code> and then setting
<code>config.mask_fn = &lt;your custom mask function&gt;</code>. For a pretrained weight with shape m x n, the custom mask
function must return only one mask (shape: m x n) which must be binary 0 or 1 with num_shira_parameters =
r(m + n) for linear layers. Device and dtype of mask must be same as base layer&#x2019;s weight&#x2019;s device and
dtype. Please see mask_functions.py for more details and to see the default random sparse mask
implementation.`,name:"mask_type"},{anchor:"peft.ShiraConfig.random_seed",description:`<strong>random_seed</strong> (<code>int</code>, <em>optional</em>, defaults to <code>None</code>) &#x2014;
random seed for the torch generator for random_mask.`,name:"random_seed"},{anchor:"peft.ShiraConfig.target_modules",description:`<strong>target_modules</strong> (<code>Union[List[str], str]</code>) &#x2014;
List of module names or regex expression of the module names to replace with SHiRA. For example, [&#x2018;q&#x2019;, &#x2018;v&#x2019;]
or &#x2018;.<em>decoder.</em>(SelfAttention|EncDecAttention).*(q|v)$&#x2018;. Only linear layers are supported.`,name:"target_modules"},{anchor:"peft.ShiraConfig.fan_in_fan_out",description:`<strong>fan_in_fan_out</strong> (<code>bool</code>) &#x2014;
Set this to True if the layer to replace stores weight like (fan_in, fan_out). For example, gpt-2 uses
<code>Conv1D</code> which stores weights like (fan_in, fan_out) and hence this should be set to <code>True</code>.`,name:"fan_in_fan_out"},{anchor:"peft.ShiraConfig.init_weights",description:`<strong>init_weights</strong> (<code>bool</code>, defaults to <code>True</code>) &#x2014;
Initialize SHiRA weight to have zero values. If set to False, SHiRA weights are initialized to randn values
instead of zeros and this is used only for testing.`,name:"init_weights"},{anchor:"peft.ShiraConfig.modules_to_save",description:`<strong>modules_to_save</strong> (<code>List[str]</code>) &#x2014;
List of modules apart from SHiRA layers to be set as trainable and saved in the final checkpoint.`,name:"modules_to_save"}],source:"https://github.com/huggingface/peft/blob/main/src/peft/tuners/shira/config.py#L28"}}),U=new re({props:{title:"ShiraModel",local:"peft.ShiraModel",headingTag:"h2"}}),P=new _e({props:{name:"class peft.ShiraModel",anchor:"peft.ShiraModel",parameters:[{name:"model",val:""},{name:"peft_config",val:": Union[PeftConfig, dict[str, PeftConfig]]"},{name:"adapter_name",val:": str"},{name:"low_cpu_mem_usage",val:": bool = False"},{name:"state_dict",val:": Optional[dict[str, torch.Tensor]] = None"}],parametersDescription:[{anchor:"peft.ShiraModel.model",description:'<strong>model</strong> (<a href="https://huggingface.co/docs/transformers/main/en/main_classes/model#transformers.PreTrainedModel" rel="nofollow">PreTrainedModel</a>) &#x2014; The model to be adapted.',name:"model"},{anchor:"peft.ShiraModel.config",description:'<strong>config</strong> (<a href="/docs/peft/main/en/package_reference/shira#peft.ShiraConfig">ShiraConfig</a>) &#x2014; The configuration of the SHiRA model.',name:"config"},{anchor:"peft.ShiraModel.adapter_name",description:"<strong>adapter_name</strong> (<code>str</code>) &#x2014; The name of the adapter, defaults to <code>&quot;default&quot;</code>.",name:"adapter_name"}],source:"https://github.com/huggingface/peft/blob/main/src/peft/tuners/shira/model.py#L29",returnDescription:`<script context="module">export const metadata = 'undefined';<\/script>


<p>The SHiRA model.</p>
`,returnType:`<script context="module">export const metadata = 'undefined';<\/script>


<p><code>torch.nn.Module</code></p>
`}}),y=new Ce({props:{anchor:"peft.ShiraModel.example",$$slots:{default:[Me]},$$scope:{ctx:G}}}),N=new ke({props:{source:"https://github.com/huggingface/peft/blob/main/docs/source/package_reference/shira.md"}}),{c(){r=d("meta"),k=s(),h=d("p"),m=s(),v(f.$$.fragment),o=s(),c=d("p"),c.innerHTML=le,z=s(),M=d("p"),M.textContent=de,D=s(),T=d("ul"),T.innerHTML=pe,J=s(),H=d("p"),H.textContent=me,W=s(),R=d("blockquote"),R.innerHTML=fe,q=s(),v(A.$$.fragment),I=s(),b=d("div"),v(L.$$.fragment),ae=s(),Z=d("p"),Z.innerHTML=ce,V=s(),v(U.$$.fragment),Q=s(),l=d("div"),v(P.$$.fragment),ne=s(),F=d("p"),F.textContent=he,oe=s(),v(y.$$.fragment),se=s(),j=d("p"),j.innerHTML=ge,ie=s(),O=d("ul"),O.innerHTML=ue,X=s(),v(N.$$.fragment),Y=s(),B=d("p"),this.h()},l(e){const t=Se("svelte-u9bgzb",document.head);r=p(t,"META",{name:!0,content:!0}),t.forEach(a),k=i(e),h=p(e,"P",{}),ee(h).forEach(a),m=i(e),w(f.$$.fragment,e),o=i(e),c=p(e,"P",{"data-svelte-h":!0}),_(c)!=="svelte-1d76ndb"&&(c.innerHTML=le),z=i(e),M=p(e,"P",{"data-svelte-h":!0}),_(M)!=="svelte-we0nyy"&&(M.textContent=de),D=i(e),T=p(e,"UL",{"data-svelte-h":!0}),_(T)!=="svelte-18w7elh"&&(T.innerHTML=pe),J=i(e),H=p(e,"P",{"data-svelte-h":!0}),_(H)!=="svelte-1cwsb16"&&(H.textContent=me),W=i(e),R=p(e,"BLOCKQUOTE",{"data-svelte-h":!0}),_(R)!=="svelte-1pi6na3"&&(R.innerHTML=fe),q=i(e),w(A.$$.fragment,e),I=i(e),b=p(e,"DIV",{class:!0});var E=ee(b);w(L.$$.fragment,E),ae=i(E),Z=p(E,"P",{"data-svelte-h":!0}),_(Z)!=="svelte-1ntmu88"&&(Z.innerHTML=ce),E.forEach(a),V=i(e),w(U.$$.fragment,e),Q=i(e),l=p(e,"DIV",{class:!0});var g=ee(l);w(P.$$.fragment,g),ne=i(g),F=p(g,"P",{"data-svelte-h":!0}),_(F)!=="svelte-1rj5pnm"&&(F.textContent=he),oe=i(g),w(y.$$.fragment,g),se=i(g),j=p(g,"P",{"data-svelte-h":!0}),_(j)!=="svelte-1xx6nm4"&&(j.innerHTML=ge),ie=i(g),O=p(g,"UL",{"data-svelte-h":!0}),_(O)!=="svelte-1pyhtwy"&&(O.innerHTML=ue),g.forEach(a),X=i(e),w(N.$$.fragment,e),Y=i(e),B=p(e,"P",{}),ee(B).forEach(a),this.h()},h(){te(r,"name","hf:doc:metadata"),te(r,"content",He),te(b,"class","docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8"),te(l,"class","docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8")},m(e,t){u(document.head,r),n(e,k,t),n(e,h,t),n(e,m,t),$(f,e,t),n(e,o,t),n(e,c,t),n(e,z,t),n(e,M,t),n(e,D,t),n(e,T,t),n(e,J,t),n(e,H,t),n(e,W,t),n(e,R,t),n(e,q,t),$(A,e,t),n(e,I,t),n(e,b,t),$(L,b,null),u(b,ae),u(b,Z),n(e,V,t),$(U,e,t),n(e,Q,t),n(e,l,t),$(P,l,null),u(l,ne),u(l,F),u(l,oe),$(y,l,null),u(l,se),u(l,j),u(l,ie),u(l,O),n(e,X,t),$(N,e,t),n(e,Y,t),n(e,B,t),K=!0},p(e,[t]){const E={};t&2&&(E.$$scope={dirty:t,ctx:e}),y.$set(E)},i(e){K||(S(f.$$.fragment,e),S(A.$$.fragment,e),S(L.$$.fragment,e),S(U.$$.fragment,e),S(P.$$.fragment,e),S(y.$$.fragment,e),S(N.$$.fragment,e),K=!0)},o(e){x(f.$$.fragment,e),x(A.$$.fragment,e),x(L.$$.fragment,e),x(U.$$.fragment,e),x(P.$$.fragment,e),x(y.$$.fragment,e),x(N.$$.fragment,e),K=!1},d(e){e&&(a(k),a(h),a(m),a(o),a(c),a(z),a(M),a(D),a(T),a(J),a(H),a(W),a(R),a(q),a(I),a(b),a(V),a(Q),a(l),a(X),a(Y),a(B)),a(r),C(f,e),C(A,e),C(L),C(U,e),C(P),C(y),C(N,e)}}}const He='{"title":"Sparse High Rank Adapters","local":"sparse-high-rank-adapters","sections":[{"title":"ShiraConfig","local":"peft.ShiraConfig","sections":[],"depth":2},{"title":"ShiraModel","local":"peft.ShiraModel","sections":[],"depth":2}],"depth":1}';function Re(G){return ye(()=>{new URLSearchParams(window.location.search).get("fw")}),[]}class Ze extends we{constructor(r){super(),$e(this,r,Re,Te,be,{})}}export{Ze as component};
