TorchNeuron: running HF models on AWS Trainium is easier than ever

2026年10月19日 00:00
站內 AI 整理稿

Back to Articles TorchNeuron: running HF models on AWS Trainium is easier than ever Published October 19, 2026 Update on GitHub Upvote 2 Régis Pierrard regisss Follow Simon Pagezy pagezyhf Follow Michael Benayoun michaelbenayoun Follow Jingya Huang Jingya Follow Alvaro Moran tengomucho Follow David Corvoysier dacorvo Follow Jeff Boudier jeffboudier Follow 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 devicemap=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 torchneuronx # noqa: F401 from torch.distributed import DeviceMesh from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig from transformers.distributed import DistributedConfig from transformers.generation.

configurationutils import CompileConfig MODELID = "Qwen/Qwen3.8-27B" MAXSEQLEN = 1024 PREFILLCHUNKSIZE = 512 dist.initprocessgroup(backend="neuron") worldsize = dist.getworldsize() model = AutoModelForCausalLM.frompretrained( MODELID, dtype=torch.

bfloat16, distributedconfig=DistributedConfig(tpsize=worldsize), devicemesh=DeviceMesh("neuron", list(range(worldsize))), ).eval() tokenizer = AutoTokenizer.frompretrained(MODELID) if tokenizer.padtoken is None: tokenizer.padtoken = tokenizer.eostoken tokenizer.

paddingside = "left" inputs = tokenizer.

applychattemplate( [{"role": "user", "content": "The future of AI is"}], addgenerationprompt=True, padding=True, tokenizerkwargs={"padtomultipleof": PREFILLCHUNKSIZE}, returntensors="pt", ) generationconfig = GenerationConfig( maxnewtokens=128, dosample=False, usecache=True, padtokenid=tokenizer.

padtokenid, eostokenid=tokenizer.eostokenid, cacheimplementation="static", maxcachelen=MAXSEQLEN, prefillchunksize=PREFILLCHUNKSIZE, compileconfig=CompileConfig(backend="neuron", fullgraph=False, dynamic=False), ) with torch.nograd(): outputids = model.

generate( inputs["inputids"], attentionmask=inputs["attentionmask"], generationconfig=generationconfig, ) if dist.getrank() == 0: promptlen = inputs["inputids"].shape[1] print(tokenizer.

decode(outputids[0, promptlen:], skipspecialtokens=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 loaddataset from transformers.

distributed import DistributedConfig from trl import ModelConfig, ScriptArguments, SFTConfig, SFTTrainer, TrlParser def main(scriptargs, trainingargs, modelargs): # The Neuron backend can't compile Dynamo's automatic dynamic shapes yet (https://github.com/huggingface/trl/issues/7660) torch.dynamo.

config.automaticdynamicshapes = False trainingargs.modelinitkwargs = { "revision": modelargs.modelrevision, "trustremotecode": trainingargs.trustremotecode, "attnimplementation": modelargs.attnimplementation, "dtype": modelargs.dtype, "devicemap": None, } if int(os.environ.

get("WORLDSIZE", "1")) > 1: # The model is sharded on the TP x FSDP grid as its weights are loaded trainingargs.modelinitkwargs["distributedconfig"] = DistributedConfig( tpsize=int(os.environ.get("TPSIZE", "1")), fsdpsize=int(os.environ.

get("FSDPSIZE", "1")), ) # Prepare dataset traindataset = loaddataset( scriptargs.datasetname, name=scriptargs.datasetconfig, split=scriptargs.datasettrainsplit, ) # UltraChat also has a string prompt column, which makes TRL treat it as a prompt-completion dataset.traindataset = traindataset.

selectcolumns(["messages"]) # Training trainer = SFTTrainer( model=modelargs.modelnameorpath, args=trainingargs, traindataset=traindataset, ) trainer.train() trainer.savemodel(trainingargs.outputdir) trainer.

end() if name == "main": parser = TrlParser((ScriptArguments, SFTConfig, ModelConfig)) scriptargs, trainingargs, modelargs = parser.parseargsandconfig() main(scriptargs, trainingargs, modelargs) Parallelism is handled natively by Transformers.

You put a DistributedConfig with the tensor-parallel (TP) and FSDP sizes in modelinitkwargs, SFTTrainer passes it to frompretrained, 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 --torchcompile 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 HFDEACTIVATEASYNCLOAD=1.The command below launches training with torchrun, which starts one process per NeuronCore.

TPSIZE and FSDPSIZE set the parallelism layout, and their product is the number of processes: here 4 x 8 = 32, matching --nprocpernode.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.TPSIZE=4 FSDPSIZE=8 HFDEACTIVATEASYNCLOAD=1 uv run torchrun --nprocpernode=32 sftneuronexample.

py \ --modelnameorpath Qwen/Qwen3-8B \ --datasetname HuggingFaceH4/ultrachat200k \ --datasettrainsplit trainsft \ --outputdir Qwen3-8B-sft-tp4-fsdp8 \ --dtype bfloat16 \ --maxlength 2048 \ --packing true \ --packingstrategy wrapped \ --learningrate 2e-5 \ --warmupsteps 0.

