{
  "@context": "https://schema.org",
  "@id": "https://aggr.aymericbeaumet.com/items/huggingface-co/2025-09-11-tricks-from-openai-gpt-oss-you-index-pointing-at-the-viewer/#webpage",
  "@type": [
    "WebPage",
    "ArchiveComponent"
  ],
  "articleBody": "OpenAI recently released their [GPT-OSS series of models](https://huggingface.co/collections/openai/gpt-oss-68911959590a1634ba11c7a4). The models feature some novel techniques like MXFP4 quantization, efficient kernels, a brand new chat format, and more. To enable the release of gpt-oss through `transformers`, we have upgraded the [library](https://github.com/huggingface/transformers/) considerably. The updates make it very efficient to **load**, **run**, and **fine-tune** the models.\n\nIn this blog post, we talk about all the upgrades in-depth, and how they become part of the transformers toolkit so other models (current and future) can benefit from them. Providing clean implementations of new methods in transformers also allows the community to quickly understand and adopt them. Frameworks such as [`MLX`](https://github.com/ml-explore/mlx-lm/pull/354), [`llama.cpp`](https://github.com/ggml-org/llama.cpp/discussions/15396) or [`vLLM`](https://docs.vllm.ai/projects/recipes/en/latest/OpenAI/GPT-OSS.html) can use the transformers code as a reference to build their own implementations.\n\nFor this release, we worked on:\n\n- [Zero-build Kernels, downloadable from the Hub](https://huggingface.co/blog/faster-transformers#zero-build-kernels-downloadable-from-the-hub)\n- [MXFP4 Quantization](https://huggingface.co/blog/faster-transformers#mxfp4-quantization)\n- [Tensor Parallelism](https://huggingface.co/blog/faster-transformers#tensor-parallelism)\n- [Expert Parallelism](https://huggingface.co/blog/faster-transformers#expert-parallelism)\n- [Dynamic Sliding Window Layer & Cache](https://huggingface.co/blog/faster-transformers#dynamic-sliding-window-layer--cache)\n- [Continuous Batching & Paged Attention](https://huggingface.co/blog/faster-transformers#continuous-batching--paged-attention)\n- [Load larger models faster](https://huggingface.co/blog/faster-transformers#load-larger-models-faster)\n\n> Best part: Most of these features should work across all major models within `transformers`!\n\n## Zero-build Kernels, downloadable from the Hub\n\nA kernel is a ***specialized***, compact program that runs on accelerators to execute tasks like matrix multiplications, activations, or normalizations. In eager PyTorch, operations trigger individual kernels sequentially, which is straightforward but can incur extra memory transfers and launch overheads. PyTorch 2.0's `torch.compile` with backends like `TorchInductor` addresses this by automatically fusing and optimizing kernels, delivering `2–10×` performance gains.\n\nIn addition, the community has created custom kernels for frequent combinations of operations, *not just individual PyTorch ops like matmul*. For example, Flash Attention was created to optimize the critical attention block that defines the transformers architecture, and is present in many models including most LLMs. By carefully combining all the attention operations inside a single kernel, memory transfers are minimized, memory use is reduced, and speedups can be achieved.\n\nThe problem is that all these various kernels are available in separate libraries, which creates a dependency bloat if they were to be added to the transformers library. Furthermore, these kernels are not just Python code, they consist of low-level cuda code, glued together with C++ and exposed through a Python layer. This means they have to be compiled in the target system, which in turn requires whatever build system is required by each kernel library.\n\nThe [kernels package](https://huggingface.co/blog/hello-hf-kernels) solves this problem by downloading pre-built binaries of supported kernels from the Hub. You just indicate the kernel you want to use, and `kernels` will look for a version compatible with your system and download it on first use.\n\n### Custom Kernels for GPT-OSS\n\n[GPT-OSS](https://github.com/huggingface/transformers/blob/0f1b128d3359a26bd18be99c26d7f04fb3cba914/src/transformers/models/gpt_oss/modeling_gpt_oss.py), a Mixture of Experts (MoE) model, is a big user of Kernels from the Hub. It leverages several custom kernels:\n\n1. Liger RMSNorm, used as [`@use_kernel_forward_from_hub(\"RMSNorm\")`](https://github.com/huggingface/transformers/blob/0f1b128d3359a26bd18be99c26d7f04fb3cba914/src/transformers/models/gpt_oss/modeling_gpt_oss.py#L46)\\`\n2. Megablocks MoE kernels: [`@use_kernel_forward_from_hub(\"MegaBlocksMoeMLP\")`](https://github.com/huggingface/transformers/blob/0f1b128d3359a26bd18be99c26d7f04fb3cba914/src/transformers/models/gpt_oss/modular_gpt_oss.py#L160)\n3. Flash Attention 3 with [support for attention sinks](https://huggingface.co/kernels-community/vllm-flash-attn3).\n4. MXFP4 triton kernels (covered [later](https://huggingface.co/blog/faster-transformers#mxfp4-in-transformers))\n\nLet's take a look at the first two ones.\n\nBehind the scenes, the decorators (1 and 2) simply point to community-contributed kernels. For example, `RMSNorm` comes from [`liger_kernels`](https://huggingface.co/kernels-community/liger_kernels), while the `MegaBlocksMoeMLP` kernel comes from [`megablocks`](https://huggingface.co/kernels-community/megablocks). Depending on your device (CUDA or ROCm) and whether you’re training or running inference, the right kernel is pulled in automatically.\n\nThis design is both **specific and general**: the RMSNorm liger kernels are already being reused across multiple models, and the MoE kernel could be applied to future MoEs as well.\n\nBecause `kernels` pulls code from the Hub, you have to opt-in to this feature by passing `use_kernels=True` in your model instantiation, as shown below. We enable `INFO` logging in the example so you can easily verify that downloadable kernels are in use.\n\n> These kernels are not compatible with `mxfp4`, so inference will happen in `bfloat16` if you use them. Please, benchmark your system for the best combination in memory and throughput that suits your project!\n\n```python\nfrom transformers import AutoTokenizer, AutoModelForCausalLM\n\nimport logging\nlogging.basicConfig(level=logging.INFO)\n\nmodel_id = \"openai/gpt-oss-20b\"\ntokenizer = AutoTokenizer.from_pretrained(model_id)\n\nmodel = AutoModelForCausalLM.from_pretrained(\n    model_id,\n    dtype=\"auto\",\n    device_map=\"auto\",\n    use_kernels=True,\n)\n```\n\nRunning a quick generation yields log messages like\n\n```shell\nINFO:root:Using layer `LigerRMSNorm` from repo `kernels-community/liger_kernels`\nINFO:root:Using layer `MegaBlocksMoeMLP` from repo `kernels-community/megablocks`\n```\n\n**Figure 1** shows that, in the system we tested, these kernels work best for larger batch sizes. We always recommend to benchmark any performance-related changes as closely to your production conditions as possible.\n\n| [![benchmark with and without kernels](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/benchmark-kernels-with-without.png)](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/benchmark-kernels-with-without.png) |\n| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| Figure 1: Benchmarking results of custom kernels                                                                                                                                                                                                                                                                               |\n\n> You can explore and play with the benchmarking script [here](https://huggingface.co/datasets/ariG23498/faster-transformers-scripts/blob/main/benchmark-kernels-with-without.py)\n\n### Flash Attention 3\n\nOpenAI gpt-oss models use *attention sinks*, which improves quality and facilitates the use of longer contexts. The vLLM team added this feature to the latest version of Flash Attention (Flash Attention 3), and the resulting custom kernel is available [on the Hub](https://huggingface.co/kernels-community/vllm-flash-attn3). Currently, this kernel is compatible with the Hopper architecture. If you have one, this is the way to enable it:\n\n```diff\nmodel = AutoModelForCausalLM.from_pretrained(\n    model_id,\n    dtype=\"auto\",\n    device_map=\"auto\",\n+    # Flash Attention with Sinks\n+    attn_implementation=\"kernels-community/vllm-flash-attn3\",\n)\n```\n\n## MXFP4 Quantization\n\nLarge language models are memory-hungry. Quantization reduces memory footprint by storing weights (and sometimes activations) in lower-precision formats. For reference, `FP32` uses 32 bits per number and `BF16` uses 16. By reducing bit width, we trade some precision for smaller models and faster memory movement.\n\nIf you want a visual primer on quantization trade-offs, [Maarten Grootendorst’s](https://huggingface.co/MaartenGr) article is excellent: [*A Visual Guide to Quantization*](https://newsletter.maartengrootendorst.com/p/a-visual-guide-to-quantization).\n\n### What is MXFP4\n\n| [![explanation of mxfp4 format](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/mxfp4.png)](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/mxfp4.png) |\n| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| Figure 2: The E2M1 format used in the MXFP4 format                                                                                                                                                                                                                    |\n\n`MXFP4` is a 4-bit floating format with E2M1 layout: 1 sign bit, 2 exponent bits, and 1 mantissa bit, as shown in **Figure 2**. On its own, E2M1 is very coarse. MXFP4 compensates with **blockwise scaling**:\n\n- Vectors are grouped into blocks of 32 elements.\n- Each block stores a shared scale that restores dynamic range when dequantizing.\n- Inside each block, 4-bit values represent numbers relative to that scale.\n\nThis blockwise scheme lets `MXFP4` keep range while using very few bits. In practice, GPT-OSS 20B fits in roughly `16 GB` of VRAM and GPT-OSS 120B fits in roughly `80 GB` when `MXFP4` is active, which is the difference between “cannot load” and “can run on a single GPU.” The catch is that matrix multiplies now have to respect block scales. Doing this efficiently at scale requires dedicated kernels.\n\n### MXFP4 in `transformers`\n\n`transformers` now includes native support for MXFP4, leveraging optimized `triton` (MXFP4) kernels for enhanced performance. This builds on the community-driven kernel distribution [discussed earlier](https://huggingface.co/blog/faster-transformers#zero-build-kernels-downloadable-from-the-hub), utilizing pre-compiled kernels from the Hub to simplify deployment.\n\nKey implementation details:\n\n- Quantizer logic: Found in the [MXFP4 quantizer file](https://github.com/huggingface/transformers/blob/0997c2f2ab08c32c8e2f90aaad06e29a7108535b/src/transformers/quantizers/quantizer_mxfp4.py), this handles the core quantization process for MXFP4.\n- Integration hooks: The [MXFP4 integration file](https://github.com/huggingface/transformers/blob/0997c2f2ab08c32c8e2f90aaad06e29a7108535b/src/transformers/integrations/mxfp4.py) enables seamless use of MXFP4 within the transformers framework.\n\nTo check if a model supports `MXFP4`, inspect its configuration:\n\n```py\nfrom transformers import GptOssConfig\n\nmodel_id = \"openai/gpt-oss-120b\"\ncfg = GptOssConfig.from_pretrained(model_id)\nprint(cfg.quantization_config)\n\n# Example output:\n# {\n#   'modules_to_not_convert': [\n#     'model.layers.*.self_attn',\n#     'model.layers.*.mlp.router',\n#     'model.embed_tokens',\n#     'lm_head'\n#   ],\n#   'quant_method': 'mxfp4'\n# }\n```\n\nIf `'quant_method': 'mxfp4'` is present, the model will automatically use the MXFP4 pathway with Triton kernels when supported.\n\n> Thanks to this [pull request](https://github.com/huggingface/transformers/pull/40176), you can fine-tune gpt-oss models and save them directly to the Hub in MXFP4 format, streamlining deployment with optimized performance.\n\n### Requirements and fallbacks\n\nTo run `MXFP4` on GPU you need:\n\n1. `accelerate`, `kernels`, and `triton>=3.4` installed. Note that `Pytorch 2.8` already comes with `triton 3.4`, so you only need to manually install triton if using `Pytorch 2.7`.\n2. NVIDIA GPU with compute capability `≥ 7.5`. This goes all the way back to Tesla, so you can run `gpt-oss-20b` on the free tiers of Google Colab and Kaggle, and on many consumer GPUs.\n\nIf these constraints are not met, `transformers` falls back to a higher-precision path (`bfloat16` is used by default), which requires about 4× the memory of MXFP4.\n\nThe [snippet](https://huggingface.co/datasets/ariG23498/faster-transformers-scripts/blob/main/memory-requirements-quantized-vs-dequantized.py) loads GPT-OSS twice on CUDA: once with `Mxfp4Config(dequantize=True)` (memory intensive) and once in the default quantized path (memory efficient). **Figure 3** shows the amount of used VRAM after each load so you can visualize the savings.\n\n| [![memory used with quantized vs dequantized models](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/quantization.png)](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/quantization.png) |\n| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| Figure 3: Memory requirements for the quantized and dequantized models                                                                                                                                                                                                                                   |\n\n### Kernels for MXFP4\n\nEfficient `MXFP4` requires kernels that understand 32-element blocks and their scales during GEMMs and fused ops. This is where **Kernels from the Hub** comes in again. `transformers` automatically pulls in the `MXFP4`-aware Triton kernels from the community repository when you load a model that needs them. The repository will appear in your local cache and will be used during the forward pass. For the `MXFP4` kernels one does not need to use the `use_kernels=True` parameter like before, it is set to default in `transformers`.\n\nQuick sanity check with the Hugging Face cache CLI, after running `gpt-oss-20b` on a GPU compatible with the triton MXFP4 kernels:\n\n```shell\nhf cache scan\n```\n\nSample output:\n\n```shell\nREPO ID                          REPO TYPE SIZE ON DISK\n-------------------------------- --------- ------------\nkernels-community/triton_kernels model           536.2K\nopenai/gpt-oss-20b               model            13.8G\n```\n\nThis indicates the MXFP4 kernels were fetched and are available for execution.\n\nLet's run some benchmarks and see how well the MXFP4 kernels perform. In **Figure 4**, we see that the `MXFP4` kernels are even better than the custom MoE and RMSNorm kernels for larger batches.\n\n| [![benchmark mxfp4 kernels](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/benchmark-mxfp4.png)](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/benchmark-mxfp4.png) |\n| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| Figure 4: MXFP4 kernel benchmark                                                                                                                                                                                                                                                      |\n\n> You can explore and play with the benchmarking script [here](https://huggingface.co/datasets/ariG23498/faster-transformers-scripts/blob/main/benchmark-mxfp4-kernels.py)\n\n## Tensor Parallelism\n\n| [![explaining tensor parallelism](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/tgi/TP.png)](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/tgi/TP.png) |\n| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| Figure 5: Explanation of tensor parallelism.                                                                                                                                                                            |\n\nTensor Parallelism (TP) splits **tensors inside a layer** across multiple GPUs (as shown in **Figure 5**). Each GPU multiplies its shard in parallel, and then partial results are collected using all-gather or all-reduce operations. This reduces per-GPU memory and keeps all GPUs working on the **same layer**, which improves throughput as sequence length or batch size grow. TP is communication-intensive and generally works best on a **single machine with fast intra-node links**.\n\n### What this enables in `transformers`\n\n`transformers` implements TP directly in `from_pretrained`. You can start with the predefined plan:\n\n```python\n# run with: torchrun --nproc-per-node 4 tp_gpt_oss.py\nimport torch\nfrom transformers import PreTrainedTokenizerFast, GptOssForCausalLM\n\nmodel_id = \"openai/gpt-oss-120b\"\ntokenizer = PreTrainedTokenizerFast.from_pretrained(model_id)\nmodel = GptOssForCausalLM.from_pretrained(\n    model_id,\n    tp_plan=\"auto\", # built in TP support\n    dtype=\"auto\",\n).eval()\n\nmessages = [\n    {\"role\": \"system\", \"content\": \"Be concise.\"},\n    {\"role\": \"user\", \"content\": \"Explain KV caching briefly.\"},\n]\ninputs = tokenizer.apply_chat_template(\n    messages,\n    add_generation_prompt=True,\n    return_tensors=\"pt\",\n    return_dict=True,\n    reasoning_effort=\"low\",\n).to(model.device)\n\nwith torch.inference_mode():\n    generations = model.generate(**inputs, max_new_tokens=128)\n\nprint(tokenizer.decode(generations[0][inputs[\"input_ids\"].shape[-1]:]))\n```\n\nIf you don’t have the infrastructure to run the above, you can just spawn a process on our GPUs using [Hugging Face Jobs](https://huggingface.co/docs/huggingface_hub/en/guides/jobs)!\n\n```bash\nhf jobs run --detach --flavor l4x4 ghcr.io/astral-sh/uv:debian /bin/bash -c \\\n  \"uv venv .venv --python 3.12 && \\\n  source .venv/bin/activate && \\\n  uv pip install --upgrade torch numpy transformers accelerate triton kernels && \\\n  wget https://huggingface.co/datasets/ariG23498/distributed/raw/main/tp_gpt_oss.py && \\\n  torchrun --nproc-per-node=4 tp_gpt_oss.py\"\n```\n\n> [`hf jobs`](https://huggingface.co/docs/huggingface_hub/guides/jobs) is available for all Hugging Face PRO & Enterprise users.\n\nUnder the hood, `tp_plan=\"auto\"` selects a predefined sharding recipe for each layer and wires the necessary [collectives](https://huggingface.co/spaces/nanotron/ultrascale-playbook?section=a0:_parallel_programming_crash_course). You can inspect the active plan with `print(model._tp_plan)` if you want to verify what is being sharded.\n\n### When to reach for TP\n\nUse TP when the model is too large for one GPU and you want **parallel compute**, not only memory placement. TP tends to scale throughput with more GPUs, especially for long sequences or larger batches.\n\n> If you are curious about how TP differs from `device_map=\"auto\"` (memory placement), this short [Stack Overflow answer](https://stackoverflow.com/questions/78852192/choose-available-gpu-devices-with-device-map) explains the distinction and when to use each.\n\nTo learn more about TP, here are two must-read resources:\n\n- [`transformers` guide](https://huggingface.co/docs/transformers/en/perf_infer_gpu_multi): Tensor parallelism, supported models, plans, and extension points.\n- [Ultra-Scale Playbook](https://huggingface.co/spaces/nanotron/ultrascale-playbook?section=tensor_parallelism): background on TP and its relationship to other parallelism modes.\n\n## Expert Parallelism\n\nExpert Parallelism (EP) shards **experts inside MoE layers** across GPUs. Each token is routed to one or a few experts, so only those experts run their feed-forward pass. Since experts are independent MLPs, we can place different experts on different ranks and exchange only the hidden states for the routed tokens. This keeps the matrix multiplies intact on each rank and replaces tensor slicing with routing and collectives.\n\nRun with multiple processes using `torchrun`. EP is enabled via the distributed configuration and works with GPT-OSS MoE layers out of the box in transformers.\n\n```python\n# run with: torchrun --nproc-per-node 4 ep_gpt_oss.py\nimport torch\nfrom transformers import PreTrainedTokenizerFast, GptOssForCausalLM\nfrom transformers.distributed import DistributedConfig\n\nmodel_id = \"openai/gpt-oss-120b\"\ntokenizer = PreTrainedTokenizerFast.from_pretrained(model_id)\nmodel = GptOssForCausalLM.from_pretrained(\n    model_id,\n    distributed_config=DistributedConfig(enable_expert_parallel=True), # enabling EP\n    dtype=\"auto\",\n).eval()\n\nmessages = [\n    {\"role\": \"system\", \"content\": \"Be concise.\"},\n    {\"role\": \"user\", \"content\": \"Explain KV caching briefly.\"},\n]\ninputs = tokenizer.apply_chat_template(\n    messages,\n    add_generation_prompt=True,\n    return_tensors=\"pt\",\n    return_dict=True,\n    reasoning_effort=\"low\",\n).to(model.device)\n\nwith torch.inference_mode():\n    generations = model.generate(**inputs, max_new_tokens=128)\n\nprint(tokenizer.decode(generations[0][inputs[\"input_ids\"].shape[-1]:]))\n```\n\nHere is how you would run using `hf jobs`\n\n```bash\nhf jobs run --detach --flavor l4x4 ghcr.io/astral-sh/uv:debian /bin/bash -c \\\n  \"uv venv .venv --python 3.12 && \\\n  source .venv/bin/activate && \\\n  uv pip install --upgrade torch numpy transformers accelerate triton kernels && \\\n  wget https://huggingface.co/datasets/ariG23498/distributed/raw/main/ep_gpt_oss.py && \\\n  torchrun --nproc-per-node=4 ep_gpt_oss.py\"\n```\n\n> When you enable Expert Parallelism, Tensor Parallelism is also activated. This means you enjoy the best of both worlds!\n\n## Dynamic Sliding Window Layer & Cache\n\nMany recent LLMs use *sliding window* attention, or a combination of sliding and global attention layers, as a means to save memory and reduce those expensive quadratic matmuls that grow with sequence length. However, the dynamic KV cache implementation in transformers used to continue to allocate space according to sequence length, without looking at the individual attention layers. You could always optimize memory using compilation (meaning, fixed shapes), but that's a separate scenario altogether.\n\n`transformers` now has a [**`DynamicSlidingWindowLayer`**](https://github.com/huggingface/transformers/blob/64ae6e6b1de2c6822a53be46aba9db68f75ec595/src/transformers/cache_utils.py#L165) and a *config‑aware* [`DynamicCache`](https://github.com/huggingface/transformers/blob/64ae6e6b1de2c6822a53be46aba9db68f75ec595/src/transformers/cache_utils.py#L959). If the model config declares sliding‑window or hybrid attention (both sliding and global attention layers are used), the cache **stops growing past the window** for the sliding layers. If you don’t pass the config, behavior stays as before (full, ever‑growing KV as sequence length grows).\n\nFor models that only use sliding window layers, such as Mistral 7B, cache memory stops growing when the sequence reaches the window size (4096, in this case). This makes sense, because the sliding layers can't look past the previous 4K tokens anyway.\n\n[![mistral cache behaviour comparison](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/mistral-dynamic-cache-with-config.png)](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/mistral-dynamic-cache-with-config.png)\n\nOpenAI gpt-oss alternates between sliding and global attention layers, which results in total KV cache memory being *halved*, as we'll see, as sequence length increases. This provides us with:\n\n- **Much lower KV‑cache memory** for models with sliding or hybrid attention (e.g. GPT‑OSS). Cache growth plateaus once the window is reached (e.g., 4K for Mistral; 128 for GPT‑OSS sliding layers), instead of scaling linearly with total generated tokens. ([GitHub](https://github.com/huggingface/transformers/pull/40039), [Transformers](https://huggingface.co/docs/transformers/en/model_doc/mistral))\n- **Speed/latency wins** on long prompts/long generations: smaller KV tensors mean lighter attention reads/writes and less memory bandwidth pressure, especially after the window is hit. (This is the central motivation behind sliding‑window/hybrid LLMs.) ([AI21](https://www.ai21.com/blog/rise-of-hybrid-llms/), [vLLM Blog](https://blog.vllm.ai/2025/08/05/gpt-oss.html))\n\n### How to use it\n\nThe optimized cache is set by default, that means **you don't have to make any changes** to your existing code. If you want to create the `DynamicCache` explicitly here is how you would do it:\n\n```python\nfrom transformers import AutoModelForCausalLM, AutoTokenizer, DynamicCache\n\nmodel_id = \"openai/gpt-oss-20b\"\n\ntokenizer = AutoTokenizer.from_pretrained(model_id)\nmodel = AutoModelForCausalLM.from_pretrained(\n    model_id,\n    dtype=\"auto\",\n    device_map=\"auto\",\n).eval()\n\nmessages = [\n    {\"role\": \"system\", \"content\": \"Always respond in riddles\"},\n    {\"role\": \"user\", \"content\": \"What is the weather like in Madrid?\"},\n]\n\ninputs = tokenizer.apply_chat_template(\n    messages,\n    add_generation_prompt=True,\n    return_tensors=\"pt\",\n    return_dict=True,\n    reasoning_effort=\"low\",\n).to(model.device)\n\ncache = DynamicCache(config=model.config) # create the cache with the model's config\n\ngenerated = model.generate(\n    **inputs,\n    max_new_tokens=500,\n    past_key_values=cache\n)\nprint(tokenizer.decode(generated[0][inputs[\"input_ids\"].shape[-1]:]))\n```\n\n**Figure 6** showcases how much of a difference it makes for us to use the Dynamic KV Cache with sliding window attention.\n\n| [![sliding window cache](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/dynamic-cache.png)](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/dynamic-cache.png) |\n| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| Figure 6: The memory analysis of dynamic cache with sliding window attention                                                                                                                                                                                                   |\n\n## Continuous Batching & Paged Attention\n\nA typical autoregressive generation process looks like **Figure 7**. You input the prefill tokens, and the model predicts each new token one after the other until it predicts the EOS (End of Sequence) token.\n\n| [![prefilling](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/prefill-tokens.png)](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/prefill-tokens.png) |\n| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| Figure 7: Autoregressive token generation                                                                                                                                                                                                                              |\n\nLet’s see what the generation process looks like when we pass a **batch** of inputs. In **Figure 8** you notice that some generations finish off earlier than the others. This mismatch of length underutilizes the GPUs.\n\n| [![static batching](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/static-batching.png)](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/static-batching.png) |\n| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| Figure 8: Static batching of sequences                                                                                                                                                                                                                                        |\n\nThis type of batching sequences is called *static batching*. While this is simple and easy to understand, it inherently comes with inefficiencies. Only after each sentence is completely generated can we move on to the next batch.\n\nTo bypass this issue, we use **dynamic batching** (also known as *continuous batching*). Instead of waiting for all the generation to finish, we schedule incoming requests to the completed generations. That way, as soon as a generation in a batch is complete, we prefill the batch with the next request. The process looks like **Figure 9**.\n\n| [![continuous batching](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/dynamic-batching.png)](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/dynamic-batching.png) |\n| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| Figure 9: Continuous Batching of sequences                                                                                                                                                                                                                                          |\n\nTransformers supports continuous batching with the `generate_batch` API. This is not meant for production-grade model serving –frameworks like vLLM and SGLang are great at that–, but can be very helpful for evaluation and experimentation. Here is an example [script](https://github.com/huggingface/transformers/blob/0f1b128d3359a26bd18be99c26d7f04fb3cba914/examples/pytorch/continuous_batching_simple.py) that runs CB end to end on `Qwen/Qwen3-4B-Instruct-2507`.\n\nWe have also performed a benchmark between Continuous Batching and Static Batching with 100 samples. In Figure 9, we note that CB is quite faster than SB.\n\n| [![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/cb-sb.png)](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/cb-sb.png) |\n| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| Figure 9: Continuous vs Static Batching Tokens/Second                                                                                                                                                                                      |\n\n> You can play around with the benchmark here: [SB](https://huggingface.co/datasets/ariG23498/faster-transformers-scripts/blob/main/sb-bench.py), [CB](https://huggingface.co/datasets/ariG23498/faster-transformers-scripts/blob/main/cb-bench.py)\n\n## Load larger models faster\n\nWhen you load a large model into your GPU, PyTorch needs to **reserve GPU memory for each layer’s weights**. Each of these requests (per layer) takes time, and for multi-billion-parameter models it can mean **thousands of tiny memory allocations**, adding up to a long wait before the model is ready. Instead of asking the GPU for new memory every single time, it can **hold on to a big chunk once** and then hand out slices from it quickly.\n\nPyTorch allocators can do exactly this. The catch is that the allocator only gets fast *after* you’ve given it some memory to work with. If you don’t “stock the pantry” first, you still end up doing many slow trips to the market. This PR (🎉 [#36380](https://github.com/huggingface/transformers/pull/36380)) taught `transformers` to **pre-stock the pantry** before it starts copying model weights.\n\nIt:\n\n- Looks at the `device_map` (where each layer will live).\n- **Pre-allocates a big enough block on each GPU**.\n- Then, as layers are copied in, they just slot neatly into this pre-reserved space.\n\nYou have to make no changes to your existing code, as this is default behaviour in `transformers`. If you use **`device_map=\"auto\"`** or provide your own device map, your model will now load faster automatically. If you’re running with **Tensor Parallel (`tp_plan=\"auto\"`) and `torchrun`** you also benefit from companion changes that make multi-GPU loading smarter.\n\n## Conclusion\n\n`transformers` moves quickly and it is community-first. The library evolves at the pace of the field because contributors shape it in the open. Pieces added for new models become part of the toolkit and are reused in future integrations.\n\nThis velocity enables day-zero integrations like the GPT-OSS series. As the stack becomes increasingly [PyTorch-first](https://x.com/LysandreJik/status/1933201171130593530), it trims bloat and doubles down on the PyTorch paths that matter in practice. The result is a cleaner core that unlocks new capabilities through community kernels, quantization, and parallelism plans, while also [standardizing model definitions](https://huggingface.co/blog/transformers-model-definition) so that architectures supported in transformers are a reference and extend across the wider ecosystem.\n\nThis post is a one-time snapshot of a process we repeatedly iterate on towards the same direction: serve the needs of the community. To be up to date with the latest additions to transformers, check the [docs](https://huggingface.co/docs/transformers/index) and [release notes](https://github.com/huggingface/transformers/releases). And please, keep sharing your feedback and releasing your models in transformers for the community to enjoy 🤗\n\n## Read More\n\nIf you want to go further into particular topics, here is a list of links that one should visit:\n\n1.  [Hugging Face GPT-OSS Recipes Repository](https://github.com/huggingface/gpt-oss-recipes)\n2.  [Welcome GPT OSS: OpenAI's New Open-Source Model Family](https://huggingface.co/blog/welcome-openai-gpt-oss)\n3.  [OpenAI Cookbook: GPT-OSS Topic](https://cookbook.openai.com/topic/gpt-oss)\n4.  [Transformers Documentation: Distributed Inference on Multiple GPUs](https://huggingface.co/docs/transformers/en/perf_infer_gpu_multi)\n5.  [Matthew Carrigan's X Thread on GPT OSS Innovations](https://x.com/carrigmat/status/1952779877569978797)\n6.  [YouTube Video: OpenAI GPT OSS Announcement](https://www.youtube.com/watch?v=bbkcEiUjehk)\n7.  [Transformers PR #36380: Faster Model Loading on Accelerators](https://github.com/huggingface/transformers/pull/36380)\n8.  [Transformers PR #36335: Update from\\_pretrained for Tensor Parallelism](https://github.com/huggingface/transformers/pull/36335)\n9.  [Transformers PR #40039: New Dynamic Sliding Window Layer and Cache](https://github.com/huggingface/transformers/pull/40039)\n10. [HAN Lab Blog: How Attention Sinks Keep Language Models Stable](https://hanlab.mit.edu/blog/streamingllm)\n",
  "authors": [],
  "captured_at": "2026-10-04T12:50:30.804479567+00:00",
  "category": "ai",
  "content_html": "<p>OpenAI recently released their <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/collections/openai/gpt-oss-68911959590a1634ba11c7a4\">GPT-OSS series of models</a>. The models feature some novel techniques like MXFP4 quantization, efficient kernels, a brand new chat format, and more. To enable the release of gpt-oss through <code>transformers</code>, we have upgraded the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/huggingface/transformers/\">library</a> considerably. The updates make it very efficient to <strong>load</strong>, <strong>run</strong>, and <strong>fine-tune</strong> the models.</p>\n<p>In this blog post, we talk about all the upgrades in-depth, and how they become part of the transformers toolkit so other models (current and future) can benefit from them. Providing clean implementations of new methods in transformers also allows the community to quickly understand and adopt them. Frameworks such as <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/ml-explore/mlx-lm/pull/354\"><code>MLX</code></a>, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/ggml-org/llama.cpp/discussions/15396\"><code>llama.cpp</code></a> or <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://docs.vllm.ai/projects/recipes/en/latest/OpenAI/GPT-OSS.html\"><code>vLLM</code></a> can use the transformers code as a reference to build their own implementations.</p>\n<p>For this release, we worked on:</p>\n<ul>\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/blog/faster-transformers#zero-build-kernels-downloadable-from-the-hub\">Zero-build Kernels, downloadable from the Hub</a></li>\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/blog/faster-transformers#mxfp4-quantization\">MXFP4 Quantization</a></li>\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/blog/faster-transformers#tensor-parallelism\">Tensor Parallelism</a></li>\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/blog/faster-transformers#expert-parallelism\">Expert Parallelism</a></li>\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/blog/faster-transformers#dynamic-sliding-window-layer--cache\">Dynamic Sliding Window Layer &amp; Cache</a></li>\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/blog/faster-transformers#continuous-batching--paged-attention\">Continuous Batching &amp; Paged Attention</a></li>\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/blog/faster-transformers#load-larger-models-faster\">Load larger models faster</a></li>\n</ul>\n<blockquote>\n<p>Best part: Most of these features should work across all major models within <code>transformers</code>!</p>\n</blockquote>\n<h2>Zero-build Kernels, downloadable from the Hub</h2>\n<p>A kernel is a <em><strong>specialized</strong></em>, compact program that runs on accelerators to execute tasks like matrix multiplications, activations, or normalizations. In eager PyTorch, operations trigger individual kernels sequentially, which is straightforward but can incur extra memory transfers and launch overheads. PyTorch 2.0's <code>torch.compile</code> with backends like <code>TorchInductor</code> addresses this by automatically fusing and optimizing kernels, delivering <code>2–10×</code> performance gains.</p>\n<p>In addition, the community has created custom kernels for frequent combinations of operations, <em>not just individual PyTorch ops like matmul</em>. For example, Flash Attention was created to optimize the critical attention block that defines the transformers architecture, and is present in many models including most LLMs. By carefully combining all the attention operations inside a single kernel, memory transfers are minimized, memory use is reduced, and speedups can be achieved.</p>\n<p>The problem is that all these various kernels are available in separate libraries, which creates a dependency bloat if they were to be added to the transformers library. Furthermore, these kernels are not just Python code, they consist of low-level cuda code, glued together with C++ and exposed through a Python layer. This means they have to be compiled in the target system, which in turn requires whatever build system is required by each kernel library.</p>\n<p>The <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/blog/hello-hf-kernels\">kernels package</a> solves this problem by downloading pre-built binaries of supported kernels from the Hub. You just indicate the kernel you want to use, and <code>kernels</code> will look for a version compatible with your system and download it on first use.</p>\n<h3>Custom Kernels for GPT-OSS</h3>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/huggingface/transformers/blob/0f1b128d3359a26bd18be99c26d7f04fb3cba914/src/transformers/models/gpt_oss/modeling_gpt_oss.py\">GPT-OSS</a>, a Mixture of Experts (MoE) model, is a big user of Kernels from the Hub. It leverages several custom kernels:</p>\n<ol>\n<li>Liger RMSNorm, used as <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/huggingface/transformers/blob/0f1b128d3359a26bd18be99c26d7f04fb3cba914/src/transformers/models/gpt_oss/modeling_gpt_oss.py#L46\"><code>@use_kernel_forward_from_hub(&quot;RMSNorm&quot;)</code></a>`</li>\n<li>Megablocks MoE kernels: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/huggingface/transformers/blob/0f1b128d3359a26bd18be99c26d7f04fb3cba914/src/transformers/models/gpt_oss/modular_gpt_oss.py#L160\"><code>@use_kernel_forward_from_hub(&quot;MegaBlocksMoeMLP&quot;)</code></a></li>\n<li>Flash Attention 3 with <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/kernels-community/vllm-flash-attn3\">support for attention sinks</a>.</li>\n<li>MXFP4 triton kernels (covered <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/blog/faster-transformers#mxfp4-in-transformers\">later</a>)</li>\n</ol>\n<p>Let's take a look at the first two ones.</p>\n<p>Behind the scenes, the decorators (1 and 2) simply point to community-contributed kernels. For example, <code>RMSNorm</code> comes from <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/kernels-community/liger_kernels\"><code>liger_kernels</code></a>, while the <code>MegaBlocksMoeMLP</code> kernel comes from <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/kernels-community/megablocks\"><code>megablocks</code></a>. Depending on your device (CUDA or ROCm) and whether you’re training or running inference, the right kernel is pulled in automatically.</p>\n<p>This design is both <strong>specific and general</strong>: the RMSNorm liger kernels are already being reused across multiple models, and the MoE kernel could be applied to future MoEs as well.</p>\n<p>Because <code>kernels</code> pulls code from the Hub, you have to opt-in to this feature by passing <code>use_kernels=True</code> in your model instantiation, as shown below. We enable <code>INFO</code> logging in the example so you can easily verify that downloadable kernels are in use.</p>\n<blockquote>\n<p>These kernels are not compatible with <code>mxfp4</code>, so inference will happen in <code>bfloat16</code> if you use them. Please, benchmark your system for the best combination in memory and throughput that suits your project!</p>\n</blockquote>\n<pre><code class=\"language-python\"><span class=\"code-snippet\" data-language=\"Python\"><span class=\"syntax-source syntax-python\"><span class=\"syntax-meta syntax-statement syntax-import syntax-python\"><span class=\"syntax-keyword syntax-control syntax-import syntax-from syntax-python\">from</span></span><span class=\"syntax-meta syntax-statement syntax-import syntax-python\"><span class=\"syntax-meta syntax-import-source syntax-python\"> <span class=\"syntax-meta syntax-import-path syntax-python\"><span class=\"syntax-meta syntax-import-name syntax-python\">transformers</span></span> <span class=\"syntax-meta syntax-statement syntax-import syntax-python\"><span class=\"syntax-keyword syntax-control syntax-import syntax-python\">import</span></span></span></span><span class=\"syntax-meta syntax-statement syntax-import syntax-python\"></span><span class=\"syntax-meta syntax-statement syntax-import syntax-python\"> <span class=\"syntax-meta syntax-generic-name syntax-python\">AutoTokenizer</span><span class=\"syntax-punctuation syntax-separator syntax-import-list syntax-python\">,</span> <span class=\"syntax-meta syntax-generic-name syntax-python\">AutoModelForCausalLM</span></span>\n\n<span class=\"syntax-meta syntax-statement syntax-import syntax-python\"><span class=\"syntax-keyword syntax-control syntax-import syntax-python\">import</span> <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">logging</span></span></span>\n<span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">logging</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span></span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-variable syntax-function syntax-python\">basicConfig</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\"><span class=\"syntax-variable syntax-parameter syntax-python\">level</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">logging</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span><span class=\"syntax-variable syntax-other syntax-constant syntax-python\">INFO</span></span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span>\n\n<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">model_id</span></span> <span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span> <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">openai/gpt-oss-20b<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span>\n<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">tokenizer</span></span> <span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span> <span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">AutoTokenizer</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span></span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-variable syntax-function syntax-python\">from_pretrained</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">model_id</span></span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span>\n\n<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">model</span></span> <span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span> <span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">AutoModelForCausalLM</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span></span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-variable syntax-function syntax-python\">from_pretrained</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\">\n    <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">model_id</span></span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span>\n    <span class=\"syntax-variable syntax-parameter syntax-python\">dtype</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">auto<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span>\n    <span class=\"syntax-variable syntax-parameter syntax-python\">device_map</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">auto<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span>\n    <span class=\"syntax-variable syntax-parameter syntax-python\">use_kernels</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-constant syntax-language syntax-python\">True</span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span>\n</span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span>\n</span></span></code></pre>\n<p>Running a quick generation yields log messages like</p>\n<pre><code class=\"language-shell\"><span class=\"code-snippet\" data-language=\"Shell\"><span class=\"syntax-source syntax-shell syntax-bash\"><span class=\"syntax-meta syntax-function-call syntax-shell\"><span class=\"syntax-variable syntax-function syntax-shell\">INFO:root:Using</span></span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-shell\"> layer <span class=\"syntax-meta syntax-group syntax-expansion syntax-command syntax-backticks syntax-shell\"><span class=\"syntax-punctuation syntax-section syntax-group syntax-begin syntax-shell\">`</span><span class=\"syntax-meta syntax-function-call syntax-shell\"><span class=\"syntax-variable syntax-function syntax-shell\">LigerRMSNorm</span></span><span class=\"syntax-punctuation syntax-section syntax-group syntax-end syntax-shell\">`</span></span> from repo <span class=\"syntax-meta syntax-group syntax-expansion syntax-command syntax-backticks syntax-shell\"><span class=\"syntax-punctuation syntax-section syntax-group syntax-begin syntax-shell\">`</span><span class=\"syntax-meta syntax-function-call syntax-shell\"><span class=\"syntax-variable syntax-function syntax-shell\">kernels-community/liger_kernels</span></span><span class=\"syntax-punctuation syntax-section syntax-group syntax-end syntax-shell\">`</span></span></span>\n<span class=\"syntax-meta syntax-function-call syntax-shell\"><span class=\"syntax-variable syntax-function syntax-shell\">INFO:root:Using</span></span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-shell\"> layer <span class=\"syntax-meta syntax-group syntax-expansion syntax-command syntax-backticks syntax-shell\"><span class=\"syntax-punctuation syntax-section syntax-group syntax-begin syntax-shell\">`</span><span class=\"syntax-meta syntax-function-call syntax-shell\"><span class=\"syntax-variable syntax-function syntax-shell\">MegaBlocksMoeMLP</span></span><span class=\"syntax-punctuation syntax-section syntax-group syntax-end syntax-shell\">`</span></span> from repo <span class=\"syntax-meta syntax-group syntax-expansion syntax-command syntax-backticks syntax-shell\"><span class=\"syntax-punctuation syntax-section syntax-group syntax-begin syntax-shell\">`</span><span class=\"syntax-meta syntax-function-call syntax-shell\"><span class=\"syntax-variable syntax-function syntax-shell\">kernels-community/megablocks</span></span><span class=\"syntax-punctuation syntax-section syntax-group syntax-end syntax-shell\">`</span></span></span>\n</span></span></code></pre>\n<p><strong>Figure 1</strong> shows that, in the system we tested, these kernels work best for larger batch sizes. We always recommend to benchmark any performance-related changes as closely to your production conditions as possible.</p>\n<table>\n<thead>\n<tr>\n<th><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/benchmark-kernels-with-without.png\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/benchmark-kernels-with-without.png\" alt=\"benchmark with and without kernels\" loading=\"eager\" decoding=\"async\" fetchpriority=\"high\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture></a></th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Figure 1: Benchmarking results of custom kernels</td>\n</tr>\n</tbody>\n</table>\n<blockquote>\n<p>You can explore and play with the benchmarking script <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/datasets/ariG23498/faster-transformers-scripts/blob/main/benchmark-kernels-with-without.py\">here</a></p>\n</blockquote>\n<h3>Flash Attention 3</h3>\n<p>OpenAI gpt-oss models use <em>attention sinks</em>, which improves quality and facilitates the use of longer contexts. The vLLM team added this feature to the latest version of Flash Attention (Flash Attention 3), and the resulting custom kernel is available <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/kernels-community/vllm-flash-attn3\">on the Hub</a>. Currently, this kernel is compatible with the Hopper architecture. If you have one, this is the way to enable it:</p>\n<pre><code class=\"language-diff\"><span class=\"code-snippet\" data-language=\"Diff\"><span class=\"syntax-source syntax-diff\">model = AutoModelForCausalLM.from_pretrained(\n    model_id,\n    dtype=&quot;auto&quot;,\n    device_map=&quot;auto&quot;,\n<span class=\"syntax-markup syntax-inserted syntax-diff\"><span class=\"syntax-punctuation syntax-definition syntax-inserted syntax-diff\">+</span>    # Flash Attention with Sinks\n</span><span class=\"syntax-markup syntax-inserted syntax-diff\"><span class=\"syntax-punctuation syntax-definition syntax-inserted syntax-diff\">+</span>    attn_implementation=&quot;kernels-community/vllm-flash-attn3&quot;,\n</span>)\n</span></span></code></pre>\n<h2>MXFP4 Quantization</h2>\n<p>Large language models are memory-hungry. Quantization reduces memory footprint by storing weights (and sometimes activations) in lower-precision formats. For reference, <code>FP32</code> uses 32 bits per number and <code>BF16</code> uses 16. By reducing bit width, we trade some precision for smaller models and faster memory movement.</p>\n<p>If you want a visual primer on quantization trade-offs, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/MaartenGr\">Maarten Grootendorst’s</a> article is excellent: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://newsletter.maartengrootendorst.com/p/a-visual-guide-to-quantization\"><em>A Visual Guide to Quantization</em></a>.</p>\n<h3>What is MXFP4</h3>\n<table>\n<thead>\n<tr>\n<th><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/mxfp4.png\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/mxfp4.png\" alt=\"explanation of mxfp4 format\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture></a></th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Figure 2: The E2M1 format used in the MXFP4 format</td>\n</tr>\n</tbody>\n</table>\n<p><code>MXFP4</code> is a 4-bit floating format with E2M1 layout: 1 sign bit, 2 exponent bits, and 1 mantissa bit, as shown in <strong>Figure 2</strong>. On its own, E2M1 is very coarse. MXFP4 compensates with <strong>blockwise scaling</strong>:</p>\n<ul>\n<li>Vectors are grouped into blocks of 32 elements.</li>\n<li>Each block stores a shared scale that restores dynamic range when dequantizing.</li>\n<li>Inside each block, 4-bit values represent numbers relative to that scale.</li>\n</ul>\n<p>This blockwise scheme lets <code>MXFP4</code> keep range while using very few bits. In practice, GPT-OSS 20B fits in roughly <code>16 GB</code> of VRAM and GPT-OSS 120B fits in roughly <code>80 GB</code> when <code>MXFP4</code> is active, which is the difference between “cannot load” and “can run on a single GPU.” The catch is that matrix multiplies now have to respect block scales. Doing this efficiently at scale requires dedicated kernels.</p>\n<h3>MXFP4 in <code>transformers</code></h3>\n<p><code>transformers</code> now includes native support for MXFP4, leveraging optimized <code>triton</code> (MXFP4) kernels for enhanced performance. This builds on the community-driven kernel distribution <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/blog/faster-transformers#zero-build-kernels-downloadable-from-the-hub\">discussed earlier</a>, utilizing pre-compiled kernels from the Hub to simplify deployment.</p>\n<p>Key implementation details:</p>\n<ul>\n<li>Quantizer logic: Found in the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/huggingface/transformers/blob/0997c2f2ab08c32c8e2f90aaad06e29a7108535b/src/transformers/quantizers/quantizer_mxfp4.py\">MXFP4 quantizer file</a>, this handles the core quantization process for MXFP4.</li>\n<li>Integration hooks: The <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/huggingface/transformers/blob/0997c2f2ab08c32c8e2f90aaad06e29a7108535b/src/transformers/integrations/mxfp4.py\">MXFP4 integration file</a> enables seamless use of MXFP4 within the transformers framework.</li>\n</ul>\n<p>To check if a model supports <code>MXFP4</code>, inspect its configuration:</p>\n<pre><code class=\"language-py\"><span class=\"code-snippet\" data-language=\"Python\"><span class=\"syntax-source syntax-python\"><span class=\"syntax-meta syntax-statement syntax-import syntax-python\"><span class=\"syntax-keyword syntax-control syntax-import syntax-from syntax-python\">from</span></span><span class=\"syntax-meta syntax-statement syntax-import syntax-python\"><span class=\"syntax-meta syntax-import-source syntax-python\"> <span class=\"syntax-meta syntax-import-path syntax-python\"><span class=\"syntax-meta syntax-import-name syntax-python\">transformers</span></span> <span class=\"syntax-meta syntax-statement syntax-import syntax-python\"><span class=\"syntax-keyword syntax-control syntax-import syntax-python\">import</span></span></span></span><span class=\"syntax-meta syntax-statement syntax-import syntax-python\"></span><span class=\"syntax-meta syntax-statement syntax-import syntax-python\"> <span class=\"syntax-meta syntax-generic-name syntax-python\">GptOssConfig</span></span>\n\n<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">model_id</span></span> <span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span> <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">openai/gpt-oss-120b<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span>\n<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">cfg</span></span> <span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span> <span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">GptOssConfig</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span></span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-variable syntax-function syntax-python\">from_pretrained</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">model_id</span></span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span>\n<span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-support syntax-function syntax-builtin syntax-python\">print</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">cfg</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span><span class=\"syntax-meta syntax-generic-name syntax-python\">quantization_config</span></span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span>\n\n<span class=\"syntax-comment syntax-line syntax-number-sign syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-python\">#</span> Example output:\n</span><span class=\"syntax-comment syntax-line syntax-number-sign syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-python\">#</span> {\n</span><span class=\"syntax-comment syntax-line syntax-number-sign syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-python\">#</span>   &#39;modules_to_not_convert&#39;: [\n</span><span class=\"syntax-comment syntax-line syntax-number-sign syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-python\">#</span>     &#39;model.layers.*.self_attn&#39;,\n</span><span class=\"syntax-comment syntax-line syntax-number-sign syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-python\">#</span>     &#39;model.layers.*.mlp.router&#39;,\n</span><span class=\"syntax-comment syntax-line syntax-number-sign syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-python\">#</span>     &#39;model.embed_tokens&#39;,\n</span><span class=\"syntax-comment syntax-line syntax-number-sign syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-python\">#</span>     &#39;lm_head&#39;\n</span><span class=\"syntax-comment syntax-line syntax-number-sign syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-python\">#</span>   ],\n</span><span class=\"syntax-comment syntax-line syntax-number-sign syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-python\">#</span>   &#39;quant_method&#39;: &#39;mxfp4&#39;\n</span><span class=\"syntax-comment syntax-line syntax-number-sign syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-python\">#</span> }\n</span></span></span></code></pre>\n<p>If <code>'quant_method': 'mxfp4'</code> is present, the model will automatically use the MXFP4 pathway with Triton kernels when supported.</p>\n<blockquote>\n<p>Thanks to this <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/huggingface/transformers/pull/40176\">pull request</a>, you can fine-tune gpt-oss models and save them directly to the Hub in MXFP4 format, streamlining deployment with optimized performance.</p>\n</blockquote>\n<h3>Requirements and fallbacks</h3>\n<p>To run <code>MXFP4</code> on GPU you need:</p>\n<ol>\n<li><code>accelerate</code>, <code>kernels</code>, and <code>triton&gt;=3.4</code> installed. Note that <code>Pytorch 2.8</code> already comes with <code>triton 3.4</code>, so you only need to manually install triton if using <code>Pytorch 2.7</code>.</li>\n<li>NVIDIA GPU with compute capability <code>≥ 7.5</code>. This goes all the way back to Tesla, so you can run <code>gpt-oss-20b</code> on the free tiers of Google Colab and Kaggle, and on many consumer GPUs.</li>\n</ol>\n<p>If these constraints are not met, <code>transformers</code> falls back to a higher-precision path (<code>bfloat16</code> is used by default), which requires about 4× the memory of MXFP4.</p>\n<p>The <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/datasets/ariG23498/faster-transformers-scripts/blob/main/memory-requirements-quantized-vs-dequantized.py\">snippet</a> loads GPT-OSS twice on CUDA: once with <code>Mxfp4Config(dequantize=True)</code> (memory intensive) and once in the default quantized path (memory efficient). <strong>Figure 3</strong> shows the amount of used VRAM after each load so you can visualize the savings.</p>\n<table>\n<thead>\n<tr>\n<th><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/quantization.png\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/quantization.png\" alt=\"memory used with quantized vs dequantized models\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture></a></th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Figure 3: Memory requirements for the quantized and dequantized models</td>\n</tr>\n</tbody>\n</table>\n<h3>Kernels for MXFP4</h3>\n<p>Efficient <code>MXFP4</code> requires kernels that understand 32-element blocks and their scales during GEMMs and fused ops. This is where <strong>Kernels from the Hub</strong> comes in again. <code>transformers</code> automatically pulls in the <code>MXFP4</code>-aware Triton kernels from the community repository when you load a model that needs them. The repository will appear in your local cache and will be used during the forward pass. For the <code>MXFP4</code> kernels one does not need to use the <code>use_kernels=True</code> parameter like before, it is set to default in <code>transformers</code>.</p>\n<p>Quick sanity check with the Hugging Face cache CLI, after running <code>gpt-oss-20b</code> on a GPU compatible with the triton MXFP4 kernels:</p>\n<pre><code class=\"language-shell\"><span class=\"code-snippet\" data-language=\"Shell\"><span class=\"syntax-source syntax-shell syntax-bash\"><span class=\"syntax-meta syntax-function-call syntax-shell\"><span class=\"syntax-variable syntax-function syntax-shell\">hf</span></span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-shell\"> cache scan</span>\n</span></span></code></pre>\n<p>Sample output:</p>\n<pre><code class=\"language-shell\"><span class=\"code-snippet\" data-language=\"Shell\"><span class=\"syntax-source syntax-shell syntax-bash\"><span class=\"syntax-meta syntax-function-call syntax-shell\"><span class=\"syntax-variable syntax-function syntax-shell\">REPO</span></span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-shell\"> ID                          REPO TYPE SIZE ON DISK</span>\n<span class=\"syntax-meta syntax-function-call syntax-shell\"><span class=\"syntax-variable syntax-function syntax-shell\">--------------------------------</span></span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-shell\"> --------- ------------</span>\n<span class=\"syntax-meta syntax-function-call syntax-shell\"><span class=\"syntax-variable syntax-function syntax-shell\">kernels-community/triton_kernels</span></span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-shell\"> model           536.2K</span>\n<span class=\"syntax-meta syntax-function-call syntax-shell\"><span class=\"syntax-variable syntax-function syntax-shell\">openai/gpt-oss-20b</span></span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-shell\">               model            13.8G</span>\n</span></span></code></pre>\n<p>This indicates the MXFP4 kernels were fetched and are available for execution.</p>\n<p>Let's run some benchmarks and see how well the MXFP4 kernels perform. In <strong>Figure 4</strong>, we see that the <code>MXFP4</code> kernels are even better than the custom MoE and RMSNorm kernels for larger batches.</p>\n<table>\n<thead>\n<tr>\n<th><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/benchmark-mxfp4.png\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/benchmark-mxfp4.png\" alt=\"benchmark mxfp4 kernels\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture></a></th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Figure 4: MXFP4 kernel benchmark</td>\n</tr>\n</tbody>\n</table>\n<blockquote>\n<p>You can explore and play with the benchmarking script <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/datasets/ariG23498/faster-transformers-scripts/blob/main/benchmark-mxfp4-kernels.py\">here</a></p>\n</blockquote>\n<h2>Tensor Parallelism</h2>\n<table>\n<thead>\n<tr>\n<th><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/tgi/TP.png\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/tgi/TP.png\" alt=\"explaining tensor parallelism\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture></a></th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Figure 5: Explanation of tensor parallelism.</td>\n</tr>\n</tbody>\n</table>\n<p>Tensor Parallelism (TP) splits <strong>tensors inside a layer</strong> across multiple GPUs (as shown in <strong>Figure 5</strong>). Each GPU multiplies its shard in parallel, and then partial results are collected using all-gather or all-reduce operations. This reduces per-GPU memory and keeps all GPUs working on the <strong>same layer</strong>, which improves throughput as sequence length or batch size grow. TP is communication-intensive and generally works best on a <strong>single machine with fast intra-node links</strong>.</p>\n<h3>What this enables in <code>transformers</code></h3>\n<p><code>transformers</code> implements TP directly in <code>from_pretrained</code>. You can start with the predefined plan:</p>\n<pre><code class=\"language-python\"><span class=\"code-snippet\" data-language=\"Python\"><span class=\"syntax-source syntax-python\"><span class=\"syntax-comment syntax-line syntax-number-sign syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-python\">#</span> run with: torchrun --nproc-per-node 4 tp_gpt_oss.py\n</span><span class=\"syntax-meta syntax-statement syntax-import syntax-python\"><span class=\"syntax-keyword syntax-control syntax-import syntax-python\">import</span> <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">torch</span></span></span>\n<span class=\"syntax-meta syntax-statement syntax-import syntax-python\"><span class=\"syntax-keyword syntax-control syntax-import syntax-from syntax-python\">from</span></span><span class=\"syntax-meta syntax-statement syntax-import syntax-python\"><span class=\"syntax-meta syntax-import-source syntax-python\"> <span class=\"syntax-meta syntax-import-path syntax-python\"><span class=\"syntax-meta syntax-import-name syntax-python\">transformers</span></span> <span class=\"syntax-meta syntax-statement syntax-import syntax-python\"><span class=\"syntax-keyword syntax-control syntax-import syntax-python\">import</span></span></span></span><span class=\"syntax-meta syntax-statement syntax-import syntax-python\"></span><span class=\"syntax-meta syntax-statement syntax-import syntax-python\"> <span class=\"syntax-meta syntax-generic-name syntax-python\">PreTrainedTokenizerFast</span><span class=\"syntax-punctuation syntax-separator syntax-import-list syntax-python\">,</span> <span class=\"syntax-meta syntax-generic-name syntax-python\">GptOssForCausalLM</span></span>\n\n<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">model_id</span></span> <span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span> <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">openai/gpt-oss-120b<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span>\n<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">tokenizer</span></span> <span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span> <span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">PreTrainedTokenizerFast</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span></span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-variable syntax-function syntax-python\">from_pretrained</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">model_id</span></span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span>\n<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">model</span></span> <span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span> <span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">GptOssForCausalLM</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span></span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-variable syntax-function syntax-python\">from_pretrained</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\">\n    <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">model_id</span></span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span>\n    <span class=\"syntax-variable syntax-parameter syntax-python\">tp_plan</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">auto<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span> <span class=\"syntax-comment syntax-line syntax-number-sign syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-python\">#</span> built in TP support\n</span>    <span class=\"syntax-variable syntax-parameter syntax-python\">dtype</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">auto<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span>\n</span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span><span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span></span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-variable syntax-function syntax-python\">eval</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span>\n\n<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">messages</span></span> <span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span> <span class=\"syntax-meta syntax-structure syntax-list syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-list syntax-begin syntax-python\">[</span>\n    <span class=\"syntax-meta syntax-structure syntax-dictionary-or-set syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-dictionary-or-set syntax-begin syntax-python\">{</span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">role<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-python\">:</span> <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">system<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-dictionary-or-set syntax-python\">,</span> <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">content<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-python\">:</span> <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">Be concise.<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-section syntax-dictionary-or-set syntax-end syntax-python\">}</span></span><span class=\"syntax-punctuation syntax-separator syntax-list syntax-python\">,</span>\n    <span class=\"syntax-meta syntax-structure syntax-dictionary-or-set syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-dictionary-or-set syntax-begin syntax-python\">{</span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">role<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-python\">:</span> <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">user<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-dictionary-or-set syntax-python\">,</span> <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">content<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-python\">:</span> <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">Explain KV caching briefly.<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-section syntax-dictionary-or-set syntax-end syntax-python\">}</span></span><span class=\"syntax-punctuation syntax-separator syntax-list syntax-python\">,</span>\n<span class=\"syntax-punctuation syntax-section syntax-list syntax-end syntax-python\">]</span></span>\n<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">inputs</span></span> <span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span> <span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">tokenizer</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span></span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-variable syntax-function syntax-python\">apply_chat_template</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\">\n    <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">messages</span></span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span>\n    <span class=\"syntax-variable syntax-parameter syntax-python\">add_generation_prompt</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-constant syntax-language syntax-python\">True</span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span>\n    <span class=\"syntax-variable syntax-parameter syntax-python\">return_tensors</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">pt<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span>\n    <span class=\"syntax-variable syntax-parameter syntax-python\">return_dict</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-constant syntax-language syntax-python\">True</span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span>\n    <span class=\"syntax-variable syntax-parameter syntax-python\">reasoning_effort</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">low<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span>\n</span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span><span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span></span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-variable syntax-function syntax-python\">to</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">model</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span><span class=\"syntax-meta syntax-generic-name syntax-python\">device</span></span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span>\n\n<span class=\"syntax-meta syntax-statement syntax-with syntax-python\"><span class=\"syntax-keyword syntax-control syntax-flow syntax-with syntax-python\">with</span> <span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">torch</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span></span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-variable syntax-function syntax-python\">inference_mode</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span><span class=\"syntax-punctuation syntax-section syntax-block syntax-with syntax-python\">:</span></span>\n    <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">generations</span></span> <span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span> <span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">model</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span></span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-variable syntax-function syntax-python\">generate</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\"><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">*</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">*</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">inputs</span></span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span> <span class=\"syntax-variable syntax-parameter syntax-python\">max_new_tokens</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-constant syntax-numeric syntax-integer syntax-decimal syntax-python\">128</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span>\n\n<span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-support syntax-function syntax-builtin syntax-python\">print</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\"><span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">tokenizer</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span></span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-variable syntax-function syntax-python\">decode</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\"><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">generations</span></span></span><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-brackets syntax-begin syntax-python\">[</span></span><span class=\"syntax-meta syntax-item-access syntax-arguments syntax-python\"><span class=\"syntax-constant syntax-numeric syntax-integer syntax-decimal syntax-python\">0</span></span><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-brackets syntax-end syntax-python\">]</span></span><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-brackets syntax-begin syntax-python\">[</span></span><span class=\"syntax-meta syntax-item-access syntax-arguments syntax-python\"><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">inputs</span></span></span><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-brackets syntax-begin syntax-python\">[</span></span><span class=\"syntax-meta syntax-item-access syntax-arguments syntax-python\"><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">input_ids<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span></span><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-brackets syntax-end syntax-python\">]</span></span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span><span class=\"syntax-meta syntax-generic-name syntax-python\">shape</span><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-brackets syntax-begin syntax-python\">[</span></span><span class=\"syntax-meta syntax-item-access syntax-arguments syntax-python\"><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-constant syntax-numeric syntax-integer syntax-decimal syntax-python\">1</span></span><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-brackets syntax-end syntax-python\">]</span></span><span class=\"syntax-punctuation syntax-separator syntax-slice syntax-python\">:</span></span><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-brackets syntax-end syntax-python\">]</span></span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span>\n</span></span></code></pre>\n<p>If you don’t have the infrastructure to run the above, you can just spawn a process on our GPUs using <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/docs/huggingface_hub/en/guides/jobs\">Hugging Face Jobs</a>!</p>\n<pre><code class=\"language-bash\"><span class=\"code-snippet\" data-language=\"Shell\"><span class=\"syntax-source syntax-shell syntax-bash\"><span class=\"syntax-meta syntax-function-call syntax-shell\"><span class=\"syntax-variable syntax-function syntax-shell\">hf</span></span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-shell\"> jobs run<span class=\"syntax-variable syntax-parameter syntax-option syntax-shell\"><span class=\"syntax-punctuation syntax-definition syntax-parameter syntax-shell\"> --</span>detach</span><span class=\"syntax-variable syntax-parameter syntax-option syntax-shell\"><span class=\"syntax-punctuation syntax-definition syntax-parameter syntax-shell\"> --</span>flavor</span> l4x4 ghcr.io/astral-sh/uv:debian /bin/bash<span class=\"syntax-variable syntax-parameter syntax-option syntax-shell\"><span class=\"syntax-punctuation syntax-definition syntax-parameter syntax-shell\"> -</span>c</span> <span class=\"syntax-punctuation syntax-separator syntax-continuation syntax-line syntax-shell\">\\\n</span>  <span class=\"syntax-string syntax-quoted syntax-double syntax-shell\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-shell\">&quot;</span>uv venv .venv --python 3.12 &amp;&amp; <span class=\"syntax-constant syntax-character syntax-escape syntax-shell\">\\\n</span>  source .venv/bin/activate &amp;&amp; <span class=\"syntax-constant syntax-character syntax-escape syntax-shell\">\\\n</span>  uv pip install --upgrade torch numpy transformers accelerate triton kernels &amp;&amp; <span class=\"syntax-constant syntax-character syntax-escape syntax-shell\">\\\n</span>  wget https://huggingface.co/datasets/ariG23498/distributed/raw/main/tp_gpt_oss.py &amp;&amp; <span class=\"syntax-constant syntax-character syntax-escape syntax-shell\">\\\n</span>  torchrun --nproc-per-node=4 tp_gpt_oss.py<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-shell\">&quot;</span></span></span>\n</span></span></code></pre>\n<blockquote>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/docs/huggingface_hub/guides/jobs\"><code>hf jobs</code></a> is available for all Hugging Face PRO &amp; Enterprise users.</p>\n</blockquote>\n<p>Under the hood, <code>tp_plan=&quot;auto&quot;</code> selects a predefined sharding recipe for each layer and wires the necessary <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/spaces/nanotron/ultrascale-playbook?section=a0:_parallel_programming_crash_course\">collectives</a>. You can inspect the active plan with <code>print(model._tp_plan)</code> if you want to verify what is being sharded.</p>\n<h3>When to reach for TP</h3>\n<p>Use TP when the model is too large for one GPU and you want <strong>parallel compute</strong>, not only memory placement. TP tends to scale throughput with more GPUs, especially for long sequences or larger batches.</p>\n<blockquote>\n<p>If you are curious about how TP differs from <code>device_map=&quot;auto&quot;</code> (memory placement), this short <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://stackoverflow.com/questions/78852192/choose-available-gpu-devices-with-device-map\">Stack Overflow answer</a> explains the distinction and when to use each.</p>\n</blockquote>\n<p>To learn more about TP, here are two must-read resources:</p>\n<ul>\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/docs/transformers/en/perf_infer_gpu_multi\"><code>transformers</code> guide</a>: Tensor parallelism, supported models, plans, and extension points.</li>\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/spaces/nanotron/ultrascale-playbook?section=tensor_parallelism\">Ultra-Scale Playbook</a>: background on TP and its relationship to other parallelism modes.</li>\n</ul>\n<h2>Expert Parallelism</h2>\n<p>Expert Parallelism (EP) shards <strong>experts inside MoE layers</strong> across GPUs. Each token is routed to one or a few experts, so only those experts run their feed-forward pass. Since experts are independent MLPs, we can place different experts on different ranks and exchange only the hidden states for the routed tokens. This keeps the matrix multiplies intact on each rank and replaces tensor slicing with routing and collectives.</p>\n<p>Run with multiple processes using <code>torchrun</code>. EP is enabled via the distributed configuration and works with GPT-OSS MoE layers out of the box in transformers.</p>\n<pre><code class=\"language-python\"><span class=\"code-snippet\" data-language=\"Python\"><span class=\"syntax-source syntax-python\"><span class=\"syntax-comment syntax-line syntax-number-sign syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-python\">#</span> run with: torchrun --nproc-per-node 4 ep_gpt_oss.py\n</span><span class=\"syntax-meta syntax-statement syntax-import syntax-python\"><span class=\"syntax-keyword syntax-control syntax-import syntax-python\">import</span> <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">torch</span></span></span>\n<span class=\"syntax-meta syntax-statement syntax-import syntax-python\"><span class=\"syntax-keyword syntax-control syntax-import syntax-from syntax-python\">from</span></span><span class=\"syntax-meta syntax-statement syntax-import syntax-python\"><span class=\"syntax-meta syntax-import-source syntax-python\"> <span class=\"syntax-meta syntax-import-path syntax-python\"><span class=\"syntax-meta syntax-import-name syntax-python\">transformers</span></span> <span class=\"syntax-meta syntax-statement syntax-import syntax-python\"><span class=\"syntax-keyword syntax-control syntax-import syntax-python\">import</span></span></span></span><span class=\"syntax-meta syntax-statement syntax-import syntax-python\"></span><span class=\"syntax-meta syntax-statement syntax-import syntax-python\"> <span class=\"syntax-meta syntax-generic-name syntax-python\">PreTrainedTokenizerFast</span><span class=\"syntax-punctuation syntax-separator syntax-import-list syntax-python\">,</span> <span class=\"syntax-meta syntax-generic-name syntax-python\">GptOssForCausalLM</span></span>\n<span class=\"syntax-meta syntax-statement syntax-import syntax-python\"><span class=\"syntax-keyword syntax-control syntax-import syntax-from syntax-python\">from</span></span><span class=\"syntax-meta syntax-statement syntax-import syntax-python\"><span class=\"syntax-meta syntax-import-source syntax-python\"> <span class=\"syntax-meta syntax-import-path syntax-python\"><span class=\"syntax-meta syntax-import-name syntax-python\">transformers</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span><span class=\"syntax-meta syntax-import-name syntax-python\">distributed</span></span> <span class=\"syntax-meta syntax-statement syntax-import syntax-python\"><span class=\"syntax-keyword syntax-control syntax-import syntax-python\">import</span></span></span></span><span class=\"syntax-meta syntax-statement syntax-import syntax-python\"></span><span class=\"syntax-meta syntax-statement syntax-import syntax-python\"> <span class=\"syntax-meta syntax-generic-name syntax-python\">DistributedConfig</span></span>\n\n<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">model_id</span></span> <span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span> <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">openai/gpt-oss-120b<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span>\n<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">tokenizer</span></span> <span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span> <span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">PreTrainedTokenizerFast</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span></span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-variable syntax-function syntax-python\">from_pretrained</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">model_id</span></span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span>\n<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">model</span></span> <span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span> <span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">GptOssForCausalLM</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span></span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-variable syntax-function syntax-python\">from_pretrained</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\">\n    <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">model_id</span></span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span>\n    <span class=\"syntax-variable syntax-parameter syntax-python\">distributed_config</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-variable syntax-function syntax-python\">DistributedConfig</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\"><span class=\"syntax-variable syntax-parameter syntax-python\">enable_expert_parallel</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-constant syntax-language syntax-python\">True</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span> <span class=\"syntax-comment syntax-line syntax-number-sign syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-python\">#</span> enabling EP\n</span>    <span class=\"syntax-variable syntax-parameter syntax-python\">dtype</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">auto<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span>\n</span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span><span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span></span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-variable syntax-function syntax-python\">eval</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span>\n\n<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">messages</span></span> <span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span> <span class=\"syntax-meta syntax-structure syntax-list syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-list syntax-begin syntax-python\">[</span>\n    <span class=\"syntax-meta syntax-structure syntax-dictionary-or-set syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-dictionary-or-set syntax-begin syntax-python\">{</span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">role<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-python\">:</span> <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">system<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-dictionary-or-set syntax-python\">,</span> <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">content<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-python\">:</span> <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">Be concise.<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-section syntax-dictionary-or-set syntax-end syntax-python\">}</span></span><span class=\"syntax-punctuation syntax-separator syntax-list syntax-python\">,</span>\n    <span class=\"syntax-meta syntax-structure syntax-dictionary-or-set syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-dictionary-or-set syntax-begin syntax-python\">{</span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">role<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-python\">:</span> <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">user<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-dictionary-or-set syntax-python\">,</span> <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">content<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-python\">:</span> <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">Explain KV caching briefly.<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-section syntax-dictionary-or-set syntax-end syntax-python\">}</span></span><span class=\"syntax-punctuation syntax-separator syntax-list syntax-python\">,</span>\n<span class=\"syntax-punctuation syntax-section syntax-list syntax-end syntax-python\">]</span></span>\n<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">inputs</span></span> <span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span> <span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">tokenizer</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span></span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-variable syntax-function syntax-python\">apply_chat_template</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\">\n    <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">messages</span></span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span>\n    <span class=\"syntax-variable syntax-parameter syntax-python\">add_generation_prompt</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-constant syntax-language syntax-python\">True</span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span>\n    <span class=\"syntax-variable syntax-parameter syntax-python\">return_tensors</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">pt<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span>\n    <span class=\"syntax-variable syntax-parameter syntax-python\">return_dict</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-constant syntax-language syntax-python\">True</span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span>\n    <span class=\"syntax-variable syntax-parameter syntax-python\">reasoning_effort</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">low<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span>\n</span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span><span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span></span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-variable syntax-function syntax-python\">to</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">model</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span><span class=\"syntax-meta syntax-generic-name syntax-python\">device</span></span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span>\n\n<span class=\"syntax-meta syntax-statement syntax-with syntax-python\"><span class=\"syntax-keyword syntax-control syntax-flow syntax-with syntax-python\">with</span> <span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">torch</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span></span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-variable syntax-function syntax-python\">inference_mode</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span><span class=\"syntax-punctuation syntax-section syntax-block syntax-with syntax-python\">:</span></span>\n    <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">generations</span></span> <span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span> <span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">model</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span></span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-variable syntax-function syntax-python\">generate</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\"><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">*</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">*</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">inputs</span></span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span> <span class=\"syntax-variable syntax-parameter syntax-python\">max_new_tokens</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-constant syntax-numeric syntax-integer syntax-decimal syntax-python\">128</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span>\n\n<span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-support syntax-function syntax-builtin syntax-python\">print</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\"><span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">tokenizer</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span></span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-variable syntax-function syntax-python\">decode</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\"><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">generations</span></span></span><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-brackets syntax-begin syntax-python\">[</span></span><span class=\"syntax-meta syntax-item-access syntax-arguments syntax-python\"><span class=\"syntax-constant syntax-numeric syntax-integer syntax-decimal syntax-python\">0</span></span><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-brackets syntax-end syntax-python\">]</span></span><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-brackets syntax-begin syntax-python\">[</span></span><span class=\"syntax-meta syntax-item-access syntax-arguments syntax-python\"><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">inputs</span></span></span><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-brackets syntax-begin syntax-python\">[</span></span><span class=\"syntax-meta syntax-item-access syntax-arguments syntax-python\"><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">input_ids<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span></span><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-brackets syntax-end syntax-python\">]</span></span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span><span class=\"syntax-meta syntax-generic-name syntax-python\">shape</span><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-brackets syntax-begin syntax-python\">[</span></span><span class=\"syntax-meta syntax-item-access syntax-arguments syntax-python\"><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-constant syntax-numeric syntax-integer syntax-decimal syntax-python\">1</span></span><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-brackets syntax-end syntax-python\">]</span></span><span class=\"syntax-punctuation syntax-separator syntax-slice syntax-python\">:</span></span><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-brackets syntax-end syntax-python\">]</span></span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span>\n</span></span></code></pre>\n<p>Here is how you would run using <code>hf jobs</code></p>\n<pre><code class=\"language-bash\"><span class=\"code-snippet\" data-language=\"Shell\"><span class=\"syntax-source syntax-shell syntax-bash\"><span class=\"syntax-meta syntax-function-call syntax-shell\"><span class=\"syntax-variable syntax-function syntax-shell\">hf</span></span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-shell\"> jobs run<span class=\"syntax-variable syntax-parameter syntax-option syntax-shell\"><span class=\"syntax-punctuation syntax-definition syntax-parameter syntax-shell\"> --</span>detach</span><span class=\"syntax-variable syntax-parameter syntax-option syntax-shell\"><span class=\"syntax-punctuation syntax-definition syntax-parameter syntax-shell\"> --</span>flavor</span> l4x4 ghcr.io/astral-sh/uv:debian /bin/bash<span class=\"syntax-variable syntax-parameter syntax-option syntax-shell\"><span class=\"syntax-punctuation syntax-definition syntax-parameter syntax-shell\"> -</span>c</span> <span class=\"syntax-punctuation syntax-separator syntax-continuation syntax-line syntax-shell\">\\\n</span>  <span class=\"syntax-string syntax-quoted syntax-double syntax-shell\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-shell\">&quot;</span>uv venv .venv --python 3.12 &amp;&amp; <span class=\"syntax-constant syntax-character syntax-escape syntax-shell\">\\\n</span>  source .venv/bin/activate &amp;&amp; <span class=\"syntax-constant syntax-character syntax-escape syntax-shell\">\\\n</span>  uv pip install --upgrade torch numpy transformers accelerate triton kernels &amp;&amp; <span class=\"syntax-constant syntax-character syntax-escape syntax-shell\">\\\n</span>  wget https://huggingface.co/datasets/ariG23498/distributed/raw/main/ep_gpt_oss.py &amp;&amp; <span class=\"syntax-constant syntax-character syntax-escape syntax-shell\">\\\n</span>  torchrun --nproc-per-node=4 ep_gpt_oss.py<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-shell\">&quot;</span></span></span>\n</span></span></code></pre>\n<blockquote>\n<p>When you enable Expert Parallelism, Tensor Parallelism is also activated. This means you enjoy the best of both worlds!</p>\n</blockquote>\n<h2>Dynamic Sliding Window Layer &amp; Cache</h2>\n<p>Many recent LLMs use <em>sliding window</em> attention, or a combination of sliding and global attention layers, as a means to save memory and reduce those expensive quadratic matmuls that grow with sequence length. However, the dynamic KV cache implementation in transformers used to continue to allocate space according to sequence length, without looking at the individual attention layers. You could always optimize memory using compilation (meaning, fixed shapes), but that's a separate scenario altogether.</p>\n<p><code>transformers</code> now has a <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/huggingface/transformers/blob/64ae6e6b1de2c6822a53be46aba9db68f75ec595/src/transformers/cache_utils.py#L165\"><strong><code>DynamicSlidingWindowLayer</code></strong></a> and a <em>config‑aware</em> <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/huggingface/transformers/blob/64ae6e6b1de2c6822a53be46aba9db68f75ec595/src/transformers/cache_utils.py#L959\"><code>DynamicCache</code></a>. If the model config declares sliding‑window or hybrid attention (both sliding and global attention layers are used), the cache <strong>stops growing past the window</strong> for the sliding layers. If you don’t pass the config, behavior stays as before (full, ever‑growing KV as sequence length grows).</p>\n<p>For models that only use sliding window layers, such as Mistral 7B, cache memory stops growing when the sequence reaches the window size (4096, in this case). This makes sense, because the sliding layers can't look past the previous 4K tokens anyway.</p>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/mistral-dynamic-cache-with-config.png\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/mistral-dynamic-cache-with-config.png\" alt=\"mistral cache behaviour comparison\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture></a></p>\n<p>OpenAI gpt-oss alternates between sliding and global attention layers, which results in total KV cache memory being <em>halved</em>, as we'll see, as sequence length increases. This provides us with:</p>\n<ul>\n<li><strong>Much lower KV‑cache memory</strong> for models with sliding or hybrid attention (e.g. GPT‑OSS). Cache growth plateaus once the window is reached (e.g., 4K for Mistral; 128 for GPT‑OSS sliding layers), instead of scaling linearly with total generated tokens. (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/huggingface/transformers/pull/40039\">GitHub</a>, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/docs/transformers/en/model_doc/mistral\">Transformers</a>)</li>\n<li><strong>Speed/latency wins</strong> on long prompts/long generations: smaller KV tensors mean lighter attention reads/writes and less memory bandwidth pressure, especially after the window is hit. (This is the central motivation behind sliding‑window/hybrid LLMs.) (<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://www.ai21.com/blog/rise-of-hybrid-llms/\">AI21</a>, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://blog.vllm.ai/2025/08/05/gpt-oss.html\">vLLM Blog</a>)</li>\n</ul>\n<h3>How to use it</h3>\n<p>The optimized cache is set by default, that means <strong>you don't have to make any changes</strong> to your existing code. If you want to create the <code>DynamicCache</code> explicitly here is how you would do it:</p>\n<pre><code class=\"language-python\"><span class=\"code-snippet\" data-language=\"Python\"><span class=\"syntax-source syntax-python\"><span class=\"syntax-meta syntax-statement syntax-import syntax-python\"><span class=\"syntax-keyword syntax-control syntax-import syntax-from syntax-python\">from</span></span><span class=\"syntax-meta syntax-statement syntax-import syntax-python\"><span class=\"syntax-meta syntax-import-source syntax-python\"> <span class=\"syntax-meta syntax-import-path syntax-python\"><span class=\"syntax-meta syntax-import-name syntax-python\">transformers</span></span> <span class=\"syntax-meta syntax-statement syntax-import syntax-python\"><span class=\"syntax-keyword syntax-control syntax-import syntax-python\">import</span></span></span></span><span class=\"syntax-meta syntax-statement syntax-import syntax-python\"></span><span class=\"syntax-meta syntax-statement syntax-import syntax-python\"> <span class=\"syntax-meta syntax-generic-name syntax-python\">AutoModelForCausalLM</span><span class=\"syntax-punctuation syntax-separator syntax-import-list syntax-python\">,</span> <span class=\"syntax-meta syntax-generic-name syntax-python\">AutoTokenizer</span><span class=\"syntax-punctuation syntax-separator syntax-import-list syntax-python\">,</span> <span class=\"syntax-meta syntax-generic-name syntax-python\">DynamicCache</span></span>\n\n<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">model_id</span></span> <span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span> <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">openai/gpt-oss-20b<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span>\n\n<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">tokenizer</span></span> <span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span> <span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">AutoTokenizer</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span></span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-variable syntax-function syntax-python\">from_pretrained</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">model_id</span></span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span>\n<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">model</span></span> <span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span> <span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">AutoModelForCausalLM</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span></span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-variable syntax-function syntax-python\">from_pretrained</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\">\n    <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">model_id</span></span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span>\n    <span class=\"syntax-variable syntax-parameter syntax-python\">dtype</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">auto<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span>\n    <span class=\"syntax-variable syntax-parameter syntax-python\">device_map</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">auto<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span>\n</span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span><span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span></span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-variable syntax-function syntax-python\">eval</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span>\n\n<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">messages</span></span> <span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span> <span class=\"syntax-meta syntax-structure syntax-list syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-list syntax-begin syntax-python\">[</span>\n    <span class=\"syntax-meta syntax-structure syntax-dictionary-or-set syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-dictionary-or-set syntax-begin syntax-python\">{</span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">role<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-python\">:</span> <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">system<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-dictionary-or-set syntax-python\">,</span> <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">content<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-python\">:</span> <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">Always respond in riddles<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-section syntax-dictionary-or-set syntax-end syntax-python\">}</span></span><span class=\"syntax-punctuation syntax-separator syntax-list syntax-python\">,</span>\n    <span class=\"syntax-meta syntax-structure syntax-dictionary-or-set syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-dictionary-or-set syntax-begin syntax-python\">{</span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">role<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-python\">:</span> <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">user<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-dictionary-or-set syntax-python\">,</span> <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">content<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-key-value syntax-python\">:</span> <span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">What is the weather like in Madrid?<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-section syntax-dictionary-or-set syntax-end syntax-python\">}</span></span><span class=\"syntax-punctuation syntax-separator syntax-list syntax-python\">,</span>\n<span class=\"syntax-punctuation syntax-section syntax-list syntax-end syntax-python\">]</span></span>\n\n<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">inputs</span></span> <span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span> <span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">tokenizer</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span></span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-variable syntax-function syntax-python\">apply_chat_template</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\">\n    <span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">messages</span></span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span>\n    <span class=\"syntax-variable syntax-parameter syntax-python\">add_generation_prompt</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-constant syntax-language syntax-python\">True</span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span>\n    <span class=\"syntax-variable syntax-parameter syntax-python\">return_tensors</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">pt<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span>\n    <span class=\"syntax-variable syntax-parameter syntax-python\">return_dict</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-constant syntax-language syntax-python\">True</span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span>\n    <span class=\"syntax-variable syntax-parameter syntax-python\">reasoning_effort</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">low<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span>\n</span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span><span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span></span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-variable syntax-function syntax-python\">to</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">model</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span><span class=\"syntax-meta syntax-generic-name syntax-python\">device</span></span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span>\n\n<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">cache</span></span> <span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span> <span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-variable syntax-function syntax-python\">DynamicCache</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\"><span class=\"syntax-variable syntax-parameter syntax-python\">config</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">model</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span><span class=\"syntax-meta syntax-generic-name syntax-python\">config</span></span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span> <span class=\"syntax-comment syntax-line syntax-number-sign syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-comment syntax-python\">#</span> create the cache with the model&#39;s config\n</span>\n<span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">generated</span></span> <span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span> <span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">model</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span></span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-variable syntax-function syntax-python\">generate</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\">\n    <span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">*</span><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">*</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">inputs</span></span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span>\n    <span class=\"syntax-variable syntax-parameter syntax-python\">max_new_tokens</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-constant syntax-numeric syntax-integer syntax-decimal syntax-python\">500</span><span class=\"syntax-punctuation syntax-separator syntax-arguments syntax-python\">,</span>\n    <span class=\"syntax-variable syntax-parameter syntax-python\">past_key_values</span><span class=\"syntax-keyword syntax-operator syntax-assignment syntax-python\">=</span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">cache</span></span>\n</span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span>\n<span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-support syntax-function syntax-builtin syntax-python\">print</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\"><span class=\"syntax-meta syntax-function-call syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">tokenizer</span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span></span><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-variable syntax-function syntax-python\">decode</span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-begin syntax-python\">(</span><span class=\"syntax-meta syntax-function-call syntax-arguments syntax-python\"><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">generated</span></span></span><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-brackets syntax-begin syntax-python\">[</span></span><span class=\"syntax-meta syntax-item-access syntax-arguments syntax-python\"><span class=\"syntax-constant syntax-numeric syntax-integer syntax-decimal syntax-python\">0</span></span><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-brackets syntax-end syntax-python\">]</span></span><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-brackets syntax-begin syntax-python\">[</span></span><span class=\"syntax-meta syntax-item-access syntax-arguments syntax-python\"><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-meta syntax-qualified-name syntax-python\"><span class=\"syntax-meta syntax-generic-name syntax-python\">inputs</span></span></span><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-brackets syntax-begin syntax-python\">[</span></span><span class=\"syntax-meta syntax-item-access syntax-arguments syntax-python\"><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\"><span class=\"syntax-punctuation syntax-definition syntax-string syntax-begin syntax-python\">&quot;</span></span></span><span class=\"syntax-meta syntax-string syntax-python\"><span class=\"syntax-string syntax-quoted syntax-double syntax-python\">input_ids<span class=\"syntax-punctuation syntax-definition syntax-string syntax-end syntax-python\">&quot;</span></span></span></span><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-brackets syntax-end syntax-python\">]</span></span><span class=\"syntax-punctuation syntax-accessor syntax-dot syntax-python\">.</span><span class=\"syntax-meta syntax-generic-name syntax-python\">shape</span><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-brackets syntax-begin syntax-python\">[</span></span><span class=\"syntax-meta syntax-item-access syntax-arguments syntax-python\"><span class=\"syntax-keyword syntax-operator syntax-arithmetic syntax-python\">-</span><span class=\"syntax-constant syntax-numeric syntax-integer syntax-decimal syntax-python\">1</span></span><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-brackets syntax-end syntax-python\">]</span></span><span class=\"syntax-punctuation syntax-separator syntax-slice syntax-python\">:</span></span><span class=\"syntax-meta syntax-item-access syntax-python\"><span class=\"syntax-punctuation syntax-section syntax-brackets syntax-end syntax-python\">]</span></span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span></span><span class=\"syntax-punctuation syntax-section syntax-arguments syntax-end syntax-python\">)</span></span>\n</span></span></code></pre>\n<p><strong>Figure 6</strong> showcases how much of a difference it makes for us to use the Dynamic KV Cache with sliding window attention.</p>\n<table>\n<thead>\n<tr>\n<th><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/dynamic-cache.png\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/dynamic-cache.png\" alt=\"sliding window cache\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture></a></th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Figure 6: The memory analysis of dynamic cache with sliding window attention</td>\n</tr>\n</tbody>\n</table>\n<h2>Continuous Batching &amp; Paged Attention</h2>\n<p>A typical autoregressive generation process looks like <strong>Figure 7</strong>. You input the prefill tokens, and the model predicts each new token one after the other until it predicts the EOS (End of Sequence) token.</p>\n<table>\n<thead>\n<tr>\n<th><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/prefill-tokens.png\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/prefill-tokens.png\" alt=\"prefilling\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture></a></th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Figure 7: Autoregressive token generation</td>\n</tr>\n</tbody>\n</table>\n<p>Let’s see what the generation process looks like when we pass a <strong>batch</strong> of inputs. In <strong>Figure 8</strong> you notice that some generations finish off earlier than the others. This mismatch of length underutilizes the GPUs.</p>\n<table>\n<thead>\n<tr>\n<th><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/static-batching.png\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/static-batching.png\" alt=\"static batching\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture></a></th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Figure 8: Static batching of sequences</td>\n</tr>\n</tbody>\n</table>\n<p>This type of batching sequences is called <em>static batching</em>. While this is simple and easy to understand, it inherently comes with inefficiencies. Only after each sentence is completely generated can we move on to the next batch.</p>\n<p>To bypass this issue, we use <strong>dynamic batching</strong> (also known as <em>continuous batching</em>). Instead of waiting for all the generation to finish, we schedule incoming requests to the completed generations. That way, as soon as a generation in a batch is complete, we prefill the batch with the next request. The process looks like <strong>Figure 9</strong>.</p>\n<table>\n<thead>\n<tr>\n<th><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/dynamic-batching.png\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/dynamic-batching.png\" alt=\"continuous batching\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture></a></th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Figure 9: Continuous Batching of sequences</td>\n</tr>\n</tbody>\n</table>\n<p>Transformers supports continuous batching with the <code>generate_batch</code> API. This is not meant for production-grade model serving –frameworks like vLLM and SGLang are great at that–, but can be very helpful for evaluation and experimentation. Here is an example <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/huggingface/transformers/blob/0f1b128d3359a26bd18be99c26d7f04fb3cba914/examples/pytorch/continuous_batching_simple.py\">script</a> that runs CB end to end on <code>Qwen/Qwen3-4B-Instruct-2507</code>.</p>\n<p>We have also performed a benchmark between Continuous Batching and Static Batching with 100 samples. In Figure 9, we note that CB is quite faster than SB.</p>\n<table>\n<thead>\n<tr>\n<th><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/cb-sb.png\"><picture class=\"article-picture article-picture-fallback\" style=\"--image-ratio:16 / 9\"><img src=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/cb-sb.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" fetchpriority=\"low\" referrerpolicy=\"no-referrer\" class=\"progressive-image\"></picture></a></th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Figure 9: Continuous vs Static Batching Tokens/Second</td>\n</tr>\n</tbody>\n</table>\n<blockquote>\n<p>You can play around with the benchmark here: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/datasets/ariG23498/faster-transformers-scripts/blob/main/sb-bench.py\">SB</a>, <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/datasets/ariG23498/faster-transformers-scripts/blob/main/cb-bench.py\">CB</a></p>\n</blockquote>\n<h2>Load larger models faster</h2>\n<p>When you load a large model into your GPU, PyTorch needs to <strong>reserve GPU memory for each layer’s weights</strong>. Each of these requests (per layer) takes time, and for multi-billion-parameter models it can mean <strong>thousands of tiny memory allocations</strong>, adding up to a long wait before the model is ready. Instead of asking the GPU for new memory every single time, it can <strong>hold on to a big chunk once</strong> and then hand out slices from it quickly.</p>\n<p>PyTorch allocators can do exactly this. The catch is that the allocator only gets fast <em>after</em> you’ve given it some memory to work with. If you don’t “stock the pantry” first, you still end up doing many slow trips to the market. This PR (🎉 <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/huggingface/transformers/pull/36380\">#36380</a>) taught <code>transformers</code> to <strong>pre-stock the pantry</strong> before it starts copying model weights.</p>\n<p>It:</p>\n<ul>\n<li>Looks at the <code>device_map</code> (where each layer will live).</li>\n<li><strong>Pre-allocates a big enough block on each GPU</strong>.</li>\n<li>Then, as layers are copied in, they just slot neatly into this pre-reserved space.</li>\n</ul>\n<p>You have to make no changes to your existing code, as this is default behaviour in <code>transformers</code>. If you use <strong><code>device_map=&quot;auto&quot;</code></strong> or provide your own device map, your model will now load faster automatically. If you’re running with <strong>Tensor Parallel (<code>tp_plan=&quot;auto&quot;</code>) and <code>torchrun</code></strong> you also benefit from companion changes that make multi-GPU loading smarter.</p>\n<h2>Conclusion</h2>\n<p><code>transformers</code> moves quickly and it is community-first. The library evolves at the pace of the field because contributors shape it in the open. Pieces added for new models become part of the toolkit and are reused in future integrations.</p>\n<p>This velocity enables day-zero integrations like the GPT-OSS series. As the stack becomes increasingly <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://x.com/LysandreJik/status/1933201171130593530\">PyTorch-first</a>, it trims bloat and doubles down on the PyTorch paths that matter in practice. The result is a cleaner core that unlocks new capabilities through community kernels, quantization, and parallelism plans, while also <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/blog/transformers-model-definition\">standardizing model definitions</a> so that architectures supported in transformers are a reference and extend across the wider ecosystem.</p>\n<p>This post is a one-time snapshot of a process we repeatedly iterate on towards the same direction: serve the needs of the community. To be up to date with the latest additions to transformers, check the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/docs/transformers/index\">docs</a> and <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/huggingface/transformers/releases\">release notes</a>. And please, keep sharing your feedback and releasing your models in transformers for the community to enjoy 🤗</p>\n<h2>Read More</h2>\n<p>If you want to go further into particular topics, here is a list of links that one should visit:</p>\n<ol>\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/huggingface/gpt-oss-recipes\">Hugging Face GPT-OSS Recipes Repository</a></li>\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/blog/welcome-openai-gpt-oss\">Welcome GPT OSS: OpenAI's New Open-Source Model Family</a></li>\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://cookbook.openai.com/topic/gpt-oss\">OpenAI Cookbook: GPT-OSS Topic</a></li>\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://huggingface.co/docs/transformers/en/perf_infer_gpu_multi\">Transformers Documentation: Distributed Inference on Multiple GPUs</a></li>\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://x.com/carrigmat/status/1952779877569978797\">Matthew Carrigan's X Thread on GPT OSS Innovations</a></li>\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://www.youtube.com/watch?v=bbkcEiUjehk\">YouTube Video: OpenAI GPT OSS Announcement</a></li>\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/huggingface/transformers/pull/36380\">Transformers PR #36380: Faster Model Loading on Accelerators</a></li>\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/huggingface/transformers/pull/36335\">Transformers PR #36335: Update from_pretrained for Tensor Parallelism</a></li>\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://github.com/huggingface/transformers/pull/40039\">Transformers PR #40039: New Dynamic Sliding Window Layer and Cache</a></li>\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://hanlab.mit.edu/blog/streamingllm\">HAN Lab Blog: How Attention Sinks Keep Language Models Stable</a></li>\n</ol>\n",
  "content_markdown": "OpenAI recently released their [GPT-OSS series of models](https://huggingface.co/collections/openai/gpt-oss-68911959590a1634ba11c7a4). The models feature some novel techniques like MXFP4 quantization, efficient kernels, a brand new chat format, and more. To enable the release of gpt-oss through `transformers`, we have upgraded the [library](https://github.com/huggingface/transformers/) considerably. The updates make it very efficient to **load**, **run**, and **fine-tune** the models.\n\nIn this blog post, we talk about all the upgrades in-depth, and how they become part of the transformers toolkit so other models (current and future) can benefit from them. Providing clean implementations of new methods in transformers also allows the community to quickly understand and adopt them. Frameworks such as [`MLX`](https://github.com/ml-explore/mlx-lm/pull/354), [`llama.cpp`](https://github.com/ggml-org/llama.cpp/discussions/15396) or [`vLLM`](https://docs.vllm.ai/projects/recipes/en/latest/OpenAI/GPT-OSS.html) can use the transformers code as a reference to build their own implementations.\n\nFor this release, we worked on:\n\n- [Zero-build Kernels, downloadable from the Hub](https://huggingface.co/blog/faster-transformers#zero-build-kernels-downloadable-from-the-hub)\n- [MXFP4 Quantization](https://huggingface.co/blog/faster-transformers#mxfp4-quantization)\n- [Tensor Parallelism](https://huggingface.co/blog/faster-transformers#tensor-parallelism)\n- [Expert Parallelism](https://huggingface.co/blog/faster-transformers#expert-parallelism)\n- [Dynamic Sliding Window Layer & Cache](https://huggingface.co/blog/faster-transformers#dynamic-sliding-window-layer--cache)\n- [Continuous Batching & Paged Attention](https://huggingface.co/blog/faster-transformers#continuous-batching--paged-attention)\n- [Load larger models faster](https://huggingface.co/blog/faster-transformers#load-larger-models-faster)\n\n> Best part: Most of these features should work across all major models within `transformers`!\n\n## Zero-build Kernels, downloadable from the Hub\n\nA kernel is a ***specialized***, compact program that runs on accelerators to execute tasks like matrix multiplications, activations, or normalizations. In eager PyTorch, operations trigger individual kernels sequentially, which is straightforward but can incur extra memory transfers and launch overheads. PyTorch 2.0's `torch.compile` with backends like `TorchInductor` addresses this by automatically fusing and optimizing kernels, delivering `2–10×` performance gains.\n\nIn addition, the community has created custom kernels for frequent combinations of operations, *not just individual PyTorch ops like matmul*. For example, Flash Attention was created to optimize the critical attention block that defines the transformers architecture, and is present in many models including most LLMs. By carefully combining all the attention operations inside a single kernel, memory transfers are minimized, memory use is reduced, and speedups can be achieved.\n\nThe problem is that all these various kernels are available in separate libraries, which creates a dependency bloat if they were to be added to the transformers library. Furthermore, these kernels are not just Python code, they consist of low-level cuda code, glued together with C++ and exposed through a Python layer. This means they have to be compiled in the target system, which in turn requires whatever build system is required by each kernel library.\n\nThe [kernels package](https://huggingface.co/blog/hello-hf-kernels) solves this problem by downloading pre-built binaries of supported kernels from the Hub. You just indicate the kernel you want to use, and `kernels` will look for a version compatible with your system and download it on first use.\n\n### Custom Kernels for GPT-OSS\n\n[GPT-OSS](https://github.com/huggingface/transformers/blob/0f1b128d3359a26bd18be99c26d7f04fb3cba914/src/transformers/models/gpt_oss/modeling_gpt_oss.py), a Mixture of Experts (MoE) model, is a big user of Kernels from the Hub. It leverages several custom kernels:\n\n1. Liger RMSNorm, used as [`@use_kernel_forward_from_hub(\"RMSNorm\")`](https://github.com/huggingface/transformers/blob/0f1b128d3359a26bd18be99c26d7f04fb3cba914/src/transformers/models/gpt_oss/modeling_gpt_oss.py#L46)\\`\n2. Megablocks MoE kernels: [`@use_kernel_forward_from_hub(\"MegaBlocksMoeMLP\")`](https://github.com/huggingface/transformers/blob/0f1b128d3359a26bd18be99c26d7f04fb3cba914/src/transformers/models/gpt_oss/modular_gpt_oss.py#L160)\n3. Flash Attention 3 with [support for attention sinks](https://huggingface.co/kernels-community/vllm-flash-attn3).\n4. MXFP4 triton kernels (covered [later](https://huggingface.co/blog/faster-transformers#mxfp4-in-transformers))\n\nLet's take a look at the first two ones.\n\nBehind the scenes, the decorators (1 and 2) simply point to community-contributed kernels. For example, `RMSNorm` comes from [`liger_kernels`](https://huggingface.co/kernels-community/liger_kernels), while the `MegaBlocksMoeMLP` kernel comes from [`megablocks`](https://huggingface.co/kernels-community/megablocks). Depending on your device (CUDA or ROCm) and whether you’re training or running inference, the right kernel is pulled in automatically.\n\nThis design is both **specific and general**: the RMSNorm liger kernels are already being reused across multiple models, and the MoE kernel could be applied to future MoEs as well.\n\nBecause `kernels` pulls code from the Hub, you have to opt-in to this feature by passing `use_kernels=True` in your model instantiation, as shown below. We enable `INFO` logging in the example so you can easily verify that downloadable kernels are in use.\n\n> These kernels are not compatible with `mxfp4`, so inference will happen in `bfloat16` if you use them. Please, benchmark your system for the best combination in memory and throughput that suits your project!\n\n```python\nfrom transformers import AutoTokenizer, AutoModelForCausalLM\n\nimport logging\nlogging.basicConfig(level=logging.INFO)\n\nmodel_id = \"openai/gpt-oss-20b\"\ntokenizer = AutoTokenizer.from_pretrained(model_id)\n\nmodel = AutoModelForCausalLM.from_pretrained(\n    model_id,\n    dtype=\"auto\",\n    device_map=\"auto\",\n    use_kernels=True,\n)\n```\n\nRunning a quick generation yields log messages like\n\n```shell\nINFO:root:Using layer `LigerRMSNorm` from repo `kernels-community/liger_kernels`\nINFO:root:Using layer `MegaBlocksMoeMLP` from repo `kernels-community/megablocks`\n```\n\n**Figure 1** shows that, in the system we tested, these kernels work best for larger batch sizes. We always recommend to benchmark any performance-related changes as closely to your production conditions as possible.\n\n| [![benchmark with and without kernels](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/benchmark-kernels-with-without.png)](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/benchmark-kernels-with-without.png) |\n| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| Figure 1: Benchmarking results of custom kernels                                                                                                                                                                                                                                                                               |\n\n> You can explore and play with the benchmarking script [here](https://huggingface.co/datasets/ariG23498/faster-transformers-scripts/blob/main/benchmark-kernels-with-without.py)\n\n### Flash Attention 3\n\nOpenAI gpt-oss models use *attention sinks*, which improves quality and facilitates the use of longer contexts. The vLLM team added this feature to the latest version of Flash Attention (Flash Attention 3), and the resulting custom kernel is available [on the Hub](https://huggingface.co/kernels-community/vllm-flash-attn3). Currently, this kernel is compatible with the Hopper architecture. If you have one, this is the way to enable it:\n\n```diff\nmodel = AutoModelForCausalLM.from_pretrained(\n    model_id,\n    dtype=\"auto\",\n    device_map=\"auto\",\n+    # Flash Attention with Sinks\n+    attn_implementation=\"kernels-community/vllm-flash-attn3\",\n)\n```\n\n## MXFP4 Quantization\n\nLarge language models are memory-hungry. Quantization reduces memory footprint by storing weights (and sometimes activations) in lower-precision formats. For reference, `FP32` uses 32 bits per number and `BF16` uses 16. By reducing bit width, we trade some precision for smaller models and faster memory movement.\n\nIf you want a visual primer on quantization trade-offs, [Maarten Grootendorst’s](https://huggingface.co/MaartenGr) article is excellent: [*A Visual Guide to Quantization*](https://newsletter.maartengrootendorst.com/p/a-visual-guide-to-quantization).\n\n### What is MXFP4\n\n| [![explanation of mxfp4 format](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/mxfp4.png)](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/mxfp4.png) |\n| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| Figure 2: The E2M1 format used in the MXFP4 format                                                                                                                                                                                                                    |\n\n`MXFP4` is a 4-bit floating format with E2M1 layout: 1 sign bit, 2 exponent bits, and 1 mantissa bit, as shown in **Figure 2**. On its own, E2M1 is very coarse. MXFP4 compensates with **blockwise scaling**:\n\n- Vectors are grouped into blocks of 32 elements.\n- Each block stores a shared scale that restores dynamic range when dequantizing.\n- Inside each block, 4-bit values represent numbers relative to that scale.\n\nThis blockwise scheme lets `MXFP4` keep range while using very few bits. In practice, GPT-OSS 20B fits in roughly `16 GB` of VRAM and GPT-OSS 120B fits in roughly `80 GB` when `MXFP4` is active, which is the difference between “cannot load” and “can run on a single GPU.” The catch is that matrix multiplies now have to respect block scales. Doing this efficiently at scale requires dedicated kernels.\n\n### MXFP4 in `transformers`\n\n`transformers` now includes native support for MXFP4, leveraging optimized `triton` (MXFP4) kernels for enhanced performance. This builds on the community-driven kernel distribution [discussed earlier](https://huggingface.co/blog/faster-transformers#zero-build-kernels-downloadable-from-the-hub), utilizing pre-compiled kernels from the Hub to simplify deployment.\n\nKey implementation details:\n\n- Quantizer logic: Found in the [MXFP4 quantizer file](https://github.com/huggingface/transformers/blob/0997c2f2ab08c32c8e2f90aaad06e29a7108535b/src/transformers/quantizers/quantizer_mxfp4.py), this handles the core quantization process for MXFP4.\n- Integration hooks: The [MXFP4 integration file](https://github.com/huggingface/transformers/blob/0997c2f2ab08c32c8e2f90aaad06e29a7108535b/src/transformers/integrations/mxfp4.py) enables seamless use of MXFP4 within the transformers framework.\n\nTo check if a model supports `MXFP4`, inspect its configuration:\n\n```py\nfrom transformers import GptOssConfig\n\nmodel_id = \"openai/gpt-oss-120b\"\ncfg = GptOssConfig.from_pretrained(model_id)\nprint(cfg.quantization_config)\n\n# Example output:\n# {\n#   'modules_to_not_convert': [\n#     'model.layers.*.self_attn',\n#     'model.layers.*.mlp.router',\n#     'model.embed_tokens',\n#     'lm_head'\n#   ],\n#   'quant_method': 'mxfp4'\n# }\n```\n\nIf `'quant_method': 'mxfp4'` is present, the model will automatically use the MXFP4 pathway with Triton kernels when supported.\n\n> Thanks to this [pull request](https://github.com/huggingface/transformers/pull/40176), you can fine-tune gpt-oss models and save them directly to the Hub in MXFP4 format, streamlining deployment with optimized performance.\n\n### Requirements and fallbacks\n\nTo run `MXFP4` on GPU you need:\n\n1. `accelerate`, `kernels`, and `triton>=3.4` installed. Note that `Pytorch 2.8` already comes with `triton 3.4`, so you only need to manually install triton if using `Pytorch 2.7`.\n2. NVIDIA GPU with compute capability `≥ 7.5`. This goes all the way back to Tesla, so you can run `gpt-oss-20b` on the free tiers of Google Colab and Kaggle, and on many consumer GPUs.\n\nIf these constraints are not met, `transformers` falls back to a higher-precision path (`bfloat16` is used by default), which requires about 4× the memory of MXFP4.\n\nThe [snippet](https://huggingface.co/datasets/ariG23498/faster-transformers-scripts/blob/main/memory-requirements-quantized-vs-dequantized.py) loads GPT-OSS twice on CUDA: once with `Mxfp4Config(dequantize=True)` (memory intensive) and once in the default quantized path (memory efficient). **Figure 3** shows the amount of used VRAM after each load so you can visualize the savings.\n\n| [![memory used with quantized vs dequantized models](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/quantization.png)](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/quantization.png) |\n| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| Figure 3: Memory requirements for the quantized and dequantized models                                                                                                                                                                                                                                   |\n\n### Kernels for MXFP4\n\nEfficient `MXFP4` requires kernels that understand 32-element blocks and their scales during GEMMs and fused ops. This is where **Kernels from the Hub** comes in again. `transformers` automatically pulls in the `MXFP4`-aware Triton kernels from the community repository when you load a model that needs them. The repository will appear in your local cache and will be used during the forward pass. For the `MXFP4` kernels one does not need to use the `use_kernels=True` parameter like before, it is set to default in `transformers`.\n\nQuick sanity check with the Hugging Face cache CLI, after running `gpt-oss-20b` on a GPU compatible with the triton MXFP4 kernels:\n\n```shell\nhf cache scan\n```\n\nSample output:\n\n```shell\nREPO ID                          REPO TYPE SIZE ON DISK\n-------------------------------- --------- ------------\nkernels-community/triton_kernels model           536.2K\nopenai/gpt-oss-20b               model            13.8G\n```\n\nThis indicates the MXFP4 kernels were fetched and are available for execution.\n\nLet's run some benchmarks and see how well the MXFP4 kernels perform. In **Figure 4**, we see that the `MXFP4` kernels are even better than the custom MoE and RMSNorm kernels for larger batches.\n\n| [![benchmark mxfp4 kernels](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/benchmark-mxfp4.png)](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/benchmark-mxfp4.png) |\n| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| Figure 4: MXFP4 kernel benchmark                                                                                                                                                                                                                                                      |\n\n> You can explore and play with the benchmarking script [here](https://huggingface.co/datasets/ariG23498/faster-transformers-scripts/blob/main/benchmark-mxfp4-kernels.py)\n\n## Tensor Parallelism\n\n| [![explaining tensor parallelism](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/tgi/TP.png)](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/tgi/TP.png) |\n| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| Figure 5: Explanation of tensor parallelism.                                                                                                                                                                            |\n\nTensor Parallelism (TP) splits **tensors inside a layer** across multiple GPUs (as shown in **Figure 5**). Each GPU multiplies its shard in parallel, and then partial results are collected using all-gather or all-reduce operations. This reduces per-GPU memory and keeps all GPUs working on the **same layer**, which improves throughput as sequence length or batch size grow. TP is communication-intensive and generally works best on a **single machine with fast intra-node links**.\n\n### What this enables in `transformers`\n\n`transformers` implements TP directly in `from_pretrained`. You can start with the predefined plan:\n\n```python\n# run with: torchrun --nproc-per-node 4 tp_gpt_oss.py\nimport torch\nfrom transformers import PreTrainedTokenizerFast, GptOssForCausalLM\n\nmodel_id = \"openai/gpt-oss-120b\"\ntokenizer = PreTrainedTokenizerFast.from_pretrained(model_id)\nmodel = GptOssForCausalLM.from_pretrained(\n    model_id,\n    tp_plan=\"auto\", # built in TP support\n    dtype=\"auto\",\n).eval()\n\nmessages = [\n    {\"role\": \"system\", \"content\": \"Be concise.\"},\n    {\"role\": \"user\", \"content\": \"Explain KV caching briefly.\"},\n]\ninputs = tokenizer.apply_chat_template(\n    messages,\n    add_generation_prompt=True,\n    return_tensors=\"pt\",\n    return_dict=True,\n    reasoning_effort=\"low\",\n).to(model.device)\n\nwith torch.inference_mode():\n    generations = model.generate(**inputs, max_new_tokens=128)\n\nprint(tokenizer.decode(generations[0][inputs[\"input_ids\"].shape[-1]:]))\n```\n\nIf you don’t have the infrastructure to run the above, you can just spawn a process on our GPUs using [Hugging Face Jobs](https://huggingface.co/docs/huggingface_hub/en/guides/jobs)!\n\n```bash\nhf jobs run --detach --flavor l4x4 ghcr.io/astral-sh/uv:debian /bin/bash -c \\\n  \"uv venv .venv --python 3.12 && \\\n  source .venv/bin/activate && \\\n  uv pip install --upgrade torch numpy transformers accelerate triton kernels && \\\n  wget https://huggingface.co/datasets/ariG23498/distributed/raw/main/tp_gpt_oss.py && \\\n  torchrun --nproc-per-node=4 tp_gpt_oss.py\"\n```\n\n> [`hf jobs`](https://huggingface.co/docs/huggingface_hub/guides/jobs) is available for all Hugging Face PRO & Enterprise users.\n\nUnder the hood, `tp_plan=\"auto\"` selects a predefined sharding recipe for each layer and wires the necessary [collectives](https://huggingface.co/spaces/nanotron/ultrascale-playbook?section=a0:_parallel_programming_crash_course). You can inspect the active plan with `print(model._tp_plan)` if you want to verify what is being sharded.\n\n### When to reach for TP\n\nUse TP when the model is too large for one GPU and you want **parallel compute**, not only memory placement. TP tends to scale throughput with more GPUs, especially for long sequences or larger batches.\n\n> If you are curious about how TP differs from `device_map=\"auto\"` (memory placement), this short [Stack Overflow answer](https://stackoverflow.com/questions/78852192/choose-available-gpu-devices-with-device-map) explains the distinction and when to use each.\n\nTo learn more about TP, here are two must-read resources:\n\n- [`transformers` guide](https://huggingface.co/docs/transformers/en/perf_infer_gpu_multi): Tensor parallelism, supported models, plans, and extension points.\n- [Ultra-Scale Playbook](https://huggingface.co/spaces/nanotron/ultrascale-playbook?section=tensor_parallelism): background on TP and its relationship to other parallelism modes.\n\n## Expert Parallelism\n\nExpert Parallelism (EP) shards **experts inside MoE layers** across GPUs. Each token is routed to one or a few experts, so only those experts run their feed-forward pass. Since experts are independent MLPs, we can place different experts on different ranks and exchange only the hidden states for the routed tokens. This keeps the matrix multiplies intact on each rank and replaces tensor slicing with routing and collectives.\n\nRun with multiple processes using `torchrun`. EP is enabled via the distributed configuration and works with GPT-OSS MoE layers out of the box in transformers.\n\n```python\n# run with: torchrun --nproc-per-node 4 ep_gpt_oss.py\nimport torch\nfrom transformers import PreTrainedTokenizerFast, GptOssForCausalLM\nfrom transformers.distributed import DistributedConfig\n\nmodel_id = \"openai/gpt-oss-120b\"\ntokenizer = PreTrainedTokenizerFast.from_pretrained(model_id)\nmodel = GptOssForCausalLM.from_pretrained(\n    model_id,\n    distributed_config=DistributedConfig(enable_expert_parallel=True), # enabling EP\n    dtype=\"auto\",\n).eval()\n\nmessages = [\n    {\"role\": \"system\", \"content\": \"Be concise.\"},\n    {\"role\": \"user\", \"content\": \"Explain KV caching briefly.\"},\n]\ninputs = tokenizer.apply_chat_template(\n    messages,\n    add_generation_prompt=True,\n    return_tensors=\"pt\",\n    return_dict=True,\n    reasoning_effort=\"low\",\n).to(model.device)\n\nwith torch.inference_mode():\n    generations = model.generate(**inputs, max_new_tokens=128)\n\nprint(tokenizer.decode(generations[0][inputs[\"input_ids\"].shape[-1]:]))\n```\n\nHere is how you would run using `hf jobs`\n\n```bash\nhf jobs run --detach --flavor l4x4 ghcr.io/astral-sh/uv:debian /bin/bash -c \\\n  \"uv venv .venv --python 3.12 && \\\n  source .venv/bin/activate && \\\n  uv pip install --upgrade torch numpy transformers accelerate triton kernels && \\\n  wget https://huggingface.co/datasets/ariG23498/distributed/raw/main/ep_gpt_oss.py && \\\n  torchrun --nproc-per-node=4 ep_gpt_oss.py\"\n```\n\n> When you enable Expert Parallelism, Tensor Parallelism is also activated. This means you enjoy the best of both worlds!\n\n## Dynamic Sliding Window Layer & Cache\n\nMany recent LLMs use *sliding window* attention, or a combination of sliding and global attention layers, as a means to save memory and reduce those expensive quadratic matmuls that grow with sequence length. However, the dynamic KV cache implementation in transformers used to continue to allocate space according to sequence length, without looking at the individual attention layers. You could always optimize memory using compilation (meaning, fixed shapes), but that's a separate scenario altogether.\n\n`transformers` now has a [**`DynamicSlidingWindowLayer`**](https://github.com/huggingface/transformers/blob/64ae6e6b1de2c6822a53be46aba9db68f75ec595/src/transformers/cache_utils.py#L165) and a *config‑aware* [`DynamicCache`](https://github.com/huggingface/transformers/blob/64ae6e6b1de2c6822a53be46aba9db68f75ec595/src/transformers/cache_utils.py#L959). If the model config declares sliding‑window or hybrid attention (both sliding and global attention layers are used), the cache **stops growing past the window** for the sliding layers. If you don’t pass the config, behavior stays as before (full, ever‑growing KV as sequence length grows).\n\nFor models that only use sliding window layers, such as Mistral 7B, cache memory stops growing when the sequence reaches the window size (4096, in this case). This makes sense, because the sliding layers can't look past the previous 4K tokens anyway.\n\n[![mistral cache behaviour comparison](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/mistral-dynamic-cache-with-config.png)](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/mistral-dynamic-cache-with-config.png)\n\nOpenAI gpt-oss alternates between sliding and global attention layers, which results in total KV cache memory being *halved*, as we'll see, as sequence length increases. This provides us with:\n\n- **Much lower KV‑cache memory** for models with sliding or hybrid attention (e.g. GPT‑OSS). Cache growth plateaus once the window is reached (e.g., 4K for Mistral; 128 for GPT‑OSS sliding layers), instead of scaling linearly with total generated tokens. ([GitHub](https://github.com/huggingface/transformers/pull/40039), [Transformers](https://huggingface.co/docs/transformers/en/model_doc/mistral))\n- **Speed/latency wins** on long prompts/long generations: smaller KV tensors mean lighter attention reads/writes and less memory bandwidth pressure, especially after the window is hit. (This is the central motivation behind sliding‑window/hybrid LLMs.) ([AI21](https://www.ai21.com/blog/rise-of-hybrid-llms/), [vLLM Blog](https://blog.vllm.ai/2025/08/05/gpt-oss.html))\n\n### How to use it\n\nThe optimized cache is set by default, that means **you don't have to make any changes** to your existing code. If you want to create the `DynamicCache` explicitly here is how you would do it:\n\n```python\nfrom transformers import AutoModelForCausalLM, AutoTokenizer, DynamicCache\n\nmodel_id = \"openai/gpt-oss-20b\"\n\ntokenizer = AutoTokenizer.from_pretrained(model_id)\nmodel = AutoModelForCausalLM.from_pretrained(\n    model_id,\n    dtype=\"auto\",\n    device_map=\"auto\",\n).eval()\n\nmessages = [\n    {\"role\": \"system\", \"content\": \"Always respond in riddles\"},\n    {\"role\": \"user\", \"content\": \"What is the weather like in Madrid?\"},\n]\n\ninputs = tokenizer.apply_chat_template(\n    messages,\n    add_generation_prompt=True,\n    return_tensors=\"pt\",\n    return_dict=True,\n    reasoning_effort=\"low\",\n).to(model.device)\n\ncache = DynamicCache(config=model.config) # create the cache with the model's config\n\ngenerated = model.generate(\n    **inputs,\n    max_new_tokens=500,\n    past_key_values=cache\n)\nprint(tokenizer.decode(generated[0][inputs[\"input_ids\"].shape[-1]:]))\n```\n\n**Figure 6** showcases how much of a difference it makes for us to use the Dynamic KV Cache with sliding window attention.\n\n| [![sliding window cache](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/dynamic-cache.png)](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/dynamic-cache.png) |\n| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| Figure 6: The memory analysis of dynamic cache with sliding window attention                                                                                                                                                                                                   |\n\n## Continuous Batching & Paged Attention\n\nA typical autoregressive generation process looks like **Figure 7**. You input the prefill tokens, and the model predicts each new token one after the other until it predicts the EOS (End of Sequence) token.\n\n| [![prefilling](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/prefill-tokens.png)](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/prefill-tokens.png) |\n| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| Figure 7: Autoregressive token generation                                                                                                                                                                                                                              |\n\nLet’s see what the generation process looks like when we pass a **batch** of inputs. In **Figure 8** you notice that some generations finish off earlier than the others. This mismatch of length underutilizes the GPUs.\n\n| [![static batching](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/static-batching.png)](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/static-batching.png) |\n| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| Figure 8: Static batching of sequences                                                                                                                                                                                                                                        |\n\nThis type of batching sequences is called *static batching*. While this is simple and easy to understand, it inherently comes with inefficiencies. Only after each sentence is completely generated can we move on to the next batch.\n\nTo bypass this issue, we use **dynamic batching** (also known as *continuous batching*). Instead of waiting for all the generation to finish, we schedule incoming requests to the completed generations. That way, as soon as a generation in a batch is complete, we prefill the batch with the next request. The process looks like **Figure 9**.\n\n| [![continuous batching](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/dynamic-batching.png)](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/dynamic-batching.png) |\n| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| Figure 9: Continuous Batching of sequences                                                                                                                                                                                                                                          |\n\nTransformers supports continuous batching with the `generate_batch` API. This is not meant for production-grade model serving –frameworks like vLLM and SGLang are great at that–, but can be very helpful for evaluation and experimentation. Here is an example [script](https://github.com/huggingface/transformers/blob/0f1b128d3359a26bd18be99c26d7f04fb3cba914/examples/pytorch/continuous_batching_simple.py) that runs CB end to end on `Qwen/Qwen3-4B-Instruct-2507`.\n\nWe have also performed a benchmark between Continuous Batching and Static Batching with 100 samples. In Figure 9, we note that CB is quite faster than SB.\n\n| [![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/cb-sb.png)](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/faster-transformers/cb-sb.png) |\n| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| Figure 9: Continuous vs Static Batching Tokens/Second                                                                                                                                                                                      |\n\n> You can play around with the benchmark here: [SB](https://huggingface.co/datasets/ariG23498/faster-transformers-scripts/blob/main/sb-bench.py), [CB](https://huggingface.co/datasets/ariG23498/faster-transformers-scripts/blob/main/cb-bench.py)\n\n## Load larger models faster\n\nWhen you load a large model into your GPU, PyTorch needs to **reserve GPU memory for each layer’s weights**. Each of these requests (per layer) takes time, and for multi-billion-parameter models it can mean **thousands of tiny memory allocations**, adding up to a long wait before the model is ready. Instead of asking the GPU for new memory every single time, it can **hold on to a big chunk once** and then hand out slices from it quickly.\n\nPyTorch allocators can do exactly this. The catch is that the allocator only gets fast *after* you’ve given it some memory to work with. If you don’t “stock the pantry” first, you still end up doing many slow trips to the market. This PR (🎉 [#36380](https://github.com/huggingface/transformers/pull/36380)) taught `transformers` to **pre-stock the pantry** before it starts copying model weights.\n\nIt:\n\n- Looks at the `device_map` (where each layer will live).\n- **Pre-allocates a big enough block on each GPU**.\n- Then, as layers are copied in, they just slot neatly into this pre-reserved space.\n\nYou have to make no changes to your existing code, as this is default behaviour in `transformers`. If you use **`device_map=\"auto\"`** or provide your own device map, your model will now load faster automatically. If you’re running with **Tensor Parallel (`tp_plan=\"auto\"`) and `torchrun`** you also benefit from companion changes that make multi-GPU loading smarter.\n\n## Conclusion\n\n`transformers` moves quickly and it is community-first. The library evolves at the pace of the field because contributors shape it in the open. Pieces added for new models become part of the toolkit and are reused in future integrations.\n\nThis velocity enables day-zero integrations like the GPT-OSS series. As the stack becomes increasingly [PyTorch-first](https://x.com/LysandreJik/status/1933201171130593530), it trims bloat and doubles down on the PyTorch paths that matter in practice. The result is a cleaner core that unlocks new capabilities through community kernels, quantization, and parallelism plans, while also [standardizing model definitions](https://huggingface.co/blog/transformers-model-definition) so that architectures supported in transformers are a reference and extend across the wider ecosystem.\n\nThis post is a one-time snapshot of a process we repeatedly iterate on towards the same direction: serve the needs of the community. To be up to date with the latest additions to transformers, check the [docs](https://huggingface.co/docs/transformers/index) and [release notes](https://github.com/huggingface/transformers/releases). And please, keep sharing your feedback and releasing your models in transformers for the community to enjoy 🤗\n\n## Read More\n\nIf you want to go further into particular topics, here is a list of links that one should visit:\n\n1.  [Hugging Face GPT-OSS Recipes Repository](https://github.com/huggingface/gpt-oss-recipes)\n2.  [Welcome GPT OSS: OpenAI's New Open-Source Model Family](https://huggingface.co/blog/welcome-openai-gpt-oss)\n3.  [OpenAI Cookbook: GPT-OSS Topic](https://cookbook.openai.com/topic/gpt-oss)\n4.  [Transformers Documentation: Distributed Inference on Multiple GPUs](https://huggingface.co/docs/transformers/en/perf_infer_gpu_multi)\n5.  [Matthew Carrigan's X Thread on GPT OSS Innovations](https://x.com/carrigmat/status/1952779877569978797)\n6.  [YouTube Video: OpenAI GPT OSS Announcement](https://www.youtube.com/watch?v=bbkcEiUjehk)\n7.  [Transformers PR #36380: Faster Model Loading on Accelerators](https://github.com/huggingface/transformers/pull/36380)\n8.  [Transformers PR #36335: Update from\\_pretrained for Tensor Parallelism](https://github.com/huggingface/transformers/pull/36335)\n9.  [Transformers PR #40039: New Dynamic Sliding Window Layer and Cache](https://github.com/huggingface/transformers/pull/40039)\n10. [HAN Lab Blog: How Attention Sinks Keep Language Models Stable](https://hanlab.mit.edu/blog/streamingllm)\n",
  "dateCreated": "2026-10-04T12:50:30.804479567+00:00",
  "date_created": "2025-09-11T00:00:00+00:00",
  "date_modified": "2025-09-11T00:00:00+00:00",
  "date_published": "2025-09-11T00:00:00+00:00",
  "description": "OpenAI recently released their GPT-OSS series of models. The models feature some novel techniques like MXFP4 quantization, efficient kernels, a brand new chat format, and more. To enable the release of gpt-oss through transformers, we have…",
  "external_url": "https://huggingface.co/blog/faster-transformers",
  "git": {
    "commit": "ebb0941c5c06a2ab2377342d607535262a3e969e",
    "path": "items/huggingface-co/2025/09/2025-09-11-tricks-from-openai-gpt-oss-you-index-pointing-at-the-viewer.md",
    "permalink": "https://github.com/aymericbeaumet/aggr-instance/blob/ebb0941c5c06a2ab2377342d607535262a3e969e/items/huggingface-co/2025/09/2025-09-11-tricks-from-openai-gpt-oss-you-index-pointing-at-the-viewer.md"
  },
  "id": "urn:aggr:item:2bd3cd8d79181fc2940310fd2566f352ade512cf",
  "isBasedOn": {
    "@id": "https://huggingface.co/blog/faster-transformers"
  },
  "mainEntity": {
    "@id": "https://huggingface.co/blog/faster-transformers",
    "@type": "CreativeWork",
    "archivedAt": {
      "@id": "https://aggr.aymericbeaumet.com/items/huggingface-co/2025-09-11-tricks-from-openai-gpt-oss-you-index-pointing-at-the-viewer/#webpage"
    },
    "dateModified": "2025-09-11T00:00:00+00:00",
    "datePublished": "2025-09-11T00:00:00+00:00",
    "headline": "Tricks from OpenAI gpt-oss YOU can use with transformers",
    "timeRequired": "PT16M",
    "url": "https://huggingface.co/blog/faster-transformers",
    "wordCount": 3422
  },
  "name": "Archived snapshot: Tricks from OpenAI gpt-oss YOU can use with transformers",
  "preview": null,
  "reading_minutes": 16,
  "replicated_at": null,
  "source": "huggingface-co",
  "source_name": "Hugging Face - Blog",
  "summary": null,
  "tags": [],
  "temporalCoverage": "2026-10-04T12:50:30.804479567+00:00",
  "title": "Tricks from OpenAI gpt-oss YOU can use with transformers",
  "url": "https://aggr.aymericbeaumet.com/items/huggingface-co/2025-09-11-tricks-from-openai-gpt-oss-you-index-pointing-at-the-viewer/",
  "word_count": 3422
}