whisper_helper.py 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035
  1. # -------------------------------------------------------------------------
  2. # Copyright (c) Microsoft Corporation. All rights reserved.
  3. # Licensed under the MIT License. See License.txt in the project root for
  4. # license information.
  5. # --------------------------------------------------------------------------
  6. import json
  7. import logging
  8. import os
  9. from pathlib import Path
  10. import numpy as np
  11. import torch
  12. from convert_generation import add_cache_indirection_to_mha, add_output_qk_to_mha, fix_past_sequence_length
  13. from optimizer import optimize_model
  14. from transformers import AutoTokenizer, WhisperConfig, WhisperForConditionalGeneration, WhisperProcessor
  15. from whisper_decoder import WhisperDecoder
  16. from whisper_encoder import WhisperEncoder
  17. from whisper_encoder_decoder_init import WhisperEncoderDecoderInit
  18. from whisper_jump_times import WhisperJumpTimes
  19. from onnxruntime import InferenceSession
  20. logger = logging.getLogger(__name__)
  21. PRETRAINED_WHISPER_MODELS = [
  22. "whisper-tiny",
  23. "whisper-tiny.en",
  24. "whisper-base",
  25. "whisper-base.en",
  26. "whisper-small",
  27. "whisper-small.en",
  28. "whisper-medium",
  29. "whisper-medium.en",
  30. "whisper-large",
  31. "whisper-large-v2",
  32. "whisper-large-v3",
  33. "whisper-large-v3-turbo",
  34. ]
  35. class WhisperHelper:
  36. @staticmethod
  37. def get_onnx_path(
  38. output_dir: str,
  39. model_name_or_path: str,
  40. suffix: str = "",
  41. new_folder: bool = False,
  42. ) -> str:
  43. """Build onnx path
  44. Args:
  45. output_dir (str): output directory
  46. model_name_or_path (str): pretrained model name, or path to the model checkpoint
  47. suffix (str, optional): suffix like "_encoder" or "_decoder_fp16" will be appended to file name. Defaults to None.
  48. new_folder (bool, optional): create a new directory for the model. Defaults to False.
  49. Returns:
  50. str: path of onnx model
  51. """
  52. model_name = model_name_or_path
  53. if os.path.isdir(model_name_or_path):
  54. model_name = Path(model_name_or_path).parts[-1]
  55. else:
  56. model_name = model_name.split("/")[-1]
  57. model_name += suffix
  58. directory = os.path.join(output_dir, model_name) if new_folder else output_dir
  59. return os.path.join(directory, model_name + ".onnx")
  60. @staticmethod
  61. def save_processing(
  62. model_name_or_path: str,
  63. provider: str,
  64. separate_encoder_and_decoder_init: bool,
  65. use_decoder_masked_mha: bool,
  66. output_qk: bool,
  67. encoder_path: str,
  68. decoder_path: str,
  69. output_dir: str,
  70. cache_dir: str,
  71. ) -> None:
  72. config = WhisperConfig.from_pretrained(model_name_or_path, cache_dir=cache_dir)
  73. config.save_pretrained(output_dir)
  74. tokenizer = AutoTokenizer.from_pretrained(model_name_or_path, cache_dir=cache_dir)
  75. tokenizer.save_pretrained(output_dir)
  76. processor = WhisperProcessor.from_pretrained(model_name_or_path, cache_dir=cache_dir)
  77. processor.save_pretrained(output_dir)
  78. # Return early since the next files are for ONNX Runtime GenAI
  79. if separate_encoder_and_decoder_init:
  80. return
  81. audio_processor_cfg = {
  82. "feature_extraction": {
  83. "sequence": [
  84. {"operation": {"name": "audio_decoder", "type": "AudioDecoder"}},
  85. {
  86. "operation": {
  87. "name": "STFT",
  88. "type": "STFTNorm",
  89. "attrs": {
  90. "n_fft": 400,
  91. "frame_length": 400,
  92. "hop_length": 160,
  93. "_comment": [
  94. 0.0,
  95. 0.0000616908073425293,
  96. 0.0002467334270477295,
  97. 0.0005550682544708252,
  98. 0.000986635684967041,
  99. 0.0015413463115692139,
  100. 0.0022190213203430176,
  101. 0.0030195116996765137,
  102. 0.003942638635635376,
  103. 0.004988163709640503,
  104. 0.006155818700790405,
  105. 0.007445335388183594,
  106. 0.008856385946273804,
  107. 0.010388582944869995,
  108. 0.012041628360748291,
  109. 0.013815045356750488,
  110. 0.01570841670036316,
  111. 0.01772129535675049,
  112. 0.019853144884109497,
  113. 0.022103488445281982,
  114. 0.02447172999382019,
  115. 0.026957333087921143,
  116. 0.029559612274169922,
  117. 0.03227800130844116,
  118. 0.03511175513267517,
  119. 0.03806024789810181,
  120. 0.0411226749420166,
  121. 0.044298380613327026,
  122. 0.04758647084236145,
  123. 0.05098623037338257,
  124. 0.05449673533439636,
  125. 0.058117181062698364,
  126. 0.06184667348861694,
  127. 0.0656842589378357,
  128. 0.06962898373603821,
  129. 0.07367992401123047,
  130. 0.0778360664844513,
  131. 0.08209633827209473,
  132. 0.08645972609519958,
  133. 0.09092515707015991,
  134. 0.09549149870872498,
  135. 0.10015767812728882,
  136. 0.10492250323295593,
  137. 0.1097848117351532,
  138. 0.11474338173866272,
  139. 0.11979702115058899,
  140. 0.12494447827339172,
  141. 0.13018447160720825,
  142. 0.1355157196521759,
  143. 0.14093685150146484,
  144. 0.1464466154575348,
  145. 0.15204361081123352,
  146. 0.1577264666557312,
  147. 0.16349375247955322,
  148. 0.16934409737586975,
  149. 0.1752760112285614,
  150. 0.18128803372383118,
  151. 0.18737870454788208,
  152. 0.19354650378227234,
  153. 0.1997898817062378,
  154. 0.20610737800598145,
  155. 0.21249738335609436,
  156. 0.21895831823349,
  157. 0.2254886031150818,
  158. 0.23208662867546082,
  159. 0.23875075578689575,
  160. 0.24547931551933289,
  161. 0.2522706985473633,
  162. 0.25912320613861084,
  163. 0.26603513956069946,
  164. 0.27300477027893066,
  165. 0.2800304591655731,
  166. 0.2871103882789612,
  167. 0.29424285888671875,
  168. 0.30142611265182495,
  169. 0.30865830183029175,
  170. 0.31593772768974304,
  171. 0.3232625722885132,
  172. 0.3306310474872589,
  173. 0.3380413055419922,
  174. 0.34549152851104736,
  175. 0.352979838848114,
  176. 0.3605044484138489,
  177. 0.3680635094642639,
  178. 0.37565508484840393,
  179. 0.38327735662460327,
  180. 0.3909284174442291,
  181. 0.39860638976097107,
  182. 0.4063093662261963,
  183. 0.41403549909591675,
  184. 0.42178282141685486,
  185. 0.4295494258403778,
  186. 0.43733343482017517,
  187. 0.44513291120529175,
  188. 0.45294591784477234,
  189. 0.46077051758766174,
  190. 0.46860480308532715,
  191. 0.4764467775821686,
  192. 0.4842946231365204,
  193. 0.492146372795105,
  194. 0.5,
  195. 0.5078536868095398,
  196. 0.515705406665802,
  197. 0.5235532522201538,
  198. 0.5313953161239624,
  199. 0.5392295718193054,
  200. 0.5470541715621948,
  201. 0.5548672080039978,
  202. 0.562666654586792,
  203. 0.5704506635665894,
  204. 0.5782172679901123,
  205. 0.5859646201133728,
  206. 0.5936906933784485,
  207. 0.6013936996459961,
  208. 0.609071671962738,
  209. 0.6167227625846863,
  210. 0.6243450045585632,
  211. 0.6319366097450256,
  212. 0.6394955515861511,
  213. 0.6470202207565308,
  214. 0.6545085310935974,
  215. 0.6619587540626526,
  216. 0.6693689823150635,
  217. 0.6767374277114868,
  218. 0.6840623021125793,
  219. 0.691341757774353,
  220. 0.6985740065574646,
  221. 0.7057572603225708,
  222. 0.7128896713256836,
  223. 0.719969630241394,
  224. 0.7269952893257141,
  225. 0.7339649796485901,
  226. 0.7408769130706787,
  227. 0.7477294206619263,
  228. 0.7545207738876343,
  229. 0.761249303817749,
  230. 0.7679134607315063,
  231. 0.774511456489563,
  232. 0.7810417413711548,
  233. 0.7875027060508728,
  234. 0.7938927412033081,
  235. 0.800210177898407,
  236. 0.8064535856246948,
  237. 0.8126214146614075,
  238. 0.8187121152877808,
  239. 0.8247240781784058,
  240. 0.8306560516357422,
  241. 0.8365063667297363,
  242. 0.8422735929489136,
  243. 0.8479564785957336,
  244. 0.8535534143447876,
  245. 0.8590631484985352,
  246. 0.8644843101501465,
  247. 0.8698155879974365,
  248. 0.8750555515289307,
  249. 0.8802030086517334,
  250. 0.8852566480636597,
  251. 0.8902152180671692,
  252. 0.8950775265693665,
  253. 0.899842381477356,
  254. 0.9045084714889526,
  255. 0.9090749025344849,
  256. 0.9135403037071228,
  257. 0.9179036617279053,
  258. 0.9221639633178711,
  259. 0.9263200759887695,
  260. 0.9303710460662842,
  261. 0.9343158006668091,
  262. 0.9381533861160278,
  263. 0.941882848739624,
  264. 0.945503294467926,
  265. 0.9490138292312622,
  266. 0.9524135589599609,
  267. 0.9557017087936401,
  268. 0.9588773250579834,
  269. 0.961939811706543,
  270. 0.9648882746696472,
  271. 0.9677220582962036,
  272. 0.9704403877258301,
  273. 0.9730427265167236,
  274. 0.9755282998085022,
  275. 0.9778965711593628,
  276. 0.9801468849182129,
  277. 0.9822787046432495,
  278. 0.9842916131019592,
  279. 0.9861849546432495,
  280. 0.9879584312438965,
  281. 0.9896113872528076,
  282. 0.9911436438560486,
  283. 0.9925546646118164,
  284. 0.9938441514968872,
  285. 0.9950118064880371,
  286. 0.996057391166687,
  287. 0.9969804883003235,
  288. 0.997780978679657,
  289. 0.9984586238861084,
  290. 0.999013364315033,
  291. 0.9994449615478516,
  292. 0.9997532367706299,
  293. 0.9999383091926575,
  294. 1,
  295. 0.9999383091926575,
  296. 0.9997532367706299,
  297. 0.9994449615478516,
  298. 0.999013364315033,
  299. 0.9984586238861084,
  300. 0.997780978679657,
  301. 0.9969804286956787,
  302. 0.9960573315620422,
  303. 0.9950118064880371,
  304. 0.9938441514968872,
  305. 0.9925546646118164,
  306. 0.9911435842514038,
  307. 0.9896113872528076,
  308. 0.9879583716392517,
  309. 0.9861849546432495,
  310. 0.9842915534973145,
  311. 0.9822787046432495,
  312. 0.9801468253135681,
  313. 0.9778964519500732,
  314. 0.9755282402038574,
  315. 0.9730426073074341,
  316. 0.9704403877258301,
  317. 0.9677219390869141,
  318. 0.9648882150650024,
  319. 0.9619396924972534,
  320. 0.9588772654533386,
  321. 0.9557015895843506,
  322. 0.9524134397506714,
  323. 0.9490137100219727,
  324. 0.9455032348632812,
  325. 0.9418827295303345,
  326. 0.9381532669067383,
  327. 0.9343156814575195,
  328. 0.9303709268569946,
  329. 0.9263200759887695,
  330. 0.9221639633178711,
  331. 0.9179036617279053,
  332. 0.913540244102478,
  333. 0.9090747833251953,
  334. 0.9045084714889526,
  335. 0.8998422622680664,
  336. 0.8950774669647217,
  337. 0.8902151584625244,
  338. 0.8852565884590149,
  339. 0.8802029490470886,
  340. 0.8750554919242859,
  341. 0.869815468788147,
  342. 0.8644842505455017,
  343. 0.8590630888938904,
  344. 0.853553295135498,
  345. 0.8479562997817993,
  346. 0.842273473739624,
  347. 0.836506187915802,
  348. 0.8306558728218079,
  349. 0.8247239589691162,
  350. 0.8187118768692017,
  351. 0.8126212358474731,
  352. 0.8064534664154053,
  353. 0.8002099990844727,
  354. 0.793892502784729,
  355. 0.7875025272369385,
  356. 0.7810416221618652,
  357. 0.7745113372802734,
  358. 0.767913281917572,
  359. 0.7612491846084595,
  360. 0.7545205950737,
  361. 0.7477291822433472,
  362. 0.7408767342567444,
  363. 0.7339648008346558,
  364. 0.7269951105117798,
  365. 0.7199694514274597,
  366. 0.7128894925117493,
  367. 0.7057570219039917,
  368. 0.6985738277435303,
  369. 0.6913415789604187,
  370. 0.684062123298645,
  371. 0.6767372488975525,
  372. 0.6693688035011292,
  373. 0.6619585752487183,
  374. 0.6545083522796631,
  375. 0.6470199823379517,
  376. 0.6394953727722168,
  377. 0.6319363117218018,
  378. 0.6243447661399841,
  379. 0.6167224645614624,
  380. 0.6090714335441589,
  381. 0.601393461227417,
  382. 0.5936904549598694,
  383. 0.5859643220901489,
  384. 0.5782170295715332,
  385. 0.5704504251480103,
  386. 0.5626664161682129,
  387. 0.5548669099807739,
  388. 0.5470539331436157,
  389. 0.5392293334007263,
  390. 0.5313950181007385,
  391. 0.5235530138015747,
  392. 0.5157051682472229,
  393. 0.507853627204895,
  394. 0.5,
  395. 0.4921463429927826,
  396. 0.484294593334198,
  397. 0.4764467477798462,
  398. 0.46860471367836,
  399. 0.4607704281806946,
  400. 0.4529458284378052,
  401. 0.4451328217983246,
  402. 0.437333345413208,
  403. 0.42954933643341064,
  404. 0.4217827320098877,
  405. 0.4140354096889496,
  406. 0.4063093066215515,
  407. 0.3986063003540039,
  408. 0.39092832803726196,
  409. 0.3832772672176361,
  410. 0.37565499544143677,
  411. 0.36806342005729675,
  412. 0.3605043888092041,
  413. 0.35297977924346924,
  414. 0.3454914391040802,
  415. 0.338041216135025,
  416. 0.33063095808029175,
  417. 0.3232625126838684,
  418. 0.3159376382827759,
  419. 0.3086581826210022,
  420. 0.3014259934425354,
  421. 0.2942427396774292,
  422. 0.28711026906967163,
  423. 0.2800303101539612,
  424. 0.2730046510696411,
  425. 0.2660350203514099,
  426. 0.2591230869293213,
  427. 0.25227057933807373,
  428. 0.24547919631004333,
  429. 0.2387506067752838,
  430. 0.23208650946617126,
  431. 0.22548848390579224,
  432. 0.21895819902420044,
  433. 0.2124972641468048,
  434. 0.2061072587966919,
  435. 0.19978976249694824,
  436. 0.1935463547706604,
  437. 0.18737855553627014,
  438. 0.18128788471221924,
  439. 0.17527586221694946,
  440. 0.1693439483642578,
  441. 0.16349363327026367,
  442. 0.15772631764411926,
  443. 0.15204349160194397,
  444. 0.14644649624824524,
  445. 0.1409367322921753,
  446. 0.13551557064056396,
  447. 0.1301843225955963,
  448. 0.12494435906410217,
  449. 0.11979690194129944,
  450. 0.11474326252937317,
  451. 0.10978469252586365,
  452. 0.10492238402366638,
  453. 0.10015755891799927,
  454. 0.09549137949943542,
  455. 0.09092503786087036,
  456. 0.08645960688591003,
  457. 0.08209621906280518,
  458. 0.07783591747283936,
  459. 0.07367980480194092,
  460. 0.06962886452674866,
  461. 0.06568413972854614,
  462. 0.06184655427932739,
  463. 0.0581170916557312,
  464. 0.0544966459274292,
  465. 0.05098611116409302,
  466. 0.04758638143539429,
  467. 0.044298261404037476,
  468. 0.04112258553504944,
  469. 0.038060128688812256,
  470. 0.03511166572570801,
  471. 0.03227788209915161,
  472. 0.02955952286720276,
  473. 0.02695724368095398,
  474. 0.024471670389175415,
  475. 0.02210339903831482,
  476. 0.01985308527946472,
  477. 0.017721205949783325,
  478. 0.015708357095718384,
  479. 0.0138150155544281,
  480. 0.012041598558425903,
  481. 0.010388582944869995,
  482. 0.008856356143951416,
  483. 0.007445335388183594,
  484. 0.006155818700790405,
  485. 0.004988163709640503,
  486. 0.003942638635635376,
  487. 0.0030195116996765137,
  488. 0.0022190213203430176,
  489. 0.0015413165092468262,
  490. 0.000986635684967041,
  491. 0.0005550682544708252,
  492. 0.0002467334270477295,
  493. 0.0000616908073425293,
  494. ],
  495. },
  496. }
  497. },
  498. {
  499. "operation": {
  500. "name": "log_mel_spectrogram",
  501. "type": "LogMelSpectrum",
  502. "attrs": {"chunk_size": 30, "hop_length": 160, "n_fft": 400, "n_mel": config.num_mel_bins},
  503. }
  504. },
  505. ]
  506. }
  507. }
  508. audio_processor_json = json.dumps(audio_processor_cfg, indent=4)
  509. with open(os.path.join(output_dir, "audio_processor_config.json"), "w") as f:
  510. f.write(audio_processor_json)
  511. provider_options = [] if "cpu" in provider else [{f"{provider}": {}}]
  512. genai_config = {
  513. "model": {
  514. "bos_token_id": config.bos_token_id,
  515. "context_length": config.max_length,
  516. "decoder": {
  517. "session_options": {
  518. "log_id": "onnxruntime-genai",
  519. "provider_options": provider_options,
  520. },
  521. "filename": os.path.basename(decoder_path),
  522. "head_size": config.d_model // config.decoder_attention_heads,
  523. "hidden_size": config.d_model,
  524. "inputs": {
  525. "input_ids": "input_ids",
  526. "past_key_names": "past_key_self_%d",
  527. "past_value_names": "past_value_self_%d",
  528. "cross_past_key_names": "past_key_cross_%d",
  529. "cross_past_value_names": "past_value_cross_%d",
  530. },
  531. "outputs": {
  532. "logits": "logits",
  533. "present_key_names": "present_key_self_%d",
  534. "present_value_names": "present_value_self_%d",
  535. },
  536. "num_attention_heads": config.decoder_attention_heads,
  537. "num_hidden_layers": config.decoder_layers,
  538. "num_key_value_heads": config.decoder_attention_heads,
  539. },
  540. "encoder": {
  541. "session_options": {
  542. "log_id": "onnxruntime-genai",
  543. "provider_options": provider_options,
  544. },
  545. "filename": os.path.basename(encoder_path),
  546. "head_size": config.d_model // config.encoder_attention_heads,
  547. "hidden_size": config.d_model,
  548. "inputs": {"audio_features": "audio_features"},
  549. "outputs": {
  550. "encoder_hidden_states": "encoder_hidden_states",
  551. "cross_present_key_names": "present_key_cross_%d",
  552. "cross_present_value_names": "present_value_cross_%d",
  553. },
  554. "num_attention_heads": config.encoder_attention_heads,
  555. "num_hidden_layers": config.encoder_layers,
  556. "num_key_value_heads": config.encoder_attention_heads,
  557. },
  558. "eos_token_id": config.eos_token_id,
  559. "pad_token_id": config.pad_token_id,
  560. "type": "whisper",
  561. "vocab_size": config.vocab_size,
  562. },
  563. "search": {
  564. "diversity_penalty": 0.0,
  565. "do_sample": False,
  566. "early_stopping": True,
  567. "length_penalty": 1.0,
  568. "max_length": config.max_length,
  569. "min_length": 0,
  570. "no_repeat_ngram_size": 0,
  571. "num_beams": 1,
  572. "num_return_sequences": 1,
  573. "past_present_share_buffer": use_decoder_masked_mha,
  574. "repetition_penalty": 1.0,
  575. "temperature": 1.0,
  576. "top_k": 1,
  577. "top_p": 1.0,
  578. },
  579. }
  580. # Requirements for the DMMHA kernel:
  581. # - Buffer sharing = true
  582. # - New input: past_sequence_length
  583. # - New input: cache_indirection
  584. # Otherwise, buffer sharing should be false and the new inputs should not be added
  585. # for beam search to work in ORT GenAI.
  586. if use_decoder_masked_mha:
  587. genai_config["model"]["decoder"]["inputs"].update(
  588. {
  589. "past_sequence_length": "past_sequence_length",
  590. "cache_indirection": "cache_indirection",
  591. }
  592. )
  593. if output_qk:
  594. genai_config["model"]["decoder"]["outputs"].update(
  595. {
  596. "output_cross_qk_names": "output_cross_qk_%d",
  597. }
  598. )
  599. with open(os.path.join(output_dir, "genai_config.json"), "w") as f:
  600. json.dump(genai_config, f, indent=4)
  601. @staticmethod
  602. def load_model(
  603. model_name_or_path: str,
  604. model_impl: str,
  605. cache_dir: str,
  606. device: torch.device,
  607. dtype: torch.dtype,
  608. merge_encoder_and_decoder_init: bool = True,
  609. no_beam_search_op: bool = False,
  610. output_qk: bool = False,
  611. ) -> dict[str, torch.nn.Module]:
  612. """Load model given a pretrained name or path, then build models for ONNX conversion.
  613. Args:
  614. model_name_or_path (str): pretrained model name or path
  615. model_impl (str): library to load model from
  616. cache_dir (str): cache directory
  617. device (torch.device): device to run the model
  618. dtype (torch.dtype): dtype to run the model
  619. merge_encoder_and_decoder_init (bool, optional): Whether merge encoder and decoder initialization into one ONNX model. Defaults to True.
  620. no_beam_search_op (bool, optional): Whether to use beam search op or not. Defaults to False.
  621. output_qk (bool, optional): Whether to output QKs to calculate batched jump times for word-level timestamps. Defaults to False.
  622. Returns:
  623. Dict[str, torch.nn.Module]: mapping from name to modules for ONNX conversion.
  624. """
  625. # Load PyTorch model
  626. if model_impl == "hf":
  627. # Load from Hugging Face
  628. model = WhisperForConditionalGeneration.from_pretrained(
  629. model_name_or_path, cache_dir=cache_dir, attn_implementation="eager"
  630. )
  631. else:
  632. # Load from OpenAI
  633. import whisper # noqa: PLC0415
  634. if not os.path.exists(model_name_or_path):
  635. name_or_path = model_name_or_path.split("/")[-1][8:]
  636. else:
  637. name_or_path = model_name_or_path
  638. model = whisper.load_model(name_or_path, device, download_root=cache_dir, in_memory=True)
  639. # Set PyTorch model properties
  640. model.eval().to(device=device)
  641. if model_impl == "hf":
  642. model.to(dtype=dtype)
  643. config = WhisperConfig.from_pretrained(model_name_or_path, cache_dir=cache_dir)
  644. # Load each component of PyTorch model
  645. decoder = WhisperDecoder(config, model, model_impl, no_beam_search_op).eval()
  646. components = {"decoder": decoder}
  647. if merge_encoder_and_decoder_init:
  648. encoder_decoder_init = WhisperEncoderDecoderInit(config, model, model_impl, no_beam_search_op).eval()
  649. components.update({"encoder": encoder_decoder_init})
  650. else:
  651. encoder = WhisperEncoder(config, model, model_impl).eval()
  652. components.update({"encoder": encoder, "decoder_init": decoder})
  653. if output_qk:
  654. batched_jump_times = WhisperJumpTimes(config, device, cache_dir).eval()
  655. components.update({"jump_times": batched_jump_times})
  656. return components
  657. @staticmethod
  658. def export_onnx(
  659. model: WhisperEncoder | WhisperEncoderDecoderInit | WhisperDecoder,
  660. onnx_model_path: str,
  661. provider: str,
  662. verbose: bool,
  663. use_external_data_format: bool,
  664. use_fp16_inputs: bool,
  665. use_int32_inputs: bool,
  666. use_encoder_hidden_states: bool,
  667. use_kv_cache_inputs: bool,
  668. ):
  669. """Export model component to ONNX
  670. Args:
  671. model (class): PyTorch class to export
  672. onnx_model_path (str): path to save ONNX model
  673. provider (str): provider to use for verifying parity on ONNX model
  674. verbose (bool): print verbose information.
  675. use_external_data_format (bool): use external data format or not.
  676. use_fp16_inputs (bool): use float16 inputs for the audio_features, encoder_hidden_states, logits, and KV caches.
  677. use_int32_inputs (bool): use int32 inputs for the decoder_input_ids.
  678. use_encoder_hidden_states (bool): use encoder_hidden_states as model input for decoder-init/decoder-without-past models.
  679. use_kv_cache_inputs (bool): use KV caches as model inputs for decoder-with-past models.
  680. """
  681. if isinstance(model, WhisperEncoder):
  682. model.export_onnx(
  683. onnx_model_path,
  684. provider,
  685. verbose,
  686. use_external_data_format,
  687. use_fp16_inputs,
  688. )
  689. elif isinstance(model, WhisperEncoderDecoderInit):
  690. model.export_onnx(
  691. onnx_model_path,
  692. provider,
  693. verbose,
  694. use_external_data_format,
  695. use_fp16_inputs,
  696. use_int32_inputs,
  697. )
  698. elif isinstance(model, WhisperDecoder):
  699. model.export_onnx(
  700. onnx_model_path,
  701. provider,
  702. verbose,
  703. use_external_data_format,
  704. use_fp16_inputs,
  705. use_int32_inputs,
  706. use_encoder_hidden_states,
  707. use_kv_cache_inputs,
  708. )
  709. elif isinstance(model, WhisperJumpTimes):
  710. model.export_onnx(
  711. onnx_model_path,
  712. provider,
  713. verbose,
  714. use_external_data_format,
  715. use_fp16_inputs,
  716. use_int32_inputs,
  717. )
  718. else:
  719. raise ValueError(f"Unknown instance for model detected: {type(model)}")
  720. @staticmethod
  721. def optimize_onnx(
  722. onnx_model_path: str,
  723. optimized_model_path: str,
  724. is_float16: bool,
  725. num_attention_heads: int,
  726. hidden_size: int,
  727. num_decoder_layers: int,
  728. use_external_data_format: bool = False,
  729. use_gpu: bool = False,
  730. provider: str = "cpu",
  731. is_decoder: bool = False,
  732. no_beam_search_op: bool = False,
  733. use_decoder_masked_mha: bool = False,
  734. output_qk: bool = False,
  735. ):
  736. """Optimize ONNX model with an option to convert it to use mixed precision."""
  737. from fusion_options import FusionOptions # noqa: PLC0415
  738. optimization_options = FusionOptions("bart")
  739. optimization_options.use_multi_head_attention = True
  740. optimization_options.disable_multi_head_attention_bias = provider == "rocm"
  741. m = optimize_model(
  742. onnx_model_path,
  743. model_type="bart",
  744. num_heads=num_attention_heads,
  745. hidden_size=hidden_size,
  746. opt_level=0,
  747. optimization_options=optimization_options,
  748. use_gpu=use_gpu,
  749. only_onnxruntime=False,
  750. )
  751. # Add `past_sequence_length`, `cache_indirection`, and `output_qk` to `MultiHeadAttention` ops
  752. if is_decoder and no_beam_search_op:
  753. if use_decoder_masked_mha:
  754. # FP16 CUDA, FP32 CUDA, and FP32 CPU use the `DecoderMaskedMultiHeadAttention` kernel
  755. # via `MultiHeadAttention`, which requires the `past_sequence_length` and
  756. # `cache_indirection` inputs
  757. m, past_seq_len_name = fix_past_sequence_length(m)
  758. m = add_cache_indirection_to_mha(m, past_seq_len_name)
  759. if output_qk:
  760. m = add_output_qk_to_mha(m, skip_node_idxs=list(range(0, 2 * num_decoder_layers, 2)))
  761. m.save_model_to_file(optimized_model_path, use_external_data_format, all_tensors_to_one_file=True)
  762. @staticmethod
  763. def pt_transcription_for_verify_onnx(
  764. processor: WhisperProcessor,
  765. pt_model: torch.nn.Module,
  766. device: torch.device,
  767. batch_size: int = 1,
  768. prompt_mode: bool = False,
  769. ):
  770. # Try to import `datasets` pip package
  771. try:
  772. from datasets import load_dataset # noqa: PLC0415
  773. except Exception as e:
  774. logger.error(f"An error occurred while importing `datasets`: {e}", exc_info=True) # noqa: G201
  775. install_cmd = "pip install datasets"
  776. logger.warning(f"Could not import `datasets`. Attempting to install `datasets` via `{install_cmd}`.")
  777. os.system(install_cmd)
  778. from datasets import load_dataset # noqa: PLC0415
  779. ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
  780. input_features_ = []
  781. if batch_size == 1:
  782. input_features = processor([ds[0]["audio"]["array"]], return_tensors="pt").input_features
  783. else:
  784. input_features_ = [
  785. processor([ds[3]["audio"]["array"]], return_tensors="pt").input_features,
  786. processor([ds[3]["audio"]["array"]], return_tensors="pt").input_features,
  787. ]
  788. assert len(input_features_) == batch_size
  789. input_features = torch.cat((input_features_[0], input_features_[1]))
  790. max_length, min_length, num_beams, num_return_sequences = 30, 0, 1, 1
  791. length_penalty, repetition_penalty = 1.0, 1.0
  792. inputs = {
  793. "input_features": input_features.to(device),
  794. "max_length": max_length,
  795. "min_length": min_length,
  796. "num_beams": num_beams,
  797. "num_return_sequences": num_return_sequences,
  798. "length_penalty": length_penalty,
  799. "repetition_penalty": repetition_penalty,
  800. "early_stopping": True,
  801. "use_cache": True,
  802. }
  803. if prompt_mode:
  804. prompts = ["John has doubts", "Maria has grave doubts"]
  805. prompt_ids = [processor.get_prompt_ids(p) for p in prompts]
  806. pt_transcription = []
  807. pt_outputs = []
  808. # The looping for model.generate is necessary here due to the limitation as per
  809. # https://huggingface.co/docs/transformers/model_doc/whisper#transformers.WhisperForConditionalGeneration.generate.prompt_ids
  810. # prompt_ids input requires a tensor of rank 1
  811. for i in range(batch_size):
  812. inputs["prompt_ids"] = torch.from_numpy(prompt_ids[i]).to(device=device)
  813. inputs["input_features"] = input_features_[i].to(device)
  814. pt_output = pt_model.generate(**inputs).detach().cpu().numpy()
  815. pt_outputs.append(pt_output)
  816. pt_transcription.append(processor.batch_decode(pt_output, skip_special_tokens=True)[0])
  817. inputs["input_features"] = input_features
  818. del inputs["prompt_ids"]
  819. else:
  820. prompt_ids = []
  821. pt_outputs = pt_model.generate(**inputs).detach().cpu().numpy()
  822. pt_transcription = [processor.batch_decode(pt_outputs, skip_special_tokens=True)[0]]
  823. pt_outputs = list(pt_outputs)
  824. del inputs["early_stopping"]
  825. del inputs["use_cache"]
  826. return inputs, pt_transcription, pt_outputs, prompt_ids
  827. @staticmethod
  828. def select_transcription_options(
  829. batch_size: int,
  830. prompt_mode: bool,
  831. ):
  832. if batch_size > 1 and prompt_mode:
  833. expected_transcription_no_comma_prompt1 = " John has doubts whether Sir Frederick Layton's work is really Greek after all and can discover in it but little of Rocky I"
  834. expected_transcription_misspelled_prompt1 = " John has doubts whether Sir Frederick Latins work is really Greek after all and can discover in it but little of Rocky I"
  835. expected_transcription_no_comma_prompt2 = " Maria has grave doubts whether Sir Frederick Layton's work is really Greek after all and can discover in it but little of Rocky"
  836. expected_transcription_misspelled_prompt2 = " Maria has grave doubts whether Sir Frederick Latins work is really Greek after all and can discover in it but little of Rocky I"
  837. expected_transcription_options = {
  838. expected_transcription_no_comma_prompt1,
  839. expected_transcription_no_comma_prompt2,
  840. expected_transcription_misspelled_prompt1,
  841. expected_transcription_misspelled_prompt2,
  842. }
  843. else:
  844. expected_transcription_no_comma = (
  845. " Mr. Quilter is the apostle of the middle classes and we are glad to welcome his gospel."
  846. )
  847. expected_transcription_with_comma = (
  848. " Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel."
  849. )
  850. expected_transcription_with_quote_and_comma = (
  851. ' "Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'
  852. )
  853. expected_transcription_options = {
  854. expected_transcription_no_comma,
  855. expected_transcription_with_comma,
  856. expected_transcription_with_quote_and_comma,
  857. }
  858. return expected_transcription_options
  859. @staticmethod
  860. def get_outputs(
  861. pt_outputs: np.ndarray,
  862. ort_outputs: np.ndarray,
  863. i: int,
  864. ):
  865. """Get PyTorch and ONNX Runtime output token ids at index i"""
  866. pt_output, ort_output = pt_outputs[i], ort_outputs[i]
  867. pt_shape, ort_shape = pt_output.shape, ort_output.shape
  868. # Hugging Face impl. + Beam Search op: PyTorch = (26,) and ORT = (30,)
  869. # OpenAI impl. + Beam Search op: PyTorch = (1, 30) and ORT = (30,)
  870. if pt_shape != ort_shape:
  871. if len(pt_shape) > 1:
  872. pt_output = pt_output[0]
  873. pt_shape = pt_output.shape
  874. if len(ort_shape) > 1:
  875. ort_output = ort_output[0]
  876. ort_shape = ort_output.shape
  877. if pt_shape[0] != ort_shape[0]:
  878. min_len = min(pt_shape[0], ort_shape[0])
  879. pt_output = pt_output[:min_len]
  880. ort_output = ort_output[:min_len]
  881. assert pt_output.shape == ort_output.shape
  882. return pt_output, ort_output
  883. @staticmethod
  884. def verify_onnx(
  885. model_name_or_path: str,
  886. cache_dir: str,
  887. ort_session: InferenceSession,
  888. device: torch.device,
  889. batch_size: int = 1,
  890. prompt_mode: bool = False,
  891. ):
  892. """Compare the result from PyTorch and ONNX Runtime to verify the ONNX model is good."""
  893. pt_model = WhisperForConditionalGeneration.from_pretrained(
  894. model_name_or_path, cache_dir=cache_dir, attn_implementation="eager"
  895. ).to(device)
  896. processor = WhisperProcessor.from_pretrained(model_name_or_path, cache_dir=cache_dir)
  897. config = WhisperConfig.from_pretrained(model_name_or_path, cache_dir=cache_dir)
  898. inputs, pt_transcription, pt_outputs, decoder_prompt_ids = WhisperHelper.pt_transcription_for_verify_onnx(
  899. processor,
  900. pt_model,
  901. device,
  902. batch_size=batch_size,
  903. prompt_mode=prompt_mode,
  904. )
  905. start_id = [config.decoder_start_token_id] # ex: [50258]
  906. prompt_ids = processor.get_decoder_prompt_ids(language="english", task="transcribe")
  907. prompt_ids = [token[1] for token in prompt_ids] # ex: [50259, 50358, 50363]
  908. forced_decoder_ids = start_id + prompt_ids # ex: [50258, 50259, 50358, 50363]
  909. ort_names = [entry.name for entry in ort_session.get_inputs()]
  910. ort_dtypes = [entry.type for entry in ort_session.get_inputs()]
  911. ort_to_np = {
  912. "tensor(float)": np.float32,
  913. "tensor(float16)": np.float16,
  914. "tensor(int64)": np.int64,
  915. "tensor(int32)": np.int32,
  916. "tensor(int8)": np.int8,
  917. "tensor(uint8)": np.uint8,
  918. }
  919. use_extra_decoding_ids = "extra_decoding_ids" in ort_names
  920. for name, dtype in zip(ort_names, ort_dtypes, strict=False):
  921. if name == "input_features":
  922. inputs[name] = inputs[name].detach().cpu().numpy()
  923. elif name == "vocab_mask":
  924. inputs[name] = np.ones(config.vocab_size, dtype=ort_to_np[dtype])
  925. elif name == "prefix_vocab_mask":
  926. inputs[name] = np.ones((batch_size, config.vocab_size), dtype=ort_to_np[dtype])
  927. elif name == "decoder_input_ids":
  928. if not prompt_mode:
  929. raw_input_ids = [start_id] if use_extra_decoding_ids else [forced_decoder_ids]
  930. inputs[name] = np.array(raw_input_ids, dtype=ort_to_np[dtype])
  931. else:
  932. # This logic handles the scenario for when prompts are not of the same size
  933. # For example if our prompt ids are [p1_id_1, p1_id_2] and [p2_id_1]
  934. # The final decoder_input_ids will look as such after padding
  935. # [prev_token, p1_id_1, p1_id_2, start_token, lang_token, transcribe_token]
  936. # [prev_token, p2_id_1, PAD_TOKEN, start_token, lang_token, transcribe_token]
  937. ort_prompts = []
  938. for i in range(batch_size):
  939. ort_prompts.append(decoder_prompt_ids[i].tolist())
  940. max_len = max(len(p) for p in ort_prompts)
  941. padded_prompts = []
  942. for p in ort_prompts:
  943. padded_prompt = [*p, *([config.pad_token_id] * (max_len - len(p)))]
  944. padded_prompts.append(padded_prompt + forced_decoder_ids)
  945. inputs[name] = np.array(padded_prompts, dtype=ort_to_np[dtype])
  946. elif name == "logits_processor":
  947. inputs[name] = np.array([1], dtype=ort_to_np[dtype])
  948. elif name == "cross_qk_layer_head":
  949. inputs[name] = np.array([[0, 0]], dtype=ort_to_np[dtype])
  950. elif name == "extra_decoding_ids":
  951. inputs[name] = np.repeat(np.array([prompt_ids], dtype=ort_to_np[dtype]), batch_size, 0)
  952. elif name == "temperature":
  953. inputs[name] = np.array([1.0], dtype=ort_to_np[dtype])
  954. else:
  955. inputs[name] = np.array([inputs[name]], dtype=ort_to_np[dtype])
  956. ort_outputs = ort_session.run(None, inputs)[0][:, 0, :]
  957. ort_transcription = processor.batch_decode(ort_outputs, skip_special_tokens=True)
  958. expected_transcription_options = WhisperHelper.select_transcription_options(batch_size, prompt_mode)
  959. parity = 1
  960. for i in range(batch_size):
  961. pt_output, ort_output = WhisperHelper.get_outputs(pt_outputs, ort_outputs, i)
  962. # Check if token ids match
  963. parity *= np.allclose(pt_output, ort_output)
  964. # Check if transcribed outputs match
  965. parity *= (
  966. pt_transcription[i] in expected_transcription_options
  967. and ort_transcription[i] in expected_transcription_options
  968. )
  969. max_diff = 0
  970. if not parity:
  971. for i in range(batch_size):
  972. pt_output, ort_output = WhisperHelper.get_outputs(pt_outputs, ort_outputs, i)
  973. diff = pt_output - ort_output
  974. max_diff_i = max(diff.min(), diff.max(), key=abs)
  975. max_diff = max(max_diff, max_diff_i)
  976. if max_diff != 0:
  977. logger.warning(f"PyTorch outputs: {pt_transcription}")
  978. logger.warning(f"ONNX Runtime outputs: {ort_transcription}")
  979. return 0