03 \ --numtrainepochs 1 \ --loggingsteps 2 \ --perdevicetrainbatchsize 4 \ --gradientaccumulationsteps 4 \ --saveonlymodel true \ --torchcompile true We ran it on 8 Trainium2 chips (32 NeuronCores), which is half a trn2.48xlarge instance.Training runs to completion, and trainer.

savemodel 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, torchneuronx # TP from torch.distributed.

devicemesh import DeviceMesh # TP from diffusers import QwenImage21Pipeline, QwenImage21Transformer2DModel, TensorParallelConfig # Distributed devices initialization dist.initprocessgroup(backend="neuron") # TP dev = torch.neuron.

currentdevice() mesh = DeviceMesh("neuron", list(range(8))) # TP=8 # Pipeline initialization model = "Qwen/Qwen-Image-2.1" transformer = QwenImage21Transformer2DModel.frompretrained( model, subfolder="transformer", torchdtype=torch.

bfloat16, parallelconfig=TensorParallelConfig(mesh=mesh), # TP ) pipe = QwenImage21Pipeline.frompretrained( model, transformer=transformer, torchdtype=torch.bfloat16, ) pipe.vae.to(dev) pipe.transformer.

compilerepeatedblocks(backend="neuron", fullgraph=True, dynamic=False) # Image generation emb, mask, = pipe.encodeprompt(prompt="A capybara wearing a wizard hat, oil painting", device="cpu") # text encoder stays on CPU image = pipe( promptembeds=emb.to(dev), promptembedsmask=mask.

to(dev) if mask is not None else None, height=1024, width=1024, numinferencesteps=40, generator=torch.Generator("cpu").manualseed(0), # same noise on every rank ).images[0] if dist.getrank() == 0: image.save("out.

png") You can run this piece of code with: NEURONLOGICALNCCONFIG=2 torchrun --nprocpernode=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.More Articles from our Blog torchprofileCUDA Profiling in PyTorch (Part 2): From nn.

Linear to a Fused MLP +1 65 June 11, 2026 torchprofileCUDA Profiling in PyTorch (Part 1): A Beginner's Guide to torch.profiler +1 182 May 29, 2026 Community EditPreview Upload images, audio, and videos by dragging in the text input, pasting, or clicking here.

Tap or paste here to upload images Comment · Sign up or log in to comment Upvote 2

Related

相關文章

AI助手初創公司Town完成1.08億美元B輪融資,估值突破10億美元

Town成立僅兩年,於四個月前正式上線,隨後在數週內實現數百萬美元的年度經常性收入(ARR)。截至目前,公司累計融資至少1.6億美元,此前於6月完成5500萬美元A輪融資。Town由前Plaid首席技術官Jean-Denis Greze創立,主要面向企業市場,為每位員工提供名為Townie的AI助手。

2 小時前

亞馬遜推開源 TorchNeuron:改一處配置,PyTorch 就能跑在自研 Trainium 上

它的賣點很直接:開發者寫好的 PyTorch 代碼,無需重寫,只改一處配置,就能在亞馬遜自研的 Trainium 芯片上原生跑起來。這套工具定於 20 日在加州聖何塞的北美 PyTorch 大會上以開源許可正式發佈。為了證明"無縫"不是嘴上說說,亞馬遜工程師把同一份 AI 訓練腳本分別跑在傳統芯片和 Trainium 上,唯獨區別是代碼裡指定所用芯片的設置參數。

2 小時前6600
MarkTechPost AI模型更新

Meet Drex Max: Nace AI’s Multimodal Decision Model for Computer-Use Agents with a Score 67.59

Nace AI has released Drex Max, a multimodal decision model for agents that use computers and browsers. The Drex Max multimodal decision model reads text and images and returns calibrated probabilities. It writes no text. Nace team reports 67.59 on the public Decision Index 0.3.2, 6.9 points above TypeSafe’s Jev 1.14. For agent builders, that means one cheap, typed call per click. TL;DR Size: Parameters not disclosed. Up to 262,144 tokens per question on the API, including image tokens. Runs on: Hosted API only (drex-max on Nace Console). No open weights or quantized builds announced. Performance: 67.59 on Decision Index 0.3.2 (public), the top score Nace lists for any decision model. Best: 98.2 on BFCL tool calling, and 92.2 on JevBench versus 86.7 for Jev 1.14. Worst: 19.0 on HLE, and 72.

4 小時前
何夕2077模型更新

本期AI資訊彙總2026年10月20日的產品更新、前沿研究、行業趨勢與開源項目,幫助讀者快速瞭解當天的重要動態

導航SecureDoc // EncryptionActive本期AI資訊彙總2026年10月20日的產品更新、前沿研究、行業趨勢與開源項目,幫助讀者快速瞭解當天的重要動態。" AI資訊 | 每日早讀 | 全網數據聚合 | 前沿科學探索 | 行業自由發聲 | 開源創新力量 | AI與人類未來 | 訪問網頁版↗️ | 進群交流🤙 今日摘要 Meta實驗顯示智能體學習效率與任務表現並不同步 Grok Bot升級電腦任務提速三倍下載暴漲七倍 可靈4.

4 小時前