• bitcoinBitcoin(BTC)$78,601.00-0.35%
  • ethereumEthereum(ETH)$2,487.740.15%
  • tetherTether(USDT)$1.00-0.01%
  • binancecoinBNB(BNB)$748.820.76%
  • rippleXRP(XRP)$1.421.57%
  • usd-coinUSDC(USDC)$1.000.01%
  • solanaSolana(SOL)$103.22-0.06%
  • tronTRON(TRX)$0.3391261.28%
  • Figure HelocFigure Heloc(FIGR_HELOC)$1.040.00%
  • zcashZcash(ZEC)$1,184.324.39%
  • HyperliquidHyperliquid(HYPE)$85.091.28%
  • dogecoinDogecoin(DOGE)$0.089540-0.43%
  • RainRain(RAIN)$0.015976-1.85%
  • USDSUSDS(USDS)$1.000.02%
  • whitebitWhiteBIT Coin(WBT)$81.376.58%
  • moneroMonero(XMR)$500.32-1.94%
  • chainlinkChainlink(LINK)$12.39-2.17%
  • leo-tokenLEO Token(LEO)$9.18-0.34%
  • cardanoCardano(ADA)$0.216352-0.92%
  • stellarStellar(XLM)$0.186910-1.29%
  • bitcoin-cashBitcoin Cash(BCH)$257.86-0.28%
  • daiDai(DAI)$1.000.00%
  • Ethena USDeEthena USDe(USDE)$1.000.01%
  • CantonCanton(CC)$0.1083791.64%
  • USD1USD1(USD1)$1.00-0.02%
  • uniswapUniswap(UNI)$6.79-2.82%
  • litecoinLitecoin(LTC)$53.70-2.48%
  • the-open-networkGram (prev. Toncoin)(GRAM)$1.38-0.27%
  • hedera-hashgraphHedera(HBAR)$0.078548-3.82%
  • avalanche-2Avalanche(AVAX)$7.95-1.33%
  • Global DollarGlobal Dollar(USDG)$1.00-0.02%
  • suiSui(SUI)$0.81-2.04%
  • shiba-inuShiba Inu(SHIB)$0.000005-1.22%
  • nearNEAR Protocol(NEAR)$2.28-0.19%
  • crypto-com-chainCronos(CRO)$0.0600414.19%
  • paypal-usdPayPal USD(PYUSD)$1.000.02%
  • BlackRock USD Institutional Digital Liquidity FundBlackRock USD Institutional Digital Liquidity Fund(BUIDL)$1.000.00%
  • MemeCoreMemeCore(M)$1.192.24%
  • tether-goldTether Gold(XAUT)$4,375.22-1.28%
  • Circle USYCCircle USYC(USYC)$1.140.01%
  • BittensorBittensor(TAO)$255.55-0.26%
  • Ripple USDRipple USD(RLUSD)$1.000.00%
  • okbOKB(OKB)$113.99-1.75%
  • Ondo US Dollar YieldOndo US Dollar Yield(USDY)$1.150.39%
  • mantleMantle(MNT)$0.631.02%
  • polkadotPolkadot(DOT)$1.2011.41%
  • AsterAster(ASTER)$0.75-1.68%
  • aaveAave(AAVE)$128.19-2.18%
  • pax-goldPAX Gold(PAXG)$4,378.35-1.29%
  • Pump.funPump.fun(PUMP)$0.0044783.02%
TradePoint.io
  • Main
  • AI & Technology
  • Stock Charts
  • Market & News
  • Business
  • Finance Tips
  • Trade Tube
  • Blog
  • Shop
No Result
View All Result
TradePoint.io
No Result
View All Result

How to Speed Up Transformer Training Using NVIDIA Apex (FusedAdam, FusedLayerNorm) and Native torch.amp

June 2, 2026
in AI & Technology
Reading Time: 2 mins read
A A
How to Speed Up Transformer Training Using NVIDIA Apex (FusedAdam, FusedLayerNorm) and Native torch.amp
ShareShareShareShareShare

YOU MAY ALSO LIKE

NSA, CISA, FBI Warn China-Based AI Firms Distill US Frontier Models – Unite.AI

How To Change And Customize Your Apple CarPlay Display

print("\n### SECTION D: end-to-end Transformer (vanilla fp32 vs Apex fused + AMP) ###")
VOCAB, D, NHEAD, LAYERS, SEQ, BATCH, STEPS = 2000, 256, 4, 4, 128, 32, 60
class Block(torch.nn.Module):
   def __init__(self, d, nhead, norm_cls):
       super().__init__()
       self.attn = torch.nn.MultiheadAttention(d, nhead, batch_first=True)
       self.ff = torch.nn.Sequential(torch.nn.Linear(d, 4 * d), torch.nn.GELU(),
                                     torch.nn.Linear(4 * d, d))
       self.n1, self.n2 = norm_cls(d), norm_cls(d)
   def forward(self, x):
       h = self.n1(x); x = x + self.attn(h, h, h, need_weights=False)[0]
       return x + self.ff(self.n2(x))
class TinyTransformer(torch.nn.Module):
   def __init__(self, norm_cls):
       super().__init__()
       self.emb = torch.nn.Embedding(VOCAB, D)
       self.blocks = torch.nn.ModuleList([Block(D, NHEAD, norm_cls) for _ in range(LAYERS)])
       self.norm = norm_cls(D)
       self.head = torch.nn.Linear(D, VOCAB)
   def forward(self, idx):
       x = self.emb(idx)
       for b in self.blocks:
           x = b(x)
       return self.head(self.norm(x))
