TorchNeuron 为 AWS Trainium 上的 PyTorch 提供了一个全新的原生后端。Transformers、Diffusers 和 Kernels 均原生支持该后端,使得在 Trainium 上运行模型以及在 HF Hub 上共享模型变得前所未有的简单。
TorchNeuron
TorchNeuron 是一个 PyTorch 插件,它为 Trainium 带来了新的后端,从而支持 eager 模式、torch.compile 以及 FSDP 和 TP 等原生分布式 API。
阅读 PyTorch 博客以了解更多关于 TorchNeuron 的信息。
自 2026 年 10 月 20 日起,TorchNeuron 将作为公开测试版提供。研究人员和开发者可以通过运行 pip install torch-neuronx 来安装它。
HF 库中的新后端与原生接口
迄今为止,在 AWS Trainium 和 Inferentia(分别专为大规模低成本训练和推理而设计的 AI 芯片)上的 Hugging Face 体验是通过 optimum-neuron 提供的。该库依赖于基于 PyTorch XLA 的 torch-neuronx 包。在当时这是自然的选择,但它意味着需要像编译器一样思考:使用懒张量而非 eager 执行、仅支持静态形状、每次图断裂都要重新编译。Optimum Neuron 的存在是为了隐藏这种复杂性,并维护自定义代码(如建模类、训练器等)以实现这一目标。
TorchNeuron 改变了这一点。它直接集成到 PyTorch 中,并将 neuron 暴露为原生设备,支持 eager 执行、PyTorch 自身的分布式原语(DTensor、FSDP2)以及 torch.compile 。
对于 Hugging Face 的库而言,Trainium 变成了与其他任何设备一样的存在:Transformers、Diffusers、Accelerate、PEFT 和 TRL 可以直接在其上运行,使用你在任何其他加速器上会使用的相同类和脚本。从现在开始,我们建议 Neuron 用户直接使用这些库,而不是通过 Optimum Neuron。
Transformers
推理
文本生成现在在 Transformers 中得到了原生支持,适用于广泛范围的模型。借助 TorchNeuron,开箱即用地支持了前 100 个最常用文本生成模型架构中的 89%,而 Optimum Neuron v0.4.5 仅支持 46%。你只需在代码中传入 device_map="neuron" 参数,你的模型就会被移动到 Neuron 设备上。
以下是一个使用张量并行进行文本生成的示例,这将使你能够充分利用你的 Neuron 实例。请注意,它使用了静态缓存进行生成,因为强烈建议在使用 Neuron 时这样做以防止频繁的重新编译。
import os
import torch
import torch.distributed as dist
import torch_neuronx
from torch.distributed import DeviceMesh
from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig
from transformers.distributed import DistributedConfig
from transformers.generation.configuration_utils import CompileConfig
MODEL_ID = "Qwen/Qwen3.8-27B"
MAX_SEQ_LEN = 1024
PREFILL_CHUNK_SIZE = 512
dist.init_process_group(backend= "neuron" )
world_size = dist.get_world_size()
model = AutoModelForCausalLM.from_pretrained(
MODEL_ID,
dtype=torch.bfloat16,
distributed_config=DistributedConfig(tp_size=world_size),
device_mesh=DeviceMesh( "neuron" , list ( range (world_size))),
). eval ()
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
if tokenizer.pad_token is None :
tokenizer.pad_token = tokenizer.eos_token
tokenizer.padding_side = "left"
inputs = tokenizer.apply_chat_template(
[{ "role" : "user" , "content" : "The future of AI is" }],
add_generation_prompt= True ,
padding= True ,
tokenizer_kwargs={ "pad_to_multiple_of" : PREFILL_CHUNK_SIZE},
return_tensors= "pt" ,
)
generation_config = GenerationConfig(
max_new_tokens= 128 ,
do_sample= False ,
use_cache= True ,
pad_token_id=tokenizer.pad_token_id,
eos_token_id=tokenizer.eos_token_id,
cache_implementation= "static" ,
max_cache_len=MAX_SEQ_LEN,
prefill_chunk_size=PREFILL_CHUNK_SIZE,
compile_config=CompileConfig(backend= "neuron" , fullgraph= False , dynamic= False ),
)
with torch.no_grad():
output_ids = model.generate(
inputs[ "input_ids" ],
attention_mask=inputs[ "attention_mask" ],
generation_config=generation_config,
)
if dist.get_rank() == 0 :
prompt_len = inputs[ "input_ids" ].shape[ 1 ]
print (tokenizer.decode(output_ids[ 0 , prompt_len:], skip_special_tokens= True ))
训练
既然 Neuron 已成为原生的 PyTorch 设备,在 Trainium 上进行训练所使用的 Hugging Face 库与任何其他加速器相同:Transformers、Accelerate、PEFT 和 TRL。你不再需要专用的训练器或模型代码的 Neuron 特定分支。标准的 TRL 微调脚本只需设置少数几个 Neuron 特定的参数,即可在 Trainium 实例上运行。
以下是一个基于 TRL 的 SFTTrainer 构建的监督微调脚本。如果你之前使用 TRL 在 GPU 上微调过模型,这个脚本看起来应该很熟悉。
import os
import torch
from datasets import load_dataset
from transformers.distributed import DistributedConfig
from trl import ModelConfig, ScriptArguments, SFTConfig, SFTTrainer, TrlParser
def main ( script_args, training_args, model_args ):
torch._dynamo.config.automatic_dynamic_shapes = False
training_args.model_init_kwargs = {
"revision" : model_args.model_revision,
"trust_remote_code" : training_args.trust_remote_code,
"attn_implementation" : model_args.attn_implementation,
"dtype" : model_args.dtype,
"device_map" : None ,
}
if int (os.environ.get( "WORLD_SIZE" , "1" )) > 1 :
training_args.model_init_kwargs[ "distributed_config" ] = DistributedConfig(
tp_size= int (os.environ.get( "TP_SIZE" , "1" )),
fsdp_size= int (os.environ.get( "FSDP_SIZE" , "1" )),
)
train_dataset = load_dataset(
script_args.dataset_name,
name=script_args.dataset_config,
split=script_args.dataset_train_split,
)
train_dataset = train_dataset.select_columns([ "messages" ])
trainer = SFTTrainer(
model=model_args.model_name_or_path,
args=training_args,
train_dataset=train_dataset,
)
trainer.train()
trainer.save_model(training_args.output_dir)
trainer.end()
if name == "main" :
parser = TrlParser((ScriptArguments, SFTConfig, ModelConfig))
script_args, training_args, model_args = parser.parse_args_and_config()
main(script_args, training_args, model_args)
并行处理由 Transformers 原生支持。你在 model_init_kwargs 中放入包含张量并行 (TP) 和 FSDP 大小的 DistributedConfig,SFTTrainer 会将其传递给 from_pretrained,模型在加载权重时即被分片。训练器检测到模型已经分布式部署,因此不会再次包装它。你不需要 --fsdp 标志或 Accelerate 的 FSDP 配置。
脚本中没有任何内容与 Trainium 绑定:相同的代码可在任何硬件上运行。在 Trainium 上运行时有几点值得注意:
静态形状。该脚本禁用了 torch.compile 中的自动动态形状,并使用包装打包(wrapped packing)来生成长度最多为 2048 个 token 的序列。在 TRL ≥ 1.16 版本中,Neuron 上的批次会被填充至 128 个 token 的倍数,从而限制了输入形状的数量。编译后的图会在后续具有相同形状的步骤中被重用。
启用 torch.compile。只需传递 --torch_compile true:在 Trainium 实例上,torch.compile 会自动检测设备并选择 Neuron 后端,无需其他配置。
禁用异步权重加载。Transformers 内置的异步权重加载功能在 Neuron 上不受支持,因此目前我们通过设置 HF_DEACTIVATE_ASYNC_LOAD=1 将其禁用。
下面的命令使用 torchrun 启动训练,它为每个 NeuronCore 启动一个进程。TP_SIZE 和 FSDP_SIZE 设置并行布局,它们的乘积即为进程数:此处为 4 x 8 = 32,与 --nproc_per_node 相匹配。这 32 个进程形成一个 4 x 8 的网格。张量并行将每一层拆分到 TP 组的 4 个核心上,而 FSDP 则在 8 个 TP 组之间分片参数、梯度和优化器状态。
TP_SIZE=4 FSDP_SIZE=8 HF_DEACTIVATE_ASYNC_LOAD=1 uv run torchrun --nproc_per_node=32 sft_neuron_example.py \
--model_name_or_path Qwen/Qwen3-8B \
--dataset_name HuggingFaceH4/ultrachat_200k \
--dataset_train_split train_sft \
--output_dir Qwen3-8B-sft-tp4-fsdp8 \
--dtype bfloat16 \
--max_length 2048 \
--packing true \
--packing_strategy wrapped \
--learning_rate 2e-5 \
--warmup_steps 0.03 \
--num_train_epochs 1 \
--logging_steps 2 \
--per_device_train_batch_size 4 \
--gradient_accumulation_steps 4 \
--save_only_model true \
--torch_compile true
我们在8个Trainium2芯片(共32个NeuronCores)上运行了该脚本,这相当于半个trn2.48xlarge实例。
训练顺利运行至完成,trainer.save_model会生成一个标准的Transformers检查点。其中没有任何内容与Neuron绑定:你可以直接将其推送到Hugging Face Hub,并在任何其他硬件上加载使用。
Diffusers
推理
Diffusers库中的许多管道都兼容TorchNeuron的eager模式和编译模式。FLUX.1-dev、FLUX.2、Qwen-Image、Qwen-Image-2.1和H3也支持张量并行,以充分利用你的Neuron设备。以下是一个展示如何使用TP的示例:
import torch, torch.distributed as dist, torch_neuronx
from torch.distributed.device_mesh import DeviceMesh
from diffusers import QwenImage21Pipeline, QwenImage21Transformer2DModel, TensorParallelConfig
dist.init_process_group(backend= "neuron" )
dev = torch.neuron.current_device()
mesh = DeviceMesh( "neuron" , list ( range ( 8 )))
model = "Qwen/Qwen-Image-2.1"
transformer = QwenImage21Transformer2DModel.from_pretrained(
model,
subfolder= "transformer" ,
torch_dtype=torch.bfloat16,
parallel_config=TensorParallelConfig(mesh=mesh),
)
pipe = QwenImage21Pipeline.from_pretrained(
model,
transformer=transformer,
torch_dtype=torch.bfloat16,
)
pipe.vae.to(dev)
pipe.transformer.compile_repeated_blocks(backend= "neuron" , fullgraph= True , dynamic= False )
emb, mask, _ = pipe.encode_prompt(prompt= "A capybara wearing a wizard hat, oil painting" , device= "cpu" )
image = pipe(
prompt_embeds=emb.to(dev),
prompt_embeds_mask=mask.to(dev) if mask is not None else None ,
height= 1024 ,
width= 1024 ,
num_inference_steps= 40 ,
generator=torch.Generator( "cpu" ).manual_seed( 0 ),
).images[ 0 ]
if dist.get_rank() == 0 :
image.save( "out.png" )
你可以使用以下命令运行此段代码:NEURON_LOGICAL_NC_CONFIG=2 torchrun --nproc_per_node=8 run.py .
越来越多的管道将支持TP。如果你喜欢的管道尚不支持,你也可以按照本指南为其添加支持。
内核
请务必查看Neuron团队提供的内核,因为Hub上将陆续提供更多Neuron内核,以加速你的模型。
Neuron内核可以使用Neuron Kernel Interface (NKI) 编写,从而获得更底层的控制来优化操作。这样,用户可以运行自己的自定义操作并将其分享到Hub上。
例如,你可以使用以下内核,在Trainium上实现高达2.4倍的视觉Transformer加速!
致谢
特别感谢AWS团队在TorchNeuron方面所做的工作,以及他们对我们反馈的快速响应,以使HF集成达到最佳状态。
TorchNeuron provides a new native backend for PyTorch on AWS Trainium. Transformers, Diffusers and Kernels natively support it, making it easier than ever to run models on Trainium and to share them on the HF hub.
TorchNeuron
TorchNeuron is a PyTorch plugin that brings a new backend for Trainium enabling support for eager mode, torch.compile and native distributed APIs like FSDP and TP.
Read the Pytorch blog to learn more about TorchNeuron.
Starting Oct. 20, 2026, TorchNeuron will be available as a public beta. Researchers and developers will be able to install it with pip install torch-neuronx .
New backend, native interface in HF libraries
To date, the Hugging Face experience on AWS Trainium and Inferentia — AI chips designed respectively for cost-effective training and inference at scale — has been delivered through optimum-neuron . This library relies on the torch-neuronx package, which is based on PyTorch XLA. It was the natural choice at the time, but it meant thinking like a compiler: lazy tensors instead of eager execution, static shapes only, a recompilation for every graph break. Optimum Neuron existed to hide that complexity, and maintained custom code (modeling classes, trainers, etc) to do so.
TorchNeuron changes this. It integrates directly into PyTorch and exposes neuron as a native device, with eager execution, PyTorch's own distributed primitives (DTensor, FSDP2) and torch.compile .
For the Hugging Face libraries, Trainium becomes a device like any other: Transformers, Diffusers, Accelerate, PEFT and TRL run on it directly, with the same classes and scripts you would use on any other accelerator. From now on, we recommend that Neuron users use these libraries directly instead of going through Optimum Neuron.
Transformers
Inference
Text generation is now natively supported in Transformers for a wide range of models. With TorchNeuron, 89% of the top 100 most-used text-generation model architectures are supported out of the box, compared to 46% with Optimum Neuron v0.4.5. You just need to pass the device_map=neuron argument in your code and your model will be moved to the Neuron devices.
The following is an example of text-generation with tensor parallelism, which will enable to fully benefit from your Neuron instance. Note that it uses a static cache for generation as this is strongly recommended with Neuron to prevent frequent recompilations.
import os
import torch
import torch.distributed as dist
import torch_neuronx
from torch.distributed import DeviceMesh
from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig
from transformers.distributed import DistributedConfig
from transformers.generation.configuration_utils import CompileConfig
MODEL_ID = "Qwen/Qwen3.8-27B"
MAX_SEQ_LEN = 1024
PREFILL_CHUNK_SIZE = 512
dist.init_process_group(backend= "neuron" )
world_size = dist.get_world_size()
model = AutoModelForCausalLM.from_pretrained(
MODEL_ID,
dtype=torch.bfloat16,
distributed_config=DistributedConfig(tp_size=world_size),
device_mesh=DeviceMesh( "neuron" , list ( range (world_size))),
). eval ()
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
if tokenizer.pad_token is None :
tokenizer.pad_token = tokenizer.eos_token
tokenizer.padding_side = "left"
inputs = tokenizer.apply_chat_template(
[{ "role" : "user" , "content" : "The future of AI is" }],
add_generation_prompt= True ,
padding= True ,
tokenizer_kwargs={ "pad_to_multiple_of" : PREFILL_CHUNK_SIZE},
return_tensors= "pt" ,
)
generation_config = GenerationConfig(
max_new_tokens= 128 ,
do_sample= False ,
use_cache= True ,
pad_token_id=tokenizer.pad_token_id,
eos_token_id=tokenizer.eos_token_id,
cache_implementation= "static" ,
max_cache_len=MAX_SEQ_LEN,
prefill_chunk_size=PREFILL_CHUNK_SIZE,
compile_config=CompileConfig(backend= "neuron" , fullgraph= False , dynamic= False ),
)
with torch.no_grad():
output_ids = model.generate(
inputs[ "input_ids" ],
attention_mask=inputs[ "attention_mask" ],
generation_config=generation_config,
)
if dist.get_rank() == 0 :
prompt_len = inputs[ "input_ids" ].shape[ 1 ]
print (tokenizer.decode(output_ids[ 0 , prompt_len:], skip_special_tokens= True ))
Training
Now that Neuron is a native PyTorch device, training on Trainium uses the same Hugging Face libraries as any other accelerator: Transformers, Accelerate, PEFT and TRL. You no longer need a dedicated trainer or a Neuron-specific fork of the model code. A standard TRL fine-tuning script runs on a Trainium instance with only a few Neuron-specific settings.
Here is a supervised fine-tuning script built on TRL's SFTTrainer . If you have fine-tuned a model with TRL on GPUs before, it should look familiar.
import os
import torch
from datasets import load_dataset
from transformers.distributed import DistributedConfig
from trl import ModelConfig, ScriptArguments, SFTConfig, SFTTrainer, TrlParser
def main ( script_args, training_args, model_args ):
torch._dynamo.config.automatic_dynamic_shapes = False
training_args.model_init_kwargs = {
"revision" : model_args.model_revision,
"trust_remote_code" : training_args.trust_remote_code,
"attn_implementation" : model_args.attn_implementation,
"dtype" : model_args.dtype,
"device_map" : None ,
}
if int (os.environ.get( "WORLD_SIZE" , "1" )) > 1 :
training_args.model_init_kwargs[ "distributed_config" ] = DistributedConfig(
tp_size= int (os.environ.get( "TP_SIZE" , "1" )),
fsdp_size= int (os.environ.get( "FSDP_SIZE" , "1" )),
)
train_dataset = load_dataset(
script_args.dataset_name,
name=script_args.dataset_config,
split=script_args.dataset_train_split,
)
train_dataset = train_dataset.select_columns([ "messages" ])
trainer = SFTTrainer(
model=model_args.model_name_or_path,
args=training_args,
train_dataset=train_dataset,
)
trainer.train()
trainer.save_model(training_args.output_dir)
trainer.end()
if name == "main" :
parser = TrlParser((ScriptArguments, SFTConfig, ModelConfig))
script_args, training_args, model_args = parser.parse_args_and_config()
main(script_args, training_args, model_args)
Parallelism is handled natively by Transformers. You put a DistributedConfig with the tensor-parallel (TP) and FSDP sizes in model_init_kwargs , SFTTrainer passes it to from_pretrained , and the model is sharded as its weights are loaded. The Trainer sees that the model is already distributed and does not wrap it again. You don't need an --fsdp flag or an Accelerate FSDP config.
Nothing in the script is tied to Trainium: the same code runs on any hardware. A few things are worth knowing when you run it on Trainium:
Static shapes. The script disables automatic dynamic shapes in torch.compile and uses wrapped packing to produce sequences of up to 2048 tokens. With TRL ≥ 1.16, batches on Neuron are padded to a multiple of 128 tokens, limiting the number of input shapes. Compiled graphs are reused for subsequent steps with the same shapes.
torch.compile on. Passing --torch_compile true is all it takes: on a Trainium instance, torch.compile detects the device and picks the Neuron backend automatically, with nothing else to configure.
Async weight loading off. The built-in asynchronous weight loading in Transformers is not supported on Neuron, so for now we disable it with HF_DEACTIVATE_ASYNC_LOAD=1 .
The command below launches training with torchrun , which starts one process per NeuronCore. TP_SIZE and FSDP_SIZE set the parallelism layout, and their product is the number of processes: here 4 x 8 = 32, matching --nproc_per_node . The 32 processes form a 4 x 8 grid. Tensor parallelism splits each layer across the 4 cores of a TP group, and FSDP shards the parameters, gradients and optimizer state across the 8 TP groups.
TP_SIZE=4 FSDP_SIZE=8 HF_DEACTIVATE_ASYNC_LOAD=1 uv run torchrun --nproc_per_node=32 sft_neuron_example.py \
--model_name_or_path Qwen/Qwen3-8B \
--dataset_name HuggingFaceH4/ultrachat_200k \
--dataset_train_split train_sft \
--output_dir Qwen3-8B-sft-tp4-fsdp8 \
--dtype bfloat16 \
--max_length 2048 \
--packing true \
--packing_strategy wrapped \
--learning_rate 2e-5 \
--warmup_steps 0.03 \
--num_train_epochs 1 \
--logging_steps 2 \
--per_device_train_batch_size 4 \
--gradient_accumulation_steps 4 \
--save_only_model true \
--torch_compile true
We ran it on 8 Trainium2 chips (32 NeuronCores), which is half a trn2.48xlarge instance.
Training runs to completion, and trainer.save_model writes a standard Transformers checkpoint. Nothing in it is tied to Neuron: you can push it to the Hugging Face Hub as is and load it on any other hardware.
Diffusers
Inference
Many pipelines from the Diffusers library are compatible with TorchNeuron in eager and compiled mode. FLUX.1-dev, FLUX.2, Qwen-Image, Qwen-Image-2.1 and H3 are also compatible with tensor parallelism to make the most of your Neuron devices. The following is an example showing how you can use TP:
import torch, torch.distributed as dist, torch_neuronx
from torch.distributed.device_mesh import DeviceMesh
from diffusers import QwenImage21Pipeline, QwenImage21Transformer2DModel, TensorParallelConfig
dist.init_process_group(backend= "neuron" )
dev = torch.neuron.current_device()
mesh = DeviceMesh( "neuron" , list ( range ( 8 )))
model = "Qwen/Qwen-Image-2.1"
transformer = QwenImage21Transformer2DModel.from_pretrained(
model,
subfolder= "transformer" ,
torch_dtype=torch.bfloat16,
parallel_config=TensorParallelConfig(mesh=mesh),
)
pipe = QwenImage21Pipeline.from_pretrained(
model,
transformer=transformer,
torch_dtype=torch.bfloat16,
)
pipe.vae.to(dev)
pipe.transformer.compile_repeated_blocks(backend= "neuron" , fullgraph= True , dynamic= False )
emb, mask, _ = pipe.encode_prompt(prompt= "A capybara wearing a wizard hat, oil painting" , device= "cpu" )
image = pipe(
prompt_embeds=emb.to(dev),
prompt_embeds_mask=mask.to(dev) if mask is not None else None ,
height= 1024 ,
width= 1024 ,
num_inference_steps= 40 ,
generator=torch.Generator( "cpu" ).manual_seed( 0 ),
).images[ 0 ]
if dist.get_rank() == 0 :
image.save( "out.png" )
You can run this piece of code with: NEURON_LOGICAL_NC_CONFIG=2 torchrun --nproc_per_node=8 run.py .
More and more pipleines will be compatible with TP. If a pipeline you like is not, you can also add support for it following this guide .
Kernels
Make sure to check out the kernels from the Neuron team as more and more Neuron kernels will become available on the Hub to speed up your models.
Neuron kernels can be written using the Neuron Kernel Interface (NKI), which gives lower control to optimize operations. This way, users can run their own custom operations and share them on the hub.
You can use for example this kernel to speed up your vision transformers with up to a x2.4 speedup on Trainium!
Acknowledgments
Special thanks to the AWS team for their work on TorchNeuron and for their reactivity to our feedback to make the HF integration as good as possible.
首次收录 · 2026-10-20 · 9.95 分