Buckets:

HuggingFaceDocBuilder's picture
download
raw
74.4 kB
<meta charset="utf-8" /><meta name="hf:doc:metadata" content="{&quot;title&quot;:&quot;Hub와 어떤 머신 러닝 프레임워크든 통합&quot;,&quot;local&quot;:&quot;integrate-any-ml-framework-with-the-hub&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;유연한 접근 방식: 도우미(helper)&quot;,&quot;local&quot;:&quot;a-flexible-approach-helpers&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;from_pretrained&quot;,&quot;local&quot;:&quot;frompretrained&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;push_to_hub&quot;,&quot;local&quot;:&quot;pushtohub&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;제한 사항&quot;,&quot;local&quot;:&quot;limitations&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3}],&quot;depth&quot;:2},{&quot;title&quot;:&quot;더욱 복잡한 접근법: 클래스 상속&quot;,&quot;local&quot;:&quot;a-more-complex-approach-class-inheritance&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;자세한 예시: PyTorch&quot;,&quot;local&quot;:&quot;a-concrete-example-pytorch&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;어떻게 사용하나요?&quot;,&quot;local&quot;:&quot;how-to-use-it&quot;,&quot;sections&quot;:[],&quot;depth&quot;:4},{&quot;title&quot;:&quot;구현&quot;,&quot;local&quot;:&quot;implementation&quot;,&quot;sections&quot;:[],&quot;depth&quot;:4}],&quot;depth&quot;:3},{&quot;title&quot;:&quot;고급 사용법&quot;,&quot;local&quot;:&quot;advanced-usage&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;모델 카드&quot;,&quot;local&quot;:&quot;model-card&quot;,&quot;sections&quot;:[],&quot;depth&quot;:4},{&quot;title&quot;:&quot;구성&quot;,&quot;local&quot;:&quot;config&quot;,&quot;sections&quot;:[],&quot;depth&quot;:4}],&quot;depth&quot;:3}],&quot;depth&quot;:2},{&quot;title&quot;:&quot;빠른 비교&quot;,&quot;local&quot;:&quot;quick-comparison&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2}],&quot;depth&quot;:1}">
<link href="/docs/huggingface_hub/pr_4113/ko/_app/immutable/assets/0.e3b0c442.css" rel="modulepreload">
<link rel="modulepreload" href="/docs/huggingface_hub/pr_4113/ko/_app/immutable/entry/start.e4d70577.js">
<link rel="modulepreload" href="/docs/huggingface_hub/pr_4113/ko/_app/immutable/chunks/scheduler.0cf4ef2e.js">
<link rel="modulepreload" href="/docs/huggingface_hub/pr_4113/ko/_app/immutable/chunks/singletons.7ad9a7dd.js">
<link rel="modulepreload" href="/docs/huggingface_hub/pr_4113/ko/_app/immutable/chunks/paths.5be5312b.js">
<link rel="modulepreload" href="/docs/huggingface_hub/pr_4113/ko/_app/immutable/entry/app.3b0f3b68.js">
<link rel="modulepreload" href="/docs/huggingface_hub/pr_4113/ko/_app/immutable/chunks/preload-helper.2e746cb0.js">
<link rel="modulepreload" href="/docs/huggingface_hub/pr_4113/ko/_app/immutable/chunks/index.abc433bf.js">
<link rel="modulepreload" href="/docs/huggingface_hub/pr_4113/ko/_app/immutable/nodes/0.c6150a55.js">
<link rel="modulepreload" href="/docs/huggingface_hub/pr_4113/ko/_app/immutable/chunks/each.e59479a4.js">
<link rel="modulepreload" href="/docs/huggingface_hub/pr_4113/ko/_app/immutable/nodes/9.63f8be1a.js">
<link rel="modulepreload" href="/docs/huggingface_hub/pr_4113/ko/_app/immutable/chunks/MermaidChart.svelte_svelte_type_style_lang.b2531632.js">
<link rel="modulepreload" href="/docs/huggingface_hub/pr_4113/ko/_app/immutable/chunks/CodeBlock.db16c7c8.js"><!-- HEAD_svelte-u9bgzb_START --><meta name="hf:doc:metadata" content="{&quot;title&quot;:&quot;Hub와 어떤 머신 러닝 프레임워크든 통합&quot;,&quot;local&quot;:&quot;integrate-any-ml-framework-with-the-hub&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;유연한 접근 방식: 도우미(helper)&quot;,&quot;local&quot;:&quot;a-flexible-approach-helpers&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;from_pretrained&quot;,&quot;local&quot;:&quot;frompretrained&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;push_to_hub&quot;,&quot;local&quot;:&quot;pushtohub&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;제한 사항&quot;,&quot;local&quot;:&quot;limitations&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3}],&quot;depth&quot;:2},{&quot;title&quot;:&quot;더욱 복잡한 접근법: 클래스 상속&quot;,&quot;local&quot;:&quot;a-more-complex-approach-class-inheritance&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;자세한 예시: PyTorch&quot;,&quot;local&quot;:&quot;a-concrete-example-pytorch&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;어떻게 사용하나요?&quot;,&quot;local&quot;:&quot;how-to-use-it&quot;,&quot;sections&quot;:[],&quot;depth&quot;:4},{&quot;title&quot;:&quot;구현&quot;,&quot;local&quot;:&quot;implementation&quot;,&quot;sections&quot;:[],&quot;depth&quot;:4}],&quot;depth&quot;:3},{&quot;title&quot;:&quot;고급 사용법&quot;,&quot;local&quot;:&quot;advanced-usage&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;모델 카드&quot;,&quot;local&quot;:&quot;model-card&quot;,&quot;sections&quot;:[],&quot;depth&quot;:4},{&quot;title&quot;:&quot;구성&quot;,&quot;local&quot;:&quot;config&quot;,&quot;sections&quot;:[],&quot;depth&quot;:4}],&quot;depth&quot;:3}],&quot;depth&quot;:2},{&quot;title&quot;:&quot;빠른 비교&quot;,&quot;local&quot;:&quot;quick-comparison&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2}],&quot;depth&quot;:1}"><!-- HEAD_svelte-u9bgzb_END --> <p></p> <div class="items-center shrink-0 min-w-[100px] max-sm:min-w-[50px] justify-end ml-auto flex" style="float: right; margin-left: 10px; display: inline-flex; position: relative; z-index: 10;"><div 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>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> </div> <h1 class="relative group"><a id="integrate-any-ml-framework-with-the-hub" 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="#integrate-any-ml-framework-with-the-hub"><span><svg class="" 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>Hub와 어떤 머신 러닝 프레임워크든 통합</span></h1> <p data-svelte-h="svelte-kpdhh9">Hugging Face Hub는 커뮤니티와 모델을 공유하는 것을 쉽게 만들어줍니다. 이는 오픈소스 생태계의 <a href="https://huggingface.co/docs/hub/models-libraries" rel="nofollow">수십 가지 라이브러리</a>를 지원합니다. 저희는 항상 협업적인 머신 러닝을 발전시키기 위해 이 라이브러리를 확대하고자 노력하고 있습니다. <code>huggingface_hub</code> 라이브러리는 어떤 Python 스크립트든지 쉽게 파일을 업로드하고 가져올 수 있는 중요한 역할을 합니다.</p> <p data-svelte-h="svelte-dd17aw">라이브러리를 Hub와 통합하는 네 가지 주요 방법이 있습니다:</p> <ol data-svelte-h="svelte-63hzai"><li><strong>Hub에 업로드하기</strong>: 모델을 Hub에 업로드하는 메소드를 구현합니다. 이에는 모델 가중치뿐만 아니라 <a href="https://huggingface.co/docs/huggingface_hub/how-to-model-cards" rel="nofollow">모델 카드</a> 및 모델 실행에 필요한 다른 관련 정보나 데이터(예: 훈련 로그)가 포함됩니다. 이 메소드는 일반적으로 <code>push_to_hub()</code>라고 합니다.</li> <li><strong>Hub에서 다운로드하기</strong>: Hub에서 모델을 가져오는 메소드를 구현합니다. 이 메소드는 모델 구성/가중치를 다운로드하고 모델을 가져와야 합니다. 이 메소드는 일반적으로 <code>from_pretrained</code> 또는 <code>load_from_hub()</code>라고 합니다.</li> <li><strong>추론 API</strong>: 라이브러리에서 지원하는 모델에 대해 무료로 추론을 실행할 수 있도록 당사 서버를 사용합니다.</li> <li><strong>위젯</strong>: Hub의 모델 랜딩 페이지에 위젯을 표시합니다. 이를 통해 사용자들은 브라우저에서 빠르게 모델을 시도할 수 있습니다.</li></ol> <p data-svelte-h="svelte-1dzsptn">이 가이드에서는 앞의 두 가지 주제에 중점을 둘 것입니다. 우리는 라이브러리를 통합하는 데 사용할 수 있는 두 가지 주요 방법을 소개하고 각각의 장단점을 설명할 것입니다. 두 가지 중 어떤 것을 선택할지에 대한 도움이 되도록 끝 부분에 내용이 요약되어 있습니다. 이는 단지 가이드라는 것을 명심하고 상황에 맞게 적응시킬 수 있는 가이드라는 점을 유념하십시오.</p> <p data-svelte-h="svelte-x5a9qo">추론 및 위젯에 관심이 있는 경우 <a href="https://huggingface.co/docs/hub/models-adding-libraries#set-up-the-inference-api" rel="nofollow">이 가이드</a>를 참조할 수 있습니다. 양쪽 모두에서 라이브러리를 Hub와 통합하고 <a href="https://huggingface.co/docs/hub/models-libraries" rel="nofollow">문서</a>에 목록에 게시하고자 하는 경우에는 언제든지 연락하실 수 있습니다.</p> <h2 class="relative group"><a id="a-flexible-approach-helpers" 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="#a-flexible-approach-helpers"><span><svg class="" 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>유연한 접근 방식: 도우미(helper)</span></h2> <p data-svelte-h="svelte-c61khq">라이브러리를 Hub에 통합하는 첫 번째 접근 방법은 실제로 <code>push_to_hub</code><code>from_pretrained</code> 메소드를 직접 구현하는 것입니다. 이를 통해 업로드/다운로드할 파일 및 입력을 처리하는 방법에 대한 완전한 유연성을 제공받을 수 있습니다. 이를 위해 <a href="./upload">파일 업로드</a><a href="./download">파일 다운로드</a> 가이드를 참조하여 자세히 알아볼 수 있습니다. 예를 들어 FastAI 통합이 구현된 방법을 보면 됩니다 (<a href="/docs/huggingface_hub/pr_4113/ko/package_reference/mixins#huggingface_hub.push_to_hub_fastai">push_to_hub_fastai()</a><a href="/docs/huggingface_hub/pr_4113/ko/package_reference/mixins#huggingface_hub.from_pretrained_fastai">from_pretrained_fastai()</a>를 참조).</p> <p data-svelte-h="svelte-u6tezb">라이브러리마다 구현 방식은 다를 수 있지만, 워크플로우는 일반적으로 비슷합니다.</p> <h3 class="relative group"><a id="frompretrained" 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="#frompretrained"><span><svg class="" 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>from_pretrained</span></h3> <p data-svelte-h="svelte-s9khbo">일반적으로 <code>from_pretrained</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 class="" 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> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">def</span> <span class="hljs-title function_">from_pretrained</span>(<span class="hljs-params">model_id: <span class="hljs-built_in">str</span></span>) -&gt; MyModelClass:
<span class="hljs-comment"># Hub로부터 모델을 다운로드</span>
cached_model = hf_hub_download(
repo_id=repo_id,
filename=<span class="hljs-string">&quot;model.pkl&quot;</span>,
library_name=<span class="hljs-string">&quot;fastai&quot;</span>,
library_version=get_fastai_version(),
)
<span class="hljs-comment"># 모델 가져오기</span>
<span class="hljs-keyword">return</span> load_model(cached_model)<!-- HTML_TAG_END --></pre></div> <h3 class="relative group"><a id="pushtohub" 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="#pushtohub"><span><svg class="" 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>push_to_hub</span></h3> <p data-svelte-h="svelte-1ow5q1r"><code>push_to_hub</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 class="" 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> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">def</span> <span class="hljs-title function_">push_to_hub</span>(<span class="hljs-params">model: MyModelClass, repo_name: <span class="hljs-built_in">str</span></span>) -&gt; <span class="hljs-literal">None</span>:
api = HfApi()
<span class="hljs-comment"># 해당 리포지토리가 아직 없다면 리포지토리를 생성하고 관련된 리포지토리 ID를 가져옵니다.</span>
repo_id = api.create_repo(repo_name, exist_ok=<span class="hljs-literal">True</span>)
<span class="hljs-comment"># 모든 파일을 임시 디렉토리에 저장하고 이를 단일 커밋으로 푸시합니다.</span>
<span class="hljs-keyword">with</span> TemporaryDirectory() <span class="hljs-keyword">as</span> tmpdir:
tmpdir = Path(tmpdir)
<span class="hljs-comment"># 가중치 저장</span>
save_model(model, tmpdir / <span class="hljs-string">&quot;model.safetensors&quot;</span>)
<span class="hljs-comment"># model card 생성</span>
card = generate_model_card(model)
(tmpdir / <span class="hljs-string">&quot;README.md&quot;</span>).write_text(card)
<span class="hljs-comment"># 로그 저장</span>
<span class="hljs-comment"># 설정 저장</span>
<span class="hljs-comment"># 평가 지표를 저장</span>
<span class="hljs-comment"># ...</span>
<span class="hljs-comment"># Hub에 푸시</span>
<span class="hljs-keyword">return</span> api.upload_folder(repo_id=repo_id, folder_path=tmpdir)<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1kj8dwl">물론 이는 단순한 예시에 불과합니다. 더 복잡한 조작(원격 파일 삭제, 가중치를 실시간으로 업로드, 로컬로 가중치를 유지 등)에 관심이 있다면 <a href="./upload">파일 업로드</a> 가이드를 참조해 주세요.</p> <h3 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 class="" 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 data-svelte-h="svelte-1aczd25">이러한 방식은 유연성을 가지고 있지만, 유지보수 측면에서 일부 단점을 가지고 있습니다. Hugging Face 사용자들은 <code>huggingface_hub</code>와 함께 작업할 때 추가 기능에 익숙합니다. 예를 들어, Hub에서 파일을 로드할 때 다음과 같은 매개변수를 제공하는 것이 일반적입니다:</p> <ul data-svelte-h="svelte-16bwbtg"><li><code>token</code>: 개인 리포지토리에서 다운로드하기 위한 토큰</li> <li><code>revision</code>: 특정 브랜치에서 다운로드하기 위한 리비전</li> <li><code>cache_dir</code>: 특정 디렉터리에 파일을 캐시하기 위한 디렉터리</li> <li><code>force_download</code>/<code>local_files_only</code>: 캐시를 재사용할 것인지 여부를 결정하는 매개변수</li> <li><code>proxies</code>: HTTP 세션 구성</li></ul> <p data-svelte-h="svelte-1d69wwb">모델을 푸시할 때는 유사한 매개변수가 지원됩니다:</p> <ul data-svelte-h="svelte-1s12qdb"><li><code>commit_message</code>: 사용자 정의 커밋 메시지</li> <li><code>private</code>: 개인 리포지토리를 만들어야 할 경우</li> <li><code>create_pr</code>: <code>main</code>에 푸시하는 대신 PR을 만드는 경우</li> <li><code>branch</code>: <code>main</code> 브랜치 대신 브랜치에 푸시하는 경우</li> <li><code>allow_patterns/ignore_patterns</code>: 업로드할 파일을 필터링하는 매개변수</li> <li><code>token</code></li> <li></li></ul> <p data-svelte-h="svelte-uyr1qn">이러한 매개변수는 위에서 본 구현에 추가하여 <code>huggingface_hub</code> 메소드로 전달할 수 있습니다. 그러나 매개변수가 변경되거나 새로운 기능이 추가되는 경우에는 패키지를 업데이트해야 합니다. 이러한 매개변수를 지원하는 것은 유지 관리할 문서가 더 많아진다는 것을 의미합니다. 이러한 제한 사항을 완화할 수 있는 방법을 보려면 다음 섹션인 <strong>클래스 상속</strong>으로 이동해 보겠습니다.</p> <h2 class="relative group"><a id="a-more-complex-approach-class-inheritance" 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="#a-more-complex-approach-class-inheritance"><span><svg class="" 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 data-svelte-h="svelte-1qrmixw">위에서 보았듯이 Hub와 통합하기 위해 라이브러리에 포함해야 할 주요 메소드는 파일을 업로드 (<code>push_to_hub</code>) 와 파일 다운로드 (<code>from_pretrained</code>)입니다. 이러한 메소드를 직접 구현할 수 있지만, 이에는 몇 가지 주의할 점이 있습니다. 이를 해결하기 위해 <code>huggingface_hub</code>은 클래스 상속을 사용하는 도구를 제공합니다. 이 도구가 어떻게 작동하는지 살펴보겠습니다!</p> <p data-svelte-h="svelte-1kjplj4">많은 경우에 라이브러리는 이미 Python 클래스를 사용하여 모델을 구현합니다. 이 클래스에는 모델의 속성 및 로드, 실행, 훈련 및 평가하는 메소드가 포함되어 있습니다. 접근 방식은 믹스인을 사용하여 이 클래스를 확장하여 업로드 및 다운로드 기능을 포함하는 것입니다. <a href="https://stackoverflow.com/a/547714" rel="nofollow">믹스인(Mixin)</a>은 기존 클래스에 여러 상속을 통해 특정 기능을 확장하기 위해 설계된 클래스입니다. <code>huggingface_hub</code>은 자체 믹스인인 <a href="/docs/huggingface_hub/pr_4113/ko/package_reference/mixins#huggingface_hub.ModelHubMixin">ModelHubMixin</a>을 제공합니다. 여기서 핵심은 동작과 이를 사용자 정의하는 방법을 이해하는 것입니다.</p> <p data-svelte-h="svelte-bl943x"><a href="/docs/huggingface_hub/pr_4113/ko/package_reference/mixins#huggingface_hub.ModelHubMixin">ModelHubMixin</a> 클래스는 세 개의 <em>공개</em> 메소드(<code>push_to_hub</code>, <code>save_pretrained</code>, <code>from_pretrained</code>)를 구현합니다. 이 메소드들은 사용자가 라이브러리를 사용하여 모델을 로드/저장할 때 호출하는 메소드입니다. 또한 <a href="/docs/huggingface_hub/pr_4113/ko/package_reference/mixins#huggingface_hub.ModelHubMixin">ModelHubMixin</a>은 두 개의 <em>비공개</em> 메소드(<code>_save_pretrained</code><code>_from_pretrained</code>)를 정의합니다. 라이브러리를 통합하려면 이 메소드들을 구현해야 합니다. :</p> <ol data-svelte-h="svelte-1wnudc9"><li>모델 클래스를 <a href="/docs/huggingface_hub/pr_4113/ko/package_reference/mixins#huggingface_hub.ModelHubMixin">ModelHubMixin</a>에서 상속합니다.</li> <li>비공개 메소드를 구현합니다:
<ul><li><a href="/docs/huggingface_hub/pr_4113/ko/package_reference/mixins#huggingface_hub.ModelHubMixin._save_pretrained">_save_pretrained()</a>: 디렉터리 경로를 입력으로 받아 모델을 해당 디렉터리에 저장하는 메소드입니다. 이 메소드에는 모델 카드, 모델 가중치, 구성 파일, 훈련 로그 및 그림 등 해당 모델에 대한 모든 관련 정보를 저장하기 위한 로직을 작성해야 합니다. <a href="https://huggingface.co/docs/hub/model-cards" rel="nofollow">모델 카드</a>는 모델을 설명하는 데 특히 중요합니다. 더 자세한 내용은 <a href="./model-cards">구현 가이드</a>를 확인하세요.</li> <li><a href="/docs/huggingface_hub/pr_4113/ko/package_reference/mixins#huggingface_hub.ModelHubMixin._from_pretrained">_from_pretrained()</a>: <code>model_id</code>를 입력으로 받아 인스턴스화된 모델을 반환하는 <strong>클래스 메소드</strong>입니다. 이 메소드는 관련 파일을 다운로드하고 가져와야 합니다.</li></ul></li> <li>완료했습니다!</li></ol> <p data-svelte-h="svelte-10ysiu6"><a href="/docs/huggingface_hub/pr_4113/ko/package_reference/mixins#huggingface_hub.ModelHubMixin">ModelHubMixin</a>의 장점은 파일의 직렬화/로드에만 신경을 쓰면 되기 때문에 즉시 사용할 수 있다는 것입니다. 리포지토리 생성, 커밋, PR 또는 리비전과 같은 사항에 대해 걱정할 필요가 없습니다. <a href="/docs/huggingface_hub/pr_4113/ko/package_reference/mixins#huggingface_hub.ModelHubMixin">ModelHubMixin</a>은 또한 공개 메소드가 문서화되고 타입에 주석이 달려있는지를 확인하며, Hub 모델의 다운로드 수를 볼 수 있도록 합니다. 이 모든 것은 <a href="/docs/huggingface_hub/pr_4113/ko/package_reference/mixins#huggingface_hub.ModelHubMixin">ModelHubMixin</a>에 의해 처리되며 사용자에게 제공됩니다.</p> <h3 class="relative group"><a id="a-concrete-example-pytorch" 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="#a-concrete-example-pytorch"><span><svg class="" 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>자세한 예시: PyTorch</span></h3> <p data-svelte-h="svelte-la0gmh">위에서 언급한 내용의 좋은 예시는 Pytorch 프레임워크를 통합한 <a href="/docs/huggingface_hub/pr_4113/ko/package_reference/mixins#huggingface_hub.PyTorchModelHubMixin">PyTorchModelHubMixin</a>입니다. 바로 사용 가능할 수 있는 메소드입니다.</p> <h4 class="relative group"><a id="how-to-use-it" 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="#how-to-use-it"><span><svg class="" 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></h4> <p data-svelte-h="svelte-qw3191">다음은 Hub에서 PyTorch 모델을 로드/저장하는 방법입니다:</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 class="" 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> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> torch
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> torch.nn <span class="hljs-keyword">as</span> nn
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> huggingface_hub <span class="hljs-keyword">import</span> PyTorchModelHubMixin
<span class="hljs-comment"># PyTorch 모델을 여러분이 흔히 사용하는 방식과 완전히 동일하게 정의하세요.</span>
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">class</span> <span class="hljs-title class_">MyModel</span>(
<span class="hljs-meta">... </span> nn.Module,
<span class="hljs-meta">... </span> PyTorchModelHubMixin, <span class="hljs-comment"># 다중 상속</span>
<span class="hljs-meta">... </span> library_name=<span class="hljs-string">&quot;keras-nlp&quot;</span>,
<span class="hljs-meta">... </span> tags=[<span class="hljs-string">&quot;keras&quot;</span>],
<span class="hljs-meta">... </span> repo_url=<span class="hljs-string">&quot;https://github.com/keras-team/keras-nlp&quot;</span>,
<span class="hljs-meta">... </span> docs_url=<span class="hljs-string">&quot;https://keras.io/keras_nlp/&quot;</span>,
<span class="hljs-meta">... </span> <span class="hljs-comment"># ^ 모델 카드를 생성하는 데 선택적인 메타데이터입니다.</span>
<span class="hljs-meta">... </span> ):
<span class="hljs-meta">... </span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self, hidden_size: <span class="hljs-built_in">int</span> = <span class="hljs-number">512</span>, vocab_size: <span class="hljs-built_in">int</span> = <span class="hljs-number">30000</span>, output_size: <span class="hljs-built_in">int</span> = <span class="hljs-number">4</span></span>):
<span class="hljs-meta">... </span> <span class="hljs-built_in">super</span>().__init__()
<span class="hljs-meta">... </span> self.param = nn.Parameter(torch.rand(hidden_size, vocab_size))
<span class="hljs-meta">... </span> self.linear = nn.Linear(output_size, vocab_size)
<span class="hljs-meta">... </span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">forward</span>(<span class="hljs-params">self, x</span>):
<span class="hljs-meta">... </span> <span class="hljs-keyword">return</span> self.linear(x + self.param)
<span class="hljs-comment"># 1. 모델 생성</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>model = MyModel(hidden_size=<span class="hljs-number">128</span>)
<span class="hljs-comment"># 설정은 입력 및 기본값을 기반으로 자동으로 생성됩니다.</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>model.param.shape[<span class="hljs-number">0</span>]
<span class="hljs-number">128</span>
<span class="hljs-comment"># 2. (선택사항) 모델을 로컬 디렉터리에 저장합니다.</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>model.save_pretrained(<span class="hljs-string">&quot;path/to/my-awesome-model&quot;</span>)
<span class="hljs-comment"># 3. 모델 가중치를 Hub에 푸시합니다.</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>model.push_to_hub(<span class="hljs-string">&quot;my-awesome-model&quot;</span>)
<span class="hljs-comment"># 4. Hub로부터 모델을 초기화합니다. =&gt; 이때 설정은 보존됩니다.</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>model = MyModel.from_pretrained(<span class="hljs-string">&quot;username/my-awesome-model&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>model.param.shape[<span class="hljs-number">0</span>]
<span class="hljs-number">128</span>
<span class="hljs-comment"># 모델 카드가 올바르게 작성되었습니다.</span>
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> huggingface_hub <span class="hljs-keyword">import</span> ModelCard
<span class="hljs-meta">&gt;&gt;&gt; </span>card = ModelCard.load(<span class="hljs-string">&quot;username/my-awesome-model&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>card.data.tags
[<span class="hljs-string">&quot;keras&quot;</span>, <span class="hljs-string">&quot;pytorch_model_hub_mixin&quot;</span>, <span class="hljs-string">&quot;model_hub_mixin&quot;</span>]
<span class="hljs-meta">&gt;&gt;&gt; </span>card.data.library_name
<span class="hljs-string">&quot;keras-nlp&quot;</span><!-- HTML_TAG_END --></pre></div> <h4 class="relative group"><a id="implementation" 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="#implementation"><span><svg class="" 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></h4> <p data-svelte-h="svelte-1mj21jf">실제 구현은 매우 간단합니다. 전체 구현은 <a href="https://github.com/huggingface/huggingface_hub/blob/main/src/huggingface_hub/hub_mixin.py" rel="nofollow">여기</a>에서 찾을 수 있습니다.</p> <ol data-svelte-h="svelte-1bzaux3"><li>클래스를 <code>ModelHubMixin</code>으로부터 상속하세요:</li></ol> <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 class="" 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> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> huggingface_hub <span class="hljs-keyword">import</span> ModelHubMixin
<span class="hljs-keyword">class</span> <span class="hljs-title class_">PyTorchModelHubMixin</span>(<span class="hljs-title class_ inherited__">ModelHubMixin</span>):
(...)<!-- HTML_TAG_END --></pre></div> <ol start="2" data-svelte-h="svelte-1awrrl0"><li><code>_save_pretrained</code> 메소드를 구현하세요:</li></ol> <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 class="" 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> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> huggingface_hub <span class="hljs-keyword">import</span> ModelHubMixin
<span class="hljs-keyword">class</span> <span class="hljs-title class_">PyTorchModelHubMixin</span>(<span class="hljs-title class_ inherited__">ModelHubMixin</span>):
(...)
<span class="hljs-keyword">def</span> <span class="hljs-title function_">_save_pretrained</span>(<span class="hljs-params">self, save_directory: Path</span>) -&gt; <span class="hljs-literal">None</span>:
<span class="hljs-string">&quot;&quot;&quot;PyTorch 모델의 가중치를 로컬 디렉터리에 저장합니다.&quot;&quot;&quot;</span>
save_model_as_safetensor(self.module, <span class="hljs-built_in">str</span>(save_directory / SAFETENSORS_SINGLE_FILE))
<!-- HTML_TAG_END --></pre></div> <ol start="3" data-svelte-h="svelte-do6xpe"><li><code>_from_pretrained</code> 메소드를 구현하세요:</li></ol> <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 class="" 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> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">class</span> <span class="hljs-title class_">PyTorchModelHubMixin</span>(<span class="hljs-title class_ inherited__">ModelHubMixin</span>):
(...)
<span class="hljs-meta"> @classmethod </span><span class="hljs-comment"># 반드시 클래스 메소드여야 합니다!</span>
<span class="hljs-keyword">def</span> <span class="hljs-title function_">_from_pretrained</span>(<span class="hljs-params">
cls,
*,
model_id: <span class="hljs-built_in">str</span>,
revision: <span class="hljs-built_in">str</span>,
cache_dir: <span class="hljs-built_in">str</span>,
force_download: <span class="hljs-built_in">bool</span>,
proxies: <span class="hljs-type">Optional</span>[<span class="hljs-built_in">dict</span>],
local_files_only: <span class="hljs-built_in">bool</span>,
token: <span class="hljs-type">Union</span>[<span class="hljs-built_in">str</span>, <span class="hljs-built_in">bool</span>, <span class="hljs-literal">None</span>],
map_location: <span class="hljs-built_in">str</span> = <span class="hljs-string">&quot;cpu&quot;</span>, <span class="hljs-comment"># 추가 인자</span>
strict: <span class="hljs-built_in">bool</span> = <span class="hljs-literal">False</span>, <span class="hljs-comment"># 추가 인자</span>
**model_kwargs,
</span>):
<span class="hljs-string">&quot;&quot;&quot;PyTorch의 사전 학습된 가중치와 모델을 반환합니다.&quot;&quot;&quot;</span>
model = cls(**model_kwargs)
<span class="hljs-keyword">if</span> os.path.isdir(model_id):
<span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;Loading weights from local directory&quot;</span>)
model_file = os.path.join(model_id, SAFETENSORS_SINGLE_FILE)
<span class="hljs-keyword">return</span> cls._load_as_safetensor(model, model_file, map_location, strict)
model_file = hf_hub_download(
repo_id=model_id,
filename=SAFETENSORS_SINGLE_FILE,
revision=revision,
cache_dir=cache_dir,
force_download=force_download,
token=token,
local_files_only=local_files_only,
)
<span class="hljs-keyword">return</span> cls._load_as_safetensor(model, model_file, map_location, strict)<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-jxjuew">이게 전부입니다! 이제 라이브러리를 통해 Hub로부터 파일을 업로드하고 다운로드할 수 있습니다.</p> <h3 class="relative group"><a id="advanced-usage" 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="#advanced-usage"><span><svg class="" 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 data-svelte-h="svelte-9wad1c">위의 섹션에서는 <a href="/docs/huggingface_hub/pr_4113/ko/package_reference/mixins#huggingface_hub.ModelHubMixin">ModelHubMixin</a>이 어떻게 작동하는지 간단히 살펴보았습니다. 이번 섹션에서는 Hugging Face Hub와 라이브러리 통합을 개선하기 위한 더 고급 기능 중 일부를 살펴보겠습니다.</p> <h4 class="relative group"><a id="model-card" 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="#model-card"><span><svg class="" 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></h4> <p data-svelte-h="svelte-1wggasg"><a href="/docs/huggingface_hub/pr_4113/ko/package_reference/mixins#huggingface_hub.ModelHubMixin">ModelHubMixin</a>은 모델 카드를 자동으로 생성합니다. 모델 카드는 모델과 함께 제공되는 중요한 정보를 제공하는 파일입니다. 모델 카드는 추가 메타데이터가 포함된 간단한 Markdown 파일입니다. 모델 카드는 발견 가능성, 재현성 및 공유를 위해 중요합니다! 더 자세한 내용은 <a href="https://huggingface.co/docs/hub/model-cards" rel="nofollow">모델 카드 가이드</a>를 확인하세요.</p> <p data-svelte-h="svelte-ipg5jn">모델 카드를 반자동으로 생성하는 것은 라이브러리로 푸시된 모든 모델이 <code>library_name</code>, <code>tags</code>, <code>license</code>, <code>pipeline_tag</code> 등과 같은 공통 메타데이터를 공유하도록 하는 좋은 방법입니다. 이를 통해 모든 모델이 Hub에서 쉽게 검색 가능하게 되고, Hub에 접속한 사용자에게 일부 리소스 링크를 제공합니다. <a href="/docs/huggingface_hub/pr_4113/ko/package_reference/mixins#huggingface_hub.ModelHubMixin">ModelHubMixin</a>을 상속할 때 메타데이터를 직접 정의할 수 있습니다:</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 class="" 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> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">class</span> <span class="hljs-title class_">UniDepthV1</span>(
nn.Module,
PyTorchModelHubMixin,
library_name=<span class="hljs-string">&quot;unidepth&quot;</span>,
repo_url=<span class="hljs-string">&quot;https://github.com/lpiccinelli-eth/UniDepth&quot;</span>,
docs_url=...,
pipeline_tag=<span class="hljs-string">&quot;depth-estimation&quot;</span>,
license=<span class="hljs-string">&quot;cc-by-nc-4.0&quot;</span>,
tags=[<span class="hljs-string">&quot;monocular-metric-depth-estimation&quot;</span>, <span class="hljs-string">&quot;arxiv:1234.56789&quot;</span>]
):
...<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1405hjl">기본적으로는 제공된 정보로 일반적인 모델 카드가 생성됩니다(예: <a href="https://huggingface.co/pyp1/VoiceCraft_giga830M" rel="nofollow">pyp1/VoiceCraft_giga830M</a>). 그러나 사용자 정의 모델 카드 템플릿을 정의할 수도 있습니다!</p> <p data-svelte-h="svelte-dp82ut">이 예에서는 <code>VoiceCraft</code> 클래스로 푸시된 모든 모델에 자동으로 인용 부분과 라이선스 세부 정보가 포함됩니다. 모델 카드 템플릿을 정의하는 방법에 대한 자세한 내용은 <a href="./model-cards">모델 카드 가이드</a>를 참조하세요.</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 class="" 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> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->MODEL_CARD_TEMPLATE = <span class="hljs-string">&quot;&quot;&quot;
---
# For reference on model card metadata, see the spec: https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1
# Doc / guide: https://huggingface.co/docs/hub/model-cards
{{ card_data }}
---
This is a VoiceCraft model. For more details, please check out the official Github repo: https://github.com/jasonppy/VoiceCraft. This model is shared under a Attribution-NonCommercial-ShareAlike 4.0 International license.
## Citation
@article{peng2024voicecraft,
author = {Peng, Puyuan and Huang, Po-Yao and Li, Daniel and Mohamed, Abdelrahman and Harwath, David},
title = {VoiceCraft: Zero-Shot Speech Editing and Text-to-Speech in the Wild},
journal = {arXiv},
year = {2024},
}
&quot;&quot;&quot;</span>
<span class="hljs-keyword">class</span> <span class="hljs-title class_">VoiceCraft</span>(
nn.Module,
PyTorchModelHubMixin,
library_name=<span class="hljs-string">&quot;voicecraft&quot;</span>,
model_card_template=MODEL_CARD_TEMPLATE,
...
):
...<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-b88p8t">마지막으로, 모델 카드 생성 프로세스를 동적 값으로 확장하려면 <code>generate_model_card()</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 class="" 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> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> huggingface_hub <span class="hljs-keyword">import</span> ModelCard, PyTorchModelHubMixin
<span class="hljs-keyword">class</span> <span class="hljs-title class_">UniDepthV1</span>(nn.Module, PyTorchModelHubMixin, ...):
(...)
<span class="hljs-keyword">def</span> <span class="hljs-title function_">generate_model_card</span>(<span class="hljs-params">self, *args, **kwargs</span>) -&gt; ModelCard:
card = <span class="hljs-built_in">super</span>().generate_model_card(*args, **kwargs)
card.data.metrics = ... <span class="hljs-comment"># 메타데이터에 메트릭 추가</span>
card.text += ... <span class="hljs-comment"># 모델 카드에 섹션 추가</span>
<span class="hljs-keyword">return</span> card<!-- HTML_TAG_END --></pre></div> <h4 class="relative group"><a id="config" 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="#config"><span><svg class="" 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></h4> <p data-svelte-h="svelte-16blsd5"><a href="/docs/huggingface_hub/pr_4113/ko/package_reference/mixins#huggingface_hub.ModelHubMixin">ModelHubMixin</a>은 모델 구성을 처리합니다. 모델을 인스턴스화할 때 입력 값들을 자동으로 확인하고 이를 <code>config.json</code> 파일에 직렬화합니다. 이렇게 함으로써 두 가지 이점이 제공됩니다:</p> <ol data-svelte-h="svelte-129pt2n"><li>사용자는 정확히 동일한 매개변수로 모델을 다시 가져올 수 있습니다.</li> <li><code>config.json</code> 파일이 자동으로 생성되면 Hub에서 분석이 가능해집니다(즉, “다운로드” 횟수가 기록됩니다).</li></ol> <p data-svelte-h="svelte-1xm33x1">하지만 이것이 실제로 어떻게 작동하는 걸까요? 사용자 관점에서 프로세스가 가능한 매끄럽도록 하기 위해 여러 규칙이 존재합니다:</p> <ul data-svelte-h="svelte-217leq"><li>만약 <code>__init__</code> 메소드가 <code>config</code> 입력을 기대한다면, 이는 자동으로 <code>config.json</code>으로 저장됩니다.</li> <li>만약 <code>config</code> 입력 매개변수에 데이터 클래스 유형(예: <code>config: Optional[MyConfigClass] = None</code>)의 어노테이션이 있다면, config 값은 올바르게 역직렬화됩니다.</li> <li>초기화할 때 전달된 모든 값들도 구성 파일에 저장됩니다. 이는 <code>config</code> 입력을 기대하지 않더라도 이점을 얻을 수 있다는 것을 의미합니다.</li></ul> <p data-svelte-h="svelte-dyo5xu">예시:</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 class="" 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> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">class</span> <span class="hljs-title class_">MyModel</span>(<span class="hljs-title class_ inherited__">ModelHubMixin</span>):
<span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">value: <span class="hljs-built_in">str</span>, size: <span class="hljs-built_in">int</span> = <span class="hljs-number">3</span></span>):
self.value = value
self.size = size
(...) <span class="hljs-comment"># _save_pretrained / _from_pretrained 구현</span>
model = MyModel(value=<span class="hljs-string">&quot;my_value&quot;</span>)
model.save_pretrained(...)
<span class="hljs-comment"># config.json 파일에는 전달된 값과 기본 값이 모두 포함됩니다.</span>
{<span class="hljs-string">&quot;value&quot;</span>: <span class="hljs-string">&quot;my_value&quot;</span>, <span class="hljs-string">&quot;size&quot;</span>: <span class="hljs-number">3</span>}<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1npamuf">그러나 값이 JSON으로 직렬화될 수 없는 경우, 기본적으로 구성 파일을 저장할 때 해당 값은 무시됩니다. 그러나 경우에 따라 라이브러리가 이미 직렬화할 수 없는 사용자 정의 객체를 예상하고 있고 해당 유형을 업데이트하고 싶지 않은 경우가 있습니다. 그렇다면 <a href="/docs/huggingface_hub/pr_4113/ko/package_reference/mixins#huggingface_hub.ModelHubMixin">ModelHubMixin</a>을 상속할 때 어떤 유형에 대한 사용자 지정 인코더/디코더를 전달할 수 있습니다. 이는 조금 더 많은 작업이 필요하지만 내부 로직을 변경하지 않고도 라이브러리를 Hub에 통합할 수 있도록 보장합니다.</p> <p data-svelte-h="svelte-pskjbf">여기서 <code>argparse.Namespace</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 class="" 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> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">class</span> <span class="hljs-title class_">VoiceCraft</span>(nn.Module):
<span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self, args</span>):
self.pattern = self.args.pattern
self.hidden_size = self.args.hidden_size
...<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-h497zb">한 가지 해결책은 <code>__init__</code> 시그니처를 <code>def __init__(self, pattern: str, hidden_size: int)</code>로 업데이트하고 클래스를 인스턴스화하는 모든 스니펫을 업데이트하는 것입니다. 이 방법은 유효한 방법이지만, 라이브러리를 사용하는 하위 응용 프로그램을 망가뜨릴 수 있습니다.</p> <p data-svelte-h="svelte-mflaxo">다른 해결책은 <code>argparse.Namespace</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 class="" 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> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> argparse <span class="hljs-keyword">import</span> Namespace
<span class="hljs-keyword">class</span> <span class="hljs-title class_">VoiceCraft</span>(
nn.Module,
PyTorchModelHubMixin, <span class="hljs-comment"># 믹스인을 상속합니다.</span>
coders={
Namespace: (
<span class="hljs-keyword">lambda</span> x: <span class="hljs-built_in">vars</span>(x), <span class="hljs-comment"># Encoder: `Namespace`를 유효한 JSON 형태로 변환하는 방법은 무엇인가요?</span>
<span class="hljs-keyword">lambda</span> data: Namespace(**data), <span class="hljs-comment"># Decoder: 딕셔너리에서 Namespace를 재구성하는 방법은 무엇인가요?</span>
)
}
):
<span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self, args: Namespace</span>): <span class="hljs-comment"># `args`에 주석을 답니다.</span>
self.pattern = self.args.pattern
self.hidden_size = self.args.hidden_size
...<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1lpr072">위의 코드 스니펫에서는 클래스의 내부 로직과 <code>__init__</code> 시그니처가 변경되지 않았습니다. 이는 기존의 모든 코드 스니펫이 여전히 작동한다는 것을 의미합니다. 이를 달성하기 위해 다음 과정을 수행하면 됩니다:</p> <ol data-svelte-h="svelte-lui4nk"><li>믹스인(<code>PytorchModelHubMixin</code>)으로부터 상속합니다.</li> <li>상속 시 <code>coders</code> 매개변수를 전달합니다. 이는 키가 처리하려는 사용자 지정 유형이고, 값은 튜플 <code>(인코더, 디코더)</code>입니다.
<ul><li>인코더는 지정된 유형의 객체를 입력으로 받아서 jsonable 값으로 반환합니다. 이는 <code>save_pretrained</code>로 모델을 저장할 때 사용됩니다.</li> <li>디코더는 원시 데이터(일반적으로 딕셔너리 타입)를 입력으로 받아서 초기 객체를 재구성합니다. 이는 <code>from_pretrained</code>로 모델을 로드할 때 사용됩니다.</li> <li><code>__init__</code> 시그니처에 유형 주석을 추가합니다. 이는 믹스인에게 클래스가 기대하는 유형과, 따라서 어떤 디코더를 사용해야 하는지를 알려주는 데 중요합니다.</li></ul></li></ol> <p data-svelte-h="svelte-8dfagu">위의 예제는 간단한 예시이기 때문에 인코더/디코더 함수는 견고하지 않습니다. 구체적인 구현을 위해서는 코너 케이스를 적절하게 처리해야 할 것입니다.</p> <h2 class="relative group"><a id="quick-comparison" 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="#quick-comparison"><span><svg class="" 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 data-svelte-h="svelte-17m8u6l">두 가지 접근 방법에 대한 장단점을 간단히 정리해보겠습니다. 아래 표는 단순히 예시일 뿐입니다. 각자 다른 프레임워크에는 고려해야 할 특정 사항이 있을 수 있습니다. 이 가이드는 통합을 다루는 아이디어와 지침을 제공하기 위한 것입니다. 언제든지 궁금한 점이 있으면 문의해 주세요!</p> <table data-svelte-h="svelte-1iq7x81"><thead><tr><th align="center">통합</th> <th align="center">helpers 사용 시</th> <th align="center"><a href="/docs/huggingface_hub/pr_4113/ko/package_reference/mixins#huggingface_hub.ModelHubMixin">ModelHubMixin</a> 사용 시</th></tr></thead> <tbody><tr><td align="center">사용자 경험</td> <td align="center"><code>model = load_from_hub(...)</code><br><code>push_to_hub(model, ...)</code></td> <td align="center"><code>model = MyModel.from_pretrained(...)</code><br><code>model.push_to_hub(...)</code></td></tr> <tr><td align="center">유연성</td> <td align="center">매우 유연합니다.<br>구현을 완전히 제어합니다.</td> <td align="center">유연성이 떨어집니다.<br>프레임워크에는 모델 클래스가 있어야 합니다.</td></tr> <tr><td align="center">유지 관리</td> <td align="center">구성 및 새로운 기능에 대한 지원을 추가하기 위한 유지 관리가 더 필요합니다. 사용자가 보고한 문제를 해결해야할 수도 있습니다.</td> <td align="center">Hub와의 대부분의 상호 작용이 <code>huggingface_hub</code>에서 구현되므로 유지 관리가 줄어듭니다.</td></tr> <tr><td align="center">문서화 / 타입 주석</td> <td align="center">수동으로 작성해야 합니다.</td> <td align="center"><code>huggingface_hub</code>에서 부분적으로 처리됩니다.</td></tr> <tr><td align="center">다운로드 횟수 표시기</td> <td align="center">수동으로 처리해야 합니다.</td> <td align="center">클래스에 <code>config</code> 속성이 있다면 기본적으로 활성화됩니다.</td></tr> <tr><td align="center">모델 카드</td> <td align="center">수동으로 처리해야 합니다.</td> <td align="center">library_name, tags 등을 활용하여 기본적으로 생성됩니다.</td></tr></tbody></table> <a class="!text-gray-400 !no-underline text-sm flex items-center not-prose mt-4" href="https://github.com/huggingface/huggingface_hub/blob/main/docs/source/ko/guides/integrations.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 data-svelte-h="svelte-zjs2n5"><span class="underline">Update</span> on GitHub</span></a> <p></p>
<script>
{
__sveltekit_1hcjqts = {
assets: "/docs/huggingface_hub/pr_4113/ko",
base: "/docs/huggingface_hub/pr_4113/ko",
env: {}
};
const element = document.currentScript.parentElement;
const data = [null,null];
Promise.all([
import("/docs/huggingface_hub/pr_4113/ko/_app/immutable/entry/start.e4d70577.js"),
import("/docs/huggingface_hub/pr_4113/ko/_app/immutable/entry/app.3b0f3b68.js")
]).then(([kit, app]) => {
kit.start(app, element, {
node_ids: [0, 9],
data,
form: null,
error: null
});
});
}
</script>

Xet Storage Details

Size:
74.4 kB
·
Xet hash:
76488080e7252c00973a99dae8ce9b9ea4c4d7e1b04a4ec32de115855a5d1363

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