g = torch.Generator(device="cpu").manual_seed(0)
data = torch.randint(0, VOCAB, (BATCH, SEQ + 1), generator=g).to(DEV)
inp, tgt = data[:, :-1], data[:, 1:]
lossfn = torch.nn.CrossEntropyLoss()
def run_training(use_apex):
   torch.manual_seed(0)
   norm_cls = (FusedLayerNorm if (use_apex and HAS_FLN and APEX_OK) else torch.nn.LayerNorm)
   model = TinyTransformer(norm_cls).to(DEV)
   if use_apex and HAS_AMP_C and APEX_OK:
       optimizer = FusedAdam(model.parameters(), lr=3e-4)
   else:
       optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4)
   scaler = torch.amp.GradScaler("cuda", enabled=use_apex)
   def one_step():
       optimizer.zero_grad(set_to_none=True)
       with torch.amp.autocast("cuda", dtype=torch.float16, enabled=use_apex):
           logits = model(inp)
           loss = lossfn(logits.reshape(-1, VOCAB), tgt.reshape(-1))
       scaler.scale(loss).backward()
       scaler.step(optimizer)
       scaler.update()
       return loss
   for _ in range(5):
       one_step()
   torch.cuda.synchronize()
   t0 = time.perf_counter()
   for _ in range(STEPS):
       loss = one_step()
   torch.cuda.synchronize()
   dt = time.perf_counter() - t0
   return loss.item(), (STEPS * BATCH * SEQ) / dt, dt
loss_v, tps_v, dt_v = run_training(use_apex=False)
print(f"  vanilla (fp32, nn.LayerNorm, AdamW)        : "
     f"{dt_v:5.2f}s  | {tps_v:9.0f} tok/s | final loss {loss_v:.3f}")
if APEX_OK and (HAS_AMP_C or HAS_FLN):
   loss_a, tps_a, dt_a = run_training(use_apex=True)
   print(f"  apex   (fp16, FusedLayerNorm, FusedAdam)   : "
         f"{dt_a:5.2f}s  | {tps_a:9.0f} tok/s | final loss {loss_a:.3f}")
   print(f"  ----> speedup: {tps_a / tps_v:0.2f}x throughput")
else:
   print("  apex path SKIPPED (no fused kernels built)")
print("\n" + "=" * 78)
print("DONE. Key takeaways:")
print("  - FusedAdam/FusedLayerNorm/FusedRMSNorm are the still-relevant Apex pieces;")
print("    speedups grow with model size & parameter count (tiny demo understates it).")
print("  - apex.amp is deprecated -> prefer torch.amp.autocast + torch.amp.GradScaler.")
print("  - FusedAdam composes cleanly with native torch.amp (Section D).")
print("  - On real workloads, also try a larger model and bf16 autocast (no scaler needed).")
print("=" * 78)

Credit: Source link

ShareTweetSendSharePin

Related Posts

NSA, CISA, FBI Warn China-Based AI Firms Distill US Frontier Models – Unite.AI
AI & Technology

NSA, CISA, FBI Warn China-Based AI Firms Distill US Frontier Models – Unite.AI

September 9, 2026
How To Change And Customize Your Apple CarPlay Display
AI & Technology

How To Change And Customize Your Apple CarPlay Display

September 8, 2026
Is There Any Benefit To Restarting Your PC Regularly?
AI & Technology

Is There Any Benefit To Restarting Your PC Regularly?

September 8, 2026
Sierra Open-Sources Hyper-τ-Bench, a Benchmark for Agent Construction
AI & Technology

Sierra Open-Sources Hyper-τ-Bench, a Benchmark for Agent Construction

September 8, 2026
Next Post
Saudi Arabian Crown Prince’s  trillion, desert-city dream in tatters as megaproject halted

Saudi Arabian Crown Prince’s $12 trillion, desert-city dream in tatters as megaproject halted

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Search

No Result
View All Result
Global Forex Shifts: Yen Carry Trade Unwinds Amid Policy Divergence

Global Forex Shifts: Yen Carry Trade Unwinds Amid Policy Divergence

September 7, 2026
How To Reset The Camera Settings On Your iPhone

How To Reset The Camera Settings On Your iPhone

September 8, 2026
Oil nears 0 a barrel as Middle East tensions fuel inflation fears

Oil nears $100 a barrel as Middle East tensions fuel inflation fears

September 8, 2026

About

Learn more

Our Services

Legal

Privacy Policy

Terms of Use

Bloggers

Learn more

Article Links

Contact

Advertise

Ask us anything

©2020- TradePoint.io - All rights reserved!

Tradepoint.io, being just a publishing and technology platform, is not a registered broker-dealer or investment adviser. So we do not provide investment advice. Rather, brokerage services are provided to clients of Tradepoint.io by independent SEC-registered broker-dealers and members of FINRA/SIPC. Every form of investing carries some risk and past performance is not a guarantee of future results. “Tradepoint.io“, “Instant Investing” and “My Trading Tools” are registered trademarks of Apperbuild, LLC.

This website is operated by Apperbuild, LLC. We have no link to any brokerage firm and we do not provide investment advice. Every information and resource we provide is solely for the education of our readers. © 2020 Apperbuild, LLC. All rights reserved.

No Result
View All Result
  • Main
  • AI & Technology
  • Stock Charts
  • Market & News
  • Business
  • Finance Tips
  • Trade Tube
  • Blog
  • Shop

© 2023 - TradePoint.io - All Rights Reserved!