Buckets:
| <meta charset="utf-8" /><meta name="hf:doc:metadata" content="{"title":"Непрерывная пакетная обработка","local":"continuous-batching","sections":[{"title":"generate_batch","local":"generatebatch","sections":[],"depth":2},{"title":"ContinuousBatchingManager","local":"continuousbatchingmanager","sections":[{"title":"Остановка менеджера","local":"shutting-down-the-manager","sections":[],"depth":3},{"title":"Добавление запросов","local":"adding-requests","sections":[],"depth":3},{"title":"Параметры выборки для каждого запроса","local":"per-request-sampling-parameters","sections":[],"depth":3},{"title":"Получение результатов","local":"retrieving-results","sections":[],"depth":3},{"title":"Потоковая передача","local":"streaming","sections":[],"depth":3}],"depth":2},{"title":"ContinuousBatchingConfig","local":"continuousbatchingconfig","sections":[{"title":"Размер страницы кэша KV","local":"kv-cache-page-size","sections":[],"depth":3},{"title":"Размер батча префилла","local":"prefill-batch-size","sections":[],"depth":3},{"title":"Ограничения по пакетам и планированию","local":"batch-and-scheduling-limits","sections":[],"depth":3},{"title":"Логарифмические вероятности","local":"log-probabilities","sections":[],"depth":3},{"title":"CUDA-графы","local":"cuda-graphs","sections":[],"depth":3},{"title":"Асинхронная пакетная обработка","local":"async-batching","sections":[],"depth":3},{"title":"Компиляция","local":"compilation","sections":[],"depth":3},{"title":"Быстрый путь декодирования","local":"decode-fast-path","sections":[],"depth":3},{"title":"Размещение на CPU","local":"cpu-offloading","sections":[],"depth":3},{"title":"Тайм-аут параллелизма тензоров","local":"tensor-parallel-timeout","sections":[],"depth":3},{"title":"Кэширование префиксов","local":"prefix-caching","sections":[],"depth":3}],"depth":2},{"title":"Выберите бэкенд внимания","local":"choose-an-attention-backend","sections":[],"depth":2},{"title":"Параллелизм тензоров","local":"tensor-parallelism","sections":[],"depth":2},{"title":"Внимание со скользящим окном","local":"sliding-window-attention","sections":[],"depth":2},{"title":"Дальнейшие шаги","local":"next-steps","sections":[],"depth":2}],"depth":1}"/> | |
| <link href="/docs/transformers/main/en/_app/immutable/entry/start.DYIO-UII.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/chunks/DSYYoqAA.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/chunks/BovLmb3z.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/entry/app.D2_KizbC.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/chunks/WyYpyc-L.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/chunks/DYBfcveH.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.ByO_lNbj.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/chunks/ZtBhN-Ei.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/nodes/38.Dfv3MLej.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/chunks/D-dvW--N.js" rel="modulepreload"> | |
| <!--12vztif--><meta name="hf:doc:metadata" content="{"title":"Continuous batching","local":"continuous-batching","sections":[{"title":"generate_batch","local":"generatebatch","sections":[],"depth":2},{"title":"ContinuousBatchingManager","local":"continuousbatchingmanager","sections":[{"title":"Shutting down the manager","local":"shutting-down-the-manager","sections":[],"depth":3},{"title":"Adding requests","local":"adding-requests","sections":[],"depth":3},{"title":"Per-request sampling parameters","local":"per-request-sampling-parameters","sections":[],"depth":3},{"title":"Retrieving results","local":"retrieving-results","sections":[],"depth":3},{"title":"Streaming","local":"streaming","sections":[],"depth":3}],"depth":2},{"title":"ContinuousBatchingConfig","local":"continuousbatchingconfig","sections":[{"title":"KV cache page size","local":"kv-cache-page-size","sections":[],"depth":3},{"title":"Prefill batch size","local":"prefill-batch-size","sections":[],"depth":3},{"title":"Batch and scheduling limits","local":"batch-and-scheduling-limits","sections":[],"depth":3},{"title":"Log probabilities","local":"log-probabilities","sections":[],"depth":3},{"title":"CUDA graphs","local":"cuda-graphs","sections":[],"depth":3},{"title":"Async batching","local":"async-batching","sections":[],"depth":3},{"title":"Compilation","local":"compilation","sections":[],"depth":3},{"title":"Decode fast path","local":"decode-fast-path","sections":[],"depth":3},{"title":"CPU offloading","local":"cpu-offloading","sections":[],"depth":3},{"title":"Tensor parallel timeout","local":"tensor-parallel-timeout","sections":[],"depth":3},{"title":"Prefix caching","local":"prefix-caching","sections":[],"depth":3}],"depth":2},{"title":"Choose an attention backend","local":"choose-an-attention-backend","sections":[],"depth":2},{"title":"Tensor parallelism","local":"tensor-parallelism","sections":[],"depth":2},{"title":"Sliding window attention","local":"sliding-window-attention","sections":[],"depth":2},{"title":"Next steps","local":"next-steps","sections":[],"depth":2}],"depth":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="continuous-batching" 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="#continuous-batching"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Непрерывная пакетная обработка<!----></span></h1><!--]--><!----> <p>Continuous batching максимизирует использование GPU, динамически пересобирая батч на каждом шаге генерации. По мере завершения запросов новые добавляются в батч немедленно, а не ждут завершения всего батча. GPU остаётся загруженным, а пропускная способность — высокой.</p> <blockquote class="tip"><p>Для производственных развёртываний используйте <a href="./serve-cli/serving_optims#continuous-batching">transformers serve</a>. Он основан на <a href="/docs/transformers/main/ru/main_classes/text_generation#transformers.ContinuousBatchingManager">ContinuousBatchingManager</a> и предоставляет HTTP-эндпоинт, совместимый с OpenAI.</p></blockquote> <!--[1--><h2 class="relative group"><a id="generatebatch" 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="#generatebatch"><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><!---->generate_batch<!----></span></h2><!--]--><!----> <p>Поддержка непрерывного батчинга (continuous batching) реализована через <a href="/docs/transformers/main/ru/main_classes/text_generation#transformers.ContinuousMixin.generate_batch">generate_batch()</a>. Передайте список токенизированных промптов и получите результаты для всех из них по завершении обработки. <code>generate_batch</code> управляет планированием внутри и блокируется до завершения всех запросов.</p> <p>Для сценариев обслуживания и потоковой передачи используйте <a href="#continuousbatchingmanager">ContinuousBatchingManager</a> напрямую для управления запросами.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">import</span> torch | |
| <span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForCausalLM, AutoTokenizer | |
| <span class="hljs-keyword">from</span> transformers.generation <span class="hljs-keyword">import</span> ContinuousBatchingConfig, GenerationConfig | |
| model = AutoModelForCausalLM.from_pretrained( | |
| <span class="hljs-string">"Qwen/Qwen3-4B"</span>, | |
| attn_implementation=<span class="hljs-string">"flash_attention_2"</span>, | |
| device_map=<span class="hljs-string">"auto"</span>, | |
| dtype=torch.bfloat16, | |
| ) | |
| tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">"Qwen/Qwen3-4B"</span>) | |
| prompts = [ | |
| <span class="hljs-string">"What's up?"</span>, | |
| <span class="hljs-string">"Name a cat breed."</span>, | |
| <span class="hljs-string">"Write a detailed history of quantum mechanics."</span>, | |
| ] | |
| inputs = [tokenizer.encode(p) <span class="hljs-keyword">for</span> p <span class="hljs-keyword">in</span> prompts] | |
| generation_config = GenerationConfig( | |
| max_new_tokens=<span class="hljs-number">64</span>, | |
| eos_token_id=tokenizer.eos_token_id, | |
| ) | |
| outputs = model.generate_batch(inputs=inputs, generation_config=generation_config) | |
| <span class="hljs-keyword">for</span> request_id, output <span class="hljs-keyword">in</span> outputs.items(): | |
| text = tokenizer.decode(output.generated_tokens, skip_special_tokens=<span class="hljs-literal">True</span>) | |
| <span class="hljs-built_in">print</span>(<span class="hljs-string">f"[<span class="hljs-subst">{request_id}</span>] <span class="hljs-subst">{text}</span>"</span>)<!----></pre></div><!----> <!--[1--><h2 class="relative group"><a id="continuousbatchingmanager" 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="#continuousbatchingmanager"><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><!---->ContinuousBatchingManager<!----></span></h2><!--]--><!----> <p><a href="/docs/transformers/main/ru/main_classes/text_generation#transformers.ContinuousBatchingManager">ContinuousBatchingManager</a> запускает фоновый поток и позволяет отправлять запросы и получать результаты независимо друг от друга. На каждом шаге генерации он проверяет завершённые запросы и планирует новые для добавления в батч. Это полезно для потоковой передачи, обслуживания в реальном времени или отправки запросов по мере их поступления.</p> <p>Используйте <a href="/docs/transformers/main/ru/main_classes/text_generation#transformers.ContinuousMixin.continuous_batching_context_manager">continuous_batching_context_manager()</a> для безопасного запуска и остановки менеджера. В примере ниже представлены входные данные переменной длины. Как только самый короткий промпт завершается, он покидает батч, а более длинные промпты продолжают генерацию. При статическом батчинге пришлось бы дополнять все промпты до одинаковой длины. Continuous batching освобождает завершённый промпт, позволяя сразу начать обработку следующего.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">with</span> model.continuous_batching_context_manager(generation_config=generation_config) <span class="hljs-keyword">as</span> manager: | |
| manager.add_request( | |
| input_ids=tokenizer.encode(<span class="hljs-string">"Write a detailed history of quantum mechanics."</span>), | |
| request_id=<span class="hljs-string">"long"</span>, | |
| max_new_tokens=<span class="hljs-number">512</span>, | |
| ) | |
| manager.add_request( | |
| input_ids=tokenizer.encode(<span class="hljs-string">"What's up?"</span>), | |
| request_id=<span class="hljs-string">"short_0"</span>, | |
| max_new_tokens=<span class="hljs-number">32</span>, | |
| ) | |
| manager.add_request( | |
| input_ids=tokenizer.encode(<span class="hljs-string">"Name a cat breed."</span>), | |
| request_id=<span class="hljs-string">"short_1"</span>, | |
| max_new_tokens=<span class="hljs-number">32</span>, | |
| ) | |
| <span class="hljs-keyword">for</span> result <span class="hljs-keyword">in</span> manager: | |
| text = tokenizer.decode(result.generated_tokens, skip_special_tokens=<span class="hljs-literal">True</span>) | |
| <span class="hljs-built_in">print</span>(<span class="hljs-string">f"[<span class="hljs-subst">{result.request_id}</span>] <span class="hljs-subst">{text}</span>"</span>)<!----></pre></div><!----> <p>Вы также можете вызвать <a href="/docs/transformers/main/ru/main_classes/text_generation#transformers.ContinuousMixin.init_continuous_batching">init_continuous_batching()</a>, чтобы самостоятельно управлять жизненным циклом.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!---->manager = model.init_continuous_batching(generation_config=generation_config) | |
| manager.start() | |
| <span class="hljs-comment"># submit and retrieve requests...</span><!----></pre></div><!----> <!--[2--><h3 class="relative group"><a id="shutting-down-the-manager" 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="#shutting-down-the-manager"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Остановка менеджера<!----></span></h3><!--]--><!----> <p>Менеджер запускает фоновый поток и управляет распределёнными ресурсами. Завершение работы происходит в два этапа, что позволяет выбрать, как обрабатывать незавершённые задачи.</p> <p>Вызовите <a href="/docs/transformers/main/ru/main_classes/text_generation#transformers.ContinuousBatchingManager.stop">stop()</a>, чтобы остановить фоновый поток. По умолчанию менеджер прекращает приём новых запросов и ожидает завершения всех запросов в очереди и активных запросов перед выходом из потока.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!---->manager.stop()<!----></pre></div><!----> <p>Передайте <code>hard_stop=True</code>, чтобы немедленно прекратить выполнение ожидающих задач. Очередные и активные запросы завершаются с ошибкой <code>RuntimeError</code> вместо нормального завершения.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!---->manager.stop(hard_stop=<span class="hljs-literal">True</span>)<!----></pre></div><!----> <p>После вызова <code>stop</code> методы <a href="/docs/transformers/main/ru/main_classes/text_generation#transformers.ContinuousBatchingManager.add_request">add_request()</a> и <a href="/docs/transformers/main/ru/main_classes/text_generation#transformers.ContinuousBatchingManager.add_requests">add_requests()</a> отклоняют новые запросы и записывают предупреждение в журнал. Вы можете снова вызвать <code>start</code>, чтобы запустить новую сессию генерации с тем же менеджером.</p> <p>Вызовите <a href="/docs/transformers/main/ru/main_classes/text_generation#transformers.ContinuousBatchingManager.destroy">destroy()</a>, чтобы освободить распределённые ресурсы. <code>destroy</code> сначала останавливает менеджер, если он ещё работает, после чего перезапустить его невозможно. Используйте этот метод, когда работа с непрерывным батчингом завершена на всё время жизни процесса.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!---->manager.destroy()<!----></pre></div><!----> <p><a href="/docs/transformers/main/ru/main_classes/text_generation#transformers.ContinuousMixin.continuous_batching_context_manager">continuous_batching_context_manager()</a> управляет этим процессом. При выходе он вызывает <code>stop</code>, а <code>destroy</code> — только если вы не передали <code>persistent_manager=True</code> для кэширования менеджера в модели для следующей сессии.</p> <!--[2--><h3 class="relative group"><a id="adding-requests" 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="#adding-requests"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Добавление запросов<!----></span></h3><!--]--><!----> <p><a href="/docs/transformers/main/ru/main_classes/text_generation#transformers.ContinuousBatchingManager.add_request">add_request()</a> отправляет один запрос. Укажите <code>request_id</code> или позвольте менеджеру сгенерировать его автоматически.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!---->manager.add_request(input_ids=input_ids, request_id=<span class="hljs-string">"my_request"</span>)<!----></pre></div><!----> <p><a href="/docs/transformers/main/ru/main_classes/text_generation#transformers.ContinuousBatchingManager.add_requests">add_requests()</a> отправляет пакет запросов сразу. Он автоматически сортирует входные данные, чтобы максимизировать попадания в кэш префиксов, когда включено разделение блоков.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!---->manager.add_requests(inputs=inputs)<!----></pre></div><!----> <p>Отмените запрос с помощью <a href="/docs/transformers/main/ru/main_classes/text_generation#transformers.ContinuousBatchingManager.cancel_request">cancel_request()</a>.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!---->manager.cancel_request(request_id=<span class="hljs-string">"my_request"</span>)<!----></pre></div><!----> <!--[2--><h3 class="relative group"><a id="per-request-sampling-parameters" 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-request-sampling-parameters"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Параметры выборки для каждого запроса<!----></span></h3><!--]--><!----> <p>Включите <code>per_request_processors</code>, чтобы применять <code>temperature</code>, <code>top_k</code> и <code>top_p</code> независимо для каждого запроса в рамках одного прохода, что позволяет использовать разные параметры выборки для разных запросов (например, креативные выводы с высокой температурой и точные выводы с низкой температурой).</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!---->cb_config = ContinuousBatchingConfig(per_request_processors=<span class="hljs-literal">True</span>) | |
| <span class="hljs-comment"># each request gets its own sampling parameters</span> | |
| manager.add_request(input_ids=inputs_a, temperature=<span class="hljs-number">0.9</span>, top_p=<span class="hljs-number">0.95</span>) | |
| manager.add_request(input_ids=inputs_b, temperature=<span class="hljs-number">0.1</span>, top_k=<span class="hljs-number">10</span>)<!----></pre></div><!----> <p>Каждый параметр в <a href="/docs/transformers/main/ru/main_classes/text_generation#transformers.GenerationConfig">GenerationConfig</a> должен иметь значение, отличное от значения по умолчанию, чтобы соответствующий logits-процессор был создан во время выполнения. Например, установите <code>temperature</code> в значение, отличное от <code>None</code> или <code>1</code>, чтобы обеспечить управление температурой для каждого запроса. Запросы с температурой <code>1</code> по-прежнему можно создавать впоследствии.</p> <!--[2--><h3 class="relative group"><a id="retrieving-results" 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="#retrieving-results"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Получение результатов<!----></span></h3><!--]--><!----> <p>Итерируйте по менеджеру, чтобы получать результаты по мере их поступления.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">for</span> result <span class="hljs-keyword">in</span> manager: | |
| <span class="hljs-built_in">print</span>(tokenizer.decode(result.generated_tokens, skip_special_tokens=<span class="hljs-literal">True</span>))<!----></pre></div><!----> <p><a href="/docs/transformers/main/ru/main_classes/text_generation#transformers.ContinuousBatchingManager.get_result">get_result()</a> получает следующий результат из очереди вывода. Передайте <code>request_id</code>, чтобы отфильтровать конкретный запрос. Если следующий результат в очереди не совпадает, он возвращается в очередь, а метод возвращает <code>None</code>.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-comment"># next available result</span> | |
| result = manager.get_result() | |
| <span class="hljs-comment"># filter for a specific request</span> | |
| result = manager.get_result(request_id=<span class="hljs-string">"my_request"</span>)<!----></pre></div><!----> <!--[2--><h3 class="relative group"><a id="streaming" 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="#streaming"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Потоковая передача<!----></span></h3><!--]--><!----> <p>Установите <code>streaming=True</code> в запросе, затем используйте <a href="/docs/transformers/main/ru/main_classes/text_generation#transformers.ContinuousBatchingManager.request_id_iter">request_id_iter()</a>, чтобы перебирать частичные результаты по мере генерации токенов.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">from</span> transformers.generation.continuous_batching <span class="hljs-keyword">import</span> RequestStatus | |
| manager.add_request(input_ids=input_ids, request_id=<span class="hljs-string">"streamed"</span>, streaming=<span class="hljs-literal">True</span>) | |
| <span class="hljs-keyword">for</span> chunk <span class="hljs-keyword">in</span> manager.request_id_iter(request_id=<span class="hljs-string">"streamed"</span>): | |
| token = tokenizer.decode(chunk.generated_tokens[-<span class="hljs-number">1</span>:], skip_special_tokens=<span class="hljs-literal">True</span>) | |
| <span class="hljs-built_in">print</span>(token, end=<span class="hljs-string">""</span>, flush=<span class="hljs-literal">True</span>) | |
| <span class="hljs-keyword">if</span> chunk.status == RequestStatus.FINISHED: | |
| <span class="hljs-keyword">break</span><!----></pre></div><!----> <!--[1--><h2 class="relative group"><a id="continuousbatchingconfig" 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="#continuousbatchingconfig"><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><!---->ContinuousBatchingConfig<!----></span></h2><!--]--><!----> <p><a href="/docs/transformers/main/ru/main_classes/continuous_batching#transformers.ContinuousBatchingConfig">ContinuousBatchingConfig</a> управляет KV-кэшем, планированием, CUDA-графиками, использованием памяти и другими параметрами. Передайте его в <code>generate_batch</code> или <a href="/docs/transformers/main/ru/main_classes/text_generation#transformers.ContinuousMixin.init_continuous_batching">init_continuous_batching()</a> с аргументом <code>continuous_batching_config</code>, отдельно от <a href="/docs/transformers/main/ru/main_classes/text_generation#transformers.GenerationConfig">GenerationConfig</a>. Эти два конфигурационных объекта описывают разные вещи. <a href="/docs/transformers/main/ru/main_classes/text_generation#transformers.GenerationConfig">GenerationConfig</a> ориентирован на модель и содержит параметры выборки и остановки, тогда как <a href="/docs/transformers/main/ru/main_classes/continuous_batching#transformers.ContinuousBatchingConfig">ContinuousBatchingConfig</a> ориентирован на аппаратное обеспечение и содержит параметры памяти и планирования.</p> <blockquote class="warning"><p>Назначение <code>continuous_batching_config</code> в <a href="/docs/transformers/main/ru/main_classes/text_generation#transformers.GenerationConfig">GenerationConfig</a> устарело, вызывает <code>FutureWarning</code> и будет удалено в v5.19.</p></blockquote> <p>По умолчанию <code>max_batch_tokens</code> равно <code>8192</code>, ограничено доступной памятью GPU и никогда не опускается ниже <code>256</code>, а <code>num_blocks</code> заполняет оставшуюся память. Используйте таблицу ниже, чтобы подобрать подходящие параметры.</p> <table><thead><tr><th>Возможность</th><th>Память</th><th>Пропускная способность</th><th>Задержка</th></tr></thead><tbody><tr><td><code>max_memory_percent</code> / <code>page_size</code></td><td>✓ управляет бюджетом KV</td><td></td><td></td></tr><tr><td><code>max_batch_tokens</code></td><td>↑ более крупные входные буферы</td><td>✓ более крупные батчи префилла</td><td>✓ TTFT при ограничении на prefill</td></tr><tr><td><code>scheduler</code></td><td></td><td>✓ политика планирования</td><td>✓ TTFT</td></tr><tr><td>CUDA-графы</td><td>↑ хранилище графа</td><td>✓ меньшие накладные расходы на диспетчеризацию</td><td>✓</td></tr><tr><td>Асинхронная пакетная обработка</td><td>↑ ~2× буферы ввода-вывода</td><td>✓ перекрывает CPU/GPU</td><td></td></tr><tr><td>Компиляция</td><td>↑ только warmup-time</td><td>✓ более быстрые прямые проходы</td><td>✓</td></tr><tr><td>Быстрый путь декодирования</td><td>↑ таблица блоков на запрос</td><td>✓ более быстрые шаги только декодирования</td><td>✓</td></tr><tr><td>Размещение на CPU</td><td>↑ закрепленная память CPU</td><td>✓ пропускает некоторые повторные префиллы</td><td></td></tr><tr><td>Кэширование префиксов</td><td>↓ общие блоки KV</td><td>✓ пропускает избыточный prefill</td><td>✓ TTFT</td></tr><tr><td>Страничная аттенция</td><td>↓ без фрагментации</td><td>✓ динамический состав батча</td><td></td></tr><tr><td>Скользящее окно</td><td>↓ ограниченный KV на слой</td><td></td><td></td></tr><tr><td>Процессоры для каждого запроса</td><td></td><td>✓ смешанные параметры выборки в рамках одной пачки</td><td></td></tr><tr><td><code>max_requests_per_batch</code></td><td>↓ ограничивает буфер логитов</td><td>✓ ограничивает размер батча</td><td></td></tr><tr><td><code>safety_margin</code></td><td></td><td></td><td>✓ защищает задержку декодирования</td></tr></tbody></table> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">from</span> transformers.generation <span class="hljs-keyword">import</span> ContinuousBatchingConfig | |
| cb_config = ContinuousBatchingConfig( | |
| max_memory_percent=<span class="hljs-number">0.8</span>, | |
| page_size=<span class="hljs-number">256</span>, <span class="hljs-comment"># KV cache page size in tokens</span> | |
| scheduler_type=<span class="hljs-string">"fifo"</span>, <span class="hljs-comment"># "fifo" or "prefill_first"</span> | |
| ) | |
| outputs = model.generate_batch( | |
| inputs=inputs, | |
| generation_config=generation_config, | |
| continuous_batching_config=cb_config, | |
| )<!----></pre></div><!----> <!--[2--><h3 class="relative group"><a id="kv-cache-page-size" 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="#kv-cache-page-size"><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><!---->Размер страницы кэша KV<!----></span></h3><!--]--><!----> <p><code>page_size</code> определяет, сколько токенов KV хранит полная страница внимания для одного слоя. Значение должно быть не менее <code>4</code>, иначе при инициализации будет выброшено исключение <code>ValueError</code>. Значение по умолчанию <code>256</code> подходит для большинства задач.</p> <blockquote class="note"><p>Параметр <code>block_size</code> устарел и заменён на <code>page_size</code>.</p></blockquote> <p>Увеличение размера страницы сокращает накладные расходы на управление памятью, но приводит к потере места, если последовательность обрывается посередине страницы. Меньшие страницы тратят меньше места, но требуют больше накладных расходов. Как правило, настраивать <code>page_size</code> не нужно. Если в вашей рабочей нагрузке много коротких запросов, попробуйте уменьшить значение. Если же есть несколько очень длинных запросов, попробуйте увеличить значение. О том, как страницы, блоки и фрагменты соотносятся между собой, см. в разделе <a href="./continuous_batching_architecture#memory-management">Управление памятью</a>.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!---->cb_config = ContinuousBatchingConfig(page_size=<span class="hljs-number">128</span>)<!----></pre></div><!----> <!--[2--><h3 class="relative group"><a id="prefill-batch-size" 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="#prefill-batch-size"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Размер батча префилла<!----></span></h3><!--]--><!----> <p><code>max_batch_tokens</code> задаёт бюджет токенов для одного прохода вперёд, то есть максимальное количество query-токенов, которые модель обрабатывает за один раз. Увеличение бюджета позволяет упаковать больше токенов промпта в каждый prefill, что повышает пропускную способность prefill и снижает время до первого токена в нагрузках с преобладанием промптов. Планировщик распределяет промпты, превышающие бюджет, по нескольким шагам. См. <a href="./continuous_batching_architecture#chunked-prefill">chunked prefill</a> для описания обработки промптов, превышающих бюджет.</p> <p>По умолчанию <code>max_batch_tokens</code> равно <code>8192</code>. Значение ограничивается доступной памятью GPU, чтобы входные тензоры в рамках батча не вытесняли KV-кэш, и никогда не опускается ниже <code>256</code>. На GPU с небольшим количеством свободной памяти это ограничение снижает значение ниже <code>8192</code>.</p> <p><code>max_batch_tokens</code> и <code>num_blocks</code> используют один и тот же бюджет памяти, поэтому они находятся в обратной зависимости друг от друга. Увеличение бюджета токенов выделяет более крупные входные буферы и оставляет меньше блоков кэша KV для одновременных или длинных запросов. Увеличивайте <code>max_batch_tokens</code>, чтобы повысить пропускную способность префилла, если у вас есть свободная память, и уменьшайте его, чтобы освободить память для дополнительных блоков KV или избежать ошибок нехватки памяти.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!---->cb_config = ContinuousBatchingConfig(max_batch_tokens=<span class="hljs-number">16384</span>)<!----></pre></div><!----> <!--[2--><h3 class="relative group"><a id="batch-and-scheduling-limits" 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="#batch-and-scheduling-limits"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Ограничения по пакетам и планированию<!----></span></h3><!--]--><!----> <p><code>max_requests_per_batch</code> ограничивает количество запросов, обрабатываемых за один проход. Модель формирует тензор logits, размер которого определяется числом токенов в батче и размером словаря, а затем он приводится к <code>fp32</code> для выборки, что удваивает занимаемую память. Для каждого запроса требуется предсказание только одного следующего токена, поэтому меньшее ограничение позволяет уменьшить размер этого тензора и избежать ошибок нехватки памяти в батчах с преобладанием prefill и большими словарями. По умолчанию значение устанавливается равным числу отправленных промптов, с запасным значением 1024, после чего оно ограничивается в соответствии с <code>max_batch_tokens</code> и <code>num_blocks</code>.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!---->cb_config = ContinuousBatchingConfig(max_requests_per_batch=<span class="hljs-number">256</span>)<!----></pre></div><!----> <p><code>safety_margin</code> резервирует долю свободного кэша для активных запросов. Когда свободная ёмкость падает ниже <code>safety_margin</code> (доли от общего размера кэша), планировщик перестаёт принимать новые prefill-запросы и продолжает только декодирование уже запущенных запросов. Это позволяет завершить активную работу в приоритете перед началом новых запросов, что защищает задержку декодирования и откладывает <a href="./continuous_batching_architecture#offloading">offloading</a>. Значение должно находиться в диапазоне от <code>0</code> до <code>1</code>, где <code>0</code> отключает резервирование.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!---->cb_config = ContinuousBatchingConfig(safety_margin=<span class="hljs-number">0.15</span>)<!----></pre></div><!----> <p>Значение по умолчанию зависит от планировщика. Для планировщика FIFO оно равно <code>0.15</code>, а для <code>prefill_first</code> — <code>0.0</code>. См. раздел <a href="./continuous_batching_architecture#admission">Admission</a>, чтобы узнать, как запас взаимодействует с планированием.</p> <!--[2--><h3 class="relative group"><a id="log-probabilities" 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="#log-probabilities"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Логарифмические вероятности<!----></span></h3><!--]--><!----> <p><a href="/docs/transformers/main/ru/main_classes/continuous_batching#transformers.ContinuousBatchingConfig">ContinuousBatchingConfig</a> возвращает лог-вероятность каждого сгенерированного токена, если <code>return_logprobs=True</code>. Это полезно для RL, где logprobs являются входными данными для некоторых циклов обучения.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!---->cb_config = ContinuousBatchingConfig(return_logprobs=<span class="hljs-literal">True</span>) | |
| <span class="hljs-comment"># generate_batch()</span> | |
| <span class="hljs-keyword">for</span> request_id, output <span class="hljs-keyword">in</span> outputs.items(): | |
| <span class="hljs-keyword">for</span> token_id, log_prob <span class="hljs-keyword">in</span> <span class="hljs-built_in">zip</span>(output.generated_tokens, output.logprobs): | |
| token = tokenizer.decode([token_id]) | |
| <span class="hljs-built_in">print</span>(<span class="hljs-string">f"<span class="hljs-subst">{token}</span> | logprob: <span class="hljs-subst">{log_prob}</span>"</span>)<!----></pre></div><!----> <!--[2--><h3 class="relative group"><a id="cuda-graphs" 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="#cuda-graphs"><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><!---->CUDA-графы<!----></span></h3><!--]--><!----> <p>CUDA-графы устраняют накладные расходы на диспетчеризацию на CPU, записывая граф выполнения на GPU один раз и воспроизводя его для батчей с совпадающими формами. Включите их явно с помощью <code>use_cuda_graph=True</code>.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!---->cb_config = ContinuousBatchingConfig(use_cuda_graph=<span class="hljs-literal">True</span>)<!----></pre></div><!----> <p>Когда менеджер активен, он дополняет длины запросов и KV до фиксированных интервалов, чтобы формы повторялись, а графы переиспользовались. Меньшие значения <code>q_padding_interval_size</code> и <code>kv_padding_interval_size</code> снижают потери вычислительных ресурсов на дополнения, но это означает, что графу приходится записывать и хранить больше уникальных форм, что требует больше памяти.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!---->cb_config = ContinuousBatchingConfig( | |
| use_cuda_graph=<span class="hljs-literal">True</span>, | |
| q_padding_interval_size=<span class="hljs-number">64</span>, | |
| kv_padding_interval_size=<span class="hljs-number">16384</span>, | |
| )<!----></pre></div><!----> <!--[2--><h3 class="relative group"><a id="async-batching" 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="#async-batching"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Асинхронная пакетная обработка<!----></span></h3><!--]--><!----> <p>Асинхронное батчинг (Async batching) перекрывает планирование следующего батча на CPU с вычислениями текущего батча на GPU. Для этого требуются CUDA-графы, а объём VRAM, используемый для входных тензоров, примерно удваивается.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!---->cb_config = ContinuousBatchingConfig( | |
| use_cuda_graph=<span class="hljs-literal">True</span>, | |
| use_async_batching=<span class="hljs-literal">True</span>, | |
| )<!----></pre></div><!----> <!--[2--><h3 class="relative group"><a id="compilation" 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="#compilation"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Компиляция<!----></span></h3><!--]--><!----> <p><code>default_compile_level</code> применяет <code>torch.compile</code> к прямым проходам модели. Компиляция обменивает разовые затраты на прогрев на ускорение прямых проходов во время генерации. Более высокие уровни выполняют более агрессивную оптимизацию, что повышает пропускную способность, но увеличивает время прогрева. Держите уровень низким для тестов и итераций бенчмарков, а для длительных сценариев обслуживания, где затраты на прогрев окупаются за множество запросов, повышайте его.</p> <p>Значение уровня варьируется от <code>0</code> до <code>3</code>. Уровень <code>0</code> является значением по умолчанию и полностью пропускает компиляцию.</p> <table><thead><tr><th>Уровень</th><th><code>mode</code></th><th><code>dynamic</code></th><th>Компромисс</th></tr></thead><tbody><tr><td>0</td><td>—</td><td>—</td><td>Компиляция не выполняется (по умолчанию), самый быстрый запуск</td></tr><tr><td>1</td><td><code>default</code></td><td><code>True</code></td><td>Небольшое ускорение, короткая разминка</td></tr><tr><td>2</td><td><code>max-autotune-no-cudagraphs</code></td><td><code>True</code></td><td>Большее ускорение, более длительная разминка</td></tr><tr><td>3</td><td><code>max-autotune-no-cudagraphs</code></td><td><code>False</code></td><td>Максимальная пропускная способность, самая длительная разминка</td></tr></tbody></table> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!---->cb_config = ContinuousBatchingConfig(default_compile_level=<span class="hljs-number">1</span>)<!----></pre></div><!----> <p>Уровень предоставляет конфигурацию по умолчанию <a href="/docs/transformers/main/ru/internal/generation_utils#transformers.CompileConfig">CompileConfig</a> для путей выполнения varlen и decode. Она применяется только к тому пути, для которого не задана явная конфигурация, поэтому <code>varlen_compile_config</code> и <code>decode_compile_config</code> имеют приоритет, если они установлены. В случае использования FlashAttention путь varlen пропускает компиляцию, так как <code>max_length_k</code> вызывает частую перекомпиляцию, поэтому в этом случае уровень влияет только на путь decode.</p> <!--[2--><h3 class="relative group"><a id="decode-fast-path" 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="#decode-fast-path"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Быстрый путь декодирования<!----></span></h3><!--]--><!----> <p>Если пакет содержит только запросы декодирования (один токен запроса на последовательность), менеджер может направить выполнение в ядро <code>flash_attn_with_kvcache</code> вместо ядра переменной длины. Это быстрее, чем путь varlen, поскольку ядро читает и записывает постраничную KV-кэш на месте через таблицу блоков, а не через ручное обновление. Подробности на уровне ядра см. в разделе <a href="./paged_attention">Paged attention</a>.</p> <p>Быстрый путь определяется размером <code>max_blocks_per_request</code>, который задаёт размеры таблицы блоков для каждого запроса. По умолчанию это значение выводится автоматически. Если в менеджере заданы <code>max_prompt_length</code> и <code>max_generated_length</code>, таблица блоков рассчитывается так, чтобы вместить максимальную длину последовательности. В противном случае используется значение по умолчанию (32 блока на запрос).</p> <p>Установите <code>max_blocks_per_request</code> в конкретное значение, чтобы явно задать размер таблицы блоков. Это полезно, если вам известна максимальная длина последовательности для каждого запроса и вы хотите ограничить затраты памяти на таблицу блоков.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!---->cb_config = ContinuousBatchingConfig(max_blocks_per_request=<span class="hljs-number">64</span>)<!----></pre></div><!----> <p>Установите <code>max_blocks_per_request=0</code>, чтобы отключить быстрый путь и заставить каждый батч проходить через ядро varlen. Это восстанавливает поведение по умолчанию до его изменения и полезно, когда быстрый путь недоступен для вашей реализации внимания (менеджер также отключает его автоматически, если базовое ядро не может быть использовано).</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!---->cb_config = ContinuousBatchingConfig(max_blocks_per_request=<span class="hljs-number">0</span>)<!----></pre></div><!----> <p>Быстрый путь опирается на ядро <code>flash_attn_with_kvcache</code>, которое доступно для двух комбинаций устройства и реализации внимания.</p> <table><thead><tr><th>Устройство</th><th><code>attn_implementation</code></th></tr></thead><tbody><tr><td>CUDA</td><td><code>flash_attention_2</code> или <code>flash_attention_3</code></td></tr><tr><td>XPU</td><td><a href="https://huggingface.co/kernels-community/flash-attn2" rel="nofollow">flash_attention_2</a></td></tr></tbody></table> <p>Для любой другой комбинации или в случае, когда ядро не может быть импортировано, менеджер переключается на путь varlen. Предупреждение записывается в журнал только при явном задании <code>max_blocks_per_request</code>.</p> <p>Полное внимание поддерживает таблицы блоков ядра, но скользящее внимание — нет. Если в модели есть хотя бы один слой скользящего внимания, включая гибридные модели, использующие также полное внимание, при инициализации значение <code>max_blocks_per_request</code> принудительно устанавливается в <code>0</code>, а любое ненулевое значение, заданное пользователем, переопределяется. Затем менеджер фиксирует в журнале, что быстрый путь декодирования недоступен, поскольку некоторые типы внимания в модели не поддерживают таблицы блоков ядра.</p> <!--[2--><h3 class="relative group"><a id="cpu-offloading" 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-offloading"><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><!--]--><!----> <p>CPU offloading копирует вытесненные блоки KV-кэша в предварительно выделенный закреплённый буфер CPU, когда GPU KV-кэш заполнен. После того, как в кэше освобождается место, менеджер копирует блоки обратно на GPU и возобновляет запрос без повторного вычисления его промпта и сгенерированных токенов.</p> <p>Установите <code>cpu_offload_space</code> в размер области подкачки на CPU в ГиБ. Значение по умолчанию, <code>0.0</code>, отключает выгрузку на 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> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!---->cb_config = ContinuousBatchingConfig(cpu_offload_space=<span class="hljs-number">8.0</span>)<!----></pre></div><!----> <p>По умолчанию <code>cpu_offload_space_safety_threshold=0.8</code> ограничивает запрашиваемое пространство 80% доступной системной оперативной памяти, если установлен <code>psutil</code>. Установите <code>cpu_offload_space=None</code>, чтобы размер пула подкачки определялся на основе порога безопасности.</p> <!--[2--><h3 class="relative group"><a id="tensor-parallel-timeout" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#tensor-parallel-timeout"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Тайм-аут параллелизма тензоров<!----></span></h3><!--]--><!----> <p>При тензорном параллелизме менеджер создаёт группу CPU-коммуникации для координации отправки запросов, их отмены и завершения работы между рангами. <code>cpu_group_timeout</code> ограничивает время, в течение которого коллективная операция в этой группе может блокироваться, прежде чем процесс завершится с ошибкой. Если один ранг зависает, таймаут не даёт остальным ждать бесконечно.</p> <p>Установите более длительный тайм-аут для рабочих нагрузок, которые редко выполняют коллективные операции, или передайте <code>None</code>, чтобы отключить его.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!---->cb_config = ContinuousBatchingConfig(cpu_group_timeout=<span class="hljs-number">600.0</span>)<!----></pre></div><!----> <!--[2--><h3 class="relative group"><a id="prefix-caching" 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="#prefix-caching"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Кэширование префиксов<!----></span></h3><!--]--><!----> <p>Когда несколько запросов имеют общий префикс, например системный промпт, менеджер повторно использует их блоки KV-кэша вместо повторного вычисления. <code>allow_block_sharing</code> по умолчанию установлено в <code>True</code>. Разделение префикса активно только тогда, когда все типы аллокаторов внимания поддерживают его, поэтому его используют только модели с полным вниманием. Чисто скользящие и гибридные модели отключают его, даже если <code>allow_block_sharing</code> равно <code>True</code>.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!---->cb_config = ContinuousBatchingConfig( | |
| allow_block_sharing=<span class="hljs-literal">True</span>, <span class="hljs-comment"># default</span> | |
| )<!----></pre></div><!----> <!--[1--><h2 class="relative group"><a id="choose-an-attention-backend" 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="#choose-an-attention-backend"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Выберите бэкенд внимания<!----></span></h2><!--]--><!----> <p>Continuous batching поддерживает FlashAttention, SDPA и <code>"paged|eager"</code>. Укажите <code>attn_implementation</code> при загрузке модели.</p> <table><thead><tr><th>Бэкенд</th><th><code>attn_implementation</code></th><th>Требования</th></tr></thead><tbody><tr><td>FlashAttention 2</td><td><code>“flash_attention_2”</code></td><td>пакет <code>flash-attn</code> или <code>kernels</code></td></tr><tr><td>FlashAttention 3</td><td><code>“flash_attention_3”</code></td><td><code>flash-attn-3</code> или пакет <code>kernels</code></td></tr><tr><td>SDPA (нативная реализация PyTorch)</td><td><code>“sdpa”</code></td><td>None</td></tr><tr><td>Eager</td><td><code>“paged|eager”</code></td><td>None</td></tr></tbody></table> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!---->model = AutoModelForCausalLM.from_pretrained( | |
| <span class="hljs-string">"Qwen/Qwen3-4B"</span>, | |
| attn_implementation=<span class="hljs-string">"flash_attention_2"</span>, | |
| device_map=<span class="hljs-string">"auto"</span>, | |
| dtype=torch.bfloat16, | |
| )<!----></pre></div><!----> <p>Continuous batching работает быстрее с FlashAttention, чем с eager или SDPA, в основном потому, что FlashAttention не требует маски внимания. Если модель поддерживает FlashAttention, модель, загруженная с <code>"eager"</code> или <code>"sdpa"</code>, переключается на FlashAttention 3, а если FlashAttention 3 не установлен — на FlashAttention 2, и выводится предупреждение. Если ни одна из версий не установлена, бэкенд не меняется.</p> <p>Чтобы сохранить eager или SDPA, например при тестировании, установите <code>auto_switch_to_flash=False</code> в <a href="/docs/transformers/main/ru/main_classes/continuous_batching#transformers.ContinuousBatchingConfig">ContinuousBatchingConfig</a>. Если бэкенд остаётся <code>"eager"</code>, continuous batching выполняется в режиме <code>"paged|eager"</code>.</p> <!--[1--><h2 class="relative group"><a id="tensor-parallelism" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#tensor-parallelism"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Параллелизм тензоров<!----></span></h2><!--]--><!----> <p>Для моделей, которые слишком велики, чтобы поместиться на одном GPU, распределите веса по устройствам с помощью тензорного параллелизма. Укажите количество устройств с помощью <code>DistributedConfig(tp_size=N)</code>. Непрерывная пакетная обработка (continuous batching) читает размер тензорного параллелизма из модели, чтобы определить размер страничной KV-кэши для каждого шарда. Список поддерживаемых архитектур и описание работы шардирования приведены в разделе <a href="./tensor_parallelism">Тензорный параллелизм</a>.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">import</span> torch | |
| <span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForCausalLM, AutoTokenizer, DistributedConfig | |
| <span class="hljs-keyword">from</span> transformers.generation <span class="hljs-keyword">import</span> ContinuousBatchingConfig, GenerationConfig | |
| distributed_config = DistributedConfig(tp_size=<span class="hljs-number">4</span>) | |
| model = AutoModelForCausalLM.from_pretrained( | |
| <span class="hljs-string">"Qwen/Qwen3-32B"</span>, | |
| attn_implementation=<span class="hljs-string">"flash_attention_2"</span>, | |
| distributed_config=distributed_config, | |
| ) | |
| tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">"Qwen/Qwen3-32B"</span>) | |
| inputs = [tokenizer.encode(p) <span class="hljs-keyword">for</span> p <span class="hljs-keyword">in</span> [<span class="hljs-string">"What's up?"</span>, <span class="hljs-string">"Name a cat breed."</span>]] | |
| generation_config = GenerationConfig(max_new_tokens=<span class="hljs-number">64</span>, eos_token_id=tokenizer.eos_token_id) | |
| outputs = model.generate_batch(inputs=inputs, generation_config=generation_config)<!----></pre></div><!----> <p>Запустите скрипт с помощью <code>torchrun</code>, установив <code>--nproc-per-node</code> в количество GPU, на которые вы хотите распределить шарды.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-shell "><!---->torchrun --nproc-per-node 4 cb_tp.py<!----></pre></div><!----> <p>Размер тензорного параллелизма должен делить <code>num_key_value_heads</code> модели (проверьте конфигурацию модели). В противном случае paged cache будет вызывать ошибку при запуске, поэтому выберите подходящее значение <code>--nproc-per-node</code>.</p> <blockquote class="warning"><p>Не задавайте <code>device_map</code> вместе с <code>distributed_config</code>. Эти параметры конфликтуют, так как <code>device_map</code> размещает целые модули на конкретных GPU, тогда как тензорное параллелизм распределяет те же параметры по всем GPU.</p></blockquote> <!--[1--><h2 class="relative group"><a id="sliding-window-attention" 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="#sliding-window-attention"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Внимание со скользящим окном<!----></span></h2><!--]--><!----> <p>Модели со скользящим окном внимания (Mistral, Gemma 2) работают с непрерывным батчингом. Скользящие слои используют <code>SlidingAttentionCacheAllocator</code>, который сохраняет только фиксированное окно последних токенов, перерабатывая небольшой набор страниц. Тип внимания определяется по <code>layer_types</code> или <code>sliding_window</code> модели, а не по <a href="/docs/transformers/main/ru/main_classes/continuous_batching#transformers.ContinuousBatchingConfig">ContinuousBatchingConfig</a>.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoConfig, AutoModelForCausalLM | |
| config = AutoConfig.from_pretrained(<span class="hljs-string">"google/gemma-2-2b"</span>) | |
| config.sliding_window = <span class="hljs-number">4096</span> | |
| model = AutoModelForCausalLM.from_pretrained( | |
| <span class="hljs-string">"google/gemma-2-2b"</span>, | |
| config=config, | |
| attn_implementation=<span class="hljs-string">"sdpa"</span>, | |
| device_map=<span class="hljs-string">"auto"</span>, | |
| dtype=torch.bfloat16, | |
| )<!----></pre></div><!----> <p><a href="#prefix-caching">Кэширование префиксов</a> и <a href="#decode-fast-path">быстрый путь декодирования</a> отключаются при наличии скользящего внимания, включая гибридные модели, которые также содержат слои полного внимания.</p> <!--[1--><h2 class="relative group"><a id="next-steps" 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="#next-steps"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Дальнейшие шаги<!----></span></h2><!--]--><!----> <ul><li>Статья <a href="https://huggingface.co/blog/continuous_batching" rel="nofollow">Continuous batching blog post</a> рассматривает кэширование KV, chunked prefill и динамическое планирование с приведением цифр бенчмарков производительности.</li> <li>Для более подробного изучения работы системы непрерывного батчинга см. документацию <a href="./continuous_batching_architecture">Архитектура непрерывного батчинга</a>.</li></ul> <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/continuous_batching.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_1m6yd5j = { | |
| 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.DYIO-UII.js"), | |
| import("/docs/transformers/main/en/_app/immutable/entry/app.D2_KizbC.js") | |
| ]).then(([kit, app]) => { | |
| kit.start(app, element, { | |
| node_ids: [0, 38], | |
| data: [null,null], | |
| form: null, | |
| error: null | |
| }); | |
| }); | |
| } | |
| </script> | |
Xet Storage Details
- Size:
- 129 kB
- Xet hash:
- d8bfbf727ff2985f1094e3597053b85ef7076ee8ac1c8eade9844e0320a870e7
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.