Buckets:

hf-doc-build/doc / diffusers /v0.43.0 /ko /optimization /tensor_parallelism.html
mishig's picture
download
raw
39.6 kB
<meta charset="utf-8" /><meta name="hf:doc:metadata" content="{&quot;title&quot;:&quot;Tensor 병렬성&quot;,&quot;local&quot;:&quot;tensor-parallelism&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Load a sharded model&quot;,&quot;local&quot;:&quot;load-a-sharded-model&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;로딩 성능&quot;,&quot;local&quot;:&quot;loading-performance&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;한계&quot;,&quot;local&quot;:&quot;limitations&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;모델에 텐서 병렬성 추가&quot;,&quot;local&quot;:&quot;add-tensor-parallelism-to-a-model&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Colwise와 rowwise&quot;,&quot;local&quot;:&quot;colwise-and-rowwise&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Fused projections&quot;,&quot;local&quot;:&quot;fused-projections&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;제외할 항목&quot;,&quot;local&quot;:&quot;what-to-leave-out&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;제약 조건 및 검증&quot;,&quot;local&quot;:&quot;constraints-and-verification&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3}],&quot;depth&quot;:2}],&quot;depth&quot;:1}"/>
<link href="/docs/diffusers/main/en/_app/immutable/entry/start.0S0_iEoG.js" rel="modulepreload">
<link href="/docs/diffusers/main/en/_app/immutable/chunks/I9eooN77.js" rel="modulepreload">
<link href="/docs/diffusers/main/en/_app/immutable/chunks/Bupkjr9f.js" rel="modulepreload">
<link href="/docs/diffusers/main/en/_app/immutable/entry/app.CPdOxCbw.js" rel="modulepreload">
<link href="/docs/diffusers/main/en/_app/immutable/chunks/CyvZ3FS5.js" rel="modulepreload">
<link href="/docs/diffusers/main/en/_app/immutable/chunks/l0QnnOED.js" rel="modulepreload">
<link href="/docs/diffusers/main/en/_app/immutable/chunks/DnVIJfC5.js" rel="modulepreload">
<link href="/docs/diffusers/main/en/_app/immutable/chunks/DsnmJJEf.js" rel="modulepreload">
<link href="/docs/diffusers/main/en/_app/immutable/nodes/0.DteTvmQZ.js" rel="modulepreload">
<link href="/docs/diffusers/main/en/_app/immutable/chunks/CoSrdQax.js" rel="modulepreload">
<link href="/docs/diffusers/main/en/_app/immutable/nodes/347.DnqzUbRP.js" rel="modulepreload">
<link href="/docs/diffusers/main/en/_app/immutable/chunks/DSPDl1gz.js" rel="modulepreload">
<!--17gkrup--><meta name="hf:doc:metadata" content="{&quot;title&quot;:&quot;Tensor parallelism&quot;,&quot;local&quot;:&quot;tensor-parallelism&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Load a sharded model&quot;,&quot;local&quot;:&quot;load-a-sharded-model&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Loading performance&quot;,&quot;local&quot;:&quot;loading-performance&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Limitations&quot;,&quot;local&quot;:&quot;limitations&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Add tensor parallelism to a model&quot;,&quot;local&quot;:&quot;add-tensor-parallelism-to-a-model&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Colwise and rowwise&quot;,&quot;local&quot;:&quot;colwise-and-rowwise&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Fused projections&quot;,&quot;local&quot;:&quot;fused-projections&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;What to leave out&quot;,&quot;local&quot;:&quot;what-to-leave-out&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Constraints and verification&quot;,&quot;local&quot;:&quot;constraints-and-verification&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3}],&quot;depth&quot;:2}],&quot;depth&quot;:1}"/><!---->
<link href="/docs/diffusers/main/en/_app/immutable/assets/0.tn0RQdqM.css" rel="modulepreload"> <!--[--><!--[0--><!--[--><!--[0--><!--[--><p></p> <div class="items-center shrink-0 min-w-[100px] max-sm:min-w-[50px] justify-end ml-auto flex" style="float: inline-end; margin-inline-start: 10px; display: inline-flex; position: relative; z-index: 10;"><div dir="ltr" class="inline-flex rounded-md max-sm:rounded-sm"><button class="inline-flex items-center gap-1 h-7 max-sm:h-7 px-2 max-sm:px-1.5 text-sm font-medium text-gray-800 border border-r-0 rounded-l-md max-sm:rounded-l-sm border-gray-200 bg-white hover:shadow-inner dark:border-gray-850 dark:bg-gray-950 dark:text-gray-200 dark:hover:bg-gray-800" aria-live="polite"><span class="inline-flex items-center justify-center rounded-md p-0.5 max-sm:p-0 hover:text-gray-800 dark:hover:text-gray-200"><svg class="sm:size-3.5 size-3" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----></span> <span dir="auto">Copy page</span></button> <button class="inline-flex items-center justify-center w-6 max-sm:w-5 h-7 max-sm:h-7 disabled:pointer-events-none text-sm text-gray-500 hover:text-gray-700 dark:hover:text-white rounded-r-md max-sm:rounded-r-sm border border-l transition border-gray-200 bg-white hover:shadow-inner dark:border-gray-850 dark:bg-gray-950 dark:text-gray-200 dark:hover:bg-gray-800" aria-haspopup="menu" aria-expanded="false" aria-label="Open copy menu"><svg class="transition-transform text-gray-400 overflow-visible sm:size-3.5 size-3 rotate-0" width="1em" height="1em" viewBox="0 0 12 7" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1 1L6 6L11 1" stroke="currentColor"></path></svg><!----></button></div> <!--[-1--><!--]--></div><!----> <!--[0--><h1 class="relative group"><a id="tensor-parallelism" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#tensor-parallelism"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Tensor 병렬성<!----></span></h1><!--]--><!----> <p><a href="https://huggingface.co/spaces/nanotron/ultrascale-playbook?section=tensor_parallelism" rel="nofollow">Tensor parallelism</a>은 모델의 가중치 행렬을 여러 디바이스에 걸쳐 분할합니다. 각 디바이스는 각 레이어의 열 방향(<code>"colwise"</code>) 또는 행 방향(<code>"rowwise"</code>) 슬라이스를 보유하며 부분 결과를 계산합니다. 레이어 경계에서의 <code>AllReduce</code> 또는 <code>AllGather</code> 연산은 부분 결과를 결합하여 전체 출력을 생성합니다. <a href="./context_parallelism">context parallelism</a>과 달리, 이는 디바이스당 <em>weight</em> 메모리를 줄여주므로 모델이 단일 디바이스에 맞지 않을 때 유용합니다. 다른 전략과의 비교를 위해 <a href="../training/distributed_inference">Distributed inference</a>를 참조하세요.</p> <!--[1--><h2 class="relative group"><a id="load-a-sharded-model" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#load-a-sharded-model"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Load a sharded model<!----></span></h2><!--]--><!----> <p>Pass a <a href="/docs/diffusers/v0.43.0/ko/api/parallel#diffusers.TensorParallelConfig">TensorParallelConfig</a> to the <code>parallel_config</code> argument of the model’s <a href="/docs/diffusers/v0.43.0/ko/api/models/overview#diffusers.ModelMixin.from_pretrained">from_pretrained()</a>. <code>tp_degree</code> is the number of devices to shard across and must divide the model’s number of attention heads. The model’s class must define a <code>_tp_plan</code>, which maps module names to a sharding style. To check whether a model supports tensor parallelism, look for this attribute on its class, such as <a href="/docs/diffusers/v0.43.0/ko/api/models/flux2_transformer#diffusers.Flux2Transformer2DModel">Flux2Transformer2DModel</a>.</p> <p>다른 모델에 플랜을 추가하려면 <a href="#add-tensor-parallelism-to-a-model">모델에 텐서 병렬성 추가</a>를 참조하세요.</p> <p>이 방식으로 로드하면 체크포인트가 읽히는 동안 샤드됩니다. 각 랭크는 각 가중치의 자기 자신의 슬라이스만 읽고 이를 해당 GPU에 직접 배치하므로, 어떤 랭크도 전체 크기의 가중치를 보유하지 않습니다. 랭크당 메모리는 <code>tp_degree</code>가 증가함에 따라 감소합니다.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> 복사됨</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">import</span> os
<span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> torch <span class="hljs-keyword">import</span> distributed <span class="hljs-keyword">as</span> dist
<span class="hljs-keyword">from</span> diffusers <span class="hljs-keyword">import</span> DiffusionPipeline, Flux2Transformer2DModel, TensorParallelConfig
<span class="hljs-keyword">def</span> <span class="hljs-title function_">main</span>():
dist.init_process_group(backend=<span class="hljs-string">&quot;nccl&quot;</span>)
rank, world_size = dist.get_rank(), dist.get_world_size()
<span class="hljs-comment"># torchrun sets LOCAL_RANK to this process&#x27;s GPU index on its node</span>
local_rank = <span class="hljs-built_in">int</span>(os.environ[<span class="hljs-string">&quot;LOCAL_RANK&quot;</span>])
device = torch.device(<span class="hljs-string">f&quot;cuda:<span class="hljs-subst">{local_rank}</span>&quot;</span>)
torch.cuda.set_device(device)
<span class="hljs-comment"># Each rank reads only its own shard of every planned weight, straight onto its own GPU.</span>
transformer = Flux2Transformer2DModel.from_pretrained(
<span class="hljs-string">&quot;black-forest-labs/FLUX.2-dev&quot;</span>,
subfolder=<span class="hljs-string">&quot;transformer&quot;</span>,
dtype=torch.bfloat16,
parallel_config=TensorParallelConfig(tp_degree=world_size),
)
pipeline = DiffusionPipeline.from_pretrained(
<span class="hljs-string">&quot;black-forest-labs/FLUX.2-dev&quot;</span>, transformer=transformer, dtype=torch.bfloat16
)
<span class="hljs-comment"># The transformer is already on its device; move the remaining components individually. Do not call</span>
<span class="hljs-comment"># `pipeline.to(device)` — that would move every rank&#x27;s shards onto the same device.</span>
pipeline.text_encoder.to(device)
pipeline.vae.to(device)
generator = torch.Generator().manual_seed(<span class="hljs-number">42</span>)
image = pipeline(prompt=<span class="hljs-string">&quot;a cat holding a sign that says hello&quot;</span>, generator=generator).images[<span class="hljs-number">0</span>]
<span class="hljs-keyword">if</span> rank == <span class="hljs-number">0</span>:
image.save(<span class="hljs-string">&quot;output.png&quot;</span>)
dist.destroy_process_group()
<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">&quot;__main__&quot;</span>:
main()<!----></pre></div><!----> <p>스크립트를 <code>tensor_parallel_flux2.py</code>로 저장하고 <code>torchrun</code>으로 실행하세요.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> 복사됨</div><!----></button><!----></div> <pre class="language-shell "><!---->torchrun --nproc-per-node 4 tensor_parallel_flux2.py<!----></pre></div><!----> <p>스크립트는 <code>tp_degree</code>를 <code>world_size</code>로 설정하므로, <code>--nproc-per-node 4</code>는 transformer를 4개의 GPU에 걸쳐 샤딩합니다.</p> <p>transformer만 샤딩됩니다. 각 랭크는 텍스트 인코더의 전체 사본을 보유하므로, 각 GPU는 텍스트 인코더와 transformer의 해당 랭크 몫을 위한 충분한 메모리가 필요합니다.</p> <!--[1--><h2 class="relative group"><a id="loading-performance" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#loading-performance"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->로딩 성능<!----></span></h2><!--]--><!----> <p><code>parallel_config</code>를 사용하여 로드하는 방식은 전체 모델을 로드한 후 <code>enable_parallelism()</code>을 호출하는 방식보다 빠르고, 랭크당 CPU 메모리 사용량이 적습니다. 아래 표는 4x A10G (23GB) 환경에서 <a href="https://huggingface.co/black-forest-labs/FLUX.2-dev" rel="nofollow">black-forest-labs/FLUX.2-dev</a> (transformer만, 32B 파라미터, bf16)에 대한 결과를 보여줍니다.</p> <table><thead><tr><th>tp_degree</th><th>method</th><th>로드 시간</th><th>peak CPU/rank</th></tr></thead><tbody><tr><td>4</td><td><code>from_pretrained(parallel_config=...)</code></td><td>12.5s</td><td>6.8GB</td></tr><tr><td>4</td><td><code>from_pretrained</code> + <code>enable_parallelism</code></td><td>30.4s</td><td>64.1GB</td></tr></tbody></table> <!--[1--><h2 class="relative group"><a id="limitations" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#limitations"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->한계<!----></span></h2><!--]--><!----> <p>Tensor parallelism은 일부 로딩 옵션 및 기능과 함께 작동하지 않으며, 샤드된 모델을 저장할 수 없습니다.</p> <ul><li><code>parallel_config</code>을 사용한 텐서 병렬 로딩은 <code>device_map</code>, <code>quantization_config</code>, <code>low_cpu_mem_usage=False</code>, <code>use_flashpack=True</code>, 또는 safetensors가 아닌 가중지와 함께 작동하지 않습니다. 각각의 경우 전체 체크포인트를 조용히 로드하는 대신 오류가 발생합니다.</li> <li>tensor parallelism을 양자화, 오프로딩 또는 LoRA 어댑터와 결합하는 경우에도 모델이 어떻게 샤딩되든 오류가 발생합니다.</li> <li>메모리에 이미 로드된 모델을 샤딩하려면 동일한 구성으로 <code>enable_parallelism()</code>을 호출합니다. 이 방법은 먼저 전체 모델을 로드한 후 샤딩을 수행하므로, 모든 랭크에 전체 체크포인트를 위한 메모리가 필요합니다. <code>parallel_config</code>를 사용하여 로드하면 이러한 비용을 피할 수 있습니다.</li> <li>텐서 병렬 모델의 저장은 <a href="/docs/diffusers/v0.43.0/ko/api/models/overview#diffusers.ModelMixin.save_pretrained">save_pretrained()</a>에서 오류를 발생시킵니다. 샤딩하기 전에 모델을 저장하세요.</li></ul> <!--[1--><h2 class="relative group"><a id="add-tensor-parallelism-to-a-model" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#add-tensor-parallelism-to-a-model"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->모델에 텐서 병렬성 추가<!----></span></h2><!--]--><!----> <p>이 섹션은 Diffusers 모델에 텐서 병렬성(tensor parallelism) 지원을 추가하려는 기여자를 위한 것입니다.</p> <p>Tensor parallelism은 <code>_tp_plan</code>이라는 클래스 속성을 정의한 모델에서만 작동합니다. 이 속성은 모듈 이름을 샤딩 스타일에 매핑합니다. 이 속성을 작성하는 것은 대부분 <em>확장</em>하는 투영과 <em>축소</em>하는 투영을 짝짓는 것을 의미합니다.</p> <p>각 키에는 <code>*</code>가 최대 하나만 포함될 수 있으며, <code>*</code> 앞부분은 <a href="https://pytorch.org/docs/stable/generated/torch.nn.ModuleList.html" rel="nofollow"><code>nn.ModuleList</code></a>로 해석되어야 하므로 하나의 항목이 모든 블록을 커버합니다. <code>*</code>가 없는 키는 모델 자체에 적용됩니다. 경로는 모델 기준 상대 경로입니다.</p> <!--[2--><h3 class="relative group"><a id="colwise-and-rowwise" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#colwise-and-rowwise"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Colwise와 rowwise<!----></span></h3><!--]--><!----> <table><thead><tr><th>스타일</th><th>Shards</th><th>각 랭크</th><th>사용</th></tr></thead><tbody><tr><td><code>"colwise"</code></td><td>출력 특징(<code>weight</code> 차원 0)</td><td>출력의 슬라이스를 계산합니다</td><td><code>to_q</code>, <code>to_k</code>, <code>to_v</code>, FFN in-projection</td></tr><tr><td><code>"rowwise"</code></td><td>입력 특징(<code>weight</code> 차원 1)</td><td>부분 합을 계산합니다</td><td><code>to_out.0</code>, FFN 출력 투사</td></tr><tr><td><code>"rowwise_split_input"</code></td><td>입력 특징(<code>weight</code> 차원 1)</td><td>복제된 입력의 슬라이스에서 부분 합을 계산합니다</td><td>입력이 복제된 독립적인 투영, 예를 들어 타임스텝 임베딩을 읽는 AdaLN 변조 투영</td></tr></tbody></table> <p><code>"colwise"</code>와 <code>"rowwise"</code>는 항상 이 순서대로 짝을 이루어야 합니다. <code>"colwise"</code> 투영은 출력을 샤드 상태로 유지하며, 바로 다음 <code>"rowwise"</code> 투영은 해당 샤드를 직접 소비하고, 블록 경계에서 한 번의 <code>AllReduce</code>만 수행하면 결과를 재구성할 수 있습니다. 이 쌍을 다른 방식으로 샤딩하면 중간에 gather가 강제되어 통신량이 훨씬 커집니다.</p> <p>Attention에서 열 방향 Q, K, V 투영은 각 rank에 head의 부분 집합을 할당하므로 <code>tp_degree</code>은 head 수를 나누어야 합니다. Encoder-stream 복제 항목(<code>add_q_proj</code>, <code>to_add_out</code>, <code>ff_context</code>)은 image-stream의 대응 항목과 동일한 패턴을 따릅니다.</p> <!--[2--><h3 class="relative group"><a id="fused-projections" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#fused-projections"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Fused projections<!----></span></h3><!--]--><!----> <p><code>Linear</code> 하나가 샤딩 대상 차원을 따라 여러 논리 텐서를 패킹하는 경우, 단순한 <code>"colwise"</code>/<code>"rowwise"</code> 슬라이싱은 연결된 부분을 가로질러 잘라내어 조각들이 어긋나게 됩니다. 대신 각 패킹된 블록을 독립적으로 샤딩하는 <code>PackedColwiseParallel</code>/<code>PackedRowwiseParallel</code>을 사용하세요.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> 복사됨</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-comment"># in src/diffusers/models/transformers/your_model.py</span>
<span class="hljs-keyword">from</span> ...hooks.tensor_parallel <span class="hljs-keyword">import</span> PackedColwiseParallel, PackedRowwiseParallel<!----></pre></div><!----> <p><code>blocks</code>는 packed 차원을 나누는 합을 가지는 비율 정수 목록입니다. 예를 들어, 동일한 절반으로 구성된 SwiGLU 게이트 및 업 프로젝션에는 <code>[1, 1]</code>을, <code>mlp_ratio=3</code>인 융합된 Q, K, V, 게이트 및 업 프로젝션에는 <code>[1, 1, 1, 3, 3]</code>을 사용합니다.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> 복사됨</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-string">&quot;transformer_blocks.*.ff.linear_in&quot;</span>: PackedColwiseParallel([<span class="hljs-number">1</span>, <span class="hljs-number">1</span>]),<!----></pre></div><!----> <p><code>blocks</code>가 config에서만 알려진 경우, <code>blocks</code>를 생략하고 대신 <code>__init__</code> 중에 <code>Linear</code>에 절대 크기를 <code>_tp_packed_col_blocks</code> 또는 <code>_tp_packed_row_blocks</code>로 저장합니다.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> 복사됨</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-comment"># in the attention module&#x27;s __init__</span>
<span class="hljs-variable language_">self</span>.to_out._tp_packed_row_blocks = [<span class="hljs-variable language_">self</span>.inner_dim, <span class="hljs-variable language_">self</span>.mlp_hidden_dim]<!----></pre></div><!----> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> 복사됨</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-comment"># in the model&#x27;s _tp_plan</span>
<span class="hljs-string">&quot;single_transformer_blocks.*.attn.to_out&quot;</span>: PackedRowwiseParallel(),<!----></pre></div><!----> <p><a href="https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/transformers/transformer_flux2.py" rel="nofollow"><code>transformer_flux2.py</code></a>의 계획은 두 가지 형태를 모두 사용합니다. double-stream SwiGLU 페어는 <code>blocks</code>를 직접 전달합니다. fused single-stream QKV 및 MLP 투영은 <code>mlp_ratio</code>와 <code>mlp_mult_factor</code>에 의존하기 때문에, 그 크기를 <code>Flux2ParallelSelfAttention.__init__</code>의 <code>Linear</code>에 저장합니다.</p> <!--[2--><h3 class="relative group"><a id="what-to-leave-out" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#what-to-leave-out"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->제외할 항목<!----></span></h3><!--]--><!----> <p>플랜에 포함되지 않은 모듈은 모든 랭크에 복제됩니다. 정규화 레이어, 패치 및 텍스트 임베딩, 그리고 최종 <code>norm_out</code>과 <code>proj_out</code>은 제외하세요. 크기가 작아 샤딩해도 메모리 절감 효과가 크지 않고 통신 오버헤드만 증가합니다. AdaLN 모듈레이션(<code>img_mod</code>과 <code>txt_mod</code>)도 보통 크기가 작아 제외해도 무방합니다. MiniMax-H3의 <code>adaln_proj.linear</code>처럼 크기가 큰 경우 <code>"rowwise_split_input"</code>로 샤딩하세요.</p> <!--[2--><h3 class="relative group"><a id="constraints-and-verification" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#constraints-and-verification"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->제약 조건 및 검증<!----></span></h3><!--]--><!----> <ul><li><code>tp_degree</code>는 <code>config.num_attention_heads</code>를 나누어야 합니다.</li> <li>각 패킹된 블록은 그 합이 아니라 <em>개별로</em> <code>tp_degree</code>로 나누어떨어져야 합니다.</li></ul> <p><a href="/docs/diffusers/v0.43.0/ko/api/models/overview#diffusers.ModelMixin.from_pretrained">from_pretrained()</a>와 <code>enable_parallelism()</code>은 가중치를 로드하거나 샤딩하기 전에 둘 다 확인합니다.</p> <p>눈으로 확인하는 대신 수치적으로 새로운 플랜을 검증하세요: 단일 디바이스에서 고정된 시드로 생성한 후, 텐서 병렬 환경에서 다시 생성하고 출력을 비교합니다. <code>"colwise"</code>/<code>"rowwise"</code>가 잘못 배치되어도 일반적으로 실행은 되며 그럴듯하지만 잘못된 이미지를 생성합니다.</p> <blockquote class="tip"><p>비슷한 아키텍처의 기존 플랜에서 시작하세요.</p> <ul><li><a href="https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/transformers/transformer_qwenimage.py" rel="nofollow"><code>transformer_qwenimage.py</code></a>에는 융합된 투영이 없으므로 모든 항목은 단순한 <code>"colwise"</code> 또는 <code>"rowwise"</code>입니다.</li> <li><a href="https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/transformers/transformer_flux.py" rel="nofollow"><code>transformer_flux.py</code></a>는 하나의 packed row-wise projection을 추가합니다.</li> <li><a href="https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/transformers/transformer_flux2.py" rel="nofollow"><code>transformer_flux2.py</code></a>는 두 가지 패킹 스타일을 모두 사용합니다.</li></ul></blockquote> <a class="!text-gray-400 !no-underline text-sm flex items-center not-prose mt-4" href="https://github.com/huggingface/diffusers/blob/main/docs/source/en/optimization/tensor_parallelism.md" target="_blank"><svg class="mr-1" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M31,16l-7,7l-1.41-1.41L28.17,16l-5.58-5.59L24,9l7,7z"></path><path d="M1,16l7-7l1.41,1.41L3.83,16l5.58,5.59L8,23l-7-7z"></path><path d="M12.419,25.484L17.639,6.552l1.932,0.518L14.351,26.002z"></path></svg><!----> <span><span class="underline">Update</span> on GitHub</span></a><!----> <p></p><!--]--><!----><!--]--><!--]--><!--]--> <!--[-1--><!--]--><!--]-->
<script>
{
__sveltekit_1qsdbwf = {
base: "/docs/diffusers/main/en",
assets: "/docs/diffusers/main/en"
};
const element = document.currentScript.parentElement;
Promise.all([
import("/docs/diffusers/main/en/_app/immutable/entry/start.0S0_iEoG.js"),
import("/docs/diffusers/main/en/_app/immutable/entry/app.CPdOxCbw.js")
]).then(([kit, app]) => {
kit.start(app, element, {
node_ids: [0, 347],
data: [null,null],
form: null,
error: null
});
});
}
</script>

Xet Storage Details

Size:
39.6 kB
·
Xet hash:
46bfaef2caaca39c8005f40370d7f52c773446b53a1753ca3f69afb741cb58c5

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.