import{s as ve,o as $e,n as we}from"../chunks/scheduler.78382b47.js";import{S as xe,i as Se,e as p,s as o,c as b,h as Ce,a as d,d as a,b as i,f as ae,g as v,j as _,k as ne,l as u,m as n,n as $,t as w,o as x,p as S}from"../chunks/index.6dd35eb6.js";import{C as Me,H as pe,E as ke}from"../chunks/MermaidChart.svelte_svelte_type_style_lang.fed9dfe4.js";import{D as be}from"../chunks/Docstring.32e826ec.js";import{C as Te}from"../chunks/CodeBlock.af1ec02e.js";import{E as He}from"../chunks/ExampleCodeBlock.7f184f2e.js";function Re(G){let r,M="Example:",h,m,f;return m=new Te({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=p("p"),r.textContent=M,h=o(),b(m.$$.fragment)},l(s){r=d(s,"P",{"data-svelte-h":!0}),_(r)!=="svelte-11lpom8"&&(r.textContent=M),h=i(s),v(m.$$.fragment,s)},m(s,c){n(s,r,c),n(s,h,c),$(m,s,c),f=!0},p:we,i(s){f||(w(m.$$.fragment,s),f=!0)},o(s){x(m.$$.fragment,s),f=!1},d(s){s&&(a(r),a(h)),S(m,s)}}}function Ae(G){let r,M,h,m,f,s,c,D,k,de='Sparse High Rank Adapters or <a href="https://huggingface.co/papers/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.',J,T,me="SHiRA currently has the following constraint:",W,H,fe="<li>Only <code>nn.Linear</code> layers are supported.</li>",q,R,ce="The abstract from the paper is:",I,A,he="<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>",V,L,Q,y,U,oe,F,ge='This is the configuration class to store the configuration of a <a href="/docs/peft/main/en/package_reference/shira#peft.ShiraModel">ShiraModel</a>.',X,P,Y,l,N,ie,j,ue="Creates a Sparse High Rank Adapter (SHiRA) Model from a pretrained model.",se,C,re,O,_e="<strong>Attributes</strong>:",le,B,ye='<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>',K,E,ee,z,te;return f=new Me({props:{containerStyle:"float: right; margin-left: 10px; display: inline-flex; position: relative; z-index: 10;"}}),c=new pe({props:{title:"Sparse High Rank Adapters",local:"sparse-high-rank-adapters",headingTag:"h1"}}),L=new pe({props:{title:"ShiraConfig",local:"peft.ShiraConfig",headingTag:"h2"}}),U=new be({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"}}),P=new pe({props:{title:"ShiraModel",local:"peft.ShiraModel",headingTag:"h2"}}),N=new be({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>
`}}),C=new He({props:{anchor:"peft.ShiraModel.example",$$slots:{default:[Re]},$$scope:{ctx:G}}}),E=new ke({props:{source:"https://github.com/huggingface/peft/blob/main/docs/source/package_reference/shira.md"}}),{c(){r=p("meta"),M=o(),h=p("p"),m=o(),b(f.$$.fragment),s=o(),b(c.$$.fragment),D=o(),k=p("p"),k.innerHTML=de,J=o(),T=p("p"),T.textContent=me,W=o(),H=p("ul"),H.innerHTML=fe,q=o(),R=p("p"),R.textContent=ce,I=o(),A=p("blockquote"),A.innerHTML=he,V=o(),b(L.$$.fragment),Q=o(),y=p("div"),b(U.$$.fragment),oe=o(),F=p("p"),F.innerHTML=ge,X=o(),b(P.$$.fragment),Y=o(),l=p("div"),b(N.$$.fragment),ie=o(),j=p("p"),j.textContent=ue,se=o(),b(C.$$.fragment),re=o(),O=p("p"),O.innerHTML=_e,le=o(),B=p("ul"),B.innerHTML=ye,K=o(),b(E.$$.fragment),ee=o(),z=p("p"),this.h()},l(e){const t=Ce("svelte-u9bgzb",document.head);r=d(t,"META",{name:!0,content:!0}),t.forEach(a),M=i(e),h=d(e,"P",{}),ae(h).forEach(a),m=i(e),v(f.$$.fragment,e),s=i(e),v(c.$$.fragment,e),D=i(e),k=d(e,"P",{"data-svelte-h":!0}),_(k)!=="svelte-e1ikb2"&&(k.innerHTML=de),J=i(e),T=d(e,"P",{"data-svelte-h":!0}),_(T)!=="svelte-we0nyy"&&(T.textContent=me),W=i(e),H=d(e,"UL",{"data-svelte-h":!0}),_(H)!=="svelte-18w7elh"&&(H.innerHTML=fe),q=i(e),R=d(e,"P",{"data-svelte-h":!0}),_(R)!=="svelte-1cwsb16"&&(R.textContent=ce),I=i(e),A=d(e,"BLOCKQUOTE",{"data-svelte-h":!0}),_(A)!=="svelte-1pi6na3"&&(A.innerHTML=he),V=i(e),v(L.$$.fragment,e),Q=i(e),y=d(e,"DIV",{class:!0});var Z=ae(y);v(U.$$.fragment,Z),oe=i(Z),F=d(Z,"P",{"data-svelte-h":!0}),_(F)!=="svelte-1ntmu88"&&(F.innerHTML=ge),Z.forEach(a),X=i(e),v(P.$$.fragment,e),Y=i(e),l=d(e,"DIV",{class:!0});var g=ae(l);v(N.$$.fragment,g),ie=i(g),j=d(g,"P",{"data-svelte-h":!0}),_(j)!=="svelte-1rj5pnm"&&(j.textContent=ue),se=i(g),v(C.$$.fragment,g),re=i(g),O=d(g,"P",{"data-svelte-h":!0}),_(O)!=="svelte-1xx6nm4"&&(O.innerHTML=_e),le=i(g),B=d(g,"UL",{"data-svelte-h":!0}),_(B)!=="svelte-1pyhtwy"&&(B.innerHTML=ye),g.forEach(a),K=i(e),v(E.$$.fragment,e),ee=i(e),z=d(e,"P",{}),ae(z).forEach(a),this.h()},h(){ne(r,"name","hf:doc:metadata"),ne(r,"content",Le),ne(y,"class","docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8"),ne(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,M,t),n(e,h,t),n(e,m,t),$(f,e,t),n(e,s,t),$(c,e,t),n(e,D,t),n(e,k,t),n(e,J,t),n(e,T,t),n(e,W,t),n(e,H,t),n(e,q,t),n(e,R,t),n(e,I,t),n(e,A,t),n(e,V,t),$(L,e,t),n(e,Q,t),n(e,y,t),$(U,y,null),u(y,oe),u(y,F),n(e,X,t),$(P,e,t),n(e,Y,t),n(e,l,t),$(N,l,null),u(l,ie),u(l,j),u(l,se),$(C,l,null),u(l,re),u(l,O),u(l,le),u(l,B),n(e,K,t),$(E,e,t),n(e,ee,t),n(e,z,t),te=!0},p(e,[t]){const Z={};t&2&&(Z.$$scope={dirty:t,ctx:e}),C.$set(Z)},i(e){te||(w(f.$$.fragment,e),w(c.$$.fragment,e),w(L.$$.fragment,e),w(U.$$.fragment,e),w(P.$$.fragment,e),w(N.$$.fragment,e),w(C.$$.fragment,e),w(E.$$.fragment,e),te=!0)},o(e){x(f.$$.fragment,e),x(c.$$.fragment,e),x(L.$$.fragment,e),x(U.$$.fragment,e),x(P.$$.fragment,e),x(N.$$.fragment,e),x(C.$$.fragment,e),x(E.$$.fragment,e),te=!1},d(e){e&&(a(M),a(h),a(m),a(s),a(D),a(k),a(J),a(T),a(W),a(H),a(q),a(R),a(I),a(A),a(V),a(Q),a(y),a(X),a(Y),a(l),a(K),a(ee),a(z)),a(r),S(f,e),S(c,e),S(L,e),S(U),S(P,e),S(N),S(C),S(E,e)}}}const Le='{"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 Ue(G){return $e(()=>{new URLSearchParams(window.location.search).get("fw")}),[]}class Oe extends xe{constructor(r){super(),Se(this,r,Ue,Ae,ve,{})}}export{Oe as component};
