Ultra-High-Throughput Transformers Engine: NVIDIA FP8/TMA, Zero-Allocation Slotted Static KV Cache, Sub-5µs CUDA Graphs, Fused Logits Sampling, Tree Speculative Decoding, Split-KV Flash-Decoding & Apple Silicon Metal (MSL) Simdgroup Kernels
0
stars
18,826
commits
Python
primary language
Aug 17, 2026
updated
The Sovereign, Ultra-Fast Fork of Transformers for Low-Bit, Ternary & Wave-Interference Intelligence.
Maintained with love by 8b-is & Peter Lodri.
PyPI:transformers-ultra· Web: transformers.vaked.dev · Sovereign CI: Trusted GitHub Actions.
transformers-ultra Existstransformers-ultra
dyad_compressor)ChunkedPrefillDecodeEngine)mlx_mps_bridge)MedusaTreeFastRunner)split_kv_decode_attention)SpeculativeFastRunner)metal_msl_kernels)MLX-QUANT)hf-mac)sparsemat/sprs)transformers-ultra ExistsTired of lying in the sunshine, staying home to watch the rain
And you are young and life is long, and there is time to kill today
And then one day you find ten years have got behind you
No one told you when to run, you missed the starting gun.
— Pink Floyd, Time
This fork was born from a moment of pure bureaucratic absurdity:
Peter Lodri (@peterlodri-sec) opened three PRs against the original upstream repository to fix critical, recurring bugs in 1-bit / 1.58-bit ternary models, BitNet quantization, and Apple Silicon MPS memory leaks. Instead of reviewing the math or benchmarking the speedup, an upstream gatekeeper remarked:
"lol this idiot is spamming MY repo"
...and banned Peter from contributing.
What a weird world. But open source belongs to no single gatekeeper. We didn't complain, we didn't wait for permission—we took the starting gun, fixed every hot path, integrated native Apple Silicon Metal & BitNet kernels, ported MEM8 wave-interference associative memory, eliminated Python reflection overhead from token generation loops, and released transformers-ultra.
8b-is/transformers operates as a 100% sovereign, independent downstream distribution. We maintain our own hardened mainline—incorporating critical community bugfixes, security patches, and Apple Silicon / low-bit acceleration without upstream gatekeeping delays.
8b-is/transformers:MeshRouterWrapper that dispatches token inputs across multiple instantiated HuggingFace experts directly inside the GenerationMixin core loop, allowing Mixture-of-Experts inference over discrete, standalone checkpoints.UltraGenerationConfigSchema and UltraQuantizationConfigSchema alongside the UltraFastCausalLMOutput dataclass for strict, zero-overhead validation and pattern matching directly from the top-level transformers namespace.<|im_start|>, <turn|>, [INST]) in user messages via escape_chat_special_tokens with zero-width separator protection.additional_special_tokens when extra_special_tokens is also present in checkpoint configs (e.g. Kimi-VL, OpenCUA, Mistral-Large)._is_hf_initialized parameter flag checking across all built-in models and accelerators (Apple Silicon MPS, CPU, Ascend NPU), skipping redundant slow normal_ weight initialization.WeightConverter and DecompressExperts to guarantee exact per-expert weight/scale dequantization under dequantize=True / run_compressed=False.input_features dtype to conv1.weight.dtype inside WhisperEncoder.forward, allowing seamless manual inference on whisper-large-v3 and whisper-large-v3-turbo without RuntimeError: Input type and bias type should be the same.HubertPositionalConvEmbedding when conv_pos_batch_norm=True by strictly propagating padding masks to prevent cross-sample batch contamination.pipeline() (#47869):
crop(-N) and crop(0) bounds to prevent negative slicing from silently retaining stale tokens in KV cache during rollback.sp_model.decode() in convert_tokens_to_string to properly decode byte-fallback tokens (<0x0A>, <0xF0>)._added_tokens_decoder via _sync_added_tokens() on all mutation paths (CpmAnt, Wav2Vec2, etc.).<0.24.0 allowing the published 0.23.1 release with XSS fix (AIKIDO-2026-10636).use_sub_norms config flag to bypass RMSNorm sub-layers for weight-quant-only checkpoints (PeetPedro/quantal-ternary).text_position_ids to text_features.dtype before computing sinusoids, preventing 93% of position embeddings from collapsing to zero.vocab_size from text_config to eliminate false out-of-vocab warnings for BOS/EOS tokens.normalize=True option using log_softmax to eliminate gauge shift artifacts in repetition penalty.torch.argmax in compute_tm to avoid IndexError crashes under half-precision inference.gemma4 and gemma4_unified mappings to AutoConfig.weight_map shard filenames in get_checkpoint_shard_files to strictly block path traversal (../) and arbitrary out-of-directory file reads.model.generation_config values are strictly preserved over pipeline defaults in Pipeline.__init__ with torch-optional runtime safety.**kwargs (num_items_in_batch) to self.loss_function across GenericForSequenceClassification, GenericForTokenClassification, Swinv2, ResNet, CLIP, SigLIP, and SigLIP2 classification heads.hf-mac):
torch.device("mps") assignment in pipelines, eliminating RuntimeError: Invalid device string 'mps:0'.safe_open buffer staging fallback for safetensors on macOS unified memory._AutogradFunction abstractions in tensor_parallel.py, accelerate.py, and monkey_patching.py for cross-platform imports.caching_allocator_warmup AttributeError when loading bitsandbytes quantized models with PEFT adapters.mistral_common dependency checking at module initialization to allow proper docstring parsing for MistralCommonBackend without falling back to a dummy object.transformers-ultraSlottedStaticCache (Zero-Allocation Decoding): Pre-allocates contiguous (batch_size, num_heads, max_cache_len, head_dim) buffers once and uses in-place slice copies (copy_()), eliminating $100%$ of dynamic CUDA allocations and memory fragmentation during autoregressive decoding.CUDAGraphFastRunner (<5µs Dispatch Latency): Records single-token forward passes into static CUDA Graphs with dedicated warmup streams, bypassing Python CPU interpreter overhead and dropping token stepping latency from ~120µs to <5µs.FusedLogitsSampler (O(K) In-Register Sampling): Fused single-pass temperature scaling, Top-K reduction, Top-P nucleus cumulative probability filtering, and multinomial sampling in a single contiguous sequence, cutting sampling overhead by up to 80% on large vocabularies ($V \ge 32k$).dyad_compressor):
TokenClassifierHead + SpanCNNHead) coupled via the asymmetric modulation gate $\tilde{I}i(x) = \sigma(\text{logit}{\text{tok}}(x) - \gamma \cdot \text{ReLU}(\text{logit}_{\text{span}}(x)))$.MUST_KEEP_PATTERN) and in-place $O(1)$ SlottedStaticCache KV slot compaction.ChunkedPrefillDecodeEngine):
mlx_mps_bridge):
torch_to_mlx, mlx_to_torch) with zero system RAM copies.MlxMpsHybridLinear: Executes MLX Metal SIMD matrix multiplication directly on PyTorch MPS activation tensors.MedusaTreeFastRunner):
MedusaTreeTopology).SlottedStaticCache.crop().split_kv_decode_attention):
BLOCK_N=512), achieving $100%$ SM occupancy even with $B=1$._split_kv_stage2_kernel) merging partial softmax states with zero precision loss.SpeculativeFastRunner):
cache.crop() on SlottedStaticCache upon candidate rejection.metal_msl_kernels):
METAL_BITNET_TERNARY_GEMM_MSL, METAL_FP8_DYNAMIC_GEMM_MSL) targeting Apple M1/M2/M3/M4 GPUs.uint32 2-bit bitmask unpacking and hardware-accelerated ternary GEMM (metal_bitnet_matmul, MetalBitNetLinear).metal_fp8_matmul, MetalFp8Linear).CUtensorMap binary memory layout matching NVIDIA Hopper SM90+ (H100/H200) and Blackwell SM100+ (B200) specifications.CUtensorMapStruct) and in-place zero-allocation buffer packing (TmaDescriptor.pack_into).torch._scaled_mm with fast accumulation and dynamic scaling (fp8_dynamic_quantize).NvidiaFp8TmaConfig, NvidiaFp8TmaHfQuantizer).sysctl hw.memsize), MPS cache flushing (torch.mps.empty_cache()), and MLX availability resolver.get_hf_gpu_tier): B200, H200, H100, MI300X, L40S, A100, L4, A10G, T4, Apple Silicon, Gaudi, and Neuron.get_recommended_attention_backend -> flash_attention_3, flash_attention_2, sdpa, eager).memory_tuning):
mimalloc and jemalloc automatic process detection and low-latency environment tuning (MIMALLOC_LARGE_OS_PAGES=1, PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True").gc.freeze()) to skip weight graph scans during inference.no_gc_cycle() context manager to eliminate stop-the-world GC pauses during token generation loops.FastTmaBufferPool for zero-allocation C buffer acquisition and recycling.MLX-QUANT):
quantize_ternary_numpy, unpack_ternary_numpy) in src/transformers/integrations/bitnet_mlx.py (commit 476ebc6).MPS accelerator detection and memory view optimizations in src/transformers/quantizers/quantizer_bitnet.py.hf-mac):MEM8Wave, MEM8MemoryStore) operating across four distinct cognitive frequency bands (Math $\Gamma$, Code $\text{B}$, Reasoning $\text{A}$, General $\Theta$) in src/transformers/integrations/mem8_wave.py (commit 476ebc6).inspect.signature AST parsing in LogitsProcessorList.__call__ via class-level signature caching (_cached_signatures) in src/transformers/generation/logits_process.py (commit 476ebc6).src/transformers/models/ to eliminate redundant unsqueeze memory view allocations (commit f736202).torch.cat on empty tensors for direct tensor assignment in src/transformers/cache_utils.py (commit 476ebc6).target-version = "py311", python_requires = ">=3.11.0").__slots__ memory layouts across wave states and descriptors, dropping per-object memory overhead by up to 50%.StrEnum for zero-overhead string enum comparisons and structural match/case pattern matching.nogil) execution.UltraGenerationConfigSchema, UltraQuantizationConfigSchema) for strict, rapid ingress deserialization.@dataclass(slots=True, kw_only=True) inference containers (UltraFastCausalLMOutput) for lightning-fast pattern matching in model outputs.# Install the ultra-fast fork
pip install transformers-ultra
English | 简体中文 | 繁體中文 | 한국어 | Español | 日本語 | हिन्दी | Русский | Português | తెలుగు | Français | Deutsch | Italiano | Tiếng Việt | العربية | اردو | বাংলা | فارسی | Türkçe |
State-of-the-art pretrained models for inference and training
Transformers acts as the model-definition framework for state-of-the-art machine learning with text, computer vision, audio, video, and multimodal models, for both inference and training.
It centralizes the model definition so that this definition is agreed upon across the ecosystem. transformers is the
pivot across frameworks: if a model definition is supported, it will be compatible with the majority of training
frameworks (Axolotl, Unsloth, DeepSpeed, FSDP, PyTorch-Lightning, ...), inference engines (vLLM, SGLang, TGI, ...),
and adjacent modeling libraries (llama.cpp, mlx, ...) which leverage the model definition from transformers.
We pledge to help support new state-of-the-art models and democratize their usage by having their model definition be simple, customizable, and efficient.
There are over 1M+ Transformers model checkpoints on the Hugging Face Hub you can use.
Explore the Hub today to find a model and use Transformers to help you get started right away.
Transformers works with Python 3.10+, and PyTorch 2.5+.
Create and activate a virtual environment with venv or uv, a fast Rust-based Python package and project manager.
# venv
python -m venv .my-env
source .my-env/bin/activate
# uv
uv venv .my-env
source .my-env/bin/activate
Install Transformers in your virtual environment.
# pip
pip install "transformers[torch]"
# uv
uv pip install "transformers[torch]"
Install Transformers from source if you want the latest changes in the library or are interested in contributing. However, the latest version may not be stable. Feel free to open an issue if you encounter an error.
git clone https://github.com/huggingface/transformers.git
cd transformers
# pip
pip install '.[torch]'
# uv
uv pip install '.[torch]'
Get started with Transformers right away with the Pipeline API. The Pipeline is a high-level inference class that supports text, audio, vision, and multimodal tasks. It handles preprocessing the input and returns the appropriate output.
Instantiate a pipeline and specify model to use for text generation. The model is downloaded and cached so you can easily reuse it again. Finally, pass some text to prompt the model.
from transformers import pipeline
pipeline = pipeline(task="text-generation", model="Qwen/Qwen2.5-1.5B")
pipeline("the secret to baking a really good cake is ")
[{'generated_text': 'the secret to baking a really good cake is 1) to use the right ingredients and 2) to follow the recipe exactly. the recipe for the cake is as follows: 1 cup of sugar, 1 cup of flour, 1 cup of milk, 1 cup of butter, 1 cup of eggs, 1 cup of chocolate chips. if you want to make 2 cakes, how much sugar do you need? To make 2 cakes, you will need 2 cups of sugar.'}]
To chat with a model, the usage pattern is the same. The only difference is you need to construct a chat history (the input to Pipeline) between you and the system.
[!TIP] You can also chat with a model directly from the command line, as long as
transformers serveis running.transformers chat Qwen/Qwen2.5-0.5B-Instruct
import torch
from transformers import pipeline
chat = [
{"role": "system", "content": "You are a sassy, wise-cracking robot as imagined by Hollywood circa 1986."},
{"role": "user", "content": "Hey, can you tell me any fun things to do in New York?"}
]
pipeline = pipeline(task="text-generation", model="meta-llama/Meta-Llama-3-8B-Instruct", dtype=torch.bfloat16, device_map="auto")
response = pipeline(chat, max_new_tokens=512)
print(response[0]["generated_text"][-1]["content"])
Expand the examples below to see how Pipeline works for different modalities and tasks.
from transformers import pipeline
pipeline = pipeline(task="automatic-speech-recognition", model="openai/whisper-large-v3")
pipeline("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac")
{'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.'}
from transformers import pipeline
pipeline = pipeline(task="image-classification", model="facebook/dinov2-small-imagenet1k-1-layer")
pipeline("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
[{'label': 'macaw', 'score': 0.997848391532898},
{'label': 'sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita',
'score': 0.0016551691805943847},
{'label': 'lorikeet', 'score': 0.00018523589824326336},
{'label': 'African grey, African gray, Psittacus erithacus',
'score': 7.85409429227002e-05},
{'label': 'quail', 'score': 5.502637941390276e-05}]
from transformers import pipeline
pipeline = pipeline(task="visual-question-answering", model="Salesforce/blip-vqa-base")
pipeline(
image="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/idefics-few-shot.jpg",
question="What is in the image?",
)
[{'answer': 'statue of liberty'}]
Easy-to-use state-of-the-art models:
Lower compute costs, smaller carbon footprint:
Choose the right framework for every part of a model's lifetime:
Easily customize a model or an example to your needs:
Transformers is more than a toolkit to use pretrained models, it's a community of projects built around it and the Hugging Face Hub. We want Transformers to enable developers, researchers, students, professors, engineers, and anyone else to build their dream projects.
In order to celebrate Transformers 100,000 stars, we wanted to put the spotlight on the community with the awesome-transformers page which lists 100 incredible projects built with Transformers.
If you own or use a project that you believe should be part of the list, please open a PR to add it!
You can test most of our models directly on their Hub model pages.
Expand each modality below to see a few example models for various use cases.
sparsemat/sprs)sparsemat/sprs is the official sparse linear algebra foundation for transformers-ultra and the sovereign constellation:
sprs representation cuts attention FLOPs from $O(N^2)$ to $O(\text{nnz})$, eliminating memory bandwidth bottlenecks.sprs compressed index traversal.use sprs::{CsMatI, TriMatI};
// Constructing a DYAD sparse attention mask kernel (O(nnz) compute)
let mut tri = TriMatI::<f32, u32>::new((seq_len, seq_len));
for (row, col, weight) in dyad_sparse_entries {
tri.add_triplet(row, col, weight);
}
let csr_attention_mask: CsMatI<f32, u32> = tri.to_csr();
We now have a paper you can cite for the 🤗 Transformers library:
@inproceedings{wolf-etal-2020-transformers,
title = "Transformers: State-of-the-Art Natural Language Processing",
author = "Thomas Wolf and Lysandre Debut and Victor Sanh and Julien Chaumond and Clement Delangue and Anthony Moi and Pierric Cistac and Tim Rault and Rémi Louf and Morgan Funtowicz and Joe Davison and Sam Shleifer and Patrick von Platen and Clara Ma and Yacine Jernite and Julien Plu and Canwen Xu and Teven Le Scao and Sylvain Gugger and Mariama Drame and Quentin Lhoest and Alexander M. Rush",
booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: System Demonstrations",
month = oct,
year = "2020",
address = "Online",
publisher = "Association for Computational Linguistics",
url = "https://aclanthology.org/2020.emnlp-demos.6/",
pages = "38--45"
}
use_sub_norms=False in BitNetConfig for zero-overhead ternary checkpoints (PeetPedro/quantal-ternary).MLX-QUANT.(top 30 of 436)
Python
99.9%
Ultra-High-Throughput Transformers Engine: NVIDIA FP8/TMA, Zero-Allocation Slotted Static KV Cache, Sub-5µs CUDA Graphs, Fused Logits Sampling, Tree Speculative Decoding, Split-KV Flash-Decoding & Apple Silicon Metal (MSL) Simdgroup Kernels
0
stars
18,826
commits
Python
primary language
Aug 17, 2026
updated
The Sovereign, Ultra-Fast Fork of Transformers for Low-Bit, Ternary & Wave-Interference Intelligence.
Maintained with love by 8b-is & Peter Lodri.
PyPI:transformers-ultra· Web: transformers.vaked.dev · Sovereign CI: Trusted GitHub Actions.
transformers-ultra Existstransformers-ultra
dyad_compressor)ChunkedPrefillDecodeEngine)mlx_mps_bridge)MedusaTreeFastRunner)split_kv_decode_attention)SpeculativeFastRunner)metal_msl_kernels)MLX-QUANT)hf-mac)sparsemat/sprs)transformers-ultra ExistsTired of lying in the sunshine, staying home to watch the rain
And you are young and life is long, and there is time to kill today
And then one day you find ten years have got behind you
No one told you when to run, you missed the starting gun.
— Pink Floyd, Time
This fork was born from a moment of pure bureaucratic absurdity:
Peter Lodri (@peterlodri-sec) opened three PRs against the original upstream repository to fix critical, recurring bugs in 1-bit / 1.58-bit ternary models, BitNet quantization, and Apple Silicon MPS memory leaks. Instead of reviewing the math or benchmarking the speedup, an upstream gatekeeper remarked:
"lol this idiot is spamming MY repo"
...and banned Peter from contributing.
What a weird world. But open source belongs to no single gatekeeper. We didn't complain, we didn't wait for permission—we took the starting gun, fixed every hot path, integrated native Apple Silicon Metal & BitNet kernels, ported MEM8 wave-interference associative memory, eliminated Python reflection overhead from token generation loops, and released transformers-ultra.
8b-is/transformers operates as a 100% sovereign, independent downstream distribution. We maintain our own hardened mainline—incorporating critical community bugfixes, security patches, and Apple Silicon / low-bit acceleration without upstream gatekeeping delays.
8b-is/transformers:MeshRouterWrapper that dispatches token inputs across multiple instantiated HuggingFace experts directly inside the GenerationMixin core loop, allowing Mixture-of-Experts inference over discrete, standalone checkpoints.UltraGenerationConfigSchema and UltraQuantizationConfigSchema alongside the UltraFastCausalLMOutput dataclass for strict, zero-overhead validation and pattern matching directly from the top-level transformers namespace.<|im_start|>, <turn|>, [INST]) in user messages via escape_chat_special_tokens with zero-width separator protection.additional_special_tokens when extra_special_tokens is also present in checkpoint configs (e.g. Kimi-VL, OpenCUA, Mistral-Large)._is_hf_initialized parameter flag checking across all built-in models and accelerators (Apple Silicon MPS, CPU, Ascend NPU), skipping redundant slow normal_ weight initialization.WeightConverter and DecompressExperts to guarantee exact per-expert weight/scale dequantization under dequantize=True / run_compressed=False.input_features dtype to conv1.weight.dtype inside WhisperEncoder.forward, allowing seamless manual inference on whisper-large-v3 and whisper-large-v3-turbo without RuntimeError: Input type and bias type should be the same.HubertPositionalConvEmbedding when conv_pos_batch_norm=True by strictly propagating padding masks to prevent cross-sample batch contamination.pipeline() (#47869):
crop(-N) and crop(0) bounds to prevent negative slicing from silently retaining stale tokens in KV cache during rollback.sp_model.decode() in convert_tokens_to_string to properly decode byte-fallback tokens (<0x0A>, <0xF0>)._added_tokens_decoder via _sync_added_tokens() on all mutation paths (CpmAnt, Wav2Vec2, etc.).<0.24.0 allowing the published 0.23.1 release with XSS fix (AIKIDO-2026-10636).use_sub_norms config flag to bypass RMSNorm sub-layers for weight-quant-only checkpoints (PeetPedro/quantal-ternary).text_position_ids to text_features.dtype before computing sinusoids, preventing 93% of position embeddings from collapsing to zero.vocab_size from text_config to eliminate false out-of-vocab warnings for BOS/EOS tokens.normalize=True option using log_softmax to eliminate gauge shift artifacts in repetition penalty.torch.argmax in compute_tm to avoid IndexError crashes under half-precision inference.gemma4 and gemma4_unified mappings to AutoConfig.weight_map shard filenames in get_checkpoint_shard_files to strictly block path traversal (../) and arbitrary out-of-directory file reads.model.generation_config values are strictly preserved over pipeline defaults in Pipeline.__init__ with torch-optional runtime safety.**kwargs (num_items_in_batch) to self.loss_function across GenericForSequenceClassification, GenericForTokenClassification, Swinv2, ResNet, CLIP, SigLIP, and SigLIP2 classification heads.hf-mac):
torch.device("mps") assignment in pipelines, eliminating RuntimeError: Invalid device string 'mps:0'.safe_open buffer staging fallback for safetensors on macOS unified memory._AutogradFunction abstractions in tensor_parallel.py, accelerate.py, and monkey_patching.py for cross-platform imports.caching_allocator_warmup AttributeError when loading bitsandbytes quantized models with PEFT adapters.mistral_common dependency checking at module initialization to allow proper docstring parsing for MistralCommonBackend without falling back to a dummy object.transformers-ultraSlottedStaticCache (Zero-Allocation Decoding): Pre-allocates contiguous (batch_size, num_heads, max_cache_len, head_dim) buffers once and uses in-place slice copies (copy_()), eliminating $100%$ of dynamic CUDA allocations and memory fragmentation during autoregressive decoding.CUDAGraphFastRunner (<5µs Dispatch Latency): Records single-token forward passes into static CUDA Graphs with dedicated warmup streams, bypassing Python CPU interpreter overhead and dropping token stepping latency from ~120µs to <5µs.FusedLogitsSampler (O(K) In-Register Sampling): Fused single-pass temperature scaling, Top-K reduction, Top-P nucleus cumulative probability filtering, and multinomial sampling in a single contiguous sequence, cutting sampling overhead by up to 80% on large vocabularies ($V \ge 32k$).dyad_compressor):
TokenClassifierHead + SpanCNNHead) coupled via the asymmetric modulation gate $\tilde{I}i(x) = \sigma(\text{logit}{\text{tok}}(x) - \gamma \cdot \text{ReLU}(\text{logit}_{\text{span}}(x)))$.MUST_KEEP_PATTERN) and in-place $O(1)$ SlottedStaticCache KV slot compaction.ChunkedPrefillDecodeEngine):
mlx_mps_bridge):
torch_to_mlx, mlx_to_torch) with zero system RAM copies.MlxMpsHybridLinear: Executes MLX Metal SIMD matrix multiplication directly on PyTorch MPS activation tensors.MedusaTreeFastRunner):
MedusaTreeTopology).SlottedStaticCache.crop().split_kv_decode_attention):
BLOCK_N=512), achieving $100%$ SM occupancy even with $B=1$._split_kv_stage2_kernel) merging partial softmax states with zero precision loss.SpeculativeFastRunner):
cache.crop() on SlottedStaticCache upon candidate rejection.metal_msl_kernels):
METAL_BITNET_TERNARY_GEMM_MSL, METAL_FP8_DYNAMIC_GEMM_MSL) targeting Apple M1/M2/M3/M4 GPUs.uint32 2-bit bitmask unpacking and hardware-accelerated ternary GEMM (metal_bitnet_matmul, MetalBitNetLinear).metal_fp8_matmul, MetalFp8Linear).CUtensorMap binary memory layout matching NVIDIA Hopper SM90+ (H100/H200) and Blackwell SM100+ (B200) specifications.CUtensorMapStruct) and in-place zero-allocation buffer packing (TmaDescriptor.pack_into).torch._scaled_mm with fast accumulation and dynamic scaling (fp8_dynamic_quantize).NvidiaFp8TmaConfig, NvidiaFp8TmaHfQuantizer).sysctl hw.memsize), MPS cache flushing (torch.mps.empty_cache()), and MLX availability resolver.get_hf_gpu_tier): B200, H200, H100, MI300X, L40S, A100, L4, A10G, T4, Apple Silicon, Gaudi, and Neuron.get_recommended_attention_backend -> flash_attention_3, flash_attention_2, sdpa, eager).memory_tuning):
mimalloc and jemalloc automatic process detection and low-latency environment tuning (MIMALLOC_LARGE_OS_PAGES=1, PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True").gc.freeze()) to skip weight graph scans during inference.no_gc_cycle() context manager to eliminate stop-the-world GC pauses during token generation loops.FastTmaBufferPool for zero-allocation C buffer acquisition and recycling.MLX-QUANT):
quantize_ternary_numpy, unpack_ternary_numpy) in src/transformers/integrations/bitnet_mlx.py (commit 476ebc6).MPS accelerator detection and memory view optimizations in src/transformers/quantizers/quantizer_bitnet.py.hf-mac):MEM8Wave, MEM8MemoryStore) operating across four distinct cognitive frequency bands (Math $\Gamma$, Code $\text{B}$, Reasoning $\text{A}$, General $\Theta$) in src/transformers/integrations/mem8_wave.py (commit 476ebc6).inspect.signature AST parsing in LogitsProcessorList.__call__ via class-level signature caching (_cached_signatures) in src/transformers/generation/logits_process.py (commit 476ebc6).src/transformers/models/ to eliminate redundant unsqueeze memory view allocations (commit f736202).torch.cat on empty tensors for direct tensor assignment in src/transformers/cache_utils.py (commit 476ebc6).target-version = "py311", python_requires = ">=3.11.0").__slots__ memory layouts across wave states and descriptors, dropping per-object memory overhead by up to 50%.StrEnum for zero-overhead string enum comparisons and structural match/case pattern matching.nogil) execution.UltraGenerationConfigSchema, UltraQuantizationConfigSchema) for strict, rapid ingress deserialization.@dataclass(slots=True, kw_only=True) inference containers (UltraFastCausalLMOutput) for lightning-fast pattern matching in model outputs.# Install the ultra-fast fork
pip install transformers-ultra
English | 简体中文 | 繁體中文 | 한국어 | Español | 日本語 | हिन्दी | Русский | Português | తెలుగు | Français | Deutsch | Italiano | Tiếng Việt | العربية | اردو | বাংলা | فارسی | Türkçe |
State-of-the-art pretrained models for inference and training
Transformers acts as the model-definition framework for state-of-the-art machine learning with text, computer vision, audio, video, and multimodal models, for both inference and training.
It centralizes the model definition so that this definition is agreed upon across the ecosystem. transformers is the
pivot across frameworks: if a model definition is supported, it will be compatible with the majority of training
frameworks (Axolotl, Unsloth, DeepSpeed, FSDP, PyTorch-Lightning, ...), inference engines (vLLM, SGLang, TGI, ...),
and adjacent modeling libraries (llama.cpp, mlx, ...) which leverage the model definition from transformers.
We pledge to help support new state-of-the-art models and democratize their usage by having their model definition be simple, customizable, and efficient.
There are over 1M+ Transformers model checkpoints on the Hugging Face Hub you can use.
Explore the Hub today to find a model and use Transformers to help you get started right away.
Transformers works with Python 3.10+, and PyTorch 2.5+.
Create and activate a virtual environment with venv or uv, a fast Rust-based Python package and project manager.
# venv
python -m venv .my-env
source .my-env/bin/activate
# uv
uv venv .my-env
source .my-env/bin/activate
Install Transformers in your virtual environment.
# pip
pip install "transformers[torch]"
# uv
uv pip install "transformers[torch]"
Install Transformers from source if you want the latest changes in the library or are interested in contributing. However, the latest version may not be stable. Feel free to open an issue if you encounter an error.
git clone https://github.com/huggingface/transformers.git
cd transformers
# pip
pip install '.[torch]'
# uv
uv pip install '.[torch]'
Get started with Transformers right away with the Pipeline API. The Pipeline is a high-level inference class that supports text, audio, vision, and multimodal tasks. It handles preprocessing the input and returns the appropriate output.
Instantiate a pipeline and specify model to use for text generation. The model is downloaded and cached so you can easily reuse it again. Finally, pass some text to prompt the model.
from transformers import pipeline
pipeline = pipeline(task="text-generation", model="Qwen/Qwen2.5-1.5B")
pipeline("the secret to baking a really good cake is ")
[{'generated_text': 'the secret to baking a really good cake is 1) to use the right ingredients and 2) to follow the recipe exactly. the recipe for the cake is as follows: 1 cup of sugar, 1 cup of flour, 1 cup of milk, 1 cup of butter, 1 cup of eggs, 1 cup of chocolate chips. if you want to make 2 cakes, how much sugar do you need? To make 2 cakes, you will need 2 cups of sugar.'}]
To chat with a model, the usage pattern is the same. The only difference is you need to construct a chat history (the input to Pipeline) between you and the system.
[!TIP] You can also chat with a model directly from the command line, as long as
transformers serveis running.transformers chat Qwen/Qwen2.5-0.5B-Instruct
import torch
from transformers import pipeline
chat = [
{"role": "system", "content": "You are a sassy, wise-cracking robot as imagined by Hollywood circa 1986."},
{"role": "user", "content": "Hey, can you tell me any fun things to do in New York?"}
]
pipeline = pipeline(task="text-generation", model="meta-llama/Meta-Llama-3-8B-Instruct", dtype=torch.bfloat16, device_map="auto")
response = pipeline(chat, max_new_tokens=512)
print(response[0]["generated_text"][-1]["content"])
Expand the examples below to see how Pipeline works for different modalities and tasks.
from transformers import pipeline
pipeline = pipeline(task="automatic-speech-recognition", model="openai/whisper-large-v3")
pipeline("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac")
{'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.'}
from transformers import pipeline
pipeline = pipeline(task="image-classification", model="facebook/dinov2-small-imagenet1k-1-layer")
pipeline("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
[{'label': 'macaw', 'score': 0.997848391532898},
{'label': 'sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita',
'score': 0.0016551691805943847},
{'label': 'lorikeet', 'score': 0.00018523589824326336},
{'label': 'African grey, African gray, Psittacus erithacus',
'score': 7.85409429227002e-05},
{'label': 'quail', 'score': 5.502637941390276e-05}]
from transformers import pipeline
pipeline = pipeline(task="visual-question-answering", model="Salesforce/blip-vqa-base")
pipeline(
image="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/idefics-few-shot.jpg",
question="What is in the image?",
)
[{'answer': 'statue of liberty'}]
Easy-to-use state-of-the-art models:
Lower compute costs, smaller carbon footprint:
Choose the right framework for every part of a model's lifetime:
Easily customize a model or an example to your needs:
Transformers is more than a toolkit to use pretrained models, it's a community of projects built around it and the Hugging Face Hub. We want Transformers to enable developers, researchers, students, professors, engineers, and anyone else to build their dream projects.
In order to celebrate Transformers 100,000 stars, we wanted to put the spotlight on the community with the awesome-transformers page which lists 100 incredible projects built with Transformers.
If you own or use a project that you believe should be part of the list, please open a PR to add it!
You can test most of our models directly on their Hub model pages.
Expand each modality below to see a few example models for various use cases.
sparsemat/sprs)sparsemat/sprs is the official sparse linear algebra foundation for transformers-ultra and the sovereign constellation:
sprs representation cuts attention FLOPs from $O(N^2)$ to $O(\text{nnz})$, eliminating memory bandwidth bottlenecks.sprs compressed index traversal.use sprs::{CsMatI, TriMatI};
// Constructing a DYAD sparse attention mask kernel (O(nnz) compute)
let mut tri = TriMatI::<f32, u32>::new((seq_len, seq_len));
for (row, col, weight) in dyad_sparse_entries {
tri.add_triplet(row, col, weight);
}
let csr_attention_mask: CsMatI<f32, u32> = tri.to_csr();
We now have a paper you can cite for the 🤗 Transformers library:
@inproceedings{wolf-etal-2020-transformers,
title = "Transformers: State-of-the-Art Natural Language Processing",
author = "Thomas Wolf and Lysandre Debut and Victor Sanh and Julien Chaumond and Clement Delangue and Anthony Moi and Pierric Cistac and Tim Rault and Rémi Louf and Morgan Funtowicz and Joe Davison and Sam Shleifer and Patrick von Platen and Clara Ma and Yacine Jernite and Julien Plu and Canwen Xu and Teven Le Scao and Sylvain Gugger and Mariama Drame and Quentin Lhoest and Alexander M. Rush",
booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: System Demonstrations",
month = oct,
year = "2020",
address = "Online",
publisher = "Association for Computational Linguistics",
url = "https://aclanthology.org/2020.emnlp-demos.6/",
pages = "38--45"
}
use_sub_norms=False in BitNetConfig for zero-overhead ternary checkpoints (PeetPedro/quantal-ternary).MLX-QUANT.(top 30 of 436)
Python
99.9%