Buckets:

mishig's picture
download
raw
96 kB
<meta charset="utf-8" /><meta name="hf:doc:metadata" content="{&quot;title&quot;:&quot;torchao&quot;,&quot;local&quot;:&quot;torchao&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Ví dụ về lượng tử hóa&quot;,&quot;local&quot;:&quot;quantization-examples&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;GPU H100&quot;,&quot;local&quot;:&quot;h100-gpu&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;GPU A100&quot;,&quot;local&quot;:&quot;a100-gpu&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Intel XPU&quot;,&quot;local&quot;:&quot;intel-xpu&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;CPU&quot;,&quot;local&quot;:&quot;cpu&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Lượng tử hóa theo Module&quot;,&quot;local&quot;:&quot;per-module-quantization&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;1. Bỏ qua lượng tử hóa cho một số lớp nhất định&quot;,&quot;local&quot;:&quot;1-skip-quantization-for-certain-layers&quot;,&quot;sections&quot;:[],&quot;depth&quot;:4},{&quot;title&quot;:&quot;2. Lượng tử hóa các lớp khác nhau với các cấu hình lượng tử hóa khác nhau (không dùng regex)&quot;,&quot;local&quot;:&quot;2-quantizing-different-layers-with-different-quantization-configs-no-regex&quot;,&quot;sections&quot;:[],&quot;depth&quot;:4},{&quot;title&quot;:&quot;3. Lượng tử hóa các lớp khác nhau với các cấu hình lượng tử hóa khác nhau (dùng regex)&quot;,&quot;local&quot;:&quot;3-quantizing-different-layers-with-different-quantization-configs-with-regex&quot;,&quot;sections&quot;:[],&quot;depth&quot;:4}],&quot;depth&quot;:3}],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Chuẩn hóa&quot;,&quot;local&quot;:&quot;serialization&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Tải các mô hình đã lượng tử hóa&quot;,&quot;local&quot;:&quot;loading-quantized-models&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Tài nguyên&quot;,&quot;local&quot;:&quot;resources&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Các vấn đề&quot;,&quot;local&quot;:&quot;issues&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2}],&quot;depth&quot;:1}"/>
<link href="/docs/transformers/main/en/_app/immutable/entry/start.CDsgEKDZ.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/CjAZ_-zP.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/DYxD-VOr.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/entry/app.DxuVi3jG.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/rBgV2CO2.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/Bqqc259Y.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/DOLBYqcr.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/DsnmJJEf.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/nodes/0.D3Lf5I--.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/CpYHmYpM.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/nodes/49.D-1uqAk4.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/DNJDeoze.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/Dtoajqbw.js" rel="modulepreload">
<!--1q5ej5h--><meta name="hf:doc:metadata" content="{&quot;title&quot;:&quot;torchao&quot;,&quot;local&quot;:&quot;torchao&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Quantization examples&quot;,&quot;local&quot;:&quot;quantization-examples&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;H100 GPU&quot;,&quot;local&quot;:&quot;h100-gpu&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;A100 GPU&quot;,&quot;local&quot;:&quot;a100-gpu&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Intel XPU&quot;,&quot;local&quot;:&quot;intel-xpu&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;CPU&quot;,&quot;local&quot;:&quot;cpu&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Per Module Quantization&quot;,&quot;local&quot;:&quot;per-module-quantization&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;1. Skip quantization for certain layers&quot;,&quot;local&quot;:&quot;1-skip-quantization-for-certain-layers&quot;,&quot;sections&quot;:[],&quot;depth&quot;:4},{&quot;title&quot;:&quot;2. Quantizing different layers with different quantization configs (no regex)&quot;,&quot;local&quot;:&quot;2-quantizing-different-layers-with-different-quantization-configs-no-regex&quot;,&quot;sections&quot;:[],&quot;depth&quot;:4},{&quot;title&quot;:&quot;3. Quantizing different layers with different quantization configs (with regex)&quot;,&quot;local&quot;:&quot;3-quantizing-different-layers-with-different-quantization-configs-with-regex&quot;,&quot;sections&quot;:[],&quot;depth&quot;:4}],&quot;depth&quot;:3}],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Serialization&quot;,&quot;local&quot;:&quot;serialization&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Loading quantized models&quot;,&quot;local&quot;:&quot;loading-quantized-models&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Resources&quot;,&quot;local&quot;:&quot;resources&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Issues&quot;,&quot;local&quot;:&quot;issues&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2}],&quot;depth&quot;:1}"/><!---->
<link href="/docs/transformers/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="torchao" 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="#torchao"><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><!---->torchao<!----></span></h1><!--]--><!----> <p><a href="https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/quantization/torchao.ipynb" rel="nofollow"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab: Torchao Demo"/></a></p> <p><a href="https://github.com/pytorch/ao" rel="nofollow">torchao</a> là thư viện tối ưu kiến trúc PyTorch, hỗ trợ các kiểu dữ liệu hiệu năng cao tùy chỉnh, lượng tử hóa và độ thưa. Nó có thể kết hợp với các tính năng PyTorch bản địa như <a href="https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html" rel="nofollow">torch.compile</a> để suy luận và huấn luyện nhanh hơn nữa.</p> <p>Xem bảng bên dưới để biết thêm các tính năng của torchao.</p> <table><thead><tr><th>Tính năng</th><th>Mô tả</th></tr></thead><tbody><tr><td><strong>Đào tạo nhận thức lượng tử hóa (QAT)</strong></td><td>Huấn luyện các mô hình lượng tử hóa với mức suy giảm độ chính xác tối thiểu (xem <a href="https://github.com/pytorch/ao/blob/main/torchao/quantization/qat/README.md" rel="nofollow">QAT README</a>)</td></tr><tr><td><strong>Đào tạo Float8</strong></td><td>Đào tạo thông lượng cao với định dạng float8 (xem tài liệu <a href="https://github.com/pytorch/torchtitan/blob/main/torchtitan/quantization/README.md" rel="nofollow">torchtitan</a> và <a href="https://huggingface.co/docs/accelerate/usage_guides/low_precision_training#configuring-torchao" rel="nofollow">Accelerate</a>)</td></tr><tr><td><strong>Hỗ trợ độ thưa</strong></td><td>Độ thưa bán cấu trúc (2:4) cho suy luận nhanh hơn (xem bài đăng trên blog <a href="https://pytorch.org/blog/accelerating-neural-network-training/" rel="nofollow">Tăng tốc huấn luyện mạng nơ-ron với độ thưa bán cấu trúc (2:4)</a>)</td></tr><tr><td><strong>Lượng tử hóa bộ tối ưu</strong></td><td>Giảm bộ nhớ trạng thái của bộ tối ưu hóa với các biến thể 4 và 8-bit của Adam</td></tr><tr><td><strong>Lượng tử hóa bộ đệm KV</strong></td><td>Cho phép suy luận ngữ cảnh dài với bộ nhớ thấp hơn</td></tr><tr><td><strong>Hỗ trợ Kernel tùy chỉnh</strong></td><td>sử dụng các ops tương thích với <code>torch.compile</code> của riêng bạn</td></tr><tr><td><strong>FSDP2</strong></td><td>Có thể kết hợp với FSDP2 để huấn luyện</td></tr></tbody></table> <blockquote class="tip"><p>Tham khảo <a href="https://github.com/pytorch/ao#torchao-pytorch-architecture-optimization" rel="nofollow">README.md</a> của torchao để biết thêm chi tiết về thư viện.</p></blockquote> <p>torchao hỗ trợ các <a href="https://github.com/pytorch/ao/blob/main/torchao/quantization/README.md" rel="nofollow">kỹ thuật lượng tử hóa</a> bên dưới.</p> <ul><li>Lượng hóa động Float8 A16W8</li> <li>Lượng tử hóa WeightOnly Float8 A16W8</li> <li>Lượng hóa động Int8 A8W8</li> <li>Lượng tử hóa chỉ trọng số Int8 A16W8</li> <li>Lượng tử hóa chỉ trọng số Int4 A16W4</li> <li>Lượng tử hóa chỉ trọng số Int4 A16W4 + Độ thưa 2:4</li> <li>Tự động lượng tử hóa</li></ul> <p>torchao cũng hỗ trợ cấu hình ở cấp độ module bằng cách chỉ định một từ điển ánh xạ từ tên đầy đủ của module đến cấu hình lượng tử hóa tương ứng. Điều này cho phép bỏ qua việc lượng tử hóa một số lớp nhất định và sử dụng cấu hình lượng tử hóa khác nhau cho các module khác nhau.</p> <p>Xem bảng bên dưới để kiểm tra xem phần cứng của bạn có tương thích hay không.</p> <table><thead><tr><th>Thành phần</th><th>Tương thích</th></tr></thead><tbody><tr><td>Phiên bản CUDA</td><td>✅ cu118, cu126, cu128</td></tr><tr><td>Phiên bản XPU</td><td>✅ pytorch2.8</td></tr><tr><td>CPU</td><td>✅ thay đổi <code>device_map="cpu"</code> (xem các ví dụ bên dưới)</td></tr></tbody></table> <p>Cài đặt torchao từ PyPi hoặc chỉ mục PyTorch bằng các lệnh sau.</p> <div class="flex space-x-2 items-center my-1.5 mr-8 h-7 !pl-0 -mx-3 md:mx-0"><!--[--><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd border-gray-800 bg-black dark:bg-gray-700 text-white">PyPi</div><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd text-gray-500 cursor-pointer opacity-90 hover:text-gray-700 dark:hover:text-gray-200 hover:shadow-sm">Chỉ mục PyTorch</div><!--]--></div> <div class="language-select"><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> Đã sao chép</div><!----></button><!----></div> <pre class="language-bash "><!----><span class="hljs-comment"># Updating 🤗 Transformers to the latest version, as the example script below uses the new auto compilation</span>
<span class="hljs-comment"># Stable release from Pypi which will default to CUDA 12.6</span>
pip install --upgrade torchao transformers<!----></pre></div><!----></div><!----> <div hidden=""><p>Phiên bản ổn định từ chỉ mục 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 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> Đã sao chép</div><!----></button><!----></div> <pre class="language-bash "><!---->pip install torchao --index-url https://download.pytorch.org/whl/cu126 <span class="hljs-comment"># options are cpu/cu118/cu126/cu128</span><!----></pre></div><!----><!----></div><!----><!----></div><!----> <p>torchao &gt;= 0.15.0 là bắt buộc. API dựa trên chuỗi (ví dụ: <code>TorchAoConfig("int4_weight_only")</code>) đã bị loại bỏ — hãy sử dụng các đối tượng <code>AOBaseConfig</code> thay thế (xem các ví dụ bên dưới).</p> <!--[1--><h2 class="relative group"><a id="quantization-examples" 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="#quantization-examples"><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><!---->Ví dụ về lượng tử hóa<!----></span></h2><!--]--><!----> <p>TorchAO cung cấp nhiều cấu hình lượng tử hóa khác nhau. Mỗi cấu hình có thể được tùy chỉnh thêm bằng các tham số như <code>group_size</code>, <code>scheme</code> và <code>layout</code> để tối ưu hóa cho phần cứng và kiến trúc mô hình cụ thể.</p> <p>Để xem danh sách đầy đủ các cấu hình khả dụng, hãy xem <a href="https://github.com/pytorch/ao/blob/main/torchao/quantization/quant_api.py" rel="nofollow">tài liệu API lượng tử hóa</a>.</p> <p>Bạn có thể tự động chọn các kiểu và cài đặt lượng tử hóa hoặc để hệ thống tự động chọn các kiểu lượng tử hóa.</p> <p>Tạo một <a href="/docs/transformers/main/vi/main_classes/quantization#transformers.TorchAoConfig">TorchAoConfig</a> và chỉ định loại lượng tử hóa cùng <code>group_size</code> của các trọng số cần lượng tử hóa (cho int8 weight only và int4 weight only). Đặt <code>cache_implementation</code> thành <code>"static"</code> để tự động <a href="https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html" rel="nofollow">torch.compile</a> phương thức forward.</p> <p>Chúng tôi sẽ đưa ra các ví dụ về các phương pháp lượng tử hóa được khuyến nghị dựa trên phần cứng, ví dụ như GPU A100, GPU H100, CPU.</p> <blockquote class="warning"><p>torchao tự động biên dịch mô hình trong lần suy luận đầu tiên nếu chúng ta đặt <code>cache_implementation="static"</code>. Mô hình sẽ được biên dịch lại mỗi khi kích thước lô (batch size) hoặc <code>max_new_tokens</code> bị thay đổi. Truyền <code>disable_compile=True</code> vào <a href="/docs/transformers/main/vi/main_classes/text_generation#transformers.GenerationMixin.generate">generate()</a> để lượng tử hóa mà không cần biên dịch.</p></blockquote> <!--[2--><h3 class="relative group"><a id="h100-gpu" 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="#h100-gpu"><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><!---->GPU H100<!----></span></h3><!--]--><!----> <div class="flex space-x-2 items-center my-1.5 mr-8 h-7 !pl-0 -mx-3 md:mx-0"><!--[--><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd border-gray-800 bg-black dark:bg-gray-700 text-white">float8-dynamic-and-weight-only</div><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd text-gray-500 cursor-pointer opacity-90 hover:text-gray-700 dark:hover:text-gray-200 hover:shadow-sm">int4-weight-only</div><!--]--></div> <div class="language-select"><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> Đã sao chép</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> TorchAoConfig, AutoModelForCausalLM, AutoTokenizer
<span class="hljs-keyword">from</span> torchao.quantization <span class="hljs-keyword">import</span> Float8DynamicActivationFloat8WeightConfig, Float8WeightOnlyConfig
quant_config = Float8DynamicActivationFloat8WeightConfig()
<span class="hljs-comment"># or float8 weight only quantization</span>
<span class="hljs-comment"># quant_config = Float8WeightOnlyConfig()</span>
quantization_config = TorchAoConfig(quant_type=quant_config)
<span class="hljs-comment"># Load and quantize the model</span>
quantized_model = AutoModelForCausalLM.from_pretrained(
<span class="hljs-string">&quot;meta-llama/Llama-3.1-8B-Instruct&quot;</span>,
dtype=<span class="hljs-string">&quot;auto&quot;</span>,
device_map=<span class="hljs-string">&quot;auto&quot;</span>,
quantization_config=quantization_config
)
tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">&quot;meta-llama/Llama-3.1-8B-Instruct&quot;</span>)
input_text = <span class="hljs-string">&quot;What are we having for dinner?&quot;</span>
input_ids = tokenizer(input_text, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>).to(quantized_model.device, quantized_model.dtype)
<span class="hljs-comment"># auto-compile the quantized model with `cache_implementation=&quot;static&quot;` to get speed up</span>
output = quantized_model.generate(**input_ids, max_new_tokens=<span class="hljs-number">10</span>, cache_implementation=<span class="hljs-string">&quot;static&quot;</span>)
<span class="hljs-built_in">print</span>(tokenizer.decode(output[<span class="hljs-number">0</span>], skip_special_tokens=<span class="hljs-literal">True</span>))<!----></pre></div><!----></div><!----> <div hidden=""><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> Đã sao chép</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> TorchAoConfig, AutoModelForCausalLM, AutoTokenizer
<span class="hljs-keyword">from</span> torchao.quantization <span class="hljs-keyword">import</span> GemliteUIntXWeightOnlyConfig
<span class="hljs-comment"># We integrated with gemlite, which optimizes for batch size N on A100 and H100</span>
quant_config = GemliteUIntXWeightOnlyConfig(group_size=<span class="hljs-number">128</span>)
quantization_config = TorchAoConfig(quant_type=quant_config)
<span class="hljs-comment"># Load and quantize the model</span>
quantized_model = AutoModelForCausalLM.from_pretrained(
<span class="hljs-string">&quot;meta-llama/Llama-3.1-8B-Instruct&quot;</span>,
dtype=<span class="hljs-string">&quot;auto&quot;</span>,
device_map=<span class="hljs-string">&quot;auto&quot;</span>,
quantization_config=quantization_config
)
tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">&quot;meta-llama/Llama-3.1-8B-Instruct&quot;</span>)
input_text = <span class="hljs-string">&quot;What are we having for dinner?&quot;</span>
input_ids = tokenizer(input_text, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>).to(quantized_model.device, quantized_model.dtype)
<span class="hljs-comment"># auto-compile the quantized model with `cache_implementation=&quot;static&quot;` to get speed up</span>
output = quantized_model.generate(**input_ids, max_new_tokens=<span class="hljs-number">10</span>, cache_implementation=<span class="hljs-string">&quot;static&quot;</span>)
<span class="hljs-built_in">print</span>(tokenizer.decode(output[<span class="hljs-number">0</span>], skip_special_tokens=<span class="hljs-literal">True</span>))<!----></pre></div><!----></div><!----><!----></div><!----> <!--[2--><h3 class="relative group"><a id="a100-gpu" 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="#a100-gpu"><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><!---->GPU A100<!----></span></h3><!--]--><!----> <div class="flex space-x-2 items-center my-1.5 mr-8 h-7 !pl-0 -mx-3 md:mx-0"><!--[--><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd border-gray-800 bg-black dark:bg-gray-700 text-white">int8-dynamic-and-weight-only</div><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd text-gray-500 cursor-pointer opacity-90 hover:text-gray-700 dark:hover:text-gray-200 hover:shadow-sm">int4-weight-only</div><!--]--></div> <div class="language-select"><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> Đã sao chép</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> TorchAoConfig, AutoModelForCausalLM, AutoTokenizer
<span class="hljs-keyword">from</span> torchao.quantization <span class="hljs-keyword">import</span> Int8DynamicActivationInt8WeightConfig, Int8WeightOnlyConfig
quant_config = Int8DynamicActivationInt8WeightConfig()
<span class="hljs-comment"># or int8 weight only quantization</span>
<span class="hljs-comment"># quant_config = Int8WeightOnlyConfig()</span>
quantization_config = TorchAoConfig(quant_type=quant_config)
<span class="hljs-comment"># Load and quantize the model</span>
quantized_model = AutoModelForCausalLM.from_pretrained(
<span class="hljs-string">&quot;meta-llama/Llama-3.1-8B-Instruct&quot;</span>,
dtype=<span class="hljs-string">&quot;auto&quot;</span>,
device_map=<span class="hljs-string">&quot;auto&quot;</span>,
quantization_config=quantization_config
)
tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">&quot;meta-llama/Llama-3.1-8B-Instruct&quot;</span>)
input_text = <span class="hljs-string">&quot;What are we having for dinner?&quot;</span>
input_ids = tokenizer(input_text, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>).to(quantized_model.device, quantized_model.dtype)
<span class="hljs-comment"># auto-compile the quantized model with `cache_implementation=&quot;static&quot;` to get speed up</span>
output = quantized_model.generate(**input_ids, max_new_tokens=<span class="hljs-number">10</span>, cache_implementation=<span class="hljs-string">&quot;static&quot;</span>)
<span class="hljs-built_in">print</span>(tokenizer.decode(output[<span class="hljs-number">0</span>], skip_special_tokens=<span class="hljs-literal">True</span>))<!----></pre></div><!----></div><!----> <div hidden=""><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> Đã sao chép</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> TorchAoConfig, AutoModelForCausalLM, AutoTokenizer
<span class="hljs-keyword">from</span> torchao.quantization <span class="hljs-keyword">import</span> GemliteUIntXWeightOnlyConfig, Int4WeightOnlyConfig
<span class="hljs-comment"># For batch size N, we recommend gemlite, which may require autotuning</span>
<span class="hljs-comment"># default is 4 bit, 8 bit is also supported by passing `bit_width=8`</span>
quant_config = GemliteUIntXWeightOnlyConfig(group_size=<span class="hljs-number">128</span>)
<span class="hljs-comment"># For batch size 1, we also have custom tinygemm kernel that&#x27;s only optimized for this</span>
<span class="hljs-comment"># We can set `use_hqq` to `True` for better accuracy</span>
<span class="hljs-comment"># quant_config = Int4WeightOnlyConfig(group_size=128, use_hqq=True)</span>
quantization_config = TorchAoConfig(quant_type=quant_config)
<span class="hljs-comment"># Load and quantize the model</span>
quantized_model = AutoModelForCausalLM.from_pretrained(
<span class="hljs-string">&quot;meta-llama/Llama-3.1-8B-Instruct&quot;</span>,
dtype=<span class="hljs-string">&quot;auto&quot;</span>,
device_map=<span class="hljs-string">&quot;auto&quot;</span>,
quantization_config=quantization_config
)
tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">&quot;meta-llama/Llama-3.1-8B-Instruct&quot;</span>)
input_text = <span class="hljs-string">&quot;What are we having for dinner?&quot;</span>
input_ids = tokenizer(input_text, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>).to(quantized_model.device, quantized_model.dtype)
<span class="hljs-comment"># auto-compile the quantized model with `cache_implementation=&quot;static&quot;` to get speed up</span>
output = quantized_model.generate(**input_ids, max_new_tokens=<span class="hljs-number">10</span>, cache_implementation=<span class="hljs-string">&quot;static&quot;</span>)
<span class="hljs-built_in">print</span>(tokenizer.decode(output[<span class="hljs-number">0</span>], skip_special_tokens=<span class="hljs-literal">True</span>))<!----></pre></div><!----></div><!----><!----></div><!----> <!--[2--><h3 class="relative group"><a id="intel-xpu" 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="#intel-xpu"><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><!---->Intel XPU<!----></span></h3><!--]--><!----> <div class="flex space-x-2 items-center my-1.5 mr-8 h-7 !pl-0 -mx-3 md:mx-0"><!--[--><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd border-gray-800 bg-black dark:bg-gray-700 text-white">int8-dynamic-and-weight-only</div><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd text-gray-500 cursor-pointer opacity-90 hover:text-gray-700 dark:hover:text-gray-200 hover:shadow-sm">int4-weight-only</div><!--]--></div> <div class="language-select"><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> Đã sao chép</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> TorchAoConfig, AutoModelForCausalLM, AutoTokenizer
<span class="hljs-keyword">from</span> torchao.quantization <span class="hljs-keyword">import</span> Int8DynamicActivationInt8WeightConfig, Int8WeightOnlyConfig
quant_config = Int8DynamicActivationInt8WeightConfig()
<span class="hljs-comment"># or int8 weight only quantization</span>
<span class="hljs-comment"># quant_config = Int8WeightOnlyConfig()</span>
quantization_config = TorchAoConfig(quant_type=quant_config)
<span class="hljs-comment"># Load and quantize the model</span>
quantized_model = AutoModelForCausalLM.from_pretrained(
<span class="hljs-string">&quot;meta-llama/Llama-3.1-8B-Instruct&quot;</span>,
dtype=<span class="hljs-string">&quot;auto&quot;</span>,
device_map=<span class="hljs-string">&quot;auto&quot;</span>,
quantization_config=quantization_config
)
tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">&quot;meta-llama/Llama-3.1-8B-Instruct&quot;</span>)
input_text = <span class="hljs-string">&quot;What are we having for dinner?&quot;</span>
input_ids = tokenizer(input_text, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>).to(quantized_model.device, quantized_model.dtype)
<span class="hljs-comment"># auto-compile the quantized model with `cache_implementation=&quot;static&quot;` to get speed up</span>
output = quantized_model.generate(**input_ids, max_new_tokens=<span class="hljs-number">10</span>, cache_implementation=<span class="hljs-string">&quot;static&quot;</span>)
<span class="hljs-built_in">print</span>(tokenizer.decode(output[<span class="hljs-number">0</span>], skip_special_tokens=<span class="hljs-literal">True</span>))<!----></pre></div><!----></div><!----> <div hidden=""><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> Đã sao chép</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> TorchAoConfig, AutoModelForCausalLM, AutoTokenizer
<span class="hljs-keyword">from</span> torchao.quantization <span class="hljs-keyword">import</span> Int4WeightOnlyConfig
quant_config = Int4WeightOnlyConfig(group_size=<span class="hljs-number">128</span>, int4_packing_format=<span class="hljs-string">&quot;plain_int32&quot;</span>)
quantization_config = TorchAoConfig(quant_type=quant_config)
<span class="hljs-comment"># Load and quantize the model</span>
quantized_model = AutoModelForCausalLM.from_pretrained(
<span class="hljs-string">&quot;meta-llama/Llama-3.1-8B-Instruct&quot;</span>,
dtype=<span class="hljs-string">&quot;auto&quot;</span>,
device_map=<span class="hljs-string">&quot;auto&quot;</span>,
quantization_config=quantization_config
)
tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">&quot;meta-llama/Llama-3.1-8B-Instruct&quot;</span>)
input_text = <span class="hljs-string">&quot;What are we having for dinner?&quot;</span>
input_ids = tokenizer(input_text, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>).to(quantized_model.device).to(quantized_model.dtype)
<span class="hljs-comment"># auto-compile the quantized model with `cache_implementation=&quot;static&quot;` to get speed up</span>
output = quantized_model.generate(**input_ids, max_new_tokens=<span class="hljs-number">10</span>, cache_implementation=<span class="hljs-string">&quot;static&quot;</span>)
<span class="hljs-built_in">print</span>(tokenizer.decode(output[<span class="hljs-number">0</span>], skip_special_tokens=<span class="hljs-literal">True</span>))<!----></pre></div><!----></div><!----><!----></div><!----> <!--[2--><h3 class="relative group"><a id="cpu" 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="#cpu"><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><!---->CPU<!----></span></h3><!--]--><!----> <div class="flex space-x-2 items-center my-1.5 mr-8 h-7 !pl-0 -mx-3 md:mx-0"><!--[--><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd border-gray-800 bg-black dark:bg-gray-700 text-white">int8-dynamic-and-weight-only</div><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd text-gray-500 cursor-pointer opacity-90 hover:text-gray-700 dark:hover:text-gray-200 hover:shadow-sm">int4-weight-only</div><!--]--></div> <div class="language-select"><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> Đã sao chép</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> TorchAoConfig, AutoModelForCausalLM, AutoTokenizer
<span class="hljs-keyword">from</span> torchao.quantization <span class="hljs-keyword">import</span> Int8DynamicActivationInt8WeightConfig, Int8WeightOnlyConfig
quant_config = Int8DynamicActivationInt8WeightConfig()
<span class="hljs-comment"># quant_config = Int8WeightOnlyConfig()</span>
quantization_config = TorchAoConfig(quant_type=quant_config)
<span class="hljs-comment"># Load and quantize the model</span>
quantized_model = AutoModelForCausalLM.from_pretrained(
<span class="hljs-string">&quot;meta-llama/Llama-3.1-8B-Instruct&quot;</span>,
dtype=<span class="hljs-string">&quot;auto&quot;</span>,
device_map=<span class="hljs-string">&quot;cpu&quot;</span>,
quantization_config=quantization_config
)
tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">&quot;meta-llama/Llama-3.1-8B-Instruct&quot;</span>)
input_text = <span class="hljs-string">&quot;What are we having for dinner?&quot;</span>
input_ids = tokenizer(input_text, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>).to(quantized_model.device, quantized_model.dtype)
<span class="hljs-comment"># auto-compile the quantized model with `cache_implementation=&quot;static&quot;` to get speed up</span>
output = quantized_model.generate(**input_ids, max_new_tokens=<span class="hljs-number">10</span>, cache_implementation=<span class="hljs-string">&quot;static&quot;</span>)
<span class="hljs-built_in">print</span>(tokenizer.decode(output[<span class="hljs-number">0</span>], skip_special_tokens=<span class="hljs-literal">True</span>))<!----></pre></div><!----></div><!----> <div hidden=""><blockquote class="tip"><p>Lượng tử hóa chỉ trọng số int4 trên CPU yêu cầu phiên bản torchao 0.15.0 trở lên.</p></blockquote> <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> Đã sao chép</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> TorchAoConfig, AutoModelForCausalLM, AutoTokenizer
<span class="hljs-keyword">from</span> torchao.prototype.quantization.int4 <span class="hljs-keyword">import</span> PrototypeInt4WeightOnlyConfig
quantization_config = TorchAoConfig(PrototypeInt4WeightOnlyConfig(group_size=<span class="hljs-number">128</span>, int4_choose_qparams_algorithm=<span class="hljs-string">&quot;tinygemm&quot;</span>))
<span class="hljs-comment"># Load and quantize the model</span>
quantized_model = AutoModelForCausalLM.from_pretrained(
<span class="hljs-string">&quot;meta-llama/Llama-3.1-8B-Instruct&quot;</span>,
dtype=<span class="hljs-string">&quot;auto&quot;</span>,
device_map=<span class="hljs-string">&quot;cpu&quot;</span>,
quantization_config=quantization_config
)
tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">&quot;meta-llama/Llama-3.1-8B-Instruct&quot;</span>)
input_text = <span class="hljs-string">&quot;What are we having for dinner?&quot;</span>
input_ids = tokenizer(input_text, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>).to(quantized_model.device).to(quantized_model.dtype)
<span class="hljs-comment"># auto-compile the quantized model with `cache_implementation=&quot;static&quot;` to get speed up</span>
output = quantized_model.generate(**input_ids, max_new_tokens=<span class="hljs-number">10</span>, cache_implementation=<span class="hljs-string">&quot;static&quot;</span>)
<span class="hljs-built_in">print</span>(tokenizer.decode(output[<span class="hljs-number">0</span>], skip_special_tokens=<span class="hljs-literal">True</span>))<!----></pre></div><!----><!----></div><!----><!----></div><!----> <!--[2--><h3 class="relative group"><a id="per-module-quantization" 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="#per-module-quantization"><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><!---->Lượng tử hóa theo Module<!----></span></h3><!--]--><!----> <!--[3--><h4 class="relative group"><a id="1-skip-quantization-for-certain-layers" 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="#1-skip-quantization-for-certain-layers"><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><!---->1. Bỏ qua lượng tử hóa cho một số lớp nhất định<!----></span></h4><!--]--><!----> <p>Với <code>FqnToConfig</code>, chúng ta có thể chỉ định cấu hình mặc định cho tất cả các lớp trong khi bỏ qua lượng tử hóa cho một số lớp nhất định.</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> Đã sao chép</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForCausalLM, AutoTokenizer, TorchAoConfig
model_id = <span class="hljs-string">&quot;meta-llama/Llama-3.1-8B-Instruct&quot;</span>
<span class="hljs-keyword">from</span> torchao.quantization <span class="hljs-keyword">import</span> Int4WeightOnlyConfig, FqnToConfig
config = Int4WeightOnlyConfig(group_size=<span class="hljs-number">128</span>)
<span class="hljs-comment"># set default to int4 (for linears), and skip quantizing `model.layers.0.self_attn.q_proj`</span>
quant_config = FqnToConfig({<span class="hljs-string">&quot;_default&quot;</span>: config, <span class="hljs-string">&quot;model.layers.0.self_attn.q_proj&quot;</span>: <span class="hljs-literal">None</span>})
quantization_config = TorchAoConfig(quant_type=quant_config)
quantized_model = AutoModelForCausalLM.from_pretrained(model_id, device_map=<span class="hljs-string">&quot;auto&quot;</span>, dtype=torch.bfloat16, quantization_config=quantization_config)
<span class="hljs-comment"># lm_head is not quantized and model.layers.0.self_attn.q_proj is not quantized</span>
<span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;quantized model:&quot;</span>, quantized_model)
tokenizer = AutoTokenizer.from_pretrained(model_id)
<span class="hljs-comment"># Manual Testing</span>
prompt = <span class="hljs-string">&quot;Hey, are you conscious? Can you talk to me?&quot;</span>
inputs = tokenizer(prompt, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>).to(quantized_model.device, quantized_model.dtype)
generated_ids = quantized_model.generate(**inputs, max_new_tokens=<span class="hljs-number">128</span>)
output_text = tokenizer.batch_decode(
generated_ids, skip_special_tokens=<span class="hljs-literal">True</span>, clean_up_tokenization_spaces=<span class="hljs-literal">False</span>
)
<span class="hljs-built_in">print</span>(output_text)<!----></pre></div><!----> <!--[3--><h4 class="relative group"><a id="2-quantizing-different-layers-with-different-quantization-configs-no-regex" 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="#2-quantizing-different-layers-with-different-quantization-configs-no-regex"><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><!---->2. Lượng tử hóa các lớp khác nhau với các cấu hình lượng tử hóa khác nhau (không dùng regex)<!----></span></h4><!--]--><!----> <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> Đã sao chép</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForCausalLM, AutoTokenizer, TorchAoConfig
model_id = <span class="hljs-string">&quot;facebook/opt-125m&quot;</span>
<span class="hljs-keyword">from</span> torchao.quantization <span class="hljs-keyword">import</span> Int4WeightOnlyConfig, FqnToConfig, Int8DynamicActivationInt4WeightConfig, IntxWeightOnlyConfig, PerAxis, MappingType
weight_dtype = torch.int8
granularity = PerAxis(<span class="hljs-number">0</span>)
mapping_type = MappingType.ASYMMETRIC
embedding_config = IntxWeightOnlyConfig(
weight_dtype=weight_dtype,
granularity=granularity,
mapping_type=mapping_type,
)
linear_config = Int8DynamicActivationInt4WeightConfig(group_size=<span class="hljs-number">128</span>)
quant_config = FqnToConfig({<span class="hljs-string">&quot;_default&quot;</span>: linear_config, <span class="hljs-string">&quot;model.decoder.embed_tokens&quot;</span>: embedding_config, <span class="hljs-string">&quot;model.decoder.embed_positions&quot;</span>: <span class="hljs-literal">None</span>})
<span class="hljs-comment"># set `include_embedding` to True in order to include embedding in quantization</span>
<span class="hljs-comment"># when `include_embedding` is True, we&#x27;ll remove input embedding from `modules_not_to_convert` as well</span>
quantization_config = TorchAoConfig(quant_type=quant_config, include_embedding=<span class="hljs-literal">True</span>)
quantized_model = AutoModelForCausalLM.from_pretrained(model_id, device_map=<span class="hljs-string">&quot;cpu&quot;</span>, dtype=torch.bfloat16, quantization_config=quantization_config)
<span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;quantized model:&quot;</span>, quantized_model)
<span class="hljs-comment"># make sure embedding is quantized</span>
<span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;embed_tokens weight:&quot;</span>, quantized_model.model.decoder.embed_tokens.weight)
tokenizer = AutoTokenizer.from_pretrained(model_id)
<span class="hljs-comment"># Manual Testing</span>
prompt = <span class="hljs-string">&quot;Hey, are you conscious? Can you talk to me?&quot;</span>
inputs = tokenizer(prompt, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>).to(<span class="hljs-string">&quot;cpu&quot;</span>, quantized_model.dtype)
generated_ids = quantized_model.generate(**inputs, max_new_tokens=<span class="hljs-number">128</span>, cache_implementation=<span class="hljs-string">&quot;static&quot;</span>)
output_text = tokenizer.batch_decode(
generated_ids, skip_special_tokens=<span class="hljs-literal">True</span>, clean_up_tokenization_spaces=<span class="hljs-literal">False</span>
)
<span class="hljs-built_in">print</span>(output_text)<!----></pre></div><!----> <!--[3--><h4 class="relative group"><a id="3-quantizing-different-layers-with-different-quantization-configs-with-regex" 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="#3-quantizing-different-layers-with-different-quantization-configs-with-regex"><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><!---->3. Lượng tử hóa các lớp khác nhau với các cấu hình lượng tử hóa khác nhau (dùng regex)<!----></span></h4><!--]--><!----> <p>Chúng ta cũng có thể sử dụng regex để chỉ định cấu hình cho tất cả các module có <code>module_fqn</code> khớp với regex, tất cả regex phải bắt đầu bằng <code>re:</code>, ví dụ <code>re:layers\..*\.gate_proj</code> sẽ khớp với tất cả các layer như <code>layers.0.gate_proj</code>. Xem <a href="https://github.com/pytorch/ao/blob/2fe0ca0899c730c528efdbec8886feaa38879f39/torchao/quantization/quant_api.py#L2392" rel="nofollow">ở đây</a> để biết thêm tài liệu.</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> Đã sao chép</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">import</span> logging
<span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForCausalLM, AutoTokenizer, TorchAoConfig
<span class="hljs-comment"># Configure logging to see warnings and debug information</span>
logging.basicConfig(
level=logging.INFO, <span class="hljs-built_in">format</span>=<span class="hljs-string">&quot;%(name)s - %(levelname)s - %(message)s&quot;</span>
)
<span class="hljs-comment"># Enable specific loggers that might contain the serialization warnings</span>
logging.getLogger(<span class="hljs-string">&quot;transformers&quot;</span>).setLevel(logging.INFO)
logging.getLogger(<span class="hljs-string">&quot;torchao&quot;</span>).setLevel(logging.INFO)
logging.getLogger(<span class="hljs-string">&quot;safetensors&quot;</span>).setLevel(logging.INFO)
logging.getLogger(<span class="hljs-string">&quot;huggingface_hub&quot;</span>).setLevel(logging.INFO)
model_id = <span class="hljs-string">&quot;facebook/opt-125m&quot;</span>
<span class="hljs-keyword">from</span> torchao.quantization <span class="hljs-keyword">import</span> (
Float8DynamicActivationFloat8WeightConfig,
Int4WeightOnlyConfig,
IntxWeightOnlyConfig,
PerRow,
PerAxis,
FqnToConfig,
Float8Tensor,
Int4TilePackedTo4dTensor,
IntxUnpackedToInt8Tensor,
)
float8dyn = Float8DynamicActivationFloat8WeightConfig(granularity=PerRow())
int4wo = Int4WeightOnlyConfig(int4_packing_format=<span class="hljs-string">&quot;tile_packed_to_4d&quot;</span>)
intxwo = IntxWeightOnlyConfig(weight_dtype=torch.int8, granularity=PerAxis(<span class="hljs-number">0</span>))
qconfig_dict = {
<span class="hljs-comment"># highest priority</span>
<span class="hljs-string">&quot;model.decoder.layers.3.self_attn.q_proj&quot;</span>: int4wo,
<span class="hljs-string">&quot;model.decoder.layers.3.self_attn.k_proj&quot;</span>: int4wo,
<span class="hljs-string">&quot;model.decoder.layers.3.self_attn.v_proj&quot;</span>: int4wo,
<span class="hljs-comment"># vllm</span>
<span class="hljs-string">&quot;model.decoder.layers.3.self_attn.qkv_proj&quot;</span>: int4wo,
<span class="hljs-string">&quot;re:model\.decoder\.layers\..+\.self_attn\.q_proj&quot;</span>: float8dyn,
<span class="hljs-string">&quot;re:model\.decoder\.layers\..+\.self_attn\.k_proj&quot;</span>: float8dyn,
<span class="hljs-string">&quot;re:model\.decoder\.layers\..+\.self_attn\.v_proj&quot;</span>: float8dyn,
<span class="hljs-comment"># this should not take effect and we&#x27;ll fallback to _default</span>
<span class="hljs-comment"># since no full mach (missing `j` in the end)</span>
<span class="hljs-string">&quot;re:model\.decoder\.layers\..+\.self_attn\.out_pro&quot;</span>: float8dyn,
<span class="hljs-comment"># vllm</span>
<span class="hljs-string">&quot;re:model\.decoder\.layers\..+\.self_attn\.qkv_proj&quot;</span>: float8dyn,
<span class="hljs-string">&quot;_default&quot;</span>: intxwo,
}
quant_config = FqnToConfig(qconfig_dict)
quantization_config = TorchAoConfig(quant_type=quant_config)
quantized_model = AutoModelForCausalLM.from_pretrained(
model_id,
device_map=<span class="hljs-string">&quot;auto&quot;</span>,
torch_dtype=torch.bfloat16,
quantization_config=quantization_config,
)
<span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;quantized model:&quot;</span>, quantized_model)
tokenizer = AutoTokenizer.from_pretrained(model_id)
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">12</span>):
<span class="hljs-keyword">if</span> i == <span class="hljs-number">3</span>:
<span class="hljs-keyword">assert</span> <span class="hljs-built_in">isinstance</span>(quantized_model.model.decoder.layers[i].self_attn.q_proj.weight, Int4TilePackedTo4dTensor)
<span class="hljs-keyword">assert</span> <span class="hljs-built_in">isinstance</span>(quantized_model.model.decoder.layers[i].self_attn.k_proj.weight, Int4TilePackedTo4dTensor)
<span class="hljs-keyword">assert</span> <span class="hljs-built_in">isinstance</span>(quantized_model.model.decoder.layers[i].self_attn.v_proj.weight, Int4TilePackedTo4dTensor)
<span class="hljs-keyword">else</span>:
<span class="hljs-keyword">assert</span> <span class="hljs-built_in">isinstance</span>(quantized_model.model.decoder.layers[i].self_attn.q_proj.weight, Float8Tensor)
<span class="hljs-keyword">assert</span> <span class="hljs-built_in">isinstance</span>(quantized_model.model.decoder.layers[i].self_attn.k_proj.weight, Float8Tensor)
<span class="hljs-keyword">assert</span> <span class="hljs-built_in">isinstance</span>(quantized_model.model.decoder.layers[i].self_attn.v_proj.weight, Float8Tensor)
<span class="hljs-keyword">assert</span> <span class="hljs-built_in">isinstance</span>(quantized_model.model.decoder.layers[i].self_attn.out_proj.weight, IntxUnpackedToInt8Tensor)
<span class="hljs-comment"># Manual Testing</span>
prompt = <span class="hljs-string">&quot;What are we having for dinner?&quot;</span>
<span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;Prompt:&quot;</span>, prompt)
inputs = tokenizer(
prompt,
return_tensors=<span class="hljs-string">&quot;pt&quot;</span>,
).to(quantized_model.device, quantized_model.dtype)
<span class="hljs-comment"># setting temperature to 0 to make sure result deterministic</span>
generated_ids = quantized_model.generate(**inputs, max_new_tokens=<span class="hljs-number">128</span>, temperature=<span class="hljs-number">0</span>)
correct_output_text = tokenizer.batch_decode(
generated_ids, skip_special_tokens=<span class="hljs-literal">True</span>, clean_up_tokenization_spaces=<span class="hljs-literal">False</span>
)
<span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;Response:&quot;</span>, correct_output_text[<span class="hljs-number">0</span>][<span class="hljs-built_in">len</span>(prompt) :])
<span class="hljs-comment"># Load model from saved checkpoint</span>
reloaded_model = AutoModelForCausalLM.from_pretrained(
save_to,
device_map=torch.accelerator.current_accelerator(),
torch_dtype=torch.bfloat16,
<span class="hljs-comment"># quantization_config=quantization_config,</span>
)
generated_ids = reloaded_model.generate(**inputs, max_new_tokens=<span class="hljs-number">128</span>, temperature=<span class="hljs-number">0</span>)
output_text = tokenizer.batch_decode(
generated_ids, skip_special_tokens=<span class="hljs-literal">True</span>, clean_up_tokenization_spaces=<span class="hljs-literal">False</span>
)
<span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;Response:&quot;</span>, output_text[<span class="hljs-number">0</span>][<span class="hljs-built_in">len</span>(prompt) :])
<span class="hljs-keyword">assert</span>(correct_output_text == output_text)<!----></pre></div><!----> <!--[1--><h2 class="relative group"><a id="serialization" 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="#serialization"><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><!---->Chuẩn hóa<!----></span></h2><!--]--><!----> <p>Việc lưu mô hình đã lượng tử hóa bằng <code>save_pretrained</code> (ở định dạng <a href="https://huggingface.co/docs/safetensors/en/index" rel="nofollow">safetensors</a>) chỉ được hỗ trợ cho torchao &gt;= v0.15. Với bất kỳ phiên bản nào thấp hơn, bạn chỉ có thể lưu thủ công dưới dạng checkpoint <code>.bin</code> không an toàn bằng <a href="https://docs.pytorch.org/docs/stable/generated/torch.save.html" rel="nofollow">torch.save</a>.</p> <div class="flex space-x-2 items-center my-1.5 mr-8 h-7 !pl-0 -mx-3 md:mx-0"><!--[--><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd border-gray-800 bg-black dark:bg-gray-700 text-white">lưu-cục-bộ</div><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd text-gray-500 cursor-pointer opacity-90 hover:text-gray-700 dark:hover:text-gray-200 hover:shadow-sm">push-to-huggingface-hub</div><!--]--></div> <div class="language-select"><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> Đã sao chép</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-comment"># torchao &gt;= 0.15</span>
output_dir = <span class="hljs-string">&quot;llama3-8b-int4wo-128&quot;</span>
quantized_model.save_pretrained(<span class="hljs-string">&quot;llama3-8b-int4wo-128&quot;</span>)<!----></pre></div><!----></div><!----> <div hidden=""><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> Đã sao chép</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-comment"># torchao &gt;= 0.15</span>
USER_ID = <span class="hljs-string">&quot;your_huggingface_user_id&quot;</span>
REPO_ID = <span class="hljs-string">&quot;llama3-8b-int4wo-128&quot;</span>
quantized_model.push_to_hub(<span class="hljs-string">f&quot;<span class="hljs-subst">{USER_ID}</span>/llama3-8b-int4wo-128&quot;</span>)
tokenizer.push_to_hub(<span class="hljs-string">f&quot;<span class="hljs-subst">{USER_ID}</span>/llama3-8b-int4wo-128&quot;</span>)<!----></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> Đã sao chép</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-comment"># torchao &lt; 0.15 -&gt; unsafe serialization</span>
filename = <span class="hljs-string">&quot;llama3-8b-int4wo-128/pytorch_model.bin&quot;</span>
torch.save(quantized_model.state_dict(), filename)<!----></pre></div><!----><!----></div><!----><!----></div><!----> <!--[1--><h2 class="relative group"><a id="loading-quantized-models" 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-quantized-models"><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><!---->Tải các mô hình đã lượng tử hóa<!----></span></h2><!--]--><!----> <p>Việc tải một mô hình đã lượng tử hóa phụ thuộc vào phương án lượng tử hóa. Đối với các phương án lượng tử hóa như int8 và float8, bạn có thể lượng tử hóa mô hình trên bất kỳ thiết bị nào và cũng có thể tải nó lên bất kỳ thiết bị nào. Ví dụ dưới đây minh họa việc lượng tử hóa một mô hình trên CPU và sau đó tải nó lên CUDA hoặc XPU.</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> Đã sao chép</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> TorchAoConfig, AutoModelForCausalLM, AutoTokenizer
<span class="hljs-keyword">from</span> torchao.quantization <span class="hljs-keyword">import</span> Int8WeightOnlyConfig
quant_config = Int8WeightOnlyConfig(group_size=<span class="hljs-number">128</span>)
quantization_config = TorchAoConfig(quant_type=quant_config)
<span class="hljs-comment"># Load and quantize the model</span>
quantized_model = AutoModelForCausalLM.from_pretrained(
<span class="hljs-string">&quot;meta-llama/Llama-3.1-8B-Instruct&quot;</span>,
dtype=<span class="hljs-string">&quot;auto&quot;</span>,
device_map=<span class="hljs-string">&quot;cpu&quot;</span>,
quantization_config=quantization_config
)
<span class="hljs-comment"># save the quantized model</span>
output_dir = <span class="hljs-string">&quot;llama-3.1-8b-torchao-int8&quot;</span>
quantized_model.save_pretrained(output_dir)
<span class="hljs-comment"># reload the quantized model</span>
reloaded_model = AutoModelForCausalLM.from_pretrained(
output_dir,
device_map=<span class="hljs-string">&quot;auto&quot;</span>,
dtype=torch.bfloat16
)
tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">&quot;meta-llama/Llama-3.1-8B-Instruct&quot;</span>)
input_text = <span class="hljs-string">&quot;What are we having for dinner?&quot;</span>
input_ids = tokenizer(input_text, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>).to(reloaded_model.device.<span class="hljs-built_in">type</span>)
output = reloaded_model.generate(**input_ids, max_new_tokens=<span class="hljs-number">10</span>)
<span class="hljs-built_in">print</span>(tokenizer.decode(output[<span class="hljs-number">0</span>], skip_special_tokens=<span class="hljs-literal">True</span>))
<!----></pre></div><!----> <p>Đối với int4, mô hình chỉ có thể được nạp trên cùng thiết bị mà nó đã được lượng tử hóa vì bố cục là cụ thể cho thiết bị đó. Ví dụ bên dưới minh họa việc lượng tử hóa và nạp mô hình trên CPU.</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> Đã sao chép</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> TorchAoConfig, AutoModelForCausalLM, AutoTokenizer
<span class="hljs-keyword">from</span> torchao.quantization <span class="hljs-keyword">import</span> Int4WeightOnlyConfig
<span class="hljs-keyword">from</span> torchao.quantization.quantize_.workflows <span class="hljs-keyword">import</span> Int4PackingFormat
quant_config = Int4WeightOnlyConfig(group_size=<span class="hljs-number">128</span>, int4_packing_format=Int4PackingFormat.PLAIN_INT32)
quantization_config = TorchAoConfig(quant_type=quant_config)
<span class="hljs-comment"># Load and quantize the model</span>
quantized_model = AutoModelForCausalLM.from_pretrained(
<span class="hljs-string">&quot;meta-llama/Llama-3.1-8B-Instruct&quot;</span>,
dtype=<span class="hljs-string">&quot;auto&quot;</span>,
device_map=<span class="hljs-string">&quot;cpu&quot;</span>,
quantization_config=quantization_config
)
<span class="hljs-comment"># save the quantized model</span>
output_dir = <span class="hljs-string">&quot;llama-3.1-8b-torchao-int4-cpu&quot;</span>
quantized_model.save_pretrained(output_dir)
<span class="hljs-comment"># reload the quantized model</span>
reloaded_model = AutoModelForCausalLM.from_pretrained(
output_dir,
device_map=<span class="hljs-string">&quot;cpu&quot;</span>,
dtype=torch.bfloat16
)
tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">&quot;meta-llama/Llama-3.1-8B-Instruct&quot;</span>)
input_text = <span class="hljs-string">&quot;What are we having for dinner?&quot;</span>
input_ids = tokenizer(input_text, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>).to(reloaded_model.device.<span class="hljs-built_in">type</span>)
output = reloaded_model.generate(**input_ids, max_new_tokens=<span class="hljs-number">10</span>)
<span class="hljs-built_in">print</span>(tokenizer.decode(output[<span class="hljs-number">0</span>], skip_special_tokens=<span class="hljs-literal">True</span>))
<!----></pre></div><!----> <!--[1--><h2 class="relative group"><a id="resources" 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="#resources"><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><!---->Tài nguyên<!----></span></h2><!--]--><!----> <p>Để có cái nhìn rõ hơn về hiệu năng dự kiến, hãy xem <a href="https://github.com/pytorch/ao/tree/main/torchao/quantization#benchmarks" rel="nofollow">benchmarks</a> cho các mô hình khác nhau với các backend CUDA và XPU. Bạn cũng có thể chạy đoạn mã bên dưới để tự benchmark một mô hình.</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> Đã sao chép</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">from</span> torch._inductor.utils <span class="hljs-keyword">import</span> do_bench_using_profiling
<span class="hljs-keyword">from</span> typing <span class="hljs-keyword">import</span> <span class="hljs-type">Callable</span>
<span class="hljs-keyword">def</span> <span class="hljs-title function_">benchmark_fn</span>(<span class="hljs-params">func: <span class="hljs-type">Callable</span>, *args, **kwargs</span>) -&gt; <span class="hljs-built_in">float</span>:
<span class="hljs-string">&quot;&quot;&quot;Thin wrapper around do_bench_using_profiling&quot;&quot;&quot;</span>
no_args = <span class="hljs-keyword">lambda</span>: func(*args, **kwargs)
time = do_bench_using_profiling(no_args)
<span class="hljs-keyword">return</span> time * <span class="hljs-number">1e3</span>
MAX_NEW_TOKENS = <span class="hljs-number">1000</span>
<span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;int4wo-128 model:&quot;</span>, benchmark_fn(quantized_model.generate, **input_ids, max_new_tokens=MAX_NEW_TOKENS, cache_implementation=<span class="hljs-string">&quot;static&quot;</span>))
bf16_model = AutoModelForCausalLM.from_pretrained(model_name, device_map=<span class="hljs-string">&quot;auto&quot;</span>, dtype=torch.bfloat16)
output = bf16_model.generate(**input_ids, max_new_tokens=<span class="hljs-number">10</span>, cache_implementation=<span class="hljs-string">&quot;static&quot;</span>) <span class="hljs-comment"># auto-compile</span>
<span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;bf16 model:&quot;</span>, benchmark_fn(bf16_model.generate, **input_ids, max_new_tokens=MAX_NEW_TOKENS, cache_implementation=<span class="hljs-string">&quot;static&quot;</span>))<!----></pre></div><!----> <blockquote class="tip"><p>Để đạt hiệu suất tốt nhất, bạn có thể sử dụng các cài đặt được khuyến nghị bằng cách gọi <code>torchao.quantization.utils.recommended_inductor_config_setter()</code></p></blockquote> <p>Tham khảo <a href="https://github.com/pytorch/ao/tree/main/torchao/quantization#other-available-quantization-techniques" rel="nofollow">Các kỹ thuật lượng hóa khác có sẵn</a> để xem thêm các ví dụ và tài liệu.</p> <!--[1--><h2 class="relative group"><a id="issues" 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="#issues"><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><!---->Các vấn đề<!----></span></h2><!--]--><!----> <p>Nếu bạn gặp bất kỳ vấn đề nào với tích hợp Transformers, vui lòng mở một issue trên kho <a href="https://github.com/huggingface/transformers/issues" rel="nofollow">Transformers</a>. Đối với các vấn đề liên quan trực tiếp đến torchao, vui lòng mở một issue trên kho <a href="https://github.com/pytorch/ao/issues" rel="nofollow">torchao</a>.</p> <a class="!text-gray-400 !no-underline text-sm flex items-center not-prose mt-4" href="https://github.com/huggingface/transformers/blob/main/docs/source/en/quantization/torchao.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_dqakyn = {
base: "/docs/transformers/main/en",
assets: "/docs/transformers/main/en"
};
const element = document.currentScript.parentElement;
Promise.all([
import("/docs/transformers/main/en/_app/immutable/entry/start.CDsgEKDZ.js"),
import("/docs/transformers/main/en/_app/immutable/entry/app.DxuVi3jG.js")
]).then(([kit, app]) => {
kit.start(app, element, {
node_ids: [0, 49],
data: [null,null],
form: null,
error: null
});
});
}
</script>

Xet Storage Details

Size:
96 kB
·
Xet hash:
0a25051d301bfb94ad4b5d083dbd90d446a05e6e3eac5755d235ca26bcaba24c

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