whisper.cpp 187 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515
  1. #include "whisper.h"
  2. #ifdef WHISPER_USE_COREML
  3. #include "coreml/whisper-encoder.h"
  4. #endif
  5. #ifdef WHISPER_USE_OPENVINO
  6. #include "openvino/whisper-openvino-encoder.h"
  7. #endif
  8. #include "ggml.h"
  9. #include <algorithm>
  10. #include <cassert>
  11. #define _USE_MATH_DEFINES
  12. #include <cmath>
  13. #include <cstdio>
  14. #include <cstdarg>
  15. #include <cstring>
  16. #include <fstream>
  17. #include <map>
  18. #include <string>
  19. #include <thread>
  20. #include <vector>
  21. #include <regex>
  22. #include <random>
  23. #if defined(_MSC_VER)
  24. #pragma warning(disable: 4244 4267) // possible loss of data
  25. #endif
  26. #if defined(GGML_BIG_ENDIAN)
  27. #include <bit>
  28. template<typename T>
  29. static T byteswap(T value) {
  30. return std::byteswap(value);
  31. }
  32. template<>
  33. float byteswap(float value) {
  34. return std::bit_cast<float>(byteswap(std::bit_cast<std::uint32_t>(value)));
  35. }
  36. template<typename T>
  37. static void byteswap_tensor_data(ggml_tensor * tensor) {
  38. T * datum = reinterpret_cast<T *>(tensor->data);
  39. for (int i = 0; i < ggml_nelements(tensor); i++) {
  40. datum[i] = byteswap(datum[i]);
  41. }
  42. }
  43. static void byteswap_tensor(ggml_tensor * tensor) {
  44. switch (tensor->type) {
  45. case GGML_TYPE_I16: {
  46. byteswap_tensor_data<int16_t>(tensor);
  47. break;
  48. }
  49. case GGML_TYPE_F16: {
  50. byteswap_tensor_data<ggml_fp16_t>(tensor);
  51. break;
  52. }
  53. case GGML_TYPE_I32: {
  54. byteswap_tensor_data<int32_t>(tensor);
  55. break;
  56. }
  57. case GGML_TYPE_F32: {
  58. byteswap_tensor_data<float>(tensor);
  59. break;
  60. }
  61. default: { // GML_TYPE_I8
  62. break;
  63. }
  64. }
  65. }
  66. #define BYTESWAP_VALUE(d) d = byteswap(d)
  67. #define BYTESWAP_FILTERS(f) \
  68. do { \
  69. for (auto & datum : f.data) { \
  70. datum = byteswap(datum); \
  71. } \
  72. } while (0)
  73. #define BYTESWAP_TENSOR(t) \
  74. do { \
  75. byteswap_tensor(t); \
  76. } while (0)
  77. #else
  78. #define BYTESWAP_VALUE(d) do {} while (0)
  79. #define BYTESWAP_FILTERS(f) do {} while (0)
  80. #define BYTESWAP_TENSOR(t) do {} while (0)
  81. #endif
  82. #define WHISPER_ASSERT(x) \
  83. do { \
  84. if (!(x)) { \
  85. log("WHISPER_ASSERT: %s:%d: %s\n", __FILE__, __LINE__, #x); \
  86. abort(); \
  87. } \
  88. } while (0)
  89. // define this to enable verbose trace logging - useful for debugging purposes
  90. //#define WHISPER_DEBUG
  91. #if defined(WHISPER_DEBUG)
  92. #define WHISPER_PRINT_DEBUG(...) \
  93. do { \
  94. fprintf(stderr, __VA_ARGS__); \
  95. } while (0)
  96. #else
  97. #define WHISPER_PRINT_DEBUG(...)
  98. #endif
  99. //#define WHISPER_USE_FLASH_ATTN
  100. //#define WHISPER_USE_FLASH_FF
  101. #define WHISPER_MAX_DECODERS 16
  102. #define WHISPER_USE_SCRATCH
  103. #define WHISPER_MAX_SCRATCH_BUFFERS 16
  104. // available whisper models
  105. enum e_model {
  106. MODEL_UNKNOWN,
  107. MODEL_TINY,
  108. MODEL_BASE,
  109. MODEL_SMALL,
  110. MODEL_MEDIUM,
  111. MODEL_LARGE,
  112. };
  113. static const std::map<std::string, std::pair<int, std::string>> g_lang = {
  114. { "en", { 0, "english", } },
  115. { "zh", { 1, "chinese", } },
  116. { "de", { 2, "german", } },
  117. { "es", { 3, "spanish", } },
  118. { "ru", { 4, "russian", } },
  119. { "ko", { 5, "korean", } },
  120. { "fr", { 6, "french", } },
  121. { "ja", { 7, "japanese", } },
  122. { "pt", { 8, "portuguese", } },
  123. { "tr", { 9, "turkish", } },
  124. { "pl", { 10, "polish", } },
  125. { "ca", { 11, "catalan", } },
  126. { "nl", { 12, "dutch", } },
  127. { "ar", { 13, "arabic", } },
  128. { "sv", { 14, "swedish", } },
  129. { "it", { 15, "italian", } },
  130. { "id", { 16, "indonesian", } },
  131. { "hi", { 17, "hindi", } },
  132. { "fi", { 18, "finnish", } },
  133. { "vi", { 19, "vietnamese", } },
  134. { "he", { 20, "hebrew", } },
  135. { "uk", { 21, "ukrainian", } },
  136. { "el", { 22, "greek", } },
  137. { "ms", { 23, "malay", } },
  138. { "cs", { 24, "czech", } },
  139. { "ro", { 25, "romanian", } },
  140. { "da", { 26, "danish", } },
  141. { "hu", { 27, "hungarian", } },
  142. { "ta", { 28, "tamil", } },
  143. { "no", { 29, "norwegian", } },
  144. { "th", { 30, "thai", } },
  145. { "ur", { 31, "urdu", } },
  146. { "hr", { 32, "croatian", } },
  147. { "bg", { 33, "bulgarian", } },
  148. { "lt", { 34, "lithuanian", } },
  149. { "la", { 35, "latin", } },
  150. { "mi", { 36, "maori", } },
  151. { "ml", { 37, "malayalam", } },
  152. { "cy", { 38, "welsh", } },
  153. { "sk", { 39, "slovak", } },
  154. { "te", { 40, "telugu", } },
  155. { "fa", { 41, "persian", } },
  156. { "lv", { 42, "latvian", } },
  157. { "bn", { 43, "bengali", } },
  158. { "sr", { 44, "serbian", } },
  159. { "az", { 45, "azerbaijani", } },
  160. { "sl", { 46, "slovenian", } },
  161. { "kn", { 47, "kannada", } },
  162. { "et", { 48, "estonian", } },
  163. { "mk", { 49, "macedonian", } },
  164. { "br", { 50, "breton", } },
  165. { "eu", { 51, "basque", } },
  166. { "is", { 52, "icelandic", } },
  167. { "hy", { 53, "armenian", } },
  168. { "ne", { 54, "nepali", } },
  169. { "mn", { 55, "mongolian", } },
  170. { "bs", { 56, "bosnian", } },
  171. { "kk", { 57, "kazakh", } },
  172. { "sq", { 58, "albanian", } },
  173. { "sw", { 59, "swahili", } },
  174. { "gl", { 60, "galician", } },
  175. { "mr", { 61, "marathi", } },
  176. { "pa", { 62, "punjabi", } },
  177. { "si", { 63, "sinhala", } },
  178. { "km", { 64, "khmer", } },
  179. { "sn", { 65, "shona", } },
  180. { "yo", { 66, "yoruba", } },
  181. { "so", { 67, "somali", } },
  182. { "af", { 68, "afrikaans", } },
  183. { "oc", { 69, "occitan", } },
  184. { "ka", { 70, "georgian", } },
  185. { "be", { 71, "belarusian", } },
  186. { "tg", { 72, "tajik", } },
  187. { "sd", { 73, "sindhi", } },
  188. { "gu", { 74, "gujarati", } },
  189. { "am", { 75, "amharic", } },
  190. { "yi", { 76, "yiddish", } },
  191. { "lo", { 77, "lao", } },
  192. { "uz", { 78, "uzbek", } },
  193. { "fo", { 79, "faroese", } },
  194. { "ht", { 80, "haitian creole", } },
  195. { "ps", { 81, "pashto", } },
  196. { "tk", { 82, "turkmen", } },
  197. { "nn", { 83, "nynorsk", } },
  198. { "mt", { 84, "maltese", } },
  199. { "sa", { 85, "sanskrit", } },
  200. { "lb", { 86, "luxembourgish", } },
  201. { "my", { 87, "myanmar", } },
  202. { "bo", { 88, "tibetan", } },
  203. { "tl", { 89, "tagalog", } },
  204. { "mg", { 90, "malagasy", } },
  205. { "as", { 91, "assamese", } },
  206. { "tt", { 92, "tatar", } },
  207. { "haw", { 93, "hawaiian", } },
  208. { "ln", { 94, "lingala", } },
  209. { "ha", { 95, "hausa", } },
  210. { "ba", { 96, "bashkir", } },
  211. { "jw", { 97, "javanese", } },
  212. { "su", { 98, "sundanese", } },
  213. };
  214. static const size_t MB = 1ull*1024*1024;
  215. static const std::map<e_model, size_t> MEM_REQ_SCRATCH0 = {
  216. { MODEL_TINY, 62ull*MB },
  217. { MODEL_BASE, 80ull*MB },
  218. { MODEL_SMALL, 120ull*MB },
  219. { MODEL_MEDIUM, 158ull*MB },
  220. { MODEL_LARGE, 198ull*MB },
  221. };
  222. static const std::map<e_model, size_t> MEM_REQ_SCRATCH1 = {
  223. { MODEL_TINY, 18ull*MB },
  224. { MODEL_BASE, 24ull*MB },
  225. { MODEL_SMALL, 36ull*MB },
  226. { MODEL_MEDIUM, 48ull*MB },
  227. { MODEL_LARGE, 60ull*MB },
  228. };
  229. static const std::map<e_model, size_t> MEM_REQ_SCRATCH2 = {
  230. { MODEL_TINY, 4ull*MB },
  231. { MODEL_BASE, 4ull*MB },
  232. { MODEL_SMALL, 6ull*MB },
  233. { MODEL_MEDIUM, 7ull*MB },
  234. { MODEL_LARGE, 9ull*MB },
  235. };
  236. static const std::map<e_model, size_t> MEM_REQ_SCRATCH3 = {
  237. { MODEL_TINY, 4ull*MB },
  238. { MODEL_BASE, 4ull*MB },
  239. { MODEL_SMALL, 6ull*MB },
  240. { MODEL_MEDIUM, 7ull*MB },
  241. { MODEL_LARGE, 9ull*MB },
  242. };
  243. static const std::map<ggml_type, std::map<e_model, size_t>> MEM_REQ_MODEL = {
  244. { GGML_TYPE_F32,
  245. {
  246. { MODEL_TINY, 74ull*MB },
  247. { MODEL_BASE, 142ull*MB },
  248. { MODEL_SMALL, 466ull*MB },
  249. { MODEL_MEDIUM, 1464ull*MB },
  250. { MODEL_LARGE, 2952ull*MB },
  251. },
  252. },
  253. { GGML_TYPE_F16,
  254. {
  255. { MODEL_TINY, 74ull*MB },
  256. { MODEL_BASE, 142ull*MB },
  257. { MODEL_SMALL, 466ull*MB },
  258. { MODEL_MEDIUM, 1464ull*MB },
  259. { MODEL_LARGE, 2952ull*MB },
  260. },
  261. },
  262. { GGML_TYPE_Q4_0,
  263. {
  264. { MODEL_TINY, 26ull*MB },
  265. { MODEL_BASE, 50ull*MB },
  266. { MODEL_SMALL, 154ull*MB },
  267. { MODEL_MEDIUM, 470ull*MB },
  268. { MODEL_LARGE, 940ull*MB },
  269. },
  270. },
  271. { GGML_TYPE_Q4_1,
  272. {
  273. { MODEL_TINY, 32ull*MB },
  274. { MODEL_BASE, 58ull*MB },
  275. { MODEL_SMALL, 182ull*MB },
  276. { MODEL_MEDIUM, 562ull*MB },
  277. { MODEL_LARGE, 1124ull*MB },
  278. },
  279. },
  280. { GGML_TYPE_Q5_0,
  281. {
  282. { MODEL_TINY, 30ull*MB },
  283. { MODEL_BASE, 54ull*MB },
  284. { MODEL_SMALL, 170ull*MB },
  285. { MODEL_MEDIUM, 516ull*MB },
  286. { MODEL_LARGE, 1034ull*MB },
  287. },
  288. },
  289. { GGML_TYPE_Q5_1,
  290. {
  291. { MODEL_TINY, 32ull*MB },
  292. { MODEL_BASE, 58ull*MB },
  293. { MODEL_SMALL, 182ull*MB },
  294. { MODEL_MEDIUM, 562ull*MB },
  295. { MODEL_LARGE, 1124ull*MB },
  296. },
  297. },
  298. { GGML_TYPE_Q8_0,
  299. {
  300. { MODEL_TINY, 45ull*MB },
  301. { MODEL_BASE, 84ull*MB },
  302. { MODEL_SMALL, 268ull*MB },
  303. { MODEL_MEDIUM, 834ull*MB },
  304. { MODEL_LARGE, 1674ull*MB },
  305. },
  306. },
  307. };
  308. static const std::map<e_model, size_t> MEM_REQ_KV_SELF = {
  309. { MODEL_TINY, 3ull*MB },
  310. { MODEL_BASE, 6ull*MB },
  311. { MODEL_SMALL, 16ull*MB },
  312. { MODEL_MEDIUM, 43ull*MB },
  313. { MODEL_LARGE, 71ull*MB },
  314. };
  315. static const std::map<e_model, size_t> MEM_REQ_KV_CROSS = {
  316. { MODEL_TINY, 9ull*MB },
  317. { MODEL_BASE, 18ull*MB },
  318. { MODEL_SMALL, 53ull*MB },
  319. { MODEL_MEDIUM, 141ull*MB },
  320. { MODEL_LARGE, 235ull*MB },
  321. };
  322. static const std::map<e_model, size_t> MEM_REQ_ENCODE = {
  323. { MODEL_TINY, 30ull*MB },
  324. { MODEL_BASE, 38ull*MB },
  325. { MODEL_SMALL, 56ull*MB },
  326. { MODEL_MEDIUM, 74ull*MB },
  327. { MODEL_LARGE, 94ull*MB },
  328. };
  329. static const std::map<e_model, size_t> MEM_REQ_DECODE = {
  330. { MODEL_TINY, 3ull*MB },
  331. { MODEL_BASE, 5ull*MB },
  332. { MODEL_SMALL, 10ull*MB },
  333. { MODEL_MEDIUM, 18ull*MB },
  334. { MODEL_LARGE, 27ull*MB },
  335. };
  336. struct whisper_mel {
  337. int n_len;
  338. int n_len_org;
  339. int n_mel;
  340. std::vector<float> data;
  341. };
  342. struct whisper_filters {
  343. int32_t n_mel;
  344. int32_t n_fft;
  345. std::vector<float> data;
  346. };
  347. struct whisper_vocab {
  348. using id = int32_t;
  349. using token = std::string;
  350. int n_vocab = 51864;
  351. std::map<token, id> token_to_id;
  352. std::map<id, token> id_to_token;
  353. // reference: https://github.com/openai/whisper/blob/248b6cb124225dd263bb9bd32d060b6517e067f8/whisper/tokenizer.py#L334-L349
  354. id token_eot = 50256;
  355. id token_sot = 50257;
  356. // task tokens (used only for multilingual models)
  357. id token_translate = 50357;
  358. id token_transcribe = 50358;
  359. // other special tokens
  360. id token_solm = 50359; // [TDRZ] used by tinydiarize models to indicate speaker turn
  361. id token_prev = 50360;
  362. id token_nosp = 50361;
  363. id token_not = 50362; // no timestamps
  364. id token_beg = 50363; // begin timestamps
  365. bool is_multilingual() const {
  366. return n_vocab == 51865;
  367. }
  368. };
  369. struct whisper_segment {
  370. int64_t t0;
  371. int64_t t1;
  372. std::string text;
  373. std::vector<whisper_token_data> tokens;
  374. bool speaker_turn_next;
  375. };
  376. // medium
  377. // hparams: {
  378. // 'n_mels': 80,
  379. // 'n_vocab': 51864,
  380. // 'n_audio_ctx': 1500,
  381. // 'n_audio_state': 1024,
  382. // 'n_audio_head': 16,
  383. // 'n_audio_layer': 24,
  384. // 'n_text_ctx': 448,
  385. // 'n_text_state': 1024,
  386. // 'n_text_head': 16,
  387. // 'n_text_layer': 24
  388. // }
  389. //
  390. // default hparams (Whisper tiny)
  391. struct whisper_hparams {
  392. int32_t n_vocab = 51864;
  393. int32_t n_audio_ctx = 1500;
  394. int32_t n_audio_state = 384;
  395. int32_t n_audio_head = 6;
  396. int32_t n_audio_layer = 4;
  397. int32_t n_text_ctx = 448;
  398. int32_t n_text_state = 384;
  399. int32_t n_text_head = 6;
  400. int32_t n_text_layer = 4;
  401. int32_t n_mels = 80;
  402. int32_t ftype = 1;
  403. float eps = 1e-5f;
  404. };
  405. // audio encoding layer
  406. struct whisper_layer_encoder {
  407. // encoder.blocks.*.attn_ln
  408. struct ggml_tensor * attn_ln_0_w;
  409. struct ggml_tensor * attn_ln_0_b;
  410. // encoder.blocks.*.attn.out
  411. struct ggml_tensor * attn_ln_1_w;
  412. struct ggml_tensor * attn_ln_1_b;
  413. // encoder.blocks.*.attn.query
  414. struct ggml_tensor * attn_q_w;
  415. struct ggml_tensor * attn_q_b;
  416. // encoder.blocks.*.attn.key
  417. struct ggml_tensor * attn_k_w;
  418. // encoder.blocks.*.attn.value
  419. struct ggml_tensor * attn_v_w;
  420. struct ggml_tensor * attn_v_b;
  421. // encoder.blocks.*.mlp_ln
  422. struct ggml_tensor * mlp_ln_w;
  423. struct ggml_tensor * mlp_ln_b;
  424. // encoder.blocks.*.mlp.0
  425. struct ggml_tensor * mlp_0_w;
  426. struct ggml_tensor * mlp_0_b;
  427. // encoder.blocks.*.mlp.2
  428. struct ggml_tensor * mlp_1_w;
  429. struct ggml_tensor * mlp_1_b;
  430. };
  431. // token decoding layer
  432. struct whisper_layer_decoder {
  433. // decoder.blocks.*.attn_ln
  434. struct ggml_tensor * attn_ln_0_w;
  435. struct ggml_tensor * attn_ln_0_b;
  436. // decoder.blocks.*.attn.out
  437. struct ggml_tensor * attn_ln_1_w;
  438. struct ggml_tensor * attn_ln_1_b;
  439. // decoder.blocks.*.attn.query
  440. struct ggml_tensor * attn_q_w;
  441. struct ggml_tensor * attn_q_b;
  442. // decoder.blocks.*.attn.key
  443. struct ggml_tensor * attn_k_w;
  444. // decoder.blocks.*.attn.value
  445. struct ggml_tensor * attn_v_w;
  446. struct ggml_tensor * attn_v_b;
  447. // decoder.blocks.*.cross_attn_ln
  448. struct ggml_tensor * cross_attn_ln_0_w;
  449. struct ggml_tensor * cross_attn_ln_0_b;
  450. // decoder.blocks.*.cross_attn.out
  451. struct ggml_tensor * cross_attn_ln_1_w;
  452. struct ggml_tensor * cross_attn_ln_1_b;
  453. // decoder.blocks.*.cross_attn.query
  454. struct ggml_tensor * cross_attn_q_w;
  455. struct ggml_tensor * cross_attn_q_b;
  456. // decoder.blocks.*.cross_attn.key
  457. struct ggml_tensor * cross_attn_k_w;
  458. // decoder.blocks.*.cross_attn.value
  459. struct ggml_tensor * cross_attn_v_w;
  460. struct ggml_tensor * cross_attn_v_b;
  461. // decoder.blocks.*.mlp_ln
  462. struct ggml_tensor * mlp_ln_w;
  463. struct ggml_tensor * mlp_ln_b;
  464. // decoder.blocks.*.mlp.0
  465. struct ggml_tensor * mlp_0_w;
  466. struct ggml_tensor * mlp_0_b;
  467. // decoder.blocks.*.mlp.2
  468. struct ggml_tensor * mlp_1_w;
  469. struct ggml_tensor * mlp_1_b;
  470. };
  471. struct whisper_kv_cache {
  472. struct ggml_tensor * k;
  473. struct ggml_tensor * v;
  474. struct ggml_context * ctx;
  475. std::vector<uint8_t> buf;
  476. int n; // number of tokens currently in the cache
  477. };
  478. struct whisper_model {
  479. e_model type = MODEL_UNKNOWN;
  480. whisper_hparams hparams;
  481. whisper_filters filters;
  482. // encoder.positional_embedding
  483. struct ggml_tensor * e_pe;
  484. // encoder.conv1
  485. struct ggml_tensor * e_conv_1_w;
  486. struct ggml_tensor * e_conv_1_b;
  487. // encoder.conv2
  488. struct ggml_tensor * e_conv_2_w;
  489. struct ggml_tensor * e_conv_2_b;
  490. // encoder.ln_post
  491. struct ggml_tensor * e_ln_w;
  492. struct ggml_tensor * e_ln_b;
  493. // decoder.positional_embedding
  494. struct ggml_tensor * d_pe;
  495. // decoder.token_embedding
  496. struct ggml_tensor * d_te;
  497. // decoder.ln
  498. struct ggml_tensor * d_ln_w;
  499. struct ggml_tensor * d_ln_b;
  500. std::vector<whisper_layer_encoder> layers_encoder;
  501. std::vector<whisper_layer_decoder> layers_decoder;
  502. // context
  503. struct ggml_context * ctx;
  504. // the model memory buffer is read-only and can be shared between processors
  505. std::vector<uint8_t> * buf;
  506. // tensors
  507. int n_loaded;
  508. std::map<std::string, struct ggml_tensor *> tensors;
  509. };
  510. struct whisper_sequence {
  511. std::vector<whisper_token_data> tokens;
  512. // the accumulated transcription in the current iteration (used to truncate the tokens array)
  513. int result_len;
  514. double sum_logprobs_all; // the sum of the log probabilities of the tokens
  515. double sum_logprobs; // the sum of the log probabilities of the tokens (first result_len tokens)
  516. double avg_logprobs; // the average log probability of the tokens
  517. double entropy; // the entropy of the tokens
  518. double score; // likelihood rank score
  519. };
  520. // TAGS: WHISPER_DECODER_INIT
  521. struct whisper_decoder {
  522. // each decoders keeps its own KV-cache
  523. whisper_kv_cache kv_self;
  524. // the currently generated sequence of tokens
  525. whisper_sequence sequence;
  526. int seek_delta; // the window shift found so far based on the decoded timestamp tokens
  527. bool failed; // has the current segment failed to decode?
  528. bool completed; // has the decoder completed the current segment?
  529. bool has_ts; // have we already sampled a non-beg timestamp token for the current segment?
  530. // new token probs, logits and logprobs after the last whisper_decode (1-dimensional array: [n_vocab])
  531. std::vector<float> probs;
  532. std::vector<float> logits;
  533. std::vector<float> logprobs;
  534. std::vector<whisper_token> tokens_tmp; // used for whisper_decode calls
  535. };
  536. struct whisper_state {
  537. int64_t t_sample_us = 0;
  538. int64_t t_encode_us = 0;
  539. int64_t t_decode_us = 0;
  540. int64_t t_mel_us = 0;
  541. int32_t n_sample = 0; // number of tokens sampled
  542. int32_t n_encode = 0; // number of encoder calls
  543. int32_t n_decode = 0; // number of decoder calls
  544. int32_t n_fail_p = 0; // number of logprob threshold failures
  545. int32_t n_fail_h = 0; // number of entropy threshold failures
  546. // cross-attention KV cache for the decoders
  547. // shared between all decoders
  548. whisper_kv_cache kv_cross;
  549. whisper_mel mel;
  550. whisper_decoder decoders[WHISPER_MAX_DECODERS] = {};
  551. // memory buffers used by encode / decode contexts
  552. std::vector<uint8_t> buf_compute;
  553. std::vector<uint8_t> buf_scratch[WHISPER_MAX_SCRATCH_BUFFERS];
  554. int buf_last = 0;
  555. size_t buf_max_size[WHISPER_MAX_SCRATCH_BUFFERS] = { 0 };
  556. // decode output (2-dimensional array: [n_tokens][n_vocab])
  557. std::vector<float> logits;
  558. std::vector<whisper_segment> result_all;
  559. std::vector<whisper_token> prompt_past;
  560. // work container used to avoid memory allocations
  561. std::vector<std::pair<double, whisper_vocab::id>> logits_id;
  562. mutable std::mt19937 rng; // used for sampling at t > 0.0
  563. int lang_id = 0; // english by default
  564. std::string path_model; // populated by whisper_init_from_file()
  565. #ifdef WHISPER_USE_COREML
  566. whisper_coreml_context * ctx_coreml = nullptr;
  567. #endif
  568. #ifdef WHISPER_USE_OPENVINO
  569. whisper_openvino_context * ctx_openvino = nullptr;
  570. #endif
  571. // [EXPERIMENTAL] token-level timestamps data
  572. int64_t t_beg = 0;
  573. int64_t t_last = 0;
  574. whisper_token tid_last;
  575. std::vector<float> energy; // PCM signal energy
  576. // [EXPERIMENTAL] speed-up techniques
  577. int32_t exp_n_audio_ctx = 0; // 0 - use default
  578. void use_buf(struct ggml_context * ctx, int i) {
  579. #if defined(WHISPER_USE_SCRATCH)
  580. size_t last_size = 0;
  581. if (i == -1) {
  582. last_size = ggml_set_scratch(ctx, { 0, 0, nullptr, });
  583. } else {
  584. auto & buf = buf_scratch[i];
  585. last_size = ggml_set_scratch(ctx, { 0, buf.size(), buf.data(), });
  586. }
  587. if (buf_last >= 0) {
  588. buf_max_size[buf_last] = std::max(buf_max_size[buf_last], last_size);
  589. }
  590. buf_last = i;
  591. #else
  592. (void) i;
  593. (void) ctx;
  594. #endif
  595. }
  596. size_t get_buf_max_mem(int i) const {
  597. #if defined(WHISPER_USE_SCRATCH)
  598. return buf_max_size[i];
  599. #else
  600. (void) i;
  601. return 0;
  602. #endif
  603. }
  604. };
  605. struct whisper_context {
  606. int64_t t_load_us = 0;
  607. int64_t t_start_us = 0;
  608. ggml_type wtype = ggml_type::GGML_TYPE_F16; // weight type (FP32 / FP16 / QX)
  609. ggml_type itype = ggml_type::GGML_TYPE_F16; // intermediate type (FP32 or FP16)
  610. whisper_model model;
  611. whisper_vocab vocab;
  612. whisper_state * state = nullptr;
  613. std::string path_model; // populated by whisper_init_from_file()
  614. };
  615. static void whisper_default_log(const char * text) {
  616. fprintf(stderr, "%s", text);
  617. }
  618. static whisper_log_callback whisper_log = whisper_default_log;
  619. #ifdef __GNUC__
  620. #ifdef __MINGW32__
  621. __attribute__((gnu_format(printf, 1, 2)))
  622. #else
  623. __attribute__((format(printf, 1, 2)))
  624. #endif
  625. #endif
  626. static void log(const char * fmt, ...) {
  627. if (!whisper_log) return;
  628. char buf[1024];
  629. va_list args;
  630. va_start(args, fmt);
  631. vsnprintf(buf, sizeof(buf), fmt, args);
  632. whisper_log(buf);
  633. }
  634. template<typename T>
  635. static void read_safe(whisper_model_loader * loader, T & dest) {
  636. loader->read(loader->context, &dest, sizeof(T));
  637. BYTESWAP_VALUE(dest);
  638. }
  639. static bool kv_cache_init(
  640. const struct whisper_hparams & hparams,
  641. const size_t mem_bytes,
  642. struct whisper_kv_cache & cache,
  643. ggml_type wtype,
  644. int n_ctx) {
  645. cache.buf.resize(mem_bytes);
  646. struct ggml_init_params params = {
  647. /*.mem_size =*/ cache.buf.size(),
  648. /*.mem_buffer =*/ cache.buf.data(),
  649. /*.no_alloc =*/ false,
  650. };
  651. cache.ctx = ggml_init(params);
  652. if (!cache.ctx) {
  653. log("%s: failed to allocate memory for kv cache\n", __func__);
  654. return false;
  655. }
  656. const int n_text_state = hparams.n_text_state;
  657. const int n_text_layer = hparams.n_text_layer;
  658. const int n_mem = n_text_layer*n_ctx;
  659. const int n_elements = n_text_state*n_mem;
  660. cache.k = ggml_new_tensor_1d(cache.ctx, wtype, n_elements);
  661. cache.v = ggml_new_tensor_1d(cache.ctx, wtype, n_elements);
  662. return true;
  663. }
  664. static bool kv_cache_reinit(struct whisper_kv_cache & cache) {
  665. WHISPER_ASSERT(cache.ctx);
  666. const int n_elements = ggml_nelements(cache.k);
  667. WHISPER_ASSERT(n_elements == ggml_nelements(cache.v));
  668. const ggml_type wtype = cache.k->type;
  669. WHISPER_ASSERT(wtype == cache.v->type);
  670. WHISPER_ASSERT(cache.buf.size() >= 2*n_elements*ggml_type_sizef(wtype));
  671. struct ggml_init_params params = {
  672. /*.mem_size =*/ cache.buf.size(),
  673. /*.mem_buffer =*/ cache.buf.data(),
  674. /*.no_alloc =*/ false,
  675. };
  676. cache.ctx = ggml_init(params);
  677. if (!cache.ctx) {
  678. log("%s: failed to allocate memory for kv cache\n", __func__);
  679. return false;
  680. }
  681. cache.k = ggml_new_tensor_1d(cache.ctx, wtype, n_elements);
  682. cache.v = ggml_new_tensor_1d(cache.ctx, wtype, n_elements);
  683. return true;
  684. }
  685. static void kv_cache_free(struct whisper_kv_cache & cache) {
  686. if (cache.ctx) {
  687. ggml_free(cache.ctx);
  688. cache.ctx = nullptr;
  689. }
  690. }
  691. // load the model from a ggml file
  692. //
  693. // file format:
  694. //
  695. // - hparams
  696. // - pre-computed mel filters
  697. // - vocab
  698. // - weights
  699. //
  700. // see the convert-pt-to-ggml.py script for details
  701. //
  702. static bool whisper_model_load(struct whisper_model_loader * loader, whisper_context & wctx) {
  703. log("%s: loading model\n", __func__);
  704. const int64_t t_start_us = ggml_time_us();
  705. wctx.t_start_us = t_start_us;
  706. auto & model = wctx.model;
  707. auto & vocab = wctx.vocab;
  708. // verify magic
  709. {
  710. uint32_t magic;
  711. read_safe(loader, magic);
  712. if (magic != GGML_FILE_MAGIC) {
  713. log("%s: invalid model data (bad magic)\n", __func__);
  714. return false;
  715. }
  716. }
  717. //load hparams
  718. {
  719. auto & hparams = model.hparams;
  720. read_safe(loader, hparams.n_vocab);
  721. read_safe(loader, hparams.n_audio_ctx);
  722. read_safe(loader, hparams.n_audio_state);
  723. read_safe(loader, hparams.n_audio_head);
  724. read_safe(loader, hparams.n_audio_layer);
  725. read_safe(loader, hparams.n_text_ctx);
  726. read_safe(loader, hparams.n_text_state);
  727. read_safe(loader, hparams.n_text_head);
  728. read_safe(loader, hparams.n_text_layer);
  729. read_safe(loader, hparams.n_mels);
  730. read_safe(loader, hparams.ftype);
  731. assert(hparams.n_text_state == hparams.n_audio_state);
  732. if (hparams.n_audio_layer == 4) {
  733. model.type = e_model::MODEL_TINY;
  734. }
  735. if (hparams.n_audio_layer == 6) {
  736. model.type = e_model::MODEL_BASE;
  737. }
  738. if (hparams.n_audio_layer == 12) {
  739. model.type = e_model::MODEL_SMALL;
  740. }
  741. if (hparams.n_audio_layer == 24) {
  742. model.type = e_model::MODEL_MEDIUM;
  743. }
  744. if (hparams.n_audio_layer == 32) {
  745. model.type = e_model::MODEL_LARGE;
  746. }
  747. const int32_t qntvr = hparams.ftype / GGML_QNT_VERSION_FACTOR;
  748. hparams.ftype %= GGML_QNT_VERSION_FACTOR;
  749. // for the big tensors, we have the option to store the data in 16-bit floats or quantized
  750. // in order to save memory and also to speed up the computation
  751. wctx.wtype = ggml_ftype_to_ggml_type((ggml_ftype) (model.hparams.ftype));
  752. if (wctx.wtype == GGML_TYPE_COUNT) {
  753. log("%s: invalid model (bad ftype value %d)\n", __func__, model.hparams.ftype);
  754. return false;
  755. }
  756. const size_t scale = model.hparams.ftype ? 1 : 2;
  757. log("%s: n_vocab = %d\n", __func__, hparams.n_vocab);
  758. log("%s: n_audio_ctx = %d\n", __func__, hparams.n_audio_ctx);
  759. log("%s: n_audio_state = %d\n", __func__, hparams.n_audio_state);
  760. log("%s: n_audio_head = %d\n", __func__, hparams.n_audio_head);
  761. log("%s: n_audio_layer = %d\n", __func__, hparams.n_audio_layer);
  762. log("%s: n_text_ctx = %d\n", __func__, hparams.n_text_ctx);
  763. log("%s: n_text_state = %d\n", __func__, hparams.n_text_state);
  764. log("%s: n_text_head = %d\n", __func__, hparams.n_text_head);
  765. log("%s: n_text_layer = %d\n", __func__, hparams.n_text_layer);
  766. log("%s: n_mels = %d\n", __func__, hparams.n_mels);
  767. log("%s: ftype = %d\n", __func__, model.hparams.ftype);
  768. log("%s: qntvr = %d\n", __func__, qntvr);
  769. log("%s: type = %d\n", __func__, model.type);
  770. // print memory requirements
  771. {
  772. // this is the total memory required to run the inference
  773. const size_t mem_required =
  774. MEM_REQ_SCRATCH0.at(model.type) +
  775. MEM_REQ_SCRATCH1.at(model.type) +
  776. MEM_REQ_SCRATCH2.at(model.type) +
  777. MEM_REQ_SCRATCH3.at(model.type) +
  778. scale*MEM_REQ_MODEL.at(wctx.wtype).at(model.type) +
  779. scale*MEM_REQ_KV_CROSS.at(model.type) +
  780. scale*std::max(MEM_REQ_ENCODE.at(model.type), MEM_REQ_DECODE.at(model.type));
  781. // this is the memory required by one decoder
  782. const size_t mem_required_decoder =
  783. scale*MEM_REQ_KV_SELF.at(model.type);
  784. log("%s: mem required = %7.2f MB (+ %7.2f MB per decoder)\n", __func__,
  785. mem_required / 1024.0 / 1024.0, mem_required_decoder / 1024.0 / 1024.0);
  786. }
  787. // initialize all memory buffers
  788. // always have at least one decoder
  789. wctx.model.buf = new std::vector<uint8_t>();
  790. wctx.model.buf->resize(scale*MEM_REQ_MODEL.at(wctx.wtype).at(model.type));
  791. // we skip initialization of the state until it is needed
  792. // because it might be that state will always be provided externally.
  793. }
  794. // load mel filters
  795. {
  796. auto & filters = wctx.model.filters;
  797. read_safe(loader, filters.n_mel);
  798. read_safe(loader, filters.n_fft);
  799. filters.data.resize(filters.n_mel * filters.n_fft);
  800. loader->read(loader->context, filters.data.data(), filters.data.size() * sizeof(float));
  801. BYTESWAP_FILTERS(filters);
  802. }
  803. // load vocab
  804. {
  805. int32_t n_vocab = 0;
  806. read_safe(loader, n_vocab);
  807. //if (n_vocab != model.hparams.n_vocab) {
  808. // log("%s: invalid model file '%s' (bad vocab size %d != %d)\n",
  809. // __func__, fname.c_str(), n_vocab, model.hparams.n_vocab);
  810. // return false;
  811. //}
  812. std::string word;
  813. std::vector<char> tmp;
  814. tmp.reserve(128);
  815. for (int i = 0; i < n_vocab; i++) {
  816. uint32_t len;
  817. read_safe(loader, len);
  818. if (len > 0) {
  819. tmp.resize(len);
  820. loader->read(loader->context, &tmp[0], tmp.size()); // read to buffer
  821. word.assign(&tmp[0], tmp.size());
  822. } else {
  823. // seems like we have an empty-string token in multi-language models (i = 50256)
  824. //log("%s: warning: empty-string token in vocab, i = %d\n", __func__, i);
  825. word = "";
  826. }
  827. vocab.token_to_id[word] = i;
  828. vocab.id_to_token[i] = word;
  829. //printf("%s: vocab[%d] = '%s'\n", __func__, i, word.c_str());
  830. }
  831. vocab.n_vocab = model.hparams.n_vocab;
  832. if (vocab.is_multilingual()) {
  833. vocab.token_eot++;
  834. vocab.token_sot++;
  835. vocab.token_translate++;
  836. vocab.token_transcribe++;
  837. vocab.token_solm++;
  838. vocab.token_prev++;
  839. vocab.token_nosp++;
  840. vocab.token_not++;
  841. vocab.token_beg++;
  842. }
  843. if (n_vocab < model.hparams.n_vocab) {
  844. log("%s: adding %d extra tokens\n", __func__, model.hparams.n_vocab - n_vocab);
  845. for (int i = n_vocab; i < model.hparams.n_vocab; i++) {
  846. if (i > vocab.token_beg) {
  847. word = "[_TT_" + std::to_string(i - vocab.token_beg) + "]";
  848. } else if (i == vocab.token_eot) {
  849. word = "[_EOT_]";
  850. } else if (i == vocab.token_sot) {
  851. word = "[_SOT_]";
  852. } else if (i == vocab.token_solm) {
  853. word = "[_SOLM_]";
  854. } else if (i == vocab.token_prev) {
  855. word = "[_PREV_]";
  856. } else if (i == vocab.token_nosp) {
  857. word = "[_NOSP_]";
  858. } else if (i == vocab.token_not) {
  859. word = "[_NOT_]";
  860. } else if (i == vocab.token_beg) {
  861. word = "[_BEG_]";
  862. } else {
  863. word = "[_extra_token_" + std::to_string(i) + "]";
  864. }
  865. vocab.token_to_id[word] = i;
  866. vocab.id_to_token[i] = word;
  867. }
  868. }
  869. }
  870. size_t ctx_size = 0;
  871. const ggml_type wtype = wctx.wtype;
  872. const ggml_type vtype = wctx.wtype == GGML_TYPE_F32 ? GGML_TYPE_F32 : GGML_TYPE_F16; // conv type
  873. {
  874. const auto & hparams = model.hparams;
  875. const int n_vocab = hparams.n_vocab;
  876. const int n_audio_ctx = hparams.n_audio_ctx;
  877. const int n_audio_state = hparams.n_audio_state;
  878. const int n_audio_layer = hparams.n_audio_layer;
  879. const int n_text_ctx = hparams.n_text_ctx;
  880. const int n_text_state = hparams.n_text_state;
  881. const int n_text_layer = hparams.n_text_layer;
  882. const int n_mels = hparams.n_mels;
  883. // encoder
  884. {
  885. ctx_size += n_audio_ctx*n_audio_state*ggml_type_sizef(GGML_TYPE_F32); // e_pe;
  886. ctx_size += 3*n_mels*n_audio_state*ggml_type_sizef(vtype); // e_conv_1_w
  887. ctx_size += n_audio_state*ggml_type_sizef(GGML_TYPE_F32); // e_conv_1_b
  888. ctx_size += 3*n_audio_state*n_audio_state*ggml_type_sizef(vtype); // e_conv_2_w
  889. ctx_size += n_audio_state*ggml_type_sizef(GGML_TYPE_F32); // e_conv_2_b
  890. ctx_size += n_audio_state*ggml_type_sizef(GGML_TYPE_F32); // e_ln_w;
  891. ctx_size += n_audio_state*ggml_type_sizef(GGML_TYPE_F32); // e_ln_b;
  892. }
  893. // decoder
  894. {
  895. ctx_size += n_text_ctx*n_text_state*ggml_type_sizef(GGML_TYPE_F32); // d_pe;
  896. ctx_size += n_vocab*n_text_state*ggml_type_sizef(wtype); // d_te;
  897. ctx_size += n_text_state*ggml_type_sizef(GGML_TYPE_F32); // d_ln_w;
  898. ctx_size += n_text_state*ggml_type_sizef(GGML_TYPE_F32); // d_ln_b;
  899. }
  900. // encoder layers
  901. {
  902. ctx_size += n_audio_layer*(n_audio_state*ggml_type_sizef(GGML_TYPE_F32)); // mlp_ln_w
  903. ctx_size += n_audio_layer*(n_audio_state*ggml_type_sizef(GGML_TYPE_F32)); // mlp_ln_b
  904. ctx_size += n_audio_layer*(4*n_audio_state*n_audio_state*ggml_type_sizef(wtype)); // mlp_0_w
  905. ctx_size += n_audio_layer*( 4*n_audio_state*ggml_type_sizef(GGML_TYPE_F32)); // mlp_0_b
  906. ctx_size += n_audio_layer*(4*n_audio_state*n_audio_state*ggml_type_sizef(wtype)); // mlp_1_w
  907. ctx_size += n_audio_layer*( n_audio_state*ggml_type_sizef(GGML_TYPE_F32)); // mlp_1_b
  908. ctx_size += n_audio_layer*(n_audio_state*ggml_type_sizef(GGML_TYPE_F32)); // attn_ln_0_w
  909. ctx_size += n_audio_layer*(n_audio_state*ggml_type_sizef(GGML_TYPE_F32)); // attn_ln_0_b
  910. ctx_size += n_audio_layer*(n_audio_state*n_audio_state*ggml_type_sizef(wtype)); // attn_q_w
  911. ctx_size += n_audio_layer*( n_audio_state*ggml_type_sizef(GGML_TYPE_F32)); // attn_q_b
  912. ctx_size += n_audio_layer*(n_audio_state*n_audio_state*ggml_type_sizef(wtype)); // attn_k_w
  913. ctx_size += n_audio_layer*(n_audio_state*n_audio_state*ggml_type_sizef(wtype)); // attn_v_w
  914. ctx_size += n_audio_layer*( n_audio_state*ggml_type_sizef(GGML_TYPE_F32)); // attn_v_b
  915. ctx_size += n_audio_layer*(n_audio_state*n_audio_state*ggml_type_sizef(wtype)); // attn_ln_1_w
  916. ctx_size += n_audio_layer*( n_audio_state*ggml_type_sizef(GGML_TYPE_F32)); // attn_ln_1_b
  917. }
  918. // decoder layers
  919. {
  920. ctx_size += n_text_layer*(n_text_state*ggml_type_sizef(GGML_TYPE_F32)); // mlp_ln_w
  921. ctx_size += n_text_layer*(n_text_state*ggml_type_sizef(GGML_TYPE_F32)); // mlp_ln_b
  922. ctx_size += n_text_layer*(4*n_text_state*n_text_state*ggml_type_sizef(wtype)); // mlp_0_w
  923. ctx_size += n_text_layer*( 4*n_text_state*ggml_type_sizef(GGML_TYPE_F32)); // mlp_0_b
  924. ctx_size += n_text_layer*(4*n_text_state*n_text_state*ggml_type_sizef(wtype)); // mlp_1_w
  925. ctx_size += n_text_layer*( n_text_state*ggml_type_sizef(GGML_TYPE_F32)); // mlp_1_b
  926. ctx_size += n_text_layer*(n_text_state*ggml_type_sizef(GGML_TYPE_F32)); // attn_ln_0_w
  927. ctx_size += n_text_layer*(n_text_state*ggml_type_sizef(GGML_TYPE_F32)); // attn_ln_0_b
  928. ctx_size += n_text_layer*(n_text_state*n_text_state*ggml_type_sizef(wtype)); // attn_q_w
  929. ctx_size += n_text_layer*( n_text_state*ggml_type_sizef(GGML_TYPE_F32)); // attn_q_b
  930. ctx_size += n_text_layer*(n_text_state*n_text_state*ggml_type_sizef(wtype)); // attn_k_w
  931. ctx_size += n_text_layer*(n_text_state*n_text_state*ggml_type_sizef(wtype)); // attn_v_w
  932. ctx_size += n_text_layer*( n_text_state*ggml_type_sizef(GGML_TYPE_F32)); // attn_v_b
  933. ctx_size += n_text_layer*(n_text_state*n_text_state*ggml_type_sizef(wtype)); // attn_ln_1_w
  934. ctx_size += n_text_layer*( n_text_state*ggml_type_sizef(GGML_TYPE_F32)); // attn_ln_1_b
  935. //
  936. ctx_size += n_text_layer*(n_text_state*ggml_type_sizef(GGML_TYPE_F32)); // cross_attn_ln_0_w
  937. ctx_size += n_text_layer*(n_text_state*ggml_type_sizef(GGML_TYPE_F32)); // cross_attn_ln_0_b
  938. ctx_size += n_text_layer*(n_text_state*n_text_state*ggml_type_sizef(wtype)); // cross_attn_q_w
  939. ctx_size += n_text_layer*( n_text_state*ggml_type_sizef(GGML_TYPE_F32)); // cross_attn_q_b
  940. ctx_size += n_text_layer*(n_text_state*n_text_state*ggml_type_sizef(wtype)); // cross_attn_k_w
  941. ctx_size += n_text_layer*(n_text_state*n_text_state*ggml_type_sizef(wtype)); // cross_attn_v_w
  942. ctx_size += n_text_layer*( n_text_state*ggml_type_sizef(GGML_TYPE_F32)); // cross_attn_v_b
  943. ctx_size += n_text_layer*(n_text_state*n_text_state*ggml_type_sizef(wtype)); // cross_attn_ln_1_w
  944. ctx_size += n_text_layer*( n_text_state*ggml_type_sizef(GGML_TYPE_F32)); // cross_attn_ln_1_b
  945. }
  946. ctx_size += (15 + 15*n_audio_layer + 24*n_text_layer)*512; // object overhead
  947. log("%s: model ctx = %7.2f MB\n", __func__, ctx_size/(1024.0*1024.0));
  948. }
  949. // create the ggml context
  950. {
  951. struct ggml_init_params params = {
  952. /*.mem_size =*/ wctx.model.buf->size(),
  953. /*.mem_buffer =*/ wctx.model.buf->data(),
  954. /*.no_alloc =*/ false,
  955. };
  956. model.ctx = ggml_init(params);
  957. if (!model.ctx) {
  958. log("%s: ggml_init() failed\n", __func__);
  959. return false;
  960. }
  961. }
  962. // prepare memory for the weights
  963. {
  964. auto & ctx = model.ctx;
  965. const auto & hparams = model.hparams;
  966. const int n_vocab = hparams.n_vocab;
  967. const int n_audio_ctx = hparams.n_audio_ctx;
  968. const int n_audio_state = hparams.n_audio_state;
  969. const int n_audio_layer = hparams.n_audio_layer;
  970. const int n_text_ctx = hparams.n_text_ctx;
  971. const int n_text_state = hparams.n_text_state;
  972. const int n_text_layer = hparams.n_text_layer;
  973. const int n_mels = hparams.n_mels;
  974. model.layers_encoder.resize(n_audio_layer);
  975. model.layers_decoder.resize(n_text_layer);
  976. // encoder
  977. {
  978. model.e_pe = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_audio_state, n_audio_ctx);
  979. model.e_conv_1_w = ggml_new_tensor_3d(ctx, vtype, 3, n_mels, n_audio_state);
  980. model.e_conv_1_b = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 1, n_audio_state);
  981. model.e_conv_2_w = ggml_new_tensor_3d(ctx, vtype, 3, n_audio_state, n_audio_state);
  982. model.e_conv_2_b = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 1, n_audio_state);
  983. model.e_ln_w = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_state);
  984. model.e_ln_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_state);
  985. // map by name
  986. model.tensors["encoder.positional_embedding"] = model.e_pe;
  987. model.tensors["encoder.conv1.weight"] = model.e_conv_1_w;
  988. model.tensors["encoder.conv1.bias"] = model.e_conv_1_b;
  989. model.tensors["encoder.conv2.weight"] = model.e_conv_2_w;
  990. model.tensors["encoder.conv2.bias"] = model.e_conv_2_b;
  991. model.tensors["encoder.ln_post.weight"] = model.e_ln_w;
  992. model.tensors["encoder.ln_post.bias"] = model.e_ln_b;
  993. for (int i = 0; i < n_audio_layer; ++i) {
  994. auto & layer = model.layers_encoder[i];
  995. layer.mlp_ln_w = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_state);
  996. layer.mlp_ln_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_state);
  997. layer.mlp_0_w = ggml_new_tensor_2d(ctx, wtype, n_audio_state, 4*n_audio_state);
  998. layer.mlp_0_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 4*n_audio_state);
  999. layer.mlp_1_w = ggml_new_tensor_2d(ctx, wtype, 4*n_audio_state, n_audio_state);
  1000. layer.mlp_1_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_state);
  1001. layer.attn_ln_0_w = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_state);
  1002. layer.attn_ln_0_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_state);
  1003. layer.attn_q_w = ggml_new_tensor_2d(ctx, wtype, n_audio_state, n_audio_state);
  1004. layer.attn_q_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_state);
  1005. layer.attn_k_w = ggml_new_tensor_2d(ctx, wtype, n_audio_state, n_audio_state);
  1006. layer.attn_v_w = ggml_new_tensor_2d(ctx, wtype, n_audio_state, n_audio_state);
  1007. layer.attn_v_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_state);
  1008. layer.attn_ln_1_w = ggml_new_tensor_2d(ctx, wtype, n_audio_state, n_audio_state);
  1009. layer.attn_ln_1_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_state);
  1010. // map by name
  1011. model.tensors["encoder.blocks." + std::to_string(i) + ".mlp_ln.weight"] = layer.mlp_ln_w;
  1012. model.tensors["encoder.blocks." + std::to_string(i) + ".mlp_ln.bias"] = layer.mlp_ln_b;
  1013. model.tensors["encoder.blocks." + std::to_string(i) + ".mlp.0.weight"] = layer.mlp_0_w;
  1014. model.tensors["encoder.blocks." + std::to_string(i) + ".mlp.0.bias"] = layer.mlp_0_b;
  1015. model.tensors["encoder.blocks." + std::to_string(i) + ".mlp.2.weight"] = layer.mlp_1_w;
  1016. model.tensors["encoder.blocks." + std::to_string(i) + ".mlp.2.bias"] = layer.mlp_1_b;
  1017. model.tensors["encoder.blocks." + std::to_string(i) + ".attn_ln.weight"] = layer.attn_ln_0_w;
  1018. model.tensors["encoder.blocks." + std::to_string(i) + ".attn_ln.bias"] = layer.attn_ln_0_b;
  1019. model.tensors["encoder.blocks." + std::to_string(i) + ".attn.query.weight"] = layer.attn_q_w;
  1020. model.tensors["encoder.blocks." + std::to_string(i) + ".attn.query.bias"] = layer.attn_q_b;
  1021. model.tensors["encoder.blocks." + std::to_string(i) + ".attn.key.weight"] = layer.attn_k_w;
  1022. model.tensors["encoder.blocks." + std::to_string(i) + ".attn.value.weight"] = layer.attn_v_w;
  1023. model.tensors["encoder.blocks." + std::to_string(i) + ".attn.value.bias"] = layer.attn_v_b;
  1024. model.tensors["encoder.blocks." + std::to_string(i) + ".attn.out.weight"] = layer.attn_ln_1_w;
  1025. model.tensors["encoder.blocks." + std::to_string(i) + ".attn.out.bias"] = layer.attn_ln_1_b;
  1026. }
  1027. }
  1028. // decoder
  1029. {
  1030. model.d_pe = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_text_state, n_text_ctx);
  1031. model.d_te = ggml_new_tensor_2d(ctx, wtype, n_text_state, n_vocab);
  1032. model.d_ln_w = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_text_state);
  1033. model.d_ln_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_text_state);
  1034. // map by name
  1035. model.tensors["decoder.positional_embedding"] = model.d_pe;
  1036. model.tensors["decoder.token_embedding.weight"] = model.d_te;
  1037. model.tensors["decoder.ln.weight"] = model.d_ln_w;
  1038. model.tensors["decoder.ln.bias"] = model.d_ln_b;
  1039. for (int i = 0; i < n_text_layer; ++i) {
  1040. auto & layer = model.layers_decoder[i];
  1041. layer.mlp_ln_w = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_text_state);
  1042. layer.mlp_ln_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_text_state);
  1043. layer.mlp_0_w = ggml_new_tensor_2d(ctx, wtype, n_text_state, 4*n_text_state);
  1044. layer.mlp_0_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 4*n_text_state);
  1045. layer.mlp_1_w = ggml_new_tensor_2d(ctx, wtype, 4*n_text_state, n_text_state);
  1046. layer.mlp_1_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_text_state);
  1047. layer.attn_ln_0_w = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_text_state);
  1048. layer.attn_ln_0_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_text_state);
  1049. layer.attn_q_w = ggml_new_tensor_2d(ctx, wtype, n_text_state, n_text_state);
  1050. layer.attn_q_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_text_state);
  1051. layer.attn_k_w = ggml_new_tensor_2d(ctx, wtype, n_text_state, n_text_state);
  1052. layer.attn_v_w = ggml_new_tensor_2d(ctx, wtype, n_text_state, n_text_state);
  1053. layer.attn_v_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_text_state);
  1054. layer.attn_ln_1_w = ggml_new_tensor_2d(ctx, wtype, n_text_state, n_text_state);
  1055. layer.attn_ln_1_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_text_state);
  1056. layer.cross_attn_ln_0_w = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_text_state);
  1057. layer.cross_attn_ln_0_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_text_state);
  1058. layer.cross_attn_q_w = ggml_new_tensor_2d(ctx, wtype, n_text_state, n_text_state);
  1059. layer.cross_attn_q_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_text_state);
  1060. layer.cross_attn_k_w = ggml_new_tensor_2d(ctx, wtype, n_text_state, n_text_state);
  1061. layer.cross_attn_v_w = ggml_new_tensor_2d(ctx, wtype, n_text_state, n_text_state);
  1062. layer.cross_attn_v_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_text_state);
  1063. layer.cross_attn_ln_1_w = ggml_new_tensor_2d(ctx, wtype, n_text_state, n_text_state);
  1064. layer.cross_attn_ln_1_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_text_state);
  1065. // map by name
  1066. model.tensors["decoder.blocks." + std::to_string(i) + ".mlp_ln.weight"] = layer.mlp_ln_w;
  1067. model.tensors["decoder.blocks." + std::to_string(i) + ".mlp_ln.bias"] = layer.mlp_ln_b;
  1068. model.tensors["decoder.blocks." + std::to_string(i) + ".mlp.0.weight"] = layer.mlp_0_w;
  1069. model.tensors["decoder.blocks." + std::to_string(i) + ".mlp.0.bias"] = layer.mlp_0_b;
  1070. model.tensors["decoder.blocks." + std::to_string(i) + ".mlp.2.weight"] = layer.mlp_1_w;
  1071. model.tensors["decoder.blocks." + std::to_string(i) + ".mlp.2.bias"] = layer.mlp_1_b;
  1072. model.tensors["decoder.blocks." + std::to_string(i) + ".attn_ln.weight"] = layer.attn_ln_0_w;
  1073. model.tensors["decoder.blocks." + std::to_string(i) + ".attn_ln.bias"] = layer.attn_ln_0_b;
  1074. model.tensors["decoder.blocks." + std::to_string(i) + ".attn.query.weight"] = layer.attn_q_w;
  1075. model.tensors["decoder.blocks." + std::to_string(i) + ".attn.query.bias"] = layer.attn_q_b;
  1076. model.tensors["decoder.blocks." + std::to_string(i) + ".attn.key.weight"] = layer.attn_k_w;
  1077. model.tensors["decoder.blocks." + std::to_string(i) + ".attn.value.weight"] = layer.attn_v_w;
  1078. model.tensors["decoder.blocks." + std::to_string(i) + ".attn.value.bias"] = layer.attn_v_b;
  1079. model.tensors["decoder.blocks." + std::to_string(i) + ".attn.out.weight"] = layer.attn_ln_1_w;
  1080. model.tensors["decoder.blocks." + std::to_string(i) + ".attn.out.bias"] = layer.attn_ln_1_b;
  1081. model.tensors["decoder.blocks." + std::to_string(i) + ".cross_attn_ln.weight"] = layer.cross_attn_ln_0_w;
  1082. model.tensors["decoder.blocks." + std::to_string(i) + ".cross_attn_ln.bias"] = layer.cross_attn_ln_0_b;
  1083. model.tensors["decoder.blocks." + std::to_string(i) + ".cross_attn.query.weight"] = layer.cross_attn_q_w;
  1084. model.tensors["decoder.blocks." + std::to_string(i) + ".cross_attn.query.bias"] = layer.cross_attn_q_b;
  1085. model.tensors["decoder.blocks." + std::to_string(i) + ".cross_attn.key.weight"] = layer.cross_attn_k_w;
  1086. model.tensors["decoder.blocks." + std::to_string(i) + ".cross_attn.value.weight"] = layer.cross_attn_v_w;
  1087. model.tensors["decoder.blocks." + std::to_string(i) + ".cross_attn.value.bias"] = layer.cross_attn_v_b;
  1088. model.tensors["decoder.blocks." + std::to_string(i) + ".cross_attn.out.weight"] = layer.cross_attn_ln_1_w;
  1089. model.tensors["decoder.blocks." + std::to_string(i) + ".cross_attn.out.bias"] = layer.cross_attn_ln_1_b;
  1090. }
  1091. }
  1092. }
  1093. // load weights
  1094. {
  1095. size_t total_size = 0;
  1096. model.n_loaded = 0;
  1097. while (true) {
  1098. int32_t n_dims;
  1099. int32_t length;
  1100. int32_t ttype;
  1101. read_safe(loader, n_dims);
  1102. read_safe(loader, length);
  1103. read_safe(loader, ttype);
  1104. if (loader->eof(loader->context)) {
  1105. break;
  1106. }
  1107. int32_t nelements = 1;
  1108. int32_t ne[4] = { 1, 1, 1, 1 };
  1109. for (int i = 0; i < n_dims; ++i) {
  1110. read_safe(loader, ne[i]);
  1111. nelements *= ne[i];
  1112. }
  1113. std::string name;
  1114. std::vector<char> tmp(length); // create a buffer
  1115. loader->read(loader->context, &tmp[0], tmp.size()); // read to buffer
  1116. name.assign(&tmp[0], tmp.size());
  1117. if (model.tensors.find(name) == model.tensors.end()) {
  1118. log("%s: unknown tensor '%s' in model file\n", __func__, name.data());
  1119. return false;
  1120. }
  1121. auto tensor = model.tensors[name.data()];
  1122. if (ggml_nelements(tensor) != nelements) {
  1123. log("%s: tensor '%s' has wrong size in model file\n", __func__, name.data());
  1124. log("%s: shape: [%d, %d, %d], expected: [%d, %d, %d]\n",
  1125. __func__, ne[0], ne[1], ne[2], (int) tensor->ne[0], (int) tensor->ne[1], (int) tensor->ne[2]);
  1126. return false;
  1127. }
  1128. if (tensor->ne[0] != ne[0] || tensor->ne[1] != ne[1] || tensor->ne[2] != ne[2]) {
  1129. log("%s: tensor '%s' has wrong shape in model file: got [%d, %d, %d], expected [%d, %d, %d]\n",
  1130. __func__, name.data(), (int) tensor->ne[0], (int) tensor->ne[1], (int) tensor->ne[2], ne[0], ne[1], ne[2]);
  1131. return false;
  1132. }
  1133. const size_t bpe = ggml_type_size(ggml_type(ttype));
  1134. if ((nelements*bpe)/ggml_blck_size(tensor->type) != ggml_nbytes(tensor)) {
  1135. log("%s: tensor '%s' has wrong size in model file: got %zu, expected %zu\n",
  1136. __func__, name.data(), ggml_nbytes(tensor), nelements*bpe);
  1137. return false;
  1138. }
  1139. loader->read(loader->context, tensor->data, ggml_nbytes(tensor));
  1140. BYTESWAP_TENSOR(tensor);
  1141. //printf("%48s - [%5d, %5d, %5d], type = %6s, %6.2f MB\n", name.data(), ne[0], ne[1], ne[2], ggml_type_name((ggml_type) ttype), ggml_nbytes(tensor)/1024.0/1024.0);
  1142. total_size += ggml_nbytes(tensor);
  1143. model.n_loaded++;
  1144. }
  1145. log("%s: model size = %7.2f MB\n", __func__, total_size/1024.0/1024.0);
  1146. if (model.n_loaded == 0) {
  1147. log("%s: WARN no tensors loaded from model file - assuming empty model for testing\n", __func__);
  1148. } else if (model.n_loaded != (int) model.tensors.size()) {
  1149. log("%s: ERROR not all tensors loaded from model file - expected %zu, got %d\n", __func__, model.tensors.size(), model.n_loaded);
  1150. return false;
  1151. }
  1152. }
  1153. wctx.t_load_us = ggml_time_us() - t_start_us;
  1154. return true;
  1155. }
  1156. // evaluate the encoder with the given state
  1157. //
  1158. // given audio recording (more specifically, its log mel spectrogram), runs forward pass of the encoder
  1159. // part of the transformer model and returns the encoded features
  1160. //
  1161. // - wctx: the model
  1162. // - wstate: the state of the encoder
  1163. // - n_threads: number of threads to use
  1164. // - mel_offset: offset in the mel spectrogram (i.e. audio offset)
  1165. //
  1166. static bool whisper_encode_internal(
  1167. whisper_context & wctx,
  1168. whisper_state & wstate,
  1169. const int mel_offset,
  1170. const int n_threads){
  1171. const int64_t t_start_us = ggml_time_us();
  1172. const auto & model = wctx.model;
  1173. const auto & mel_inp = wstate.mel;
  1174. const auto & hparams = model.hparams;
  1175. const int n_ctx = wstate.exp_n_audio_ctx > 0 ? wstate.exp_n_audio_ctx : hparams.n_audio_ctx;
  1176. const int n_state = hparams.n_audio_state;
  1177. const int n_head = hparams.n_audio_head;
  1178. const int n_layer = hparams.n_audio_layer;
  1179. const int n_mels = hparams.n_mels;
  1180. assert(mel_inp.n_mel == n_mels);
  1181. struct ggml_init_params params = {
  1182. /*.mem_size =*/ wstate.buf_compute.size(),
  1183. /*.mem_buffer =*/ wstate.buf_compute.data(),
  1184. /*.no_alloc =*/ false,
  1185. };
  1186. struct ggml_context * ctx0 = ggml_init(params);
  1187. wstate.use_buf(ctx0, 0);
  1188. struct ggml_tensor * mel = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 2*n_ctx, n_mels);
  1189. assert(mel->type == GGML_TYPE_F32);
  1190. {
  1191. float * dst = (float *) mel->data;
  1192. memset(dst, 0, ggml_nbytes(mel));
  1193. const int i0 = std::min(mel_offset, mel_inp.n_len);
  1194. const int i1 = std::min(mel_offset + 2*n_ctx, mel_inp.n_len);
  1195. for (int j = 0; j < mel_inp.n_mel; ++j) {
  1196. for (int i = i0; i < i1; ++i) {
  1197. dst[j*2*n_ctx + (i - i0)] = mel_inp.data[j*mel_inp.n_len + i];
  1198. }
  1199. }
  1200. }
  1201. struct ggml_tensor * cur;
  1202. #ifndef WHISPER_USE_COREML
  1203. const bool use_coreml = false;
  1204. #else
  1205. const bool use_coreml = wstate.ctx_coreml != nullptr;
  1206. #endif
  1207. #ifndef WHISPER_USE_OPENVINO
  1208. const bool use_openvino = false;
  1209. #else
  1210. const bool use_openvino = wstate.ctx_openvino != nullptr;
  1211. #endif
  1212. if (!use_coreml && !use_openvino) {
  1213. // convolution + gelu
  1214. {
  1215. wstate.use_buf(ctx0, 1);
  1216. cur = ggml_conv_1d_ph(ctx0, model.e_conv_1_w, mel, 1, 1);
  1217. cur = ggml_add(ctx0,
  1218. ggml_repeat(ctx0,
  1219. model.e_conv_1_b,
  1220. cur),
  1221. cur);
  1222. cur = ggml_gelu(ctx0, cur);
  1223. wstate.use_buf(ctx0, 0);
  1224. cur = ggml_conv_1d_ph(ctx0, model.e_conv_2_w, cur, 2, 1);
  1225. cur = ggml_add(ctx0,
  1226. ggml_repeat(ctx0,
  1227. model.e_conv_2_b,
  1228. cur),
  1229. cur);
  1230. cur = ggml_gelu(ctx0, cur);
  1231. }
  1232. wstate.use_buf(ctx0, 3);
  1233. // ===================================================================
  1234. // NOTE: experimenting with partial evaluation of the encoder (ignore)
  1235. //static int iter = -1;
  1236. //const int n_iter = 1500/n_ctx;
  1237. //iter = (iter + 1) % n_iter;
  1238. //if (iter == 0) {
  1239. // memset(model.memory_cross_k->data, 0, ggml_nbytes(model.memory_cross_k));
  1240. // memset(model.memory_cross_v->data, 0, ggml_nbytes(model.memory_cross_v));
  1241. //}
  1242. static int iter = 0;
  1243. const size_t e_pe_stride = model.e_pe->ne[0]*ggml_element_size(model.e_pe);
  1244. const size_t e_pe_offset = model.e_pe->ne[0]*ggml_element_size(model.e_pe)*n_ctx*iter;
  1245. struct ggml_tensor * e_pe = ggml_view_2d(ctx0, model.e_pe, model.e_pe->ne[0], n_ctx, e_pe_stride, e_pe_offset);
  1246. cur = ggml_add(ctx0, e_pe, ggml_transpose(ctx0, cur));
  1247. // ===================================================================
  1248. // original:
  1249. //cur = ggml_add(ctx0, model.e_pe, ggml_transpose(ctx0, cur));
  1250. struct ggml_tensor * inpL = cur;
  1251. for (int il = 0; il < n_layer; ++il) {
  1252. const auto & layer = model.layers_encoder[il];
  1253. // norm
  1254. {
  1255. wstate.use_buf(ctx0, 0);
  1256. cur = ggml_norm(ctx0, inpL, hparams.eps);
  1257. // cur = ln_0_w*cur + ln_0_b
  1258. cur = ggml_add(ctx0,
  1259. ggml_mul(ctx0,
  1260. ggml_repeat(ctx0, layer.attn_ln_0_w, cur),
  1261. cur),
  1262. ggml_repeat(ctx0, layer.attn_ln_0_b, cur));
  1263. }
  1264. // self-attention
  1265. {
  1266. wstate.use_buf(ctx0, 1);
  1267. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0,
  1268. layer.attn_q_w,
  1269. cur);
  1270. Qcur = ggml_add(ctx0,
  1271. ggml_repeat(ctx0,
  1272. layer.attn_q_b,
  1273. Qcur),
  1274. Qcur);
  1275. //Qcur = ggml_scale_inplace(ctx0, Qcur, ggml_new_f32(ctx0, pow(float(n_state)/n_head, -0.25)));
  1276. // note: no bias for Key
  1277. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0,
  1278. layer.attn_k_w,
  1279. cur);
  1280. //Kcur = ggml_scale_inplace(ctx0, Kcur, ggml_new_f32(ctx0, pow(float(n_state)/n_head, -0.25)));
  1281. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0,
  1282. layer.attn_v_w,
  1283. cur);
  1284. Vcur = ggml_add(ctx0,
  1285. ggml_repeat(ctx0,
  1286. layer.attn_v_b,
  1287. Vcur),
  1288. Vcur);
  1289. // ------
  1290. wstate.use_buf(ctx0, 0);
  1291. #ifdef WHISPER_USE_FLASH_ATTN
  1292. struct ggml_tensor * Q =
  1293. ggml_permute(ctx0,
  1294. ggml_cpy(ctx0,
  1295. Qcur,
  1296. ggml_new_tensor_3d(ctx0, wctx.itype, n_state/n_head, n_head, n_ctx)),
  1297. 0, 2, 1, 3);
  1298. struct ggml_tensor * K =
  1299. ggml_permute(ctx0,
  1300. ggml_cpy(ctx0,
  1301. Kcur,
  1302. ggml_new_tensor_3d(ctx0, wctx.itype, n_state/n_head, n_head, n_ctx)),
  1303. 0, 2, 1, 3);
  1304. struct ggml_tensor * V =
  1305. ggml_cpy(ctx0,
  1306. ggml_permute(ctx0,
  1307. ggml_reshape_3d(ctx0,
  1308. Vcur,
  1309. n_state/n_head, n_head, n_ctx),
  1310. 1, 2, 0, 3),
  1311. ggml_new_tensor_3d(ctx0, wctx.itype, n_ctx, n_state/n_head, n_head));
  1312. struct ggml_tensor * KQV = ggml_flash_attn(ctx0, Q, K, V, false);
  1313. #else
  1314. struct ggml_tensor * Q =
  1315. ggml_permute(ctx0,
  1316. ggml_cpy(ctx0,
  1317. Qcur,
  1318. ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_state/n_head, n_head, n_ctx)),
  1319. 0, 2, 1, 3);
  1320. struct ggml_tensor * K =
  1321. ggml_permute(ctx0,
  1322. ggml_cpy(ctx0,
  1323. Kcur,
  1324. ggml_new_tensor_3d(ctx0, wctx.itype, n_state/n_head, n_head, n_ctx)),
  1325. 0, 2, 1, 3);
  1326. // K * Q
  1327. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  1328. struct ggml_tensor * KQ_scaled =
  1329. ggml_scale_inplace(ctx0,
  1330. KQ,
  1331. ggml_new_f32(ctx0, 1.0f/sqrt(float(n_state)/n_head))
  1332. );
  1333. struct ggml_tensor * KQ_soft_max = ggml_soft_max_inplace(ctx0, KQ_scaled);
  1334. struct ggml_tensor * V =
  1335. ggml_cpy(ctx0,
  1336. ggml_permute(ctx0,
  1337. ggml_reshape_3d(ctx0,
  1338. Vcur,
  1339. n_state/n_head, n_head, n_ctx),
  1340. 1, 2, 0, 3),
  1341. ggml_new_tensor_3d(ctx0, wctx.itype, n_ctx, n_state/n_head, n_head)
  1342. );
  1343. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  1344. #endif
  1345. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  1346. wstate.use_buf(ctx0, 1);
  1347. cur = ggml_cpy(ctx0,
  1348. KQV_merged,
  1349. ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_state, n_ctx));
  1350. }
  1351. // projection
  1352. {
  1353. wstate.use_buf(ctx0, 0);
  1354. cur = ggml_mul_mat(ctx0,
  1355. layer.attn_ln_1_w,
  1356. cur);
  1357. wstate.use_buf(ctx0, 1);
  1358. cur = ggml_add(ctx0,
  1359. ggml_repeat(ctx0, layer.attn_ln_1_b, cur),
  1360. cur);
  1361. }
  1362. wstate.use_buf(ctx0, 2);
  1363. // add the input
  1364. cur = ggml_add(ctx0, cur, inpL);
  1365. struct ggml_tensor * inpFF = cur;
  1366. // feed-forward network
  1367. {
  1368. // norm
  1369. {
  1370. wstate.use_buf(ctx0, 0);
  1371. cur = ggml_norm(ctx0, inpFF, hparams.eps);
  1372. wstate.use_buf(ctx0, 1);
  1373. // cur = mlp_ln_w*cur + mlp_ln_b
  1374. cur = ggml_add(ctx0,
  1375. ggml_mul(ctx0,
  1376. ggml_repeat(ctx0, layer.mlp_ln_w, cur),
  1377. cur),
  1378. ggml_repeat(ctx0, layer.mlp_ln_b, cur));
  1379. }
  1380. #ifdef WHISPER_USE_FLASH_FF
  1381. wstate.use_buf(ctx0, 0);
  1382. cur = ggml_flash_ff(ctx0,
  1383. ggml_cpy(ctx0, cur, ggml_new_tensor_2d(ctx0, wstate.itype, n_state, n_ctx)),
  1384. layer.mlp_0_w, layer.mlp_0_b, layer.mlp_1_w, layer.mlp_1_b);
  1385. #else
  1386. wstate.use_buf(ctx0, 0);
  1387. // fully connected
  1388. cur = ggml_mul_mat(ctx0,
  1389. layer.mlp_0_w,
  1390. cur);
  1391. wstate.use_buf(ctx0, 1);
  1392. cur = ggml_add(ctx0,
  1393. ggml_repeat(ctx0, layer.mlp_0_b, cur),
  1394. cur);
  1395. wstate.use_buf(ctx0, 0);
  1396. // GELU activation
  1397. cur = ggml_gelu(ctx0, cur);
  1398. wstate.use_buf(ctx0, 1);
  1399. // projection
  1400. cur = ggml_mul_mat(ctx0,
  1401. layer.mlp_1_w,
  1402. cur);
  1403. wstate.use_buf(ctx0, 0);
  1404. cur = ggml_add(ctx0,
  1405. ggml_repeat(ctx0, layer.mlp_1_b, cur),
  1406. cur);
  1407. #endif
  1408. }
  1409. wstate.use_buf(ctx0, 3);
  1410. inpL = ggml_add(ctx0, cur, inpFF);
  1411. }
  1412. cur = inpL;
  1413. // norm
  1414. {
  1415. wstate.use_buf(ctx0, 0);
  1416. cur = ggml_norm(ctx0, cur, hparams.eps);
  1417. wstate.use_buf(ctx0, 1);
  1418. // cur = ln_f_g*cur + ln_f_b
  1419. cur = ggml_add(ctx0,
  1420. ggml_mul(ctx0,
  1421. ggml_repeat(ctx0, model.e_ln_w, cur),
  1422. cur),
  1423. ggml_repeat(ctx0, model.e_ln_b, cur));
  1424. }
  1425. wstate.use_buf(ctx0, -1);
  1426. // run the computation
  1427. {
  1428. struct ggml_cgraph gf = {};
  1429. ggml_build_forward_expand (&gf, cur);
  1430. ggml_graph_compute_with_ctx(ctx0, &gf, n_threads);
  1431. //ggml_graph_print(&gf);
  1432. }
  1433. }
  1434. #ifdef WHISPER_USE_COREML
  1435. else if (use_coreml) {
  1436. wstate.use_buf(ctx0, -1);
  1437. cur = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_state, n_ctx);
  1438. whisper_coreml_encode(wstate.ctx_coreml, (float *) mel->data, (float *) cur->data);
  1439. }
  1440. #endif
  1441. #ifdef WHISPER_USE_OPENVINO
  1442. else if (use_openvino) {
  1443. wstate.use_buf(ctx0, -1);
  1444. cur = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_state, n_ctx);
  1445. if (!whisper_openvino_encode(wstate.ctx_openvino, mel, cur)) {
  1446. return false;
  1447. }
  1448. }
  1449. #endif
  1450. // cur
  1451. //{
  1452. // printf("ne0 = %d\n", cur->ne[0]);
  1453. // printf("ne1 = %d\n", cur->ne[1]);
  1454. // for (int i = 0; i < 10; ++i) {
  1455. // printf("%8.4f ", ((float *)(cur->data))[i]);
  1456. // }
  1457. // printf("... ");
  1458. // for (int i = cur->ne[0] - 10; i < cur->ne[0]; ++i) {
  1459. // printf("%8.4f ", ((float *)(cur->data))[i]);
  1460. // }
  1461. // printf("\n");
  1462. //}
  1463. // pre-compute cross-attention memory
  1464. {
  1465. struct ggml_cgraph gf = {};
  1466. // TODO: hack to disconnect the encoded features from the previous graph
  1467. cur->op = GGML_OP_NONE;
  1468. cur->src[0] = nullptr;
  1469. cur->src[1] = nullptr;
  1470. for (int il = 0; il < model.hparams.n_text_layer; ++il) {
  1471. auto& layer = model.layers_decoder[il];
  1472. wstate.use_buf(ctx0, 0);
  1473. struct ggml_tensor* Kcross = ggml_mul_mat(ctx0,
  1474. layer.cross_attn_k_w,
  1475. cur);
  1476. Kcross = ggml_scale_inplace(ctx0, Kcross, ggml_new_f32(ctx0, pow(float(n_state) / n_head, -0.25)));
  1477. wstate.use_buf(ctx0, 1);
  1478. struct ggml_tensor* Vcross = ggml_mul_mat(ctx0,
  1479. layer.cross_attn_v_w,
  1480. cur);
  1481. Vcross = ggml_add(ctx0,
  1482. ggml_repeat(ctx0,
  1483. layer.cross_attn_v_b,
  1484. Vcross),
  1485. Vcross);
  1486. wstate.use_buf(ctx0, -1);
  1487. Vcross = ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcross, n_state, n_ctx));
  1488. struct ggml_tensor * k = ggml_view_1d(ctx0, wstate.kv_cross.k, n_state*n_ctx, (ggml_element_size(wstate.kv_cross.k)*n_state)*(il*n_ctx));
  1489. struct ggml_tensor * v = ggml_view_2d(ctx0, wstate.kv_cross.v, n_ctx, n_state,
  1490. ( n_ctx)*ggml_element_size(wstate.kv_cross.v),
  1491. (il*n_ctx)*ggml_element_size(wstate.kv_cross.v)*n_state);
  1492. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Kcross, k));
  1493. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Vcross, v));
  1494. }
  1495. ggml_graph_compute_with_ctx(ctx0, &gf, n_threads);
  1496. //ggml_graph_print(&gf);
  1497. }
  1498. ////////////////////////////////////////////////////////////////////////////
  1499. //printf("%s: used_mem = %f MB, %f MB, %f MB %f MB %f MB\n", __func__,
  1500. // ggml_used_mem(ctx0)/1024.0/1024.0,
  1501. // wstate.get_buf_max_mem(0)/1024.0/1024.0,
  1502. // wstate.get_buf_max_mem(1)/1024.0/1024.0,
  1503. // wstate.get_buf_max_mem(2)/1024.0/1024.0,
  1504. // wstate.get_buf_max_mem(3)/1024.0/1024.0);
  1505. ggml_free(ctx0);
  1506. wstate.t_encode_us += ggml_time_us() - t_start_us;
  1507. wstate.n_encode++;
  1508. return true;
  1509. }
  1510. // evaluate the decoder
  1511. //
  1512. // given text prompt + audio features -> computes the logits for the next token
  1513. //
  1514. // - model: the model
  1515. // - n_threads: number of threads to use
  1516. // - tokens: text prompt
  1517. // - n_tokens: number of tokens in the prompt
  1518. // - n_past: number of past tokens to prefix the prompt with
  1519. //
  1520. static bool whisper_decode_internal(
  1521. whisper_context & wctx,
  1522. whisper_state & wstate,
  1523. whisper_decoder & decoder,
  1524. const whisper_token * tokens,
  1525. const int n_tokens,
  1526. const int n_past,
  1527. const int n_threads) {
  1528. const int64_t t_start_us = ggml_time_us();
  1529. const auto & model = wctx.model;
  1530. const auto & hparams = model.hparams;
  1531. auto & kv_self = decoder.kv_self;
  1532. WHISPER_ASSERT(!!kv_self.ctx);
  1533. auto & logits_out = wstate.logits;
  1534. const int n_vocab = hparams.n_vocab;
  1535. const int n_ctx = hparams.n_text_ctx;
  1536. const int n_state = hparams.n_text_state;
  1537. const int n_head = hparams.n_text_head;
  1538. const int n_layer = hparams.n_text_layer;
  1539. const int N = n_tokens;
  1540. const int M = wstate.exp_n_audio_ctx > 0 ? wstate.exp_n_audio_ctx : hparams.n_audio_ctx;
  1541. //WHISPER_PRINT_DEBUG("%s: n_past = %d, N = %d, M = %d, n_ctx = %d\n", __func__, n_past, N, M, n_ctx);
  1542. struct ggml_init_params params = {
  1543. /*.mem_size =*/ wstate.buf_compute.size(),
  1544. /*.mem_buffer =*/ wstate.buf_compute.data(),
  1545. /*.no_alloc =*/ false,
  1546. };
  1547. struct ggml_context * ctx0 = ggml_init(params);
  1548. struct ggml_cgraph gf = {};
  1549. struct ggml_tensor * embd = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  1550. memcpy(embd->data, tokens, N*ggml_element_size(embd));
  1551. struct ggml_tensor * position = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  1552. for (int i = 0; i < N; ++i) {
  1553. ((int32_t *) position->data)[i] = n_past + i;
  1554. }
  1555. wstate.use_buf(ctx0, 3);
  1556. // token encoding + position encoding
  1557. struct ggml_tensor * cur =
  1558. ggml_add(ctx0,
  1559. ggml_get_rows(ctx0, model.d_te, embd),
  1560. ggml_get_rows(ctx0, model.d_pe, position));
  1561. struct ggml_tensor * inpL = cur;
  1562. for (int il = 0; il < n_layer; ++il) {
  1563. const auto & layer = model.layers_decoder[il];
  1564. // norm
  1565. {
  1566. wstate.use_buf(ctx0, 0);
  1567. cur = ggml_norm(ctx0, inpL, hparams.eps);
  1568. // cur = ln_0_w*cur + ln_0_b
  1569. cur = ggml_add(ctx0,
  1570. ggml_mul(ctx0,
  1571. ggml_repeat(ctx0, layer.attn_ln_0_w, cur),
  1572. cur),
  1573. ggml_repeat(ctx0, layer.attn_ln_0_b, cur));
  1574. }
  1575. // self-attention
  1576. {
  1577. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0,
  1578. layer.attn_q_w,
  1579. cur);
  1580. Qcur = ggml_add(ctx0,
  1581. ggml_repeat(ctx0,
  1582. layer.attn_q_b,
  1583. Qcur),
  1584. Qcur);
  1585. Qcur = ggml_scale_inplace(ctx0, Qcur, ggml_new_f32(ctx0, pow(float(n_state)/n_head, -0.25)));
  1586. // note: no bias for Key
  1587. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0,
  1588. layer.attn_k_w,
  1589. cur);
  1590. Kcur = ggml_scale_inplace(ctx0, Kcur, ggml_new_f32(ctx0, pow(float(n_state)/n_head, -0.25)));
  1591. // store key and value to memory
  1592. {
  1593. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0,
  1594. layer.attn_v_w,
  1595. cur);
  1596. Vcur = ggml_add(ctx0,
  1597. ggml_repeat(ctx0,
  1598. layer.attn_v_b,
  1599. Vcur),
  1600. Vcur);
  1601. Vcur = ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_state, N));
  1602. struct ggml_tensor * k = ggml_view_1d(ctx0, kv_self.k, N*n_state, (ggml_element_size(kv_self.k)*n_state)*(il*n_ctx + n_past));
  1603. struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, N, n_state,
  1604. ( n_ctx)*ggml_element_size(kv_self.v),
  1605. (il*n_ctx)*ggml_element_size(kv_self.v)*n_state + n_past*ggml_element_size(kv_self.v));
  1606. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Kcur, k));
  1607. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Vcur, v));
  1608. }
  1609. // ------
  1610. wstate.use_buf(ctx0, 0);
  1611. struct ggml_tensor * Q =
  1612. ggml_permute(ctx0,
  1613. ggml_cpy(ctx0,
  1614. Qcur,
  1615. ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_state/n_head, n_head, N)),
  1616. 0, 2, 1, 3);
  1617. struct ggml_tensor * K =
  1618. ggml_permute(ctx0,
  1619. ggml_reshape_3d(ctx0,
  1620. ggml_view_1d(ctx0, kv_self.k, (n_past + N)*n_state, il*n_ctx*ggml_element_size(kv_self.k)*n_state),
  1621. n_state/n_head, n_head, n_past + N),
  1622. 0, 2, 1, 3);
  1623. wstate.use_buf(ctx0, 1);
  1624. // K * Q
  1625. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  1626. //struct ggml_tensor * KQ_scaled =
  1627. // ggml_scale_inplace(ctx0,
  1628. // KQ,
  1629. // ggml_new_f32(ctx0, 1.0f/sqrt(float(n_state)/n_head))
  1630. // );
  1631. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf_inplace(ctx0, KQ, n_past);
  1632. struct ggml_tensor * KQ_soft_max = ggml_soft_max_inplace(ctx0, KQ_masked);
  1633. struct ggml_tensor * V =
  1634. ggml_view_3d(ctx0, kv_self.v,
  1635. n_past + N, n_state/n_head, n_head,
  1636. n_ctx*ggml_element_size(kv_self.v),
  1637. n_ctx*ggml_element_size(kv_self.v)*n_state/n_head,
  1638. il*n_ctx*ggml_element_size(kv_self.v)*n_state);
  1639. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  1640. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  1641. cur = ggml_cpy(ctx0,
  1642. KQV_merged,
  1643. ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_state, N));
  1644. }
  1645. // projection
  1646. {
  1647. wstate.use_buf(ctx0, 0);
  1648. cur = ggml_mul_mat(ctx0,
  1649. layer.attn_ln_1_w,
  1650. cur);
  1651. wstate.use_buf(ctx0, 1);
  1652. cur = ggml_add(ctx0,
  1653. ggml_repeat(ctx0, layer.attn_ln_1_b, cur),
  1654. cur);
  1655. }
  1656. wstate.use_buf(ctx0, 2);
  1657. // add the input
  1658. struct ggml_tensor * inpCA = ggml_add(ctx0, cur, inpL);
  1659. // norm
  1660. {
  1661. wstate.use_buf(ctx0, 0);
  1662. cur = ggml_norm(ctx0, inpCA, hparams.eps); // note: we use inpCA here
  1663. // cur = ln_0_w*cur + ln_0_b
  1664. cur = ggml_add(ctx0,
  1665. ggml_mul(ctx0,
  1666. ggml_repeat(ctx0, layer.cross_attn_ln_0_w, cur),
  1667. cur),
  1668. ggml_repeat(ctx0, layer.cross_attn_ln_0_b, cur));
  1669. }
  1670. // cross-attention
  1671. {
  1672. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0,
  1673. layer.cross_attn_q_w,
  1674. cur);
  1675. Qcur = ggml_add(ctx0,
  1676. ggml_repeat(ctx0,
  1677. layer.cross_attn_q_b,
  1678. Qcur),
  1679. Qcur);
  1680. Qcur = ggml_scale_inplace(ctx0, Qcur, ggml_new_f32(ctx0, pow(float(n_state)/n_head, -0.25)));
  1681. // Kcross is already scaled
  1682. struct ggml_tensor * Kcross =
  1683. ggml_reshape_3d(ctx0,
  1684. ggml_view_1d(ctx0, wstate.kv_cross.k, M*n_state, il*M*ggml_element_size(wstate.kv_cross.k)*n_state),
  1685. n_state/n_head, n_head, M);
  1686. //struct ggml_tensor * Vcross =
  1687. // ggml_reshape_3d(ctx0,
  1688. // ggml_view_1d(ctx0, wstate.kv_cross.v, M*n_state, il*M*ggml_element_size(wstate.kv_cross.v)*n_state),
  1689. // n_state/n_head, n_head, M);
  1690. //struct ggml_tensor * V_trans =
  1691. // ggml_cpy(ctx0,
  1692. // ggml_permute(ctx0, Vcross, 1, 2, 0, 3),
  1693. // ggml_new_tensor_3d(ctx0, Vcross->type, M, n_state/n_head, n_head));
  1694. struct ggml_tensor * V =
  1695. ggml_view_3d(ctx0, wstate.kv_cross.v,
  1696. M, n_state/n_head, n_head,
  1697. M*ggml_element_size(wstate.kv_cross.v),
  1698. M*ggml_element_size(wstate.kv_cross.v)*n_state/n_head,
  1699. il*M*ggml_element_size(wstate.kv_cross.v)*n_state);
  1700. // ------
  1701. struct ggml_tensor * Q =
  1702. ggml_permute(ctx0,
  1703. ggml_cpy(ctx0,
  1704. Qcur,
  1705. ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_state/n_head, n_head, N)),
  1706. 0, 2, 1, 3);
  1707. struct ggml_tensor * K = ggml_permute(ctx0, Kcross, 0, 2, 1, 3);
  1708. // K * Q
  1709. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  1710. //struct ggml_tensor * KQ_scaled =
  1711. // ggml_scale_inplace(ctx0,
  1712. // KQ,
  1713. // ggml_new_f32(ctx0, 1.0f/sqrt(float(n_state)/n_head))
  1714. // );
  1715. // no masking for cross-attention
  1716. //struct ggml_tensor * KQ_masked = ggml_diag_mask_inf_inplace(ctx0, KQ_scaled, n_past);
  1717. struct ggml_tensor * KQ_soft_max = ggml_soft_max_inplace(ctx0, KQ);
  1718. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  1719. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  1720. // cur = KQV_merged.contiguous().view(n_state, N)
  1721. cur = ggml_cpy(ctx0,
  1722. KQV_merged,
  1723. ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_state, N));
  1724. }
  1725. // projection
  1726. {
  1727. wstate.use_buf(ctx0, 0);
  1728. cur = ggml_mul_mat(ctx0,
  1729. layer.cross_attn_ln_1_w,
  1730. cur);
  1731. wstate.use_buf(ctx0, 1);
  1732. cur = ggml_add(ctx0,
  1733. ggml_repeat(ctx0, layer.cross_attn_ln_1_b, cur),
  1734. cur);
  1735. }
  1736. wstate.use_buf(ctx0, 2);
  1737. // add the input
  1738. cur = ggml_add(ctx0, cur, inpCA);
  1739. struct ggml_tensor * inpFF = cur;
  1740. // feed-forward network
  1741. {
  1742. // norm
  1743. {
  1744. wstate.use_buf(ctx0, 0);
  1745. cur = ggml_norm(ctx0, inpFF, hparams.eps);
  1746. wstate.use_buf(ctx0, 1);
  1747. // cur = mlp_ln_w*cur + mlp_ln_b
  1748. cur = ggml_add(ctx0,
  1749. ggml_mul(ctx0,
  1750. ggml_repeat(ctx0, layer.mlp_ln_w, cur),
  1751. cur),
  1752. ggml_repeat(ctx0, layer.mlp_ln_b, cur));
  1753. }
  1754. wstate.use_buf(ctx0, 0);
  1755. // fully connected
  1756. cur = ggml_mul_mat(ctx0,
  1757. layer.mlp_0_w,
  1758. cur);
  1759. wstate.use_buf(ctx0, 1);
  1760. cur = ggml_add(ctx0,
  1761. ggml_repeat(ctx0, layer.mlp_0_b, cur),
  1762. cur);
  1763. wstate.use_buf(ctx0, 0);
  1764. // GELU activation
  1765. cur = ggml_gelu(ctx0, cur);
  1766. wstate.use_buf(ctx0, 1);
  1767. // projection
  1768. cur = ggml_mul_mat(ctx0,
  1769. layer.mlp_1_w,
  1770. cur);
  1771. wstate.use_buf(ctx0, 0);
  1772. cur = ggml_add(ctx0,
  1773. ggml_repeat(ctx0, layer.mlp_1_b, cur),
  1774. cur);
  1775. }
  1776. wstate.use_buf(ctx0, 3);
  1777. inpL = ggml_add(ctx0, cur, inpFF);
  1778. }
  1779. cur = inpL;
  1780. // norm
  1781. {
  1782. wstate.use_buf(ctx0, 0);
  1783. cur = ggml_norm(ctx0, cur, hparams.eps);
  1784. wstate.use_buf(ctx0, 1);
  1785. cur = ggml_add(ctx0,
  1786. ggml_mul(ctx0,
  1787. ggml_repeat(ctx0, model.d_ln_w, cur),
  1788. cur),
  1789. ggml_repeat(ctx0, model.d_ln_b, cur));
  1790. }
  1791. wstate.use_buf(ctx0, 0);
  1792. // compute logits only for the last token
  1793. // comment this line to compute logits for all N tokens
  1794. // might be useful in the future
  1795. cur = ggml_view_2d(ctx0, cur, cur->ne[0], 1, cur->nb[1], (cur->ne[1] - 1)*cur->nb[1]);
  1796. struct ggml_tensor * logits = ggml_mul_mat(ctx0, model.d_te, cur);
  1797. wstate.use_buf(ctx0, -1);
  1798. // run the computation
  1799. {
  1800. ggml_build_forward_expand (&gf, logits);
  1801. ggml_graph_compute_with_ctx(ctx0, &gf, n_threads);
  1802. }
  1803. // extract logits for all N tokens
  1804. //logits_out.resize(N*n_vocab);
  1805. //memcpy(logits_out.data(), ggml_get_data(logits), sizeof(float)*N*n_vocab);
  1806. // extract logits only for the last token
  1807. logits_out.resize(n_vocab);
  1808. memcpy(logits_out.data(), ggml_get_data(logits), sizeof(float)*n_vocab);
  1809. if (N > 1) {
  1810. //printf("%s: used_mem = %f MB, %f MB, %f MB %f MB %f MB\n", __func__,
  1811. // ggml_used_mem(ctx0)/1024.0/1024.0,
  1812. // wstate.get_buf_max_mem(0)/1024.0/1024.0,
  1813. // wstate.get_buf_max_mem(1)/1024.0/1024.0,
  1814. // wstate.get_buf_max_mem(2)/1024.0/1024.0,
  1815. // wstate.get_buf_max_mem(3)/1024.0/1024.0);
  1816. }
  1817. ggml_free(ctx0);
  1818. wstate.t_decode_us += ggml_time_us() - t_start_us;
  1819. wstate.n_decode++;
  1820. return true;
  1821. }
  1822. // 500 -> 00:05.000
  1823. // 6000 -> 01:00.000
  1824. static std::string to_timestamp(int64_t t, bool comma = false) {
  1825. int64_t msec = t * 10;
  1826. int64_t hr = msec / (1000 * 60 * 60);
  1827. msec = msec - hr * (1000 * 60 * 60);
  1828. int64_t min = msec / (1000 * 60);
  1829. msec = msec - min * (1000 * 60);
  1830. int64_t sec = msec / 1000;
  1831. msec = msec - sec * 1000;
  1832. char buf[32];
  1833. snprintf(buf, sizeof(buf), "%02d:%02d:%02d%s%03d", (int) hr, (int) min, (int) sec, comma ? "," : ".", (int) msec);
  1834. return std::string(buf);
  1835. }
  1836. #define SIN_COS_N_COUNT WHISPER_N_FFT
  1837. static float sin_vals[SIN_COS_N_COUNT];
  1838. static float cos_vals[SIN_COS_N_COUNT];
  1839. // In FFT, we frequently use sine and cosine operations with the same values.
  1840. // We can use precalculated values to speed up the process.
  1841. static void fill_sin_cos_table() {
  1842. static bool is_filled = false;
  1843. if (is_filled) return;
  1844. for (int i = 0; i < SIN_COS_N_COUNT; i++) {
  1845. double theta = (2*M_PI*i)/SIN_COS_N_COUNT;
  1846. sin_vals[i] = sinf(theta);
  1847. cos_vals[i] = cosf(theta);
  1848. }
  1849. is_filled = true;
  1850. }
  1851. // naive Discrete Fourier Transform
  1852. // input is real-valued
  1853. // output is complex-valued
  1854. static void dft(const std::vector<float> & in, std::vector<float> & out) {
  1855. int N = in.size();
  1856. out.resize(N*2);
  1857. const int sin_cos_step = SIN_COS_N_COUNT / N;
  1858. for (int k = 0; k < N; k++) {
  1859. float re = 0;
  1860. float im = 0;
  1861. for (int n = 0; n < N; n++) {
  1862. int idx = (k * n * sin_cos_step) % (SIN_COS_N_COUNT); // t = 2*M_PI*k*n/N
  1863. re += in[n]*cos_vals[idx]; // cos(t)
  1864. im -= in[n]*sin_vals[idx]; // sin(t)
  1865. }
  1866. out[k*2 + 0] = re;
  1867. out[k*2 + 1] = im;
  1868. }
  1869. }
  1870. // Cooley-Tukey FFT
  1871. // poor man's implementation - use something better
  1872. // input is real-valued
  1873. // output is complex-valued
  1874. static void fft(const std::vector<float> & in, std::vector<float> & out) {
  1875. out.resize(in.size()*2);
  1876. int N = in.size();
  1877. if (N == 1) {
  1878. out[0] = in[0];
  1879. out[1] = 0;
  1880. return;
  1881. }
  1882. if (N%2 == 1) {
  1883. dft(in, out);
  1884. return;
  1885. }
  1886. std::vector<float> even;
  1887. std::vector<float> odd;
  1888. even.reserve(N/2);
  1889. odd.reserve(N/2);
  1890. for (int i = 0; i < N; i++) {
  1891. if (i % 2 == 0) {
  1892. even.push_back(in[i]);
  1893. } else {
  1894. odd.push_back(in[i]);
  1895. }
  1896. }
  1897. std::vector<float> even_fft;
  1898. std::vector<float> odd_fft;
  1899. fft(even, even_fft);
  1900. fft(odd, odd_fft);
  1901. const int sin_cos_step = SIN_COS_N_COUNT / N;
  1902. for (int k = 0; k < N/2; k++) {
  1903. int idx = k * sin_cos_step; // t = 2*M_PI*k/N
  1904. float re = cos_vals[idx]; // cos(t)
  1905. float im = -sin_vals[idx]; // sin(t)
  1906. float re_odd = odd_fft[2*k + 0];
  1907. float im_odd = odd_fft[2*k + 1];
  1908. out[2*k + 0] = even_fft[2*k + 0] + re*re_odd - im*im_odd;
  1909. out[2*k + 1] = even_fft[2*k + 1] + re*im_odd + im*re_odd;
  1910. out[2*(k + N/2) + 0] = even_fft[2*k + 0] - re*re_odd + im*im_odd;
  1911. out[2*(k + N/2) + 1] = even_fft[2*k + 1] - re*im_odd - im*re_odd;
  1912. }
  1913. }
  1914. static bool hann_window(int length, bool periodic, std::vector<float> & output) {
  1915. if (output.size() < static_cast<size_t>(length)) {
  1916. output.resize(length);
  1917. }
  1918. int offset = -1;
  1919. if (periodic) {
  1920. offset = 0;
  1921. }
  1922. for (int i = 0; i < length; i++) {
  1923. output[i] = 0.5*(1.0 - cosf((2.0*M_PI*i)/(length + offset)));
  1924. }
  1925. return true;
  1926. }
  1927. static void log_mel_spectrogram_worker_thread(int ith, const std::vector<float> & hann, const std::vector<float> & samples,
  1928. int n_samples, int frame_size, int frame_step, int n_threads,
  1929. const whisper_filters & filters, whisper_mel & mel) {
  1930. std::vector<float> fft_in(frame_size, 0.0);
  1931. std::vector<float> fft_out(2 * frame_step);
  1932. // make sure n_fft == 1 + (WHISPER_N_FFT / 2), bin_0 to bin_nyquist
  1933. int n_fft = 1 + (frame_size / 2);
  1934. int i = ith;
  1935. // calculate FFT only when fft_in are not all zero
  1936. for (; i < std::min(n_samples / frame_step + 1, mel.n_len); i += n_threads) {
  1937. const int offset = i * frame_step;
  1938. // apply Hanning window (~10% faster)
  1939. for (int j = 0; j < std::min(frame_size, n_samples - offset); j++) {
  1940. fft_in[j] = hann[j] * samples[offset + j];
  1941. }
  1942. // fill the rest with zeros
  1943. if (n_samples - offset < frame_size) {
  1944. std::fill(fft_in.begin() + (n_samples - offset), fft_in.end(), 0.0);
  1945. }
  1946. // FFT
  1947. fft(fft_in, fft_out);
  1948. // Calculate modulus^2 of complex numbers
  1949. // Use pow(fft_out[2 * j + 0], 2) + pow(fft_out[2 * j + 1], 2) causes inference quality problem? Interesting.
  1950. for (int j = 0; j < frame_size; j++) {
  1951. fft_out[j] = (fft_out[2 * j + 0] * fft_out[2 * j + 0] + fft_out[2 * j + 1] * fft_out[2 * j + 1]);
  1952. }
  1953. // mel spectrogram
  1954. for (int j = 0; j < mel.n_mel; j++) {
  1955. double sum = 0.0;
  1956. // unroll loop (suggested by GH user @lunixbochs)
  1957. int k = 0;
  1958. for (k = 0; k < n_fft - 3; k += 4) {
  1959. sum +=
  1960. fft_out[k + 0] * filters.data[j * n_fft + k + 0] +
  1961. fft_out[k + 1] * filters.data[j * n_fft + k + 1] +
  1962. fft_out[k + 2] * filters.data[j * n_fft + k + 2] +
  1963. fft_out[k + 3] * filters.data[j * n_fft + k + 3];
  1964. }
  1965. // handle n_fft remainder
  1966. for (; k < n_fft; k++) {
  1967. sum += fft_out[k] * filters.data[j * n_fft + k];
  1968. }
  1969. sum = log10(std::max(sum, 1e-10));
  1970. mel.data[j * mel.n_len + i] = sum;
  1971. }
  1972. }
  1973. // Otherwise fft_out are all zero
  1974. double sum = log10(1e-10);
  1975. for (; i < mel.n_len; i += n_threads) {
  1976. for (int j = 0; j < mel.n_mel; j++) {
  1977. mel.data[j * mel.n_len + i] = sum;
  1978. }
  1979. }
  1980. }
  1981. // ref: https://github.com/openai/whisper/blob/main/whisper/audio.py#L110-L157
  1982. static bool log_mel_spectrogram(
  1983. whisper_state & wstate,
  1984. const float * samples,
  1985. const int n_samples,
  1986. const int /*sample_rate*/,
  1987. const int frame_size,
  1988. const int frame_step,
  1989. const int n_mel,
  1990. const int n_threads,
  1991. const whisper_filters & filters,
  1992. const bool debug,
  1993. whisper_mel & mel) {
  1994. const int64_t t_start_us = ggml_time_us();
  1995. // Hanning window (Use cosf to eliminate difference)
  1996. // ref: https://pytorch.org/docs/stable/generated/torch.hann_window.html
  1997. // ref: https://github.com/openai/whisper/blob/main/whisper/audio.py#L147
  1998. std::vector<float> hann;
  1999. hann_window(frame_size, true, hann);
  2000. // Calculate the length of padding
  2001. int64_t stage_1_pad = WHISPER_SAMPLE_RATE * 30;
  2002. int64_t stage_2_pad = frame_size / 2;
  2003. // Initialize a vector and copy data from C array to it.
  2004. std::vector<float> samples_padded;
  2005. samples_padded.resize(n_samples + stage_1_pad + stage_2_pad * 2);
  2006. std::copy(samples, samples + n_samples, samples_padded.begin() + stage_2_pad);
  2007. // pad 30 seconds of zeros at the end of audio (480,000 samples) + reflective pad 200 samples at the end of audio
  2008. std::fill(samples_padded.begin() + n_samples + stage_2_pad, samples_padded.begin() + n_samples + stage_1_pad + 2 * stage_2_pad, 0);
  2009. // reflective pad 200 samples at the beginning of audio
  2010. std::reverse_copy(samples + 1, samples + 1 + stage_2_pad, samples_padded.begin());
  2011. mel.n_mel = n_mel;
  2012. // https://github.com/pytorch/pytorch/blob/main/aten/src/ATen/native/SpectralOps.cpp#L936
  2013. // Calculate number of frames + remove the last frame
  2014. mel.n_len = (samples_padded.size() - frame_size) / frame_step;
  2015. // Calculate semi-padded sample length to ensure compatibility
  2016. mel.n_len_org = 1 + (n_samples + stage_2_pad - frame_size) / frame_step;
  2017. mel.data.resize(mel.n_mel * mel.n_len);
  2018. {
  2019. std::vector<std::thread> workers(n_threads - 1);
  2020. for (int iw = 0; iw < n_threads - 1; ++iw) {
  2021. workers[iw] = std::thread(
  2022. log_mel_spectrogram_worker_thread, iw + 1, std::cref(hann), samples_padded,
  2023. n_samples + stage_2_pad, frame_size, frame_step, n_threads,
  2024. std::cref(filters), std::ref(mel));
  2025. }
  2026. // main thread
  2027. log_mel_spectrogram_worker_thread(0, hann, samples_padded, n_samples + stage_2_pad, frame_size, frame_step, n_threads, filters, mel);
  2028. for (int iw = 0; iw < n_threads - 1; ++iw) {
  2029. workers[iw].join();
  2030. }
  2031. }
  2032. // clamping and normalization
  2033. double mmax = -1e20;
  2034. for (int i = 0; i < mel.n_mel*mel.n_len; i++) {
  2035. if (mel.data[i] > mmax) {
  2036. mmax = mel.data[i];
  2037. }
  2038. }
  2039. mmax -= 8.0;
  2040. for (int i = 0; i < mel.n_mel*mel.n_len; i++) {
  2041. if (mel.data[i] < mmax) {
  2042. mel.data[i] = mmax;
  2043. }
  2044. mel.data[i] = (mel.data[i] + 4.0)/4.0;
  2045. }
  2046. wstate.t_mel_us += ggml_time_us() - t_start_us;
  2047. // Dump log_mel_spectrogram
  2048. if (debug) {
  2049. std::ofstream outFile("log_mel_spectrogram.json");
  2050. outFile << "[";
  2051. for (uint64_t i = 0; i < mel.data.size() - 1; i++) {
  2052. outFile << mel.data[i] << ", ";
  2053. }
  2054. outFile << mel.data[mel.data.size() - 1] << "]";
  2055. outFile.close();
  2056. }
  2057. return true;
  2058. }
  2059. // split text into tokens
  2060. //
  2061. // ref: https://github.com/openai/gpt-2/blob/a74da5d99abaaba920de8131d64da2862a8f213b/src/encoder.py#L53
  2062. //
  2063. // Regex (Python):
  2064. // r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+"""
  2065. //
  2066. // Regex (C++):
  2067. // R"('s|'t|'re|'ve|'m|'ll|'d| ?[[:alpha:]]+| ?[[:digit:]]+| ?[^\s[:alpha:][:digit:]]+|\s+(?!\S)|\s+)"
  2068. //
  2069. static std::vector<whisper_vocab::id> tokenize(const whisper_vocab & vocab, const std::string & text) {
  2070. std::vector<std::string> words;
  2071. // first split the text into words
  2072. {
  2073. std::string str = text;
  2074. std::string pat = R"('s|'t|'re|'ve|'m|'ll|'d| ?[[:alpha:]]+| ?[[:digit:]]+| ?[^\s[:alpha:][:digit:]]+|\s+(?!\S)|\s+)";
  2075. std::regex re(pat);
  2076. std::smatch m;
  2077. while (std::regex_search(str, m, re)) {
  2078. for (auto x : m) {
  2079. words.push_back(x);
  2080. }
  2081. str = m.suffix();
  2082. }
  2083. }
  2084. // find the longest tokens that form the words:
  2085. std::vector<whisper_vocab::id> tokens;
  2086. for (const auto & word : words) {
  2087. if (word.empty()) continue;
  2088. int i = 0;
  2089. int n = word.size();
  2090. while (i < n) {
  2091. int j = n;
  2092. bool found = false;
  2093. while (j > i) {
  2094. auto sub = word.substr(i, j-i);
  2095. auto it = vocab.token_to_id.find(sub);
  2096. if (it != vocab.token_to_id.end()) {
  2097. tokens.push_back(it->second);
  2098. i = j;
  2099. found = true;
  2100. break;
  2101. }
  2102. --j;
  2103. }
  2104. if (!found) {
  2105. log("unknown token\n");
  2106. ++i;
  2107. }
  2108. }
  2109. }
  2110. return tokens;
  2111. }
  2112. //
  2113. // interface implementation
  2114. //
  2115. #ifdef WHISPER_USE_COREML
  2116. // replace .bin with -encoder.mlmodelc
  2117. static std::string whisper_get_coreml_path_encoder(std::string path_bin) {
  2118. auto pos = path_bin.rfind('.');
  2119. if (pos != std::string::npos) {
  2120. path_bin = path_bin.substr(0, pos);
  2121. }
  2122. // match "-qx_x"
  2123. pos = path_bin.rfind('-');
  2124. if (pos != std::string::npos) {
  2125. auto sub = path_bin.substr(pos);
  2126. if (sub.size() == 5 && sub[1] == 'q' && sub[3] == '_') {
  2127. path_bin = path_bin.substr(0, pos);
  2128. }
  2129. }
  2130. path_bin += "-encoder.mlmodelc";
  2131. return path_bin;
  2132. }
  2133. #endif
  2134. #ifdef WHISPER_USE_OPENVINO
  2135. // replace .bin with-encoder-openvino.xml
  2136. static std::string whisper_openvino_get_path_encoder(std::string path_bin) {
  2137. auto pos = path_bin.rfind('.');
  2138. if (pos != std::string::npos) {
  2139. path_bin = path_bin.substr(0, pos);
  2140. }
  2141. path_bin += "-encoder-openvino.xml";
  2142. return path_bin;
  2143. }
  2144. static std::string whisper_openvino_get_path_cache(std::string path_bin) {
  2145. auto pos = path_bin.rfind('.');
  2146. if (pos != std::string::npos) {
  2147. path_bin = path_bin.substr(0, pos);
  2148. }
  2149. path_bin += "-encoder-openvino-cache";
  2150. return path_bin;
  2151. }
  2152. #endif
  2153. struct whisper_state * whisper_init_state(whisper_context * ctx) {
  2154. fill_sin_cos_table();
  2155. whisper_state * state = new whisper_state;
  2156. const size_t scale = ctx->model.hparams.ftype ? 1 : 2;
  2157. if (!kv_cache_init(ctx->model.hparams, scale * MEM_REQ_KV_SELF.at(ctx->model.type), state->decoders[0].kv_self, ctx->itype, ctx->model.hparams.n_text_ctx)) {
  2158. log("%s: kv_cache_init() failed for self-attention cache\n", __func__);
  2159. delete state;
  2160. return nullptr;
  2161. }
  2162. {
  2163. const size_t memory_size = ggml_nbytes(state->decoders[0].kv_self.k) + ggml_nbytes(state->decoders[0].kv_self.v);
  2164. log("%s: kv self size = %7.2f MB\n", __func__, memory_size / 1024.0 / 1024.0);
  2165. }
  2166. if (!kv_cache_init(ctx->model.hparams, scale * MEM_REQ_KV_CROSS.at(ctx->model.type), state->kv_cross, ctx->itype, ctx->model.hparams.n_audio_ctx)) {
  2167. log("%s: kv_cache_init() failed for cross-attention cache\n", __func__);
  2168. delete state;
  2169. return nullptr;
  2170. }
  2171. {
  2172. const size_t memory_size = ggml_nbytes(state->kv_cross.k) + ggml_nbytes(state->kv_cross.v);
  2173. log("%s: kv cross size = %7.2f MB\n", __func__, memory_size / 1024.0 / 1024.0);
  2174. }
  2175. #ifdef WHISPER_USE_COREML
  2176. const auto path_coreml = whisper_get_coreml_path_encoder(ctx->path_model);
  2177. log("%s: loading Core ML model from '%s'\n", __func__, path_coreml.c_str());
  2178. log("%s: first run on a device may take a while ...\n", __func__);
  2179. state->ctx_coreml = whisper_coreml_init(path_coreml.c_str());
  2180. if (!state->ctx_coreml) {
  2181. log("%s: failed to load Core ML model from '%s'\n", __func__, path_coreml.c_str());
  2182. #ifndef WHISPER_COREML_ALLOW_FALLBACK
  2183. return nullptr;
  2184. #endif
  2185. } else {
  2186. log("%s: Core ML model loaded\n", __func__);
  2187. }
  2188. #endif
  2189. state->logits.reserve(ctx->vocab.n_vocab * ctx->model.hparams.n_text_ctx);
  2190. state->logits_id.reserve(ctx->model.hparams.n_vocab);
  2191. // TAGS: WHISPER_DECODER_INIT
  2192. state->decoders[0].sequence.tokens.reserve(ctx->model.hparams.n_text_ctx);
  2193. state->decoders[0].probs.reserve(ctx->vocab.n_vocab);
  2194. state->decoders[0].logits.reserve(ctx->vocab.n_vocab);
  2195. state->decoders[0].logprobs.reserve(ctx->vocab.n_vocab);
  2196. state->buf_compute.resize(scale * std::max(MEM_REQ_ENCODE.at(ctx->model.type), MEM_REQ_DECODE.at(ctx->model.type)));
  2197. state->buf_scratch[0].resize(MEM_REQ_SCRATCH0.at(ctx->model.type));
  2198. state->buf_scratch[1].resize(MEM_REQ_SCRATCH1.at(ctx->model.type));
  2199. state->buf_scratch[2].resize(MEM_REQ_SCRATCH2.at(ctx->model.type));
  2200. state->buf_scratch[3].resize(MEM_REQ_SCRATCH3.at(ctx->model.type));
  2201. state->rng = std::mt19937(0);
  2202. return state;
  2203. }
  2204. int whisper_ctx_init_openvino_encoder(
  2205. struct whisper_context * ctx,
  2206. const char * model_path,
  2207. const char * device,
  2208. const char * cache_dir) {
  2209. #ifndef WHISPER_USE_OPENVINO
  2210. (void)(ctx);
  2211. (void)(model_path);
  2212. (void)(device);
  2213. (void)(cache_dir);
  2214. return 1;
  2215. #else
  2216. if (!model_path && ctx->path_model.empty()) {
  2217. log("%s: model_path is nullptr, and ctx has no model_path set.\n", __func__);
  2218. return 1;
  2219. }
  2220. std::string path_encoder;
  2221. if (!model_path) {
  2222. //if model_path is not set, attempt to find it in the same directory as ggml-<model>.bin model
  2223. path_encoder = whisper_openvino_get_path_encoder(ctx->path_model);
  2224. } else {
  2225. path_encoder = model_path;
  2226. }
  2227. std::string path_cache;
  2228. if (!cache_dir) {
  2229. //if cache_dir is not set, set it as a dir residing next to ggml-<model>.bin
  2230. path_cache = whisper_openvino_get_path_cache(ctx->path_model);
  2231. } else {
  2232. path_cache = cache_dir;
  2233. }
  2234. log("%s: loading OpenVINO model from '%s'\n", __func__, path_encoder.c_str());
  2235. log("%s: first run on a device may take a while ...\n", __func__);
  2236. ctx->state->ctx_openvino = whisper_openvino_init(path_encoder.c_str(), device, path_cache.c_str());
  2237. if (!ctx->state->ctx_openvino) {
  2238. log("%s: failed to init OpenVINO encoder from '%s'\n", __func__, path_encoder.c_str());
  2239. return 1;
  2240. } else {
  2241. log("%s: OpenVINO model loaded\n", __func__);
  2242. }
  2243. return 0;
  2244. #endif
  2245. }
  2246. struct whisper_context * whisper_init_from_file_no_state(const char * path_model) {
  2247. log("%s: loading model from '%s'\n", __func__, path_model);
  2248. auto fin = std::ifstream(path_model, std::ios::binary);
  2249. if (!fin) {
  2250. log("%s: failed to open '%s'\n", __func__, path_model);
  2251. return nullptr;
  2252. }
  2253. whisper_model_loader loader = {};
  2254. loader.context = &fin;
  2255. loader.read = [](void * ctx, void * output, size_t read_size) {
  2256. std::ifstream * fin = (std::ifstream*)ctx;
  2257. fin->read((char *)output, read_size);
  2258. return read_size;
  2259. };
  2260. loader.eof = [](void * ctx) {
  2261. std::ifstream * fin = (std::ifstream*)ctx;
  2262. return fin->eof();
  2263. };
  2264. loader.close = [](void * ctx) {
  2265. std::ifstream * fin = (std::ifstream*)ctx;
  2266. fin->close();
  2267. };
  2268. auto ctx = whisper_init_no_state(&loader);
  2269. if (ctx) {
  2270. ctx->path_model = path_model;
  2271. }
  2272. return ctx;
  2273. }
  2274. struct whisper_context * whisper_init_from_buffer_no_state(void * buffer, size_t buffer_size) {
  2275. struct buf_context {
  2276. uint8_t* buffer;
  2277. size_t size;
  2278. size_t current_offset;
  2279. };
  2280. buf_context ctx = { reinterpret_cast<uint8_t*>(buffer), buffer_size, 0 };
  2281. log("%s: loading model from buffer\n", __func__);
  2282. whisper_model_loader loader = {};
  2283. loader.context = &ctx;
  2284. loader.read = [](void * ctx, void * output, size_t read_size) {
  2285. buf_context * buf = reinterpret_cast<buf_context *>(ctx);
  2286. size_t size_to_copy = buf->current_offset + read_size < buf->size ? read_size : buf->size - buf->current_offset;
  2287. memcpy(output, buf->buffer + buf->current_offset, size_to_copy);
  2288. buf->current_offset += size_to_copy;
  2289. return size_to_copy;
  2290. };
  2291. loader.eof = [](void * ctx) {
  2292. buf_context * buf = reinterpret_cast<buf_context *>(ctx);
  2293. return buf->current_offset >= buf->size;
  2294. };
  2295. loader.close = [](void * /*ctx*/) { };
  2296. return whisper_init_no_state(&loader);
  2297. }
  2298. struct whisper_context * whisper_init_no_state(struct whisper_model_loader * loader) {
  2299. ggml_time_init();
  2300. whisper_context * ctx = new whisper_context;
  2301. if (!whisper_model_load(loader, *ctx)) {
  2302. loader->close(loader->context);
  2303. log("%s: failed to load model\n", __func__);
  2304. delete ctx;
  2305. return nullptr;
  2306. }
  2307. loader->close(loader->context);
  2308. return ctx;
  2309. }
  2310. struct whisper_context * whisper_init_from_file(const char * path_model) {
  2311. whisper_context * ctx = whisper_init_from_file_no_state(path_model);
  2312. if (!ctx) {
  2313. return nullptr;
  2314. }
  2315. ctx->state = whisper_init_state(ctx);
  2316. if (!ctx->state) {
  2317. whisper_free(ctx);
  2318. return nullptr;
  2319. }
  2320. return ctx;
  2321. }
  2322. struct whisper_context * whisper_init_from_buffer(void * buffer, size_t buffer_size) {
  2323. whisper_context * ctx = whisper_init_from_buffer_no_state(buffer, buffer_size);
  2324. if (!ctx) {
  2325. return nullptr;
  2326. }
  2327. ctx->state = whisper_init_state(ctx);
  2328. if (!ctx->state) {
  2329. whisper_free(ctx);
  2330. return nullptr;
  2331. }
  2332. return ctx;
  2333. }
  2334. struct whisper_context * whisper_init(struct whisper_model_loader * loader) {
  2335. whisper_context * ctx = whisper_init_no_state(loader);
  2336. if (!ctx) {
  2337. return nullptr;
  2338. }
  2339. ctx->state = whisper_init_state(ctx);
  2340. if (!ctx->state) {
  2341. whisper_free(ctx);
  2342. return nullptr;
  2343. }
  2344. return ctx;
  2345. }
  2346. void whisper_free_state(struct whisper_state * state)
  2347. {
  2348. if (state) {
  2349. kv_cache_free(state->kv_cross);
  2350. for (int i = 0; i < WHISPER_MAX_DECODERS; ++i) {
  2351. kv_cache_free(state->decoders[i].kv_self);
  2352. }
  2353. #ifdef WHISPER_USE_COREML
  2354. if (state->ctx_coreml != nullptr) {
  2355. whisper_coreml_free(state->ctx_coreml);
  2356. state->ctx_coreml = nullptr;
  2357. }
  2358. #endif
  2359. #ifdef WHISPER_USE_OPENVINO
  2360. if (state->ctx_openvino != nullptr) {
  2361. whisper_openvino_free(state->ctx_openvino);
  2362. state->ctx_openvino = nullptr;
  2363. }
  2364. #endif
  2365. delete state;
  2366. }
  2367. }
  2368. void whisper_free(struct whisper_context * ctx) {
  2369. if (ctx) {
  2370. if (ctx->model.ctx) {
  2371. ggml_free(ctx->model.ctx);
  2372. }
  2373. if (ctx->model.buf) {
  2374. delete ctx->model.buf;
  2375. }
  2376. whisper_free_state(ctx->state);
  2377. delete ctx;
  2378. }
  2379. }
  2380. void whisper_free_params(struct whisper_full_params * params) {
  2381. if (params) {
  2382. delete params;
  2383. }
  2384. }
  2385. int whisper_pcm_to_mel_with_state(struct whisper_context * ctx, struct whisper_state * state, const float * samples, int n_samples, int n_threads) {
  2386. if (!log_mel_spectrogram(*state, samples, n_samples, WHISPER_SAMPLE_RATE, WHISPER_N_FFT, WHISPER_HOP_LENGTH, WHISPER_N_MEL, n_threads, ctx->model.filters, false, state->mel)) {
  2387. log("%s: failed to compute mel spectrogram\n", __func__);
  2388. return -1;
  2389. }
  2390. return 0;
  2391. }
  2392. int whisper_pcm_to_mel(struct whisper_context * ctx, const float * samples, int n_samples, int n_threads) {
  2393. return whisper_pcm_to_mel_with_state(ctx, ctx->state, samples, n_samples, n_threads);
  2394. }
  2395. // same as whisper_pcm_to_mel, but applies a Phase Vocoder to speed up the audio x2 (PV without phase lock is not good)
  2396. int whisper_pcm_to_mel_phase_vocoder_with_state(struct whisper_context * ctx, struct whisper_state * state, const float * samples, int n_samples, int n_threads) {
  2397. if (!log_mel_spectrogram(*state, samples, n_samples, WHISPER_SAMPLE_RATE, 2 * WHISPER_N_FFT, 2 * WHISPER_HOP_LENGTH, WHISPER_N_MEL, n_threads, ctx->model.filters, false, state->mel)) {
  2398. log("%s: failed to compute mel spectrogram\n", __func__);
  2399. return -1;
  2400. }
  2401. return 0;
  2402. }
  2403. // same as whisper_pcm_to_mel, but applies a Phase Vocoder to speed up the audio x2 (PV without phase lock is not good)
  2404. int whisper_pcm_to_mel_phase_vocoder(struct whisper_context * ctx, const float * samples, int n_samples, int n_threads) {
  2405. return whisper_pcm_to_mel_phase_vocoder_with_state(ctx, ctx->state, samples, n_samples, n_threads);
  2406. }
  2407. // same as whisper_pcm_to_mel, but applies WSOLA to speed up the audio x2
  2408. // TODO
  2409. // same as whisper_pcm_to_mel, but applies HPTSM to speed up the audio x2
  2410. // TODO
  2411. // same as whisper_pcm_to_mel, but applies PV (with phase lock) to speed up the audio x2
  2412. // TODO
  2413. int whisper_set_mel_with_state(
  2414. struct whisper_context * /*ctx*/,
  2415. struct whisper_state * state,
  2416. const float * data,
  2417. int n_len,
  2418. int n_mel) {
  2419. if (n_mel != WHISPER_N_MEL) {
  2420. log("%s: invalid number of mel bands: %d (expected %d)\n", __func__, n_mel, WHISPER_N_MEL);
  2421. return -1;
  2422. }
  2423. state->mel.n_len = n_len;
  2424. state->mel.n_len_org = n_len;
  2425. state->mel.n_mel = n_mel;
  2426. state->mel.data.resize(n_len*n_mel);
  2427. memcpy(state->mel.data.data(), data, n_len*n_mel*sizeof(float));
  2428. return 0;
  2429. }
  2430. int whisper_set_mel(
  2431. struct whisper_context * ctx,
  2432. const float * data,
  2433. int n_len,
  2434. int n_mel) {
  2435. return whisper_set_mel_with_state(ctx, ctx->state, data, n_len, n_mel);
  2436. }
  2437. int whisper_encode_with_state(struct whisper_context * ctx, struct whisper_state * state, int offset, int n_threads) {
  2438. if (!whisper_encode_internal(*ctx, *state, offset, n_threads)) {
  2439. log("%s: failed to eval\n", __func__);
  2440. return -1;
  2441. }
  2442. return 0;
  2443. }
  2444. int whisper_encode(struct whisper_context * ctx, int offset, int n_threads) {
  2445. if (!whisper_encode_internal(*ctx, *ctx->state, offset, n_threads)) {
  2446. log("%s: failed to eval\n", __func__);
  2447. return -1;
  2448. }
  2449. return 0;
  2450. }
  2451. int whisper_decode_with_state(struct whisper_context * ctx, struct whisper_state * state, const whisper_token * tokens, int n_tokens, int n_past, int n_threads) {
  2452. const int selected_decoder_id = 0;
  2453. if (!whisper_decode_internal(*ctx, *state, state->decoders[selected_decoder_id], tokens, n_tokens, n_past, n_threads)) {
  2454. log("%s: failed to eval\n", __func__);
  2455. return 1;
  2456. }
  2457. return 0;
  2458. }
  2459. int whisper_decode(struct whisper_context * ctx, const whisper_token * tokens, int n_tokens, int n_past, int n_threads) {
  2460. // TODO: add selected_decoder_id to state
  2461. const int selected_decoder_id = 0;
  2462. if (ctx->state == nullptr) {
  2463. log("%s: ERROR state was not loaded.\n", __func__);
  2464. return false;
  2465. }
  2466. if (!whisper_decode_internal(*ctx, *ctx->state, ctx->state->decoders[selected_decoder_id], tokens, n_tokens, n_past, n_threads)) {
  2467. log("%s: failed to eval\n", __func__);
  2468. return 1;
  2469. }
  2470. return 0;
  2471. }
  2472. int whisper_tokenize(struct whisper_context * ctx, const char * text, whisper_token * tokens, int n_max_tokens) {
  2473. const auto res = tokenize(ctx->vocab, text);
  2474. if (n_max_tokens < (int) res.size()) {
  2475. log("%s: too many resulting tokens: %d (max %d)\n", __func__, (int) res.size(), n_max_tokens);
  2476. return -1;
  2477. }
  2478. for (int i = 0; i < (int) res.size(); i++) {
  2479. tokens[i] = res[i];
  2480. }
  2481. return res.size();
  2482. }
  2483. int whisper_lang_max_id() {
  2484. auto max_id = 0;
  2485. for (const auto & kv : g_lang) {
  2486. max_id = std::max(max_id, kv.second.first);
  2487. }
  2488. return max_id;
  2489. }
  2490. int whisper_lang_id(const char * lang) {
  2491. if (!g_lang.count(lang)) {
  2492. for (const auto & kv : g_lang) {
  2493. if (kv.second.second == lang) {
  2494. return kv.second.first;
  2495. }
  2496. }
  2497. log("%s: unknown language '%s'\n", __func__, lang);
  2498. return -1;
  2499. }
  2500. return g_lang.at(lang).first;
  2501. }
  2502. const char * whisper_lang_str(int id) {
  2503. for (const auto & kv : g_lang) {
  2504. if (kv.second.first == id) {
  2505. return kv.first.c_str();
  2506. }
  2507. }
  2508. log("%s: unknown language id %d\n", __func__, id);
  2509. return nullptr;
  2510. }
  2511. int whisper_lang_auto_detect_with_state(
  2512. struct whisper_context * ctx,
  2513. struct whisper_state * state,
  2514. int offset_ms,
  2515. int n_threads,
  2516. float * lang_probs) {
  2517. const int seek = offset_ms/10;
  2518. if (seek < 0) {
  2519. log("%s: offset %dms is before the start of the audio\n", __func__, offset_ms);
  2520. return -1;
  2521. }
  2522. if (seek >= state->mel.n_len_org) {
  2523. log("%s: offset %dms is past the end of the audio (%dms)\n", __func__, offset_ms, state->mel.n_len_org*10);
  2524. return -2;
  2525. }
  2526. // run the encoder
  2527. if (whisper_encode_with_state(ctx, state, seek, n_threads) != 0) {
  2528. log("%s: failed to encode\n", __func__);
  2529. return -6;
  2530. }
  2531. const std::vector<whisper_token> prompt = { whisper_token_sot(ctx) };
  2532. if (whisper_decode_with_state(ctx, state, prompt.data(), prompt.size(), 0, n_threads) != 0) {
  2533. log("%s: failed to decode\n", __func__);
  2534. return -7;
  2535. }
  2536. auto & logits_id = state->logits_id;
  2537. logits_id.clear();
  2538. for (const auto & kv : g_lang) {
  2539. const auto token_lang = whisper_token_lang(ctx, kv.second.first);
  2540. logits_id.emplace_back(state->logits[token_lang], kv.second.first);
  2541. }
  2542. // sort descending
  2543. {
  2544. using pair_type = std::remove_reference<decltype(logits_id)>::type::value_type;
  2545. std::sort(logits_id.begin(), logits_id.end(), [](const pair_type & a, const pair_type & b) {
  2546. return a.first > b.first;
  2547. });
  2548. }
  2549. // softmax
  2550. {
  2551. const auto max = logits_id[0].first;
  2552. double sum = 0.0f;
  2553. for (auto & kv : logits_id) {
  2554. kv.first = exp(kv.first - max);
  2555. sum += kv.first;
  2556. }
  2557. for (auto & kv : logits_id) {
  2558. kv.first /= sum;
  2559. }
  2560. }
  2561. {
  2562. for (const auto & prob : logits_id) {
  2563. if (lang_probs) {
  2564. lang_probs[prob.second] = prob.first;
  2565. }
  2566. //printf("%s: lang %2d (%3s): %f\n", __func__, prob.second, whisper_lang_str(prob.second), prob.first);
  2567. }
  2568. }
  2569. return logits_id[0].second;
  2570. }
  2571. int whisper_lang_auto_detect(
  2572. struct whisper_context * ctx,
  2573. int offset_ms,
  2574. int n_threads,
  2575. float * lang_probs) {
  2576. return whisper_lang_auto_detect_with_state(ctx, ctx->state, offset_ms, n_threads, lang_probs);
  2577. }
  2578. int whisper_model_n_vocab(struct whisper_context * ctx) {
  2579. return ctx->model.hparams.n_vocab;
  2580. }
  2581. int whisper_model_n_audio_ctx(struct whisper_context * ctx) {
  2582. return ctx->model.hparams.n_audio_ctx;
  2583. }
  2584. int whisper_model_n_audio_state(struct whisper_context * ctx) {
  2585. return ctx->model.hparams.n_audio_state;
  2586. }
  2587. int whisper_model_n_audio_head(struct whisper_context * ctx) {
  2588. return ctx->model.hparams.n_audio_head;
  2589. }
  2590. int whisper_model_n_audio_layer(struct whisper_context * ctx) {
  2591. return ctx->model.hparams.n_audio_layer;
  2592. }
  2593. int whisper_model_n_text_ctx(struct whisper_context * ctx) {
  2594. return ctx->model.hparams.n_text_ctx;
  2595. }
  2596. int whisper_model_n_text_state(struct whisper_context * ctx) {
  2597. return ctx->model.hparams.n_text_state;
  2598. }
  2599. int whisper_model_n_text_head(struct whisper_context * ctx) {
  2600. return ctx->model.hparams.n_text_head;
  2601. }
  2602. int whisper_model_n_text_layer(struct whisper_context * ctx) {
  2603. return ctx->model.hparams.n_text_layer;
  2604. }
  2605. int whisper_model_n_mels(struct whisper_context * ctx) {
  2606. return ctx->model.hparams.n_mels;
  2607. }
  2608. int whisper_model_ftype(struct whisper_context * ctx) {
  2609. return ctx->model.hparams.ftype;
  2610. }
  2611. int whisper_model_type(struct whisper_context * ctx) {
  2612. return ctx->model.type;
  2613. }
  2614. const char *whisper_model_type_readable(struct whisper_context * ctx) {
  2615. switch (ctx->model.type) {
  2616. case e_model::MODEL_TINY:
  2617. return "tiny";
  2618. case e_model::MODEL_BASE:
  2619. return "base";
  2620. case e_model::MODEL_SMALL:
  2621. return "small";
  2622. case e_model::MODEL_MEDIUM:
  2623. return "medium";
  2624. case e_model::MODEL_LARGE:
  2625. return "large";
  2626. default:
  2627. return "unknown";
  2628. }
  2629. }
  2630. int whisper_n_len_from_state(struct whisper_state * state) {
  2631. return state->mel.n_len_org;
  2632. }
  2633. int whisper_n_len(struct whisper_context * ctx) {
  2634. return ctx->state->mel.n_len_org;
  2635. }
  2636. int whisper_n_vocab(struct whisper_context * ctx) {
  2637. return ctx->vocab.n_vocab;
  2638. }
  2639. int whisper_n_text_ctx(struct whisper_context * ctx) {
  2640. return ctx->model.hparams.n_text_ctx;
  2641. }
  2642. int whisper_n_audio_ctx(struct whisper_context * ctx) {
  2643. return ctx->model.hparams.n_audio_ctx;
  2644. }
  2645. int whisper_is_multilingual(struct whisper_context * ctx) {
  2646. return ctx->vocab.is_multilingual() ? 1 : 0;
  2647. }
  2648. float * whisper_get_logits(struct whisper_context * ctx) {
  2649. return ctx->state->logits.data();
  2650. }
  2651. float * whisper_get_logits_from_state(struct whisper_state * state) {
  2652. return state->logits.data();
  2653. }
  2654. const char * whisper_token_to_str(struct whisper_context * ctx, whisper_token token) {
  2655. return ctx->vocab.id_to_token.at(token).c_str();
  2656. }
  2657. whisper_token whisper_token_eot(struct whisper_context * ctx) {
  2658. return ctx->vocab.token_eot;
  2659. }
  2660. whisper_token whisper_token_sot(struct whisper_context * ctx) {
  2661. return ctx->vocab.token_sot;
  2662. }
  2663. whisper_token whisper_token_solm(struct whisper_context * ctx) {
  2664. return ctx->vocab.token_solm;
  2665. }
  2666. whisper_token whisper_token_prev(struct whisper_context * ctx) {
  2667. return ctx->vocab.token_prev;
  2668. }
  2669. whisper_token whisper_token_nosp(struct whisper_context * ctx) {
  2670. return ctx->vocab.token_nosp;
  2671. }
  2672. whisper_token whisper_token_not(struct whisper_context * ctx) {
  2673. return ctx->vocab.token_not;
  2674. }
  2675. whisper_token whisper_token_beg(struct whisper_context * ctx) {
  2676. return ctx->vocab.token_beg;
  2677. }
  2678. whisper_token whisper_token_lang(struct whisper_context * ctx, int lang_id) {
  2679. return whisper_token_sot(ctx) + 1 + lang_id;
  2680. }
  2681. whisper_token whisper_token_translate(struct whisper_context * ctx) {
  2682. return ctx->vocab.token_translate;
  2683. }
  2684. whisper_token whisper_token_transcribe(struct whisper_context * ctx) {
  2685. return ctx->vocab.token_transcribe;
  2686. }
  2687. void whisper_print_timings(struct whisper_context * ctx) {
  2688. const int64_t t_end_us = ggml_time_us();
  2689. log("\n");
  2690. log("%s: load time = %8.2f ms\n", __func__, ctx->t_load_us / 1000.0f);
  2691. if (ctx->state != nullptr) {
  2692. const int32_t n_sample = std::max(1, ctx->state->n_sample);
  2693. const int32_t n_encode = std::max(1, ctx->state->n_encode);
  2694. const int32_t n_decode = std::max(1, ctx->state->n_decode);
  2695. log("%s: fallbacks = %3d p / %3d h\n", __func__, ctx->state->n_fail_p, ctx->state->n_fail_h);
  2696. log("%s: mel time = %8.2f ms\n", __func__, ctx->state->t_mel_us / 1000.0f);
  2697. log("%s: sample time = %8.2f ms / %5d runs (%8.2f ms per run)\n", __func__, 1e-3f * ctx->state->t_sample_us, n_sample, 1e-3f * ctx->state->t_sample_us / n_sample);
  2698. log("%s: encode time = %8.2f ms / %5d runs (%8.2f ms per run)\n", __func__, 1e-3f * ctx->state->t_encode_us, n_encode, 1e-3f * ctx->state->t_encode_us / n_encode);
  2699. log("%s: decode time = %8.2f ms / %5d runs (%8.2f ms per run)\n", __func__, 1e-3f * ctx->state->t_decode_us, n_decode, 1e-3f * ctx->state->t_decode_us / n_decode);
  2700. }
  2701. log("%s: total time = %8.2f ms\n", __func__, (t_end_us - ctx->t_start_us)/1000.0f);
  2702. }
  2703. void whisper_reset_timings(struct whisper_context * ctx) {
  2704. if (ctx->state != nullptr) {
  2705. ctx->state->t_sample_us = 0;
  2706. ctx->state->t_encode_us = 0;
  2707. ctx->state->t_decode_us = 0;
  2708. }
  2709. }
  2710. static int whisper_has_coreml(void) {
  2711. #ifdef WHISPER_USE_COREML
  2712. return 1;
  2713. #else
  2714. return 0;
  2715. #endif
  2716. }
  2717. static int whisper_has_openvino(void) {
  2718. #ifdef WHISPER_USE_OPENVINO
  2719. return 1;
  2720. #else
  2721. return 0;
  2722. #endif
  2723. }
  2724. const char * whisper_print_system_info(void) {
  2725. static std::string s;
  2726. s = "";
  2727. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  2728. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  2729. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  2730. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  2731. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  2732. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  2733. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  2734. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  2735. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  2736. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  2737. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  2738. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  2739. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  2740. s += "COREML = " + std::to_string(whisper_has_coreml()) + " | ";
  2741. s += "OPENVINO = " + std::to_string(whisper_has_openvino()) + " | ";
  2742. return s.c_str();
  2743. }
  2744. ////////////////////////////////////////////////////////////////////////////
  2745. struct whisper_full_params * whisper_full_default_params_by_ref(enum whisper_sampling_strategy strategy) {
  2746. struct whisper_full_params params = whisper_full_default_params(strategy);
  2747. struct whisper_full_params* result = new whisper_full_params();
  2748. *result = params;
  2749. return result;
  2750. }
  2751. struct whisper_full_params whisper_full_default_params(enum whisper_sampling_strategy strategy) {
  2752. struct whisper_full_params result = {
  2753. /*.strategy =*/ strategy,
  2754. /*.n_threads =*/ std::min(4, (int32_t) std::thread::hardware_concurrency()),
  2755. /*.n_max_text_ctx =*/ 16384,
  2756. /*.offset_ms =*/ 0,
  2757. /*.duration_ms =*/ 0,
  2758. /*.translate =*/ false,
  2759. /*.no_context =*/ true,
  2760. /*.single_segment =*/ false,
  2761. /*.print_special =*/ false,
  2762. /*.print_progress =*/ true,
  2763. /*.print_realtime =*/ false,
  2764. /*.print_timestamps =*/ true,
  2765. /*.token_timestamps =*/ false,
  2766. /*.thold_pt =*/ 0.01f,
  2767. /*.thold_ptsum =*/ 0.01f,
  2768. /*.max_len =*/ 0,
  2769. /*.split_on_word =*/ false,
  2770. /*.max_tokens =*/ 0,
  2771. /*.speed_up =*/ false,
  2772. /*.debug_mode =*/ false,
  2773. /*.audio_ctx =*/ 0,
  2774. /*.tdrz_enable =*/ false,
  2775. /*.initial_prompt =*/ nullptr,
  2776. /*.prompt_tokens =*/ nullptr,
  2777. /*.prompt_n_tokens =*/ 0,
  2778. /*.language =*/ "en",
  2779. /*.detect_language =*/ false,
  2780. /*.suppress_blank =*/ true,
  2781. /*.suppress_non_speech_tokens =*/ false,
  2782. /*.temperature =*/ 0.0f,
  2783. /*.max_initial_ts =*/ 1.0f,
  2784. /*.length_penalty =*/ -1.0f,
  2785. /*.temperature_inc =*/ 0.4f,
  2786. /*.entropy_thold =*/ 2.4f,
  2787. /*.logprob_thold =*/ -1.0f,
  2788. /*.no_speech_thold =*/ 0.6f,
  2789. /*.greedy =*/ {
  2790. /*.best_of =*/ -1,
  2791. },
  2792. /*.beam_search =*/ {
  2793. /*.beam_size =*/ -1,
  2794. /*.patience =*/ -1.0f,
  2795. },
  2796. /*.new_segment_callback =*/ nullptr,
  2797. /*.new_segment_callback_user_data =*/ nullptr,
  2798. /*.progress_callback =*/ nullptr,
  2799. /*.progress_callback_user_data =*/ nullptr,
  2800. /*.encoder_begin_callback =*/ nullptr,
  2801. /*.encoder_begin_callback_user_data =*/ nullptr,
  2802. /*.logits_filter_callback =*/ nullptr,
  2803. /*.logits_filter_callback_user_data =*/ nullptr,
  2804. };
  2805. switch (strategy) {
  2806. case WHISPER_SAMPLING_GREEDY:
  2807. {
  2808. result.greedy = {
  2809. /*.best_of =*/ 2, // TODO: increase to 5 when we speed-up batch decoding
  2810. };
  2811. } break;
  2812. case WHISPER_SAMPLING_BEAM_SEARCH:
  2813. {
  2814. result.beam_search = {
  2815. /*.beam_size =*/ 2, // TODO: increase to 5 when we speed-up batch decoding
  2816. /*.patience =*/ -1.0f,
  2817. };
  2818. } break;
  2819. }
  2820. return result;
  2821. }
  2822. // forward declarations
  2823. static std::vector<float> get_signal_energy(const float * signal, int n_samples, int n_samples_per_half_window);
  2824. static void whisper_exp_compute_token_level_timestamps(
  2825. struct whisper_context & ctx,
  2826. struct whisper_state & state,
  2827. int i_segment,
  2828. float thold_pt,
  2829. float thold_ptsum);
  2830. static inline bool should_split_on_word(const char * txt, bool split_on_word) {
  2831. if (!split_on_word) return true;
  2832. return txt[0] == ' ';
  2833. }
  2834. // wrap the last segment to max_len characters
  2835. // returns the number of new segments
  2836. static int whisper_wrap_segment(struct whisper_context & ctx, struct whisper_state & state, int max_len, bool split_on_word) {
  2837. auto segment = state.result_all.back();
  2838. int res = 1;
  2839. int acc = 0;
  2840. std::string text;
  2841. for (int i = 0; i < (int) segment.tokens.size(); i++) {
  2842. const auto & token = segment.tokens[i];
  2843. if (token.id >= whisper_token_eot(&ctx)) {
  2844. continue;
  2845. }
  2846. const auto txt = whisper_token_to_str(&ctx, token.id);
  2847. const int cur = strlen(txt);
  2848. if (acc + cur > max_len && i > 0 && should_split_on_word(txt, split_on_word)) {
  2849. state.result_all.back().text = std::move(text);
  2850. state.result_all.back().t1 = token.t0;
  2851. state.result_all.back().tokens.resize(i);
  2852. state.result_all.back().speaker_turn_next = false;
  2853. state.result_all.push_back({});
  2854. state.result_all.back().t0 = token.t0;
  2855. state.result_all.back().t1 = segment.t1;
  2856. // add tokens [i, end] to the new segment
  2857. state.result_all.back().tokens.insert(
  2858. state.result_all.back().tokens.end(),
  2859. segment.tokens.begin() + i,
  2860. segment.tokens.end());
  2861. state.result_all.back().speaker_turn_next = segment.speaker_turn_next;
  2862. acc = 0;
  2863. text = "";
  2864. segment = state.result_all.back();
  2865. i = -1;
  2866. res++;
  2867. } else {
  2868. acc += cur;
  2869. text += txt;
  2870. }
  2871. }
  2872. state.result_all.back().text = std::move(text);
  2873. return res;
  2874. }
  2875. static const std::vector<std::string> non_speech_tokens = {
  2876. "\"", "#", "(", ")", "*", "+", "/", ":", ";", "<", "=", ">", "@", "[", "\\", "]", "^",
  2877. "_", "`", "{", "|", "}", "~", "「", "」", "『", "』", "<<", ">>", "<<<", ">>>", "--",
  2878. "---", "-(", "-[", "('", "(\"", "((", "))", "(((", ")))", "[[", "]]", "{{", "}}", "♪♪",
  2879. "♪♪♪","♩", "♪", "♫", "♬", "♭", "♮", "♯"
  2880. };
  2881. // process the logits for the selected decoder
  2882. // - applies logit filters
  2883. // - computes logprobs and probs
  2884. static void whisper_process_logits(
  2885. struct whisper_context & ctx,
  2886. struct whisper_state & state,
  2887. const struct whisper_full_params params,
  2888. struct whisper_decoder & decoder,
  2889. float temperature) {
  2890. const auto & vocab = ctx.vocab;
  2891. const auto & tokens_cur = decoder.sequence.tokens;
  2892. const bool is_initial = tokens_cur.size() == 0;
  2893. const int n_logits = vocab.id_to_token.size();
  2894. WHISPER_ASSERT(n_logits == ctx.vocab.n_vocab);
  2895. // extract the logits for the last token
  2896. // we will be mutating, and therefore we don't want to use the ctx.logits buffer directly
  2897. auto & probs = decoder.probs;
  2898. auto & logits = decoder.logits;
  2899. auto & logprobs = decoder.logprobs;
  2900. {
  2901. logits.resize(n_logits);
  2902. memcpy(logits.data(), state.logits.data() + (state.logits.size() - n_logits), n_logits*sizeof(float));
  2903. if (temperature > 0.0f) {
  2904. for (int i = 0; i < n_logits; i++) {
  2905. logits[i] /= temperature;
  2906. }
  2907. }
  2908. // will be populated a bit later
  2909. probs.resize(n_logits);
  2910. logprobs.resize(n_logits);
  2911. }
  2912. // apply logit filters here
  2913. // ref: https://github.com/openai/whisper/blob/0b1ba3d46ebf7fe6f953acfd8cad62a4f851b49f/whisper/decoding.py#L480-L493
  2914. {
  2915. // suppress blank
  2916. // https://github.com/openai/whisper/blob/0b1ba3d46ebf7fe6f953acfd8cad62a4f851b49f/whisper/decoding.py#L388-L390
  2917. if (params.suppress_blank) {
  2918. if (is_initial) {
  2919. logits[vocab.token_eot] = -INFINITY;
  2920. logits[vocab.token_to_id.at(" ")] = -INFINITY;
  2921. }
  2922. }
  2923. // suppress <|notimestamps|> token
  2924. // ref: https://github.com/openai/whisper/blob/0b1ba3d46ebf7fe6f953acfd8cad62a4f851b49f/whisper/decoding.py#L410-L412
  2925. logits[vocab.token_not] = -INFINITY;
  2926. // suppress sot and nosp tokens
  2927. logits[vocab.token_sot] = -INFINITY;
  2928. logits[vocab.token_nosp] = -INFINITY; // TODO: ignore this token for now
  2929. // [TDRZ] when tinydiarize is disabled, suppress solm token
  2930. if (params.tdrz_enable == false) {
  2931. logits[vocab.token_solm] = -INFINITY;
  2932. }
  2933. // suppress task tokens
  2934. logits[vocab.token_translate] = -INFINITY;
  2935. logits[vocab.token_transcribe] = -INFINITY;
  2936. if (params.logits_filter_callback) {
  2937. params.logits_filter_callback(&ctx, &state, tokens_cur.data(), tokens_cur.size(), logits.data(), params.logits_filter_callback_user_data);
  2938. }
  2939. // suppress non-speech tokens
  2940. // ref: https://github.com/openai/whisper/blob/7858aa9c08d98f75575035ecd6481f462d66ca27/whisper/tokenizer.py#L224-L253
  2941. if (params.suppress_non_speech_tokens) {
  2942. for (const std::string & token : non_speech_tokens) {
  2943. const std::string suppress_tokens[] = {token, " " + token};
  2944. for (const std::string & suppress_token : suppress_tokens) {
  2945. if (vocab.token_to_id.find(suppress_token) != vocab.token_to_id.end()) {
  2946. logits[vocab.token_to_id.at(suppress_token)] = -INFINITY;
  2947. }
  2948. }
  2949. }
  2950. // allow hyphens "-" and single quotes "'" between words, but not at the beginning of a word
  2951. if (vocab.token_to_id.find(" -") != vocab.token_to_id.end()) {
  2952. logits[vocab.token_to_id.at(" -")] = -INFINITY;
  2953. }
  2954. if (vocab.token_to_id.find(" '") != vocab.token_to_id.end()) {
  2955. logits[vocab.token_to_id.at(" '")] = -INFINITY;
  2956. }
  2957. }
  2958. // timestamps have to appear in pairs, except directly before EOT; mask logits accordingly
  2959. // https://github.com/openai/whisper/blob/0b1ba3d46ebf7fe6f953acfd8cad62a4f851b49f/whisper/decoding.py#L414-L424
  2960. {
  2961. const bool last_was_timestamp = tokens_cur.size() > 0 && tokens_cur.back().id >= vocab.token_beg;
  2962. const bool penultimate_was_timestamp = tokens_cur.size() < 2 || tokens_cur[tokens_cur.size() - 2].id >= vocab.token_beg;
  2963. //log("last_was_timestamp=%d penultimate_was_timestamp=%d\n", last_was_timestamp, penultimate_was_timestamp);
  2964. if (last_was_timestamp) {
  2965. if (penultimate_was_timestamp) {
  2966. for (int i = vocab.token_beg; i < n_logits; ++i) {
  2967. logits[i] = -INFINITY;
  2968. }
  2969. } else {
  2970. for (int i = 0; i < vocab.token_eot; ++i) {
  2971. logits[i] = -INFINITY;
  2972. }
  2973. }
  2974. }
  2975. }
  2976. // the initial timestamp cannot be larger than max_initial_ts
  2977. // ref: https://github.com/openai/whisper/blob/0b1ba3d46ebf7fe6f953acfd8cad62a4f851b49f/whisper/decoding.py#L426-L429
  2978. if (is_initial && params.max_initial_ts > 0.0f) {
  2979. const float precision = float(WHISPER_CHUNK_SIZE)/ctx.model.hparams.n_audio_ctx;
  2980. const int tid0 = std::round(params.max_initial_ts/precision);
  2981. for (int i = vocab.token_beg + tid0 + 1; i < n_logits; ++i) {
  2982. logits[i] = -INFINITY;
  2983. }
  2984. }
  2985. // condition timestamp tokens to be increasing
  2986. // ref: https://github.com/openai/whisper/pull/831#issuecomment-1385910556
  2987. if (decoder.has_ts) {
  2988. const int tid0 = decoder.seek_delta/2;
  2989. for (int i = vocab.token_beg; i < vocab.token_beg + tid0; ++i) {
  2990. logits[i] = -INFINITY;
  2991. }
  2992. }
  2993. // populate the logprobs array (log_softmax)
  2994. {
  2995. const float logit_max = *std::max_element(logits.begin(), logits.end());
  2996. float logsumexp = 0.0f;
  2997. for (int i = 0; i < n_logits; ++i) {
  2998. if (logits[i] > -INFINITY) {
  2999. logsumexp += expf(logits[i] - logit_max);
  3000. }
  3001. }
  3002. logsumexp = logf(logsumexp) + logit_max;
  3003. for (int i = 0; i < n_logits; ++i) {
  3004. if (logits[i] > -INFINITY) {
  3005. logprobs[i] = logits[i] - logsumexp;
  3006. } else {
  3007. logprobs[i] = -INFINITY;
  3008. }
  3009. }
  3010. }
  3011. // if sum of probability over timestamps is above any other token, sample timestamp
  3012. // ref: https://github.com/openai/whisper/blob/0b1ba3d46ebf7fe6f953acfd8cad62a4f851b49f/whisper/decoding.py#L431-L437
  3013. {
  3014. // logsumexp over timestamps
  3015. float timestamp_logprob = -INFINITY;
  3016. {
  3017. float logsumexp = 0.0f;
  3018. const float logprob_max = *std::max_element(logprobs.begin() + vocab.token_beg, logprobs.end());
  3019. for (int i = vocab.token_beg; i < n_logits; ++i) {
  3020. if (logprobs[i] > -INFINITY) {
  3021. logsumexp += expf(logprobs[i] - logprob_max);
  3022. }
  3023. }
  3024. if (logsumexp > 0.0f) {
  3025. timestamp_logprob = logf(logsumexp) + logprob_max;
  3026. }
  3027. }
  3028. const float max_text_token_logprob = *std::max_element(logprobs.begin(), logprobs.begin() + vocab.token_beg);
  3029. //log("timestamp_logprob=%f max_text_token_logprob=%f\n", timestamp_logprob, max_text_token_logprob);
  3030. if (timestamp_logprob > max_text_token_logprob) {
  3031. for (int i = 0; i < vocab.token_beg; ++i) {
  3032. logits[i] = -INFINITY;
  3033. logprobs[i] = -INFINITY;
  3034. }
  3035. }
  3036. }
  3037. }
  3038. // compute probs
  3039. {
  3040. for (int i = 0; i < n_logits; ++i) {
  3041. if (logits[i] == -INFINITY) {
  3042. probs[i] = 0.0f;
  3043. } else {
  3044. probs[i] = expf(logprobs[i]);
  3045. }
  3046. }
  3047. }
  3048. #if 0
  3049. // print first 100 logits - token string : logit
  3050. for (int i = 0; i < 100; i++) {
  3051. const auto token = vocab.id_to_token.at(i);
  3052. const auto prob = probs[i];
  3053. const auto logit = logits[i];
  3054. const auto logprob = logprobs[i];
  3055. printf("%s : prob=%9.5f logit=%9.5f logprob=%9.5f\n", token.c_str(), prob, logit, logprob);
  3056. }
  3057. // "And", "and", " And", " and"
  3058. printf("logits[\"and\"] = %f\n", logits[vocab.token_to_id.at("and")]);
  3059. printf("logits[\"And\"] = %f\n", logits[vocab.token_to_id.at("And")]);
  3060. printf("logits[\" and\"] = %f\n", logits[vocab.token_to_id.at(" and")]);
  3061. printf("logits[\" And\"] = %f\n", logits[vocab.token_to_id.at(" And")]);
  3062. printf("logits[\" so\"] = %f\n", logits[vocab.token_to_id.at(" so")]);
  3063. printf("logprobs[\"and\"] = %f\n", logprobs[vocab.token_to_id.at("and")]);
  3064. printf("logprobs[\"And\"] = %f\n", logprobs[vocab.token_to_id.at("And")]);
  3065. printf("logprobs[\" and\"] = %f\n", logprobs[vocab.token_to_id.at(" and")]);
  3066. printf("logprobs[\" And\"] = %f\n", logprobs[vocab.token_to_id.at(" And")]);
  3067. printf("logprobs[\" so\"] = %f\n", logprobs[vocab.token_to_id.at(" so")]);
  3068. printf("probs[\"and\"] = %f\n", probs[vocab.token_to_id.at("and")]);
  3069. printf("probs[\"And\"] = %f\n", probs[vocab.token_to_id.at("And")]);
  3070. printf("probs[\" and\"] = %f\n", probs[vocab.token_to_id.at(" and")]);
  3071. printf("probs[\" And\"] = %f\n", probs[vocab.token_to_id.at(" And")]);
  3072. printf("probs[\" so\"] = %f\n", probs[vocab.token_to_id.at(" so")]);
  3073. #endif
  3074. }
  3075. static whisper_token_data whisper_sample_token(
  3076. whisper_context & ctx,
  3077. whisper_state & state,
  3078. const whisper_decoder & decoder,
  3079. bool best) {
  3080. whisper_token_data result = {
  3081. 0, 0, 0.0f, 0.0f, 0.0f, 0.0f, -1, -1, 0.0f,
  3082. };
  3083. const auto & vocab = ctx.vocab;
  3084. const auto & probs = decoder.probs;
  3085. const auto & logprobs = decoder.logprobs;
  3086. const int n_logits = vocab.n_vocab;
  3087. {
  3088. double sum_ts = 0.0;
  3089. double max_ts = 0.0;
  3090. for (int i = vocab.token_beg; i < n_logits; i++) {
  3091. if (probs[i] == -INFINITY) {
  3092. continue;
  3093. }
  3094. sum_ts += probs[i];
  3095. if (max_ts < probs[i]) {
  3096. max_ts = probs[i];
  3097. result.tid = i;
  3098. }
  3099. }
  3100. result.pt = max_ts/(sum_ts + 1e-10);
  3101. result.ptsum = sum_ts;
  3102. }
  3103. if (best) {
  3104. for (int i = 0; i < n_logits; ++i) {
  3105. if (result.p < probs[i]) {
  3106. result.id = i;
  3107. result.p = probs[i];
  3108. result.plog = logprobs[i];
  3109. }
  3110. }
  3111. } else {
  3112. std::discrete_distribution<> dist(probs.begin(), probs.end());
  3113. result.id = dist(state.rng);
  3114. result.p = probs[result.id];
  3115. result.plog = logprobs[result.id];
  3116. }
  3117. if (result.id >= vocab.token_beg) {
  3118. result.tid = result.id;
  3119. result.pt = result.p;
  3120. }
  3121. state.n_sample++;
  3122. return result;
  3123. }
  3124. static std::vector<whisper_token_data> whisper_sample_token_topk(
  3125. whisper_context & ctx,
  3126. whisper_state & state,
  3127. const whisper_decoder & decoder,
  3128. int k) {
  3129. const auto & vocab = ctx.vocab;
  3130. const auto & probs = decoder.probs;
  3131. const auto & logits = decoder.logits;
  3132. const auto & logprobs = decoder.logprobs;
  3133. const int n_logits = vocab.n_vocab;
  3134. auto & logits_id = state.logits_id;
  3135. logits_id.clear();
  3136. for (int i = 0; i < n_logits; ++i) {
  3137. logits_id.push_back({ logits[i], i });
  3138. }
  3139. std::partial_sort(
  3140. logits_id.begin(),
  3141. logits_id.begin() + k, logits_id.end(),
  3142. [](const std::pair<double, whisper_token> & a, const std::pair<double, whisper_token> & b) {
  3143. return a.first > b.first;
  3144. });
  3145. std::vector<whisper_token_data> result;
  3146. result.reserve(k);
  3147. whisper_token tid = vocab.token_beg;
  3148. float pt = 0.0;
  3149. float ptsum = 0.0;
  3150. {
  3151. double sum_ts = 0.0;
  3152. double max_ts = 0.0;
  3153. for (int i = vocab.token_beg; i < n_logits; i++) {
  3154. if (probs[i] == -INFINITY) {
  3155. continue;
  3156. }
  3157. sum_ts += probs[i];
  3158. if (max_ts < probs[i]) {
  3159. max_ts = probs[i];
  3160. tid = i;
  3161. }
  3162. }
  3163. pt = max_ts/(sum_ts + 1e-10);
  3164. ptsum = sum_ts;
  3165. }
  3166. for (int i = 0; i < k; ++i) {
  3167. const auto id = logits_id[i].second;
  3168. result.push_back({ id, tid, probs[id], logprobs[id], pt, ptsum, -1, -1, 0.0f, });
  3169. if (result[i].id >= vocab.token_beg) {
  3170. result[i].tid = result[i].id;
  3171. result[i].pt = result[i].p;
  3172. }
  3173. }
  3174. state.n_sample++;
  3175. return result;
  3176. }
  3177. // ref: https://github.com/openai/whisper/blob/0b1ba3d46ebf7fe6f953acfd8cad62a4f851b49f/whisper/decoding.py#L178-L192
  3178. static void whisper_sequence_score(
  3179. const struct whisper_full_params & params,
  3180. whisper_sequence & sequence) {
  3181. if (sequence.result_len == 0) {
  3182. return;
  3183. }
  3184. double result = 0.0f;
  3185. for (int i = 0; i < sequence.result_len; ++i) {
  3186. result += sequence.tokens[i].plog;
  3187. }
  3188. sequence.sum_logprobs = result;
  3189. sequence.avg_logprobs = result/sequence.result_len;
  3190. double penalty = sequence.result_len;
  3191. if (params.length_penalty > 0.0f) {
  3192. penalty = pow((5.0 + penalty)/6.0, params.length_penalty);
  3193. }
  3194. sequence.score = result/penalty;
  3195. // compute the entropy of the sequence of the last 32 tokens
  3196. {
  3197. const int n = 32;
  3198. int cnt = 0;
  3199. double entropy = 0.0f;
  3200. std::map<whisper_token, int> token_counts;
  3201. for (int i = std::max(0, sequence.result_len - n); i < sequence.result_len; ++i) {
  3202. token_counts[sequence.tokens[i].id]++;
  3203. cnt++;
  3204. }
  3205. for (const auto & kv : token_counts) {
  3206. const auto p = kv.second/(double)cnt;
  3207. entropy -= p*log(p);
  3208. //WHISPER_PRINT_DEBUG("entropy: %d %f %f, count %d\n", kv.first, p, log(p), kv.second);
  3209. }
  3210. sequence.entropy = entropy;
  3211. }
  3212. }
  3213. int whisper_full_with_state(
  3214. struct whisper_context * ctx,
  3215. struct whisper_state * state,
  3216. struct whisper_full_params params,
  3217. const float * samples,
  3218. int n_samples) {
  3219. // clear old results
  3220. auto & result_all = state->result_all;
  3221. result_all.clear();
  3222. if (n_samples > 0) {
  3223. // compute log mel spectrogram
  3224. if (params.speed_up) {
  3225. // TODO: Replace PV with more advanced algorithm
  3226. log("%s: failed to compute log mel spectrogram\n", __func__);
  3227. return -1;
  3228. } else {
  3229. if (whisper_pcm_to_mel_with_state(ctx, state, samples, n_samples, params.n_threads) != 0) {
  3230. log("%s: failed to compute log mel spectrogram\n", __func__);
  3231. return -2;
  3232. }
  3233. }
  3234. }
  3235. // auto-detect language if not specified
  3236. if (params.language == nullptr || strlen(params.language) == 0 || strcmp(params.language, "auto") == 0 || params.detect_language) {
  3237. std::vector<float> probs(whisper_lang_max_id() + 1, 0.0f);
  3238. const auto lang_id = whisper_lang_auto_detect_with_state(ctx, state, 0, params.n_threads, probs.data());
  3239. if (lang_id < 0) {
  3240. log("%s: failed to auto-detect language\n", __func__);
  3241. return -3;
  3242. }
  3243. state->lang_id = lang_id;
  3244. params.language = whisper_lang_str(lang_id);
  3245. log("%s: auto-detected language: %s (p = %f)\n", __func__, params.language, probs[whisper_lang_id(params.language)]);
  3246. if (params.detect_language) {
  3247. return 0;
  3248. }
  3249. }
  3250. if (params.token_timestamps) {
  3251. state->t_beg = 0;
  3252. state->t_last = 0;
  3253. state->tid_last = 0;
  3254. if (n_samples > 0) {
  3255. state->energy = get_signal_energy(samples, n_samples, 32);
  3256. }
  3257. }
  3258. const int seek_start = params.offset_ms/10;
  3259. const int seek_end = params.duration_ms == 0 ? whisper_n_len_from_state(state) : seek_start + params.duration_ms/10;
  3260. // if length of spectrogram is less than 1.0s (100 frames), then return
  3261. // basically don't process anything that is less than 1.0s
  3262. // see issue #39: https://github.com/ggerganov/whisper.cpp/issues/39
  3263. if (seek_end < seek_start + (params.speed_up ? 50 : 100)) {
  3264. return 0;
  3265. }
  3266. // a set of temperatures to use
  3267. // [ t0, t0 + delta, t0 + 2*delta, ..., < 1.0f + 1e-6f ]
  3268. std::vector<float> temperatures;
  3269. if (params.temperature_inc > 0.0f) {
  3270. for (float t = params.temperature; t < 1.0f + 1e-6f; t += params.temperature_inc) {
  3271. temperatures.push_back(t);
  3272. }
  3273. } else {
  3274. temperatures.push_back(params.temperature);
  3275. }
  3276. // initialize the decoders
  3277. int n_decoders = 1;
  3278. switch (params.strategy) {
  3279. case WHISPER_SAMPLING_GREEDY:
  3280. {
  3281. n_decoders = params.greedy.best_of;
  3282. } break;
  3283. case WHISPER_SAMPLING_BEAM_SEARCH:
  3284. {
  3285. n_decoders = std::max(params.greedy.best_of, params.beam_search.beam_size);
  3286. } break;
  3287. };
  3288. n_decoders = std::max(1, n_decoders);
  3289. // TAGS: WHISPER_DECODER_INIT
  3290. for (int j = 1; j < n_decoders; j++) {
  3291. auto & decoder = state->decoders[j];
  3292. if (decoder.kv_self.ctx == nullptr) {
  3293. decoder.kv_self = state->decoders[0].kv_self;
  3294. if (!kv_cache_reinit(decoder.kv_self)) {
  3295. log("%s: kv_cache_reinit() failed for self-attention, decoder %d\n", __func__, j);
  3296. return -4;
  3297. }
  3298. WHISPER_PRINT_DEBUG("%s: initialized self-attention kv cache, decoder %d\n", __func__, j);
  3299. decoder.sequence.tokens.reserve(state->decoders[0].sequence.tokens.capacity());
  3300. decoder.probs.resize (ctx->vocab.n_vocab);
  3301. decoder.logits.resize (ctx->vocab.n_vocab);
  3302. decoder.logprobs.resize(ctx->vocab.n_vocab);
  3303. }
  3304. }
  3305. // the accumulated text context so far
  3306. auto & prompt_past = state->prompt_past;
  3307. if (params.no_context) {
  3308. prompt_past.clear();
  3309. }
  3310. // prepare prompt
  3311. {
  3312. std::vector<whisper_token> prompt_tokens;
  3313. // initial prompt
  3314. if (!params.prompt_tokens && params.initial_prompt) {
  3315. prompt_tokens.resize(1024);
  3316. prompt_tokens.resize(whisper_tokenize(ctx, params.initial_prompt, prompt_tokens.data(), prompt_tokens.size()));
  3317. params.prompt_tokens = prompt_tokens.data();
  3318. params.prompt_n_tokens = prompt_tokens.size();
  3319. }
  3320. // prepend the prompt tokens to the prompt_past
  3321. if (params.prompt_tokens && params.prompt_n_tokens > 0) {
  3322. // parse tokens from the pointer
  3323. for (int i = 0; i < params.prompt_n_tokens; i++) {
  3324. prompt_past.push_back(params.prompt_tokens[i]);
  3325. }
  3326. std::rotate(prompt_past.begin(), prompt_past.end() - params.prompt_n_tokens, prompt_past.end());
  3327. }
  3328. }
  3329. // overwrite audio_ctx, max allowed is hparams.n_audio_ctx
  3330. if (params.audio_ctx > whisper_n_audio_ctx(ctx)) {
  3331. log("%s: audio_ctx is larger than the maximum allowed (%d > %d)\n", __func__, params.audio_ctx, whisper_n_audio_ctx(ctx));
  3332. return -5;
  3333. }
  3334. state->exp_n_audio_ctx = params.audio_ctx;
  3335. // these tokens determine the task that will be performed
  3336. std::vector<whisper_token> prompt_init = { whisper_token_sot(ctx) };
  3337. if (whisper_is_multilingual(ctx)) {
  3338. const int lang_id = whisper_lang_id(params.language);
  3339. state->lang_id = lang_id;
  3340. prompt_init.push_back(whisper_token_lang(ctx, lang_id));
  3341. if (params.translate) {
  3342. prompt_init.push_back(whisper_token_translate(ctx));
  3343. } else {
  3344. prompt_init.push_back(whisper_token_transcribe(ctx));
  3345. }
  3346. }
  3347. int seek = seek_start;
  3348. std::vector<whisper_token> prompt;
  3349. prompt.reserve(whisper_n_text_ctx(ctx));
  3350. // beam-search helpers
  3351. struct kv_buf {
  3352. std::vector<uint8_t> k;
  3353. std::vector<uint8_t> v;
  3354. };
  3355. std::vector<kv_buf> kv_bufs;
  3356. struct beam_candidate {
  3357. int decoder_idx;
  3358. int seek_delta;
  3359. bool has_ts;
  3360. whisper_sequence sequence;
  3361. };
  3362. std::vector<beam_candidate> beam_candidates;
  3363. // main loop
  3364. while (true) {
  3365. if (params.progress_callback) {
  3366. const int progress_cur = (100*(seek - seek_start))/(seek_end - seek_start);
  3367. params.progress_callback(
  3368. ctx, ctx->state, progress_cur, params.progress_callback_user_data);
  3369. }
  3370. // of only 1 second left, then stop
  3371. if (seek + 100 >= seek_end) {
  3372. break;
  3373. }
  3374. if (params.encoder_begin_callback) {
  3375. if (params.encoder_begin_callback(ctx, state, params.encoder_begin_callback_user_data) == false) {
  3376. log("%s: encoder_begin_callback returned false - aborting\n", __func__);
  3377. break;
  3378. }
  3379. }
  3380. // encode audio features starting at offset seek
  3381. if (!whisper_encode_internal(*ctx, *state, seek, params.n_threads)) {
  3382. log("%s: failed to encode\n", __func__);
  3383. return -6;
  3384. }
  3385. // if there is a very short audio segment left to process, we remove any past prompt since it tends
  3386. // to confuse the decoder and often make it repeat or hallucinate stuff
  3387. if (seek > seek_start && seek + 500 >= seek_end) {
  3388. prompt_past.clear();
  3389. }
  3390. int best_decoder_id = 0;
  3391. for (int it = 0; it < (int) temperatures.size(); ++it) {
  3392. const float t_cur = temperatures[it];
  3393. int n_decoders_cur = 1;
  3394. switch (params.strategy) {
  3395. case whisper_sampling_strategy::WHISPER_SAMPLING_GREEDY:
  3396. {
  3397. if (t_cur > 0.0f) {
  3398. n_decoders_cur = params.greedy.best_of;
  3399. }
  3400. } break;
  3401. case whisper_sampling_strategy::WHISPER_SAMPLING_BEAM_SEARCH:
  3402. {
  3403. if (t_cur > 0.0f) {
  3404. n_decoders_cur = params.greedy.best_of;
  3405. } else {
  3406. n_decoders_cur = params.beam_search.beam_size;
  3407. }
  3408. } break;
  3409. };
  3410. n_decoders_cur = std::max(1, n_decoders_cur);
  3411. WHISPER_PRINT_DEBUG("\n%s: decoding with %d decoders, temperature = %.2f\n", __func__, n_decoders_cur, t_cur);
  3412. // TAGS: WHISPER_DECODER_INIT
  3413. for (int j = 0; j < n_decoders_cur; ++j) {
  3414. auto & decoder = state->decoders[j];
  3415. decoder.kv_self.n = 0;
  3416. decoder.sequence.tokens.clear();
  3417. decoder.sequence.result_len = 0;
  3418. decoder.sequence.sum_logprobs_all = 0.0;
  3419. decoder.sequence.sum_logprobs = -INFINITY;
  3420. decoder.sequence.avg_logprobs = -INFINITY;
  3421. decoder.sequence.entropy = 0.0;
  3422. decoder.sequence.score = -INFINITY;
  3423. decoder.seek_delta = 100*WHISPER_CHUNK_SIZE;
  3424. decoder.failed = false;
  3425. decoder.completed = false;
  3426. decoder.has_ts = false;
  3427. }
  3428. // init prompt and kv cache for the current iteration
  3429. // run whisper_decoder() only for decoder 0 and copy the results for the other decoders
  3430. {
  3431. prompt.clear();
  3432. // if we have already generated some text, use it as a prompt to condition the next generation
  3433. if (!prompt_past.empty() && t_cur < 0.5f && params.n_max_text_ctx > 0) {
  3434. int n_take = std::min(std::min(params.n_max_text_ctx, whisper_n_text_ctx(ctx)/2), int(prompt_past.size()));
  3435. prompt = { whisper_token_prev(ctx) };
  3436. prompt.insert(prompt.begin() + 1, prompt_past.end() - n_take, prompt_past.end());
  3437. }
  3438. // init new transcription with sot, language (opt) and task tokens
  3439. prompt.insert(prompt.end(), prompt_init.begin(), prompt_init.end());
  3440. // print the prompt
  3441. WHISPER_PRINT_DEBUG("\n\n");
  3442. for (int i = 0; i < (int) prompt.size(); i++) {
  3443. WHISPER_PRINT_DEBUG("%s: prompt[%d] = %s\n", __func__, i, ctx->vocab.id_to_token.at(prompt[i]).c_str());
  3444. }
  3445. WHISPER_PRINT_DEBUG("\n\n");
  3446. if (!whisper_decode_internal(*ctx, *state, state->decoders[0], prompt.data(), prompt.size(), 0, params.n_threads)) {
  3447. log("%s: failed to decode\n", __func__);
  3448. return -7;
  3449. }
  3450. {
  3451. const int64_t t_start_sample_us = ggml_time_us();
  3452. whisper_process_logits(*ctx, *state, params, state->decoders[0], t_cur);
  3453. state->decoders[0].kv_self.n += prompt.size();
  3454. for (int j = 1; j < n_decoders_cur; ++j) {
  3455. auto & decoder = state->decoders[j];
  3456. memcpy(decoder.kv_self.k->data, state->decoders[0].kv_self.k->data, ggml_nbytes(decoder.kv_self.k));
  3457. memcpy(decoder.kv_self.v->data, state->decoders[0].kv_self.v->data, ggml_nbytes(decoder.kv_self.v));
  3458. decoder.kv_self.n += prompt.size();
  3459. memcpy(decoder.probs.data(), state->decoders[0].probs.data(), decoder.probs.size()*sizeof(decoder.probs[0]));
  3460. memcpy(decoder.logits.data(), state->decoders[0].logits.data(), decoder.logits.size()*sizeof(decoder.logits[0]));
  3461. memcpy(decoder.logprobs.data(), state->decoders[0].logprobs.data(), decoder.logprobs.size()*sizeof(decoder.logprobs[0]));
  3462. }
  3463. state->t_sample_us += ggml_time_us() - t_start_sample_us;
  3464. }
  3465. }
  3466. for (int i = 0, n_max = whisper_n_text_ctx(ctx)/2 - 4; i < n_max; ++i) {
  3467. const int64_t t_start_sample_us = ggml_time_us();
  3468. // store the KV caches of all decoders when doing beam-search
  3469. if (params.strategy == whisper_sampling_strategy::WHISPER_SAMPLING_BEAM_SEARCH) {
  3470. kv_bufs.resize(n_decoders_cur);
  3471. for (int j = 0; j < n_decoders_cur; ++j) {
  3472. auto & decoder = state->decoders[j];
  3473. if (decoder.completed || decoder.failed) {
  3474. continue;
  3475. }
  3476. kv_bufs[j].k.resize(ggml_nbytes(decoder.kv_self.k));
  3477. kv_bufs[j].v.resize(ggml_nbytes(decoder.kv_self.v));
  3478. memcpy(kv_bufs[j].k.data(), decoder.kv_self.k->data, kv_bufs[j].k.size());
  3479. memcpy(kv_bufs[j].v.data(), decoder.kv_self.v->data, kv_bufs[j].v.size());
  3480. }
  3481. beam_candidates.clear();
  3482. }
  3483. // generate new sequence candidates for each decoder
  3484. for (int j = 0; j < n_decoders_cur; ++j) {
  3485. auto & decoder = state->decoders[j];
  3486. if (decoder.completed || decoder.failed) {
  3487. continue;
  3488. }
  3489. switch (params.strategy) {
  3490. case whisper_sampling_strategy::WHISPER_SAMPLING_GREEDY:
  3491. {
  3492. if (t_cur < 1e-6f) {
  3493. decoder.sequence.tokens.push_back(whisper_sample_token(*ctx, *state, decoder, true));
  3494. } else {
  3495. decoder.sequence.tokens.push_back(whisper_sample_token(*ctx, *state, decoder, false));
  3496. }
  3497. decoder.sequence.sum_logprobs_all += decoder.sequence.tokens.back().plog;
  3498. } break;
  3499. case whisper_sampling_strategy::WHISPER_SAMPLING_BEAM_SEARCH:
  3500. {
  3501. const auto tokens_new = whisper_sample_token_topk(*ctx, *state, decoder, params.beam_search.beam_size);
  3502. for (const auto & token : tokens_new) {
  3503. beam_candidates.push_back({ j, decoder.seek_delta, decoder.has_ts, decoder.sequence });
  3504. beam_candidates.back().sequence.tokens.push_back(token);
  3505. beam_candidates.back().sequence.sum_logprobs_all += token.plog;
  3506. //WHISPER_PRINT_DEBUG("%s: beam candidate: %s (%f, %f)\n", __func__, ctx->vocab.id_to_token.at(token.id).c_str(), token.plog, beam_candidates.back().sequence.sum_logprobs_all);
  3507. }
  3508. } break;
  3509. };
  3510. }
  3511. // for beam-search, choose the top candidates and update the KV caches
  3512. if (params.strategy == whisper_sampling_strategy::WHISPER_SAMPLING_BEAM_SEARCH) {
  3513. std::sort(
  3514. beam_candidates.begin(),
  3515. beam_candidates.end(),
  3516. [](const beam_candidate & a, const beam_candidate & b) {
  3517. return a.sequence.sum_logprobs_all > b.sequence.sum_logprobs_all;
  3518. });
  3519. uint32_t cur_c = 0;
  3520. for (int j = 0; j < n_decoders_cur; ++j) {
  3521. auto & decoder = state->decoders[j];
  3522. if (decoder.completed || decoder.failed) {
  3523. continue;
  3524. }
  3525. auto & cur = beam_candidates[cur_c++];
  3526. while (beam_candidates.size() > cur_c && beam_candidates[cur_c].sequence.sum_logprobs_all == cur.sequence.sum_logprobs_all && i > 0) {
  3527. ++cur_c;
  3528. }
  3529. decoder.sequence = cur.sequence;
  3530. decoder.seek_delta = cur.seek_delta;
  3531. decoder.has_ts = cur.has_ts;
  3532. memcpy(decoder.kv_self.k->data, kv_bufs[cur.decoder_idx].k.data(), kv_bufs[cur.decoder_idx].k.size());
  3533. memcpy(decoder.kv_self.v->data, kv_bufs[cur.decoder_idx].v.data(), kv_bufs[cur.decoder_idx].v.size());
  3534. WHISPER_PRINT_DEBUG("%s: beam search: decoder %d: from decoder %d: token = %10s, plog = %8.5f, sum_logprobs = %8.5f\n",
  3535. __func__, j, cur.decoder_idx, ctx->vocab.id_to_token.at(decoder.sequence.tokens.back().id).c_str(), decoder.sequence.tokens.back().plog, decoder.sequence.sum_logprobs_all);
  3536. }
  3537. }
  3538. // update the decoder state
  3539. // - check if the sequence is completed
  3540. // - check if the sequence is failed
  3541. // - update sliding window based on timestamp tokens
  3542. for (int j = 0; j < n_decoders_cur; ++j) {
  3543. auto & decoder = state->decoders[j];
  3544. if (decoder.completed || decoder.failed) {
  3545. continue;
  3546. }
  3547. auto & has_ts = decoder.has_ts;
  3548. auto & failed = decoder.failed;
  3549. auto & completed = decoder.completed;
  3550. auto & seek_delta = decoder.seek_delta;
  3551. auto & result_len = decoder.sequence.result_len;
  3552. {
  3553. const auto & token = decoder.sequence.tokens.back();
  3554. // timestamp token - update sliding window
  3555. if (token.id > whisper_token_beg(ctx)) {
  3556. const int seek_delta_new = 2*(token.id - whisper_token_beg(ctx));
  3557. // do not allow to go back in time
  3558. if (has_ts && seek_delta > seek_delta_new && result_len < i) {
  3559. failed = true; // TODO: maybe this is not a failure ?
  3560. continue;
  3561. }
  3562. seek_delta = seek_delta_new;
  3563. result_len = i + 1;
  3564. has_ts = true;
  3565. }
  3566. #ifdef WHISPER_DEBUG
  3567. {
  3568. const auto tt = token.pt > 0.10 ? ctx->vocab.id_to_token.at(token.tid) : "[?]";
  3569. WHISPER_PRINT_DEBUG("%s: id = %3d, decoder = %d, token = %6d, p = %6.3f, ts = %10s, %6.3f, result_len = %4d '%s'\n",
  3570. __func__, i, j, token.id, token.p, tt.c_str(), token.pt, result_len, ctx->vocab.id_to_token.at(token.id).c_str());
  3571. }
  3572. #endif
  3573. // end of segment
  3574. if (token.id == whisper_token_eot(ctx) || // end of text token
  3575. (params.max_tokens > 0 && i >= params.max_tokens) || // max tokens per segment reached
  3576. (has_ts && seek + seek_delta + 100 >= seek_end) // end of audio reached
  3577. ) {
  3578. if (result_len == 0) {
  3579. if (seek + seek_delta + 100 >= seek_end) {
  3580. result_len = i + 1;
  3581. } else {
  3582. failed = true;
  3583. continue;
  3584. }
  3585. }
  3586. if (params.single_segment) {
  3587. result_len = i + 1;
  3588. seek_delta = 100*WHISPER_CHUNK_SIZE;
  3589. }
  3590. completed = true;
  3591. continue;
  3592. }
  3593. // TESTS: if no tensors are loaded, it means we are running tests
  3594. if (ctx->model.n_loaded == 0) {
  3595. seek_delta = 100*WHISPER_CHUNK_SIZE;
  3596. completed = true;
  3597. continue;
  3598. }
  3599. }
  3600. // sometimes, the decoding can get stuck in a repetition loop
  3601. // this is an attempt to mitigate such cases - we flag the decoding as failed and use a fallback strategy
  3602. if (i == n_max - 1 && (result_len == 0 || seek_delta < 100*WHISPER_CHUNK_SIZE/2)) {
  3603. failed = true;
  3604. continue;
  3605. }
  3606. }
  3607. // check if all decoders have finished (i.e. completed or failed)
  3608. {
  3609. bool completed_all = true;
  3610. for (int j = 0; j < n_decoders_cur; ++j) {
  3611. auto & decoder = state->decoders[j];
  3612. if (decoder.completed || decoder.failed) {
  3613. continue;
  3614. }
  3615. completed_all = false;
  3616. }
  3617. if (completed_all) {
  3618. break;
  3619. }
  3620. }
  3621. state->t_sample_us += ggml_time_us() - t_start_sample_us;
  3622. // obtain logits for the next token
  3623. for (int j = 0; j < n_decoders_cur; ++j) {
  3624. auto & decoder = state->decoders[j];
  3625. if (decoder.failed || decoder.completed) {
  3626. continue;
  3627. }
  3628. decoder.tokens_tmp.resize(1);
  3629. decoder.tokens_tmp[0] = decoder.sequence.tokens.back().id;
  3630. //WHISPER_PRINT_DEBUG("%s: decoder %d: token %d, kv_self.n %d, seek_delta %d\n", __func__, j, decoder.tokens_tmp[0], decoder.kv_self.n, decoder.seek_delta);
  3631. if (!whisper_decode_internal(*ctx, *state, decoder, decoder.tokens_tmp.data(), decoder.tokens_tmp.size(), decoder.kv_self.n, params.n_threads)) {
  3632. log("%s: failed to decode\n", __func__);
  3633. return -8;
  3634. }
  3635. {
  3636. const int64_t t_start_sample_us = ggml_time_us();
  3637. whisper_process_logits(*ctx, *state, params, decoder, t_cur);
  3638. ++decoder.kv_self.n;
  3639. state->t_sample_us += ggml_time_us() - t_start_sample_us;
  3640. }
  3641. }
  3642. }
  3643. // rank the resulting sequences and select the best one
  3644. {
  3645. double best_score = -INFINITY;
  3646. for (int j = 0; j < n_decoders_cur; ++j) {
  3647. auto & decoder = state->decoders[j];
  3648. if (decoder.failed) {
  3649. continue;
  3650. }
  3651. decoder.sequence.tokens.resize(decoder.sequence.result_len);
  3652. whisper_sequence_score(params, decoder.sequence);
  3653. WHISPER_PRINT_DEBUG("%s: decoder %2d: score = %8.5f, result_len = %3d, avg_logprobs = %8.5f, entropy = %8.5f\n",
  3654. __func__, j, decoder.sequence.score, decoder.sequence.result_len, decoder.sequence.avg_logprobs, decoder.sequence.entropy);
  3655. if (decoder.sequence.result_len > 32 && decoder.sequence.entropy < params.entropy_thold) {
  3656. WHISPER_PRINT_DEBUG("%s: decoder %2d: failed due to entropy %8.5f < %8.5f\n",
  3657. __func__, j, decoder.sequence.entropy, params.entropy_thold);
  3658. decoder.failed = true;
  3659. state->n_fail_h++;
  3660. continue;
  3661. }
  3662. if (best_score < decoder.sequence.score) {
  3663. best_score = decoder.sequence.score;
  3664. best_decoder_id = j;
  3665. }
  3666. }
  3667. WHISPER_PRINT_DEBUG("%s: best decoder = %d\n", __func__, best_decoder_id);
  3668. }
  3669. // was the decoding successful for the current temperature?
  3670. // do fallback only if:
  3671. // - we are not at the last temperature
  3672. // - we are not at the end of the audio (3 sec)
  3673. if (it != (int) temperatures.size() - 1 &&
  3674. seek_end - seek > 10*WHISPER_CHUNK_SIZE) {
  3675. bool success = true;
  3676. const auto & decoder = state->decoders[best_decoder_id];
  3677. if (decoder.failed || decoder.sequence.avg_logprobs < params.logprob_thold) {
  3678. success = false;
  3679. state->n_fail_p++;
  3680. }
  3681. if (success) {
  3682. //for (auto & token : ctx->decoders[best_decoder_id].sequence.tokens) {
  3683. // WHISPER_PRINT_DEBUG("%s: token = %d, p = %6.3f, pt = %6.3f, ts = %s, str = %s\n", __func__, token.id, token.p, token.pt, ctx->vocab.id_to_token.at(token.tid).c_str(), ctx->vocab.id_to_token.at(token.id).c_str());
  3684. //}
  3685. break;
  3686. }
  3687. }
  3688. WHISPER_PRINT_DEBUG("\n%s: failed to decode with temperature = %.2f\n", __func__, t_cur);
  3689. }
  3690. // output results through a user-provided callback
  3691. {
  3692. const auto & best_decoder = state->decoders[best_decoder_id];
  3693. const auto seek_delta = best_decoder.seek_delta;
  3694. const auto result_len = best_decoder.sequence.result_len;
  3695. const auto & tokens_cur = best_decoder.sequence.tokens;
  3696. //WHISPER_PRINT_DEBUG("prompt_init.size() = %d, prompt.size() = %d, result_len = %d, seek_delta = %d\n", prompt_init.size(), prompt.size(), result_len, seek_delta);
  3697. // update prompt_past
  3698. prompt_past.clear();
  3699. if (prompt.front() == whisper_token_prev(ctx)) {
  3700. prompt_past.insert(prompt_past.end(), prompt.begin() + 1, prompt.end() - prompt_init.size());
  3701. }
  3702. for (int i = 0; i < result_len; ++i) {
  3703. prompt_past.push_back(tokens_cur[i].id);
  3704. }
  3705. if (!tokens_cur.empty() && ctx->model.n_loaded > 0) {
  3706. int i0 = 0;
  3707. auto t0 = seek + 2*(tokens_cur.front().tid - whisper_token_beg(ctx));
  3708. std::string text;
  3709. bool speaker_turn_next = false;
  3710. for (int i = 0; i < (int) tokens_cur.size(); i++) {
  3711. //printf("%s: %18s %6.3f %18s %6.3f\n", __func__,
  3712. // ctx->vocab.id_to_token[tokens_cur[i].id].c_str(), tokens_cur[i].p,
  3713. // ctx->vocab.id_to_token[tokens_cur[i].tid].c_str(), tokens_cur[i].pt);
  3714. if (params.print_special || tokens_cur[i].id < whisper_token_eot(ctx)) {
  3715. text += whisper_token_to_str(ctx, tokens_cur[i].id);
  3716. }
  3717. // [TDRZ] record if speaker turn was predicted after current segment
  3718. if (params.tdrz_enable && tokens_cur[i].id == whisper_token_solm(ctx)) {
  3719. speaker_turn_next = true;
  3720. }
  3721. if (tokens_cur[i].id > whisper_token_beg(ctx) && !params.single_segment) {
  3722. const auto t1 = seek + 2*(tokens_cur[i].tid - whisper_token_beg(ctx));
  3723. if (!text.empty()) {
  3724. const auto tt0 = params.speed_up ? 2*t0 : t0;
  3725. const auto tt1 = params.speed_up ? 2*t1 : t1;
  3726. if (params.print_realtime) {
  3727. if (params.print_timestamps) {
  3728. printf("[%s --> %s] %s\n", to_timestamp(tt0).c_str(), to_timestamp(tt1).c_str(), text.c_str());
  3729. } else {
  3730. printf("%s", text.c_str());
  3731. fflush(stdout);
  3732. }
  3733. }
  3734. //printf("tt0 = %d, tt1 = %d, text = %s, token = %s, token_id = %d, tid = %d\n", tt0, tt1, text.c_str(), ctx->vocab.id_to_token[tokens_cur[i].id].c_str(), tokens_cur[i].id, tokens_cur[i].tid);
  3735. result_all.push_back({ tt0, tt1, text, {}, speaker_turn_next });
  3736. for (int j = i0; j <= i; j++) {
  3737. result_all.back().tokens.push_back(tokens_cur[j]);
  3738. }
  3739. int n_new = 1;
  3740. if (params.token_timestamps) {
  3741. whisper_exp_compute_token_level_timestamps(
  3742. *ctx, *state, result_all.size() - 1, params.thold_pt, params.thold_ptsum);
  3743. if (params.max_len > 0) {
  3744. n_new = whisper_wrap_segment(*ctx, *state, params.max_len, params.split_on_word);
  3745. }
  3746. }
  3747. if (params.new_segment_callback) {
  3748. params.new_segment_callback(ctx, state, n_new, params.new_segment_callback_user_data);
  3749. }
  3750. }
  3751. text = "";
  3752. while (i < (int) tokens_cur.size() && tokens_cur[i].id > whisper_token_beg(ctx)) {
  3753. i++;
  3754. }
  3755. i--;
  3756. t0 = t1;
  3757. i0 = i + 1;
  3758. speaker_turn_next = false;
  3759. }
  3760. }
  3761. if (!text.empty()) {
  3762. const auto t1 = seek + seek_delta;
  3763. const auto tt0 = params.speed_up ? 2*t0 : t0;
  3764. const auto tt1 = params.speed_up ? 2*t1 : t1;
  3765. if (params.print_realtime) {
  3766. if (params.print_timestamps) {
  3767. printf("[%s --> %s] %s\n", to_timestamp(tt0).c_str(), to_timestamp(tt1).c_str(), text.c_str());
  3768. } else {
  3769. printf("%s", text.c_str());
  3770. fflush(stdout);
  3771. }
  3772. }
  3773. result_all.push_back({ tt0, tt1, text, {} , speaker_turn_next });
  3774. for (int j = i0; j < (int) tokens_cur.size(); j++) {
  3775. result_all.back().tokens.push_back(tokens_cur[j]);
  3776. }
  3777. int n_new = 1;
  3778. if (params.token_timestamps) {
  3779. whisper_exp_compute_token_level_timestamps(
  3780. *ctx, *state, result_all.size() - 1, params.thold_pt, params.thold_ptsum);
  3781. if (params.max_len > 0) {
  3782. n_new = whisper_wrap_segment(*ctx, *state, params.max_len, params.split_on_word);
  3783. }
  3784. }
  3785. if (params.new_segment_callback) {
  3786. params.new_segment_callback(ctx, state, n_new, params.new_segment_callback_user_data);
  3787. }
  3788. }
  3789. }
  3790. // update audio window
  3791. seek += seek_delta;
  3792. WHISPER_PRINT_DEBUG("seek = %d, seek_delta = %d\n", seek, seek_delta);
  3793. }
  3794. }
  3795. return 0;
  3796. }
  3797. int whisper_full(
  3798. struct whisper_context * ctx,
  3799. struct whisper_full_params params,
  3800. const float * samples,
  3801. int n_samples) {
  3802. return whisper_full_with_state(ctx, ctx->state, params, samples, n_samples);
  3803. }
  3804. int whisper_full_parallel(
  3805. struct whisper_context * ctx,
  3806. struct whisper_full_params params,
  3807. const float * samples,
  3808. int n_samples,
  3809. int n_processors) {
  3810. if (n_processors == 1) {
  3811. return whisper_full(ctx, params, samples, n_samples);
  3812. }
  3813. int ret = 0;
  3814. // prepare separate states for each thread
  3815. std::vector<whisper_state*> states;
  3816. const int offset_samples = (WHISPER_SAMPLE_RATE*params.offset_ms)/1000;
  3817. const int n_samples_per_processor = (n_samples - offset_samples)/n_processors;
  3818. // the calling thread will process the first chunk
  3819. // while the other threads will process the remaining chunks
  3820. std::vector<std::thread> workers(n_processors - 1);
  3821. for (int i = 0; i < n_processors - 1; ++i) {
  3822. // create a new state for each thread
  3823. states.push_back(whisper_init_state(ctx));
  3824. const int start_samples = offset_samples + (i + 1)*n_samples_per_processor;
  3825. const int n_samples_cur = (i == n_processors - 2) ? n_samples - start_samples : n_samples_per_processor;
  3826. auto params_cur = params;
  3827. params_cur.offset_ms = 0;
  3828. params_cur.print_progress = false;
  3829. params_cur.print_realtime = false;
  3830. params_cur.new_segment_callback = nullptr;
  3831. params_cur.new_segment_callback_user_data = nullptr;
  3832. params_cur.progress_callback = nullptr;
  3833. params_cur.progress_callback_user_data = nullptr;
  3834. workers[i] = std::thread(whisper_full_with_state, ctx, states[i], std::move(params_cur), samples + start_samples, n_samples_cur);
  3835. }
  3836. {
  3837. auto params_cur = params;
  3838. // We need to disable the print real-time for this one as well, otherwise it will show only for the first chunk.
  3839. params_cur.print_realtime = false;
  3840. // Run the first transformation using default state but only for the first chunk.
  3841. ret = whisper_full_with_state(ctx, ctx->state, std::move(params_cur), samples, offset_samples + n_samples_per_processor);
  3842. }
  3843. for (int i = 0; i < n_processors - 1; ++i) {
  3844. workers[i].join();
  3845. }
  3846. const int64_t offset_t = (int64_t) params.offset_ms/10.0;
  3847. // combine results into result_state->result_all from all other states
  3848. for (int i = 0; i < n_processors - 1; ++i) {
  3849. auto& results_i = states[i]->result_all;
  3850. for (auto& result : results_i) {
  3851. // correct the segment timestamp taking into account the offset
  3852. result.t0 += 100 * ((i + 1) * n_samples_per_processor) / WHISPER_SAMPLE_RATE + offset_t;
  3853. result.t1 += 100 * ((i + 1) * n_samples_per_processor) / WHISPER_SAMPLE_RATE + offset_t;
  3854. // make sure that segments are not overlapping
  3855. if (!ctx->state->result_all.empty()) {
  3856. result.t0 = std::max(result.t0, ctx->state->result_all.back().t1);
  3857. }
  3858. ctx->state->result_all.push_back(std::move(result));
  3859. // call the new_segment_callback for each segment
  3860. if (params.new_segment_callback) {
  3861. params.new_segment_callback(ctx, ctx->state, 1, params.new_segment_callback_user_data);
  3862. }
  3863. }
  3864. ctx->state->t_mel_us += states[i]->t_mel_us;
  3865. ctx->state->t_sample_us += states[i]->t_sample_us;
  3866. ctx->state->t_encode_us += states[i]->t_encode_us;
  3867. ctx->state->t_decode_us += states[i]->t_decode_us;
  3868. whisper_free_state(states[i]);
  3869. }
  3870. // average the timings
  3871. ctx->state->t_mel_us /= n_processors;
  3872. ctx->state->t_sample_us /= n_processors;
  3873. ctx->state->t_encode_us /= n_processors;
  3874. ctx->state->t_decode_us /= n_processors;
  3875. // print information about the audio boundaries
  3876. log("\n");
  3877. log("%s: the audio has been split into %d chunks at the following times:\n", __func__, n_processors);
  3878. for (int i = 0; i < n_processors - 1; ++i) {
  3879. log("%s: split %d - %s\n", __func__, (i + 1), to_timestamp(100*((i + 1)*n_samples_per_processor)/WHISPER_SAMPLE_RATE + offset_t).c_str());
  3880. }
  3881. log("%s: the transcription quality may be degraded near these boundaries\n", __func__);
  3882. return ret;
  3883. }
  3884. int whisper_full_n_segments_from_state(struct whisper_state * state) {
  3885. return state->result_all.size();
  3886. }
  3887. int whisper_full_n_segments(struct whisper_context * ctx) {
  3888. return ctx->state->result_all.size();
  3889. }
  3890. int whisper_full_lang_id_from_state(struct whisper_state * state) {
  3891. return state->lang_id;
  3892. }
  3893. int whisper_full_lang_id(struct whisper_context * ctx) {
  3894. return ctx->state->lang_id;
  3895. }
  3896. int64_t whisper_full_get_segment_t0_from_state(struct whisper_state * state, int i_segment) {
  3897. return state->result_all[i_segment].t0;
  3898. }
  3899. int64_t whisper_full_get_segment_t0(struct whisper_context * ctx, int i_segment) {
  3900. return ctx->state->result_all[i_segment].t0;
  3901. }
  3902. int64_t whisper_full_get_segment_t1_from_state(struct whisper_state * state, int i_segment) {
  3903. return state->result_all[i_segment].t1;
  3904. }
  3905. int64_t whisper_full_get_segment_t1(struct whisper_context * ctx, int i_segment) {
  3906. return ctx->state->result_all[i_segment].t1;
  3907. }
  3908. bool whisper_full_get_segment_speaker_turn_next(struct whisper_context * ctx, int i_segment) {
  3909. return ctx->state->result_all[i_segment].speaker_turn_next;
  3910. }
  3911. const char * whisper_full_get_segment_text_from_state(struct whisper_state * state, int i_segment) {
  3912. return state->result_all[i_segment].text.c_str();
  3913. }
  3914. const char * whisper_full_get_segment_text(struct whisper_context * ctx, int i_segment) {
  3915. return ctx->state->result_all[i_segment].text.c_str();
  3916. }
  3917. int whisper_full_n_tokens_from_state(struct whisper_state * state, int i_segment) {
  3918. return state->result_all[i_segment].tokens.size();
  3919. }
  3920. int whisper_full_n_tokens(struct whisper_context * ctx, int i_segment) {
  3921. return ctx->state->result_all[i_segment].tokens.size();
  3922. }
  3923. const char * whisper_full_get_token_text_from_state(struct whisper_context * ctx, struct whisper_state * state, int i_segment, int i_token) {
  3924. return ctx->vocab.id_to_token[state->result_all[i_segment].tokens[i_token].id].c_str();
  3925. }
  3926. const char* whisper_full_get_token_text(struct whisper_context * ctx, int i_segment, int i_token) {
  3927. return ctx->vocab.id_to_token[ctx->state->result_all[i_segment].tokens[i_token].id].c_str();
  3928. }
  3929. whisper_token whisper_full_get_token_id_from_state(struct whisper_state * state, int i_segment, int i_token) {
  3930. return state->result_all[i_segment].tokens[i_token].id;
  3931. }
  3932. whisper_token whisper_full_get_token_id(struct whisper_context * ctx, int i_segment, int i_token) {
  3933. return ctx->state->result_all[i_segment].tokens[i_token].id;
  3934. }
  3935. struct whisper_token_data whisper_full_get_token_data_from_state(struct whisper_state * state, int i_segment, int i_token) {
  3936. return state->result_all[i_segment].tokens[i_token];
  3937. }
  3938. struct whisper_token_data whisper_full_get_token_data(struct whisper_context * ctx, int i_segment, int i_token) {
  3939. return ctx->state->result_all[i_segment].tokens[i_token];
  3940. }
  3941. float whisper_full_get_token_p_from_state(struct whisper_state * state, int i_segment, int i_token) {
  3942. return state->result_all[i_segment].tokens[i_token].p;
  3943. }
  3944. float whisper_full_get_token_p(struct whisper_context * ctx, int i_segment, int i_token) {
  3945. return ctx->state->result_all[i_segment].tokens[i_token].p;
  3946. }
  3947. // =================================================================================================
  3948. //
  3949. // Temporary interface needed for exposing ggml interface
  3950. // Will be removed in the future when ggml becomes a separate library
  3951. //
  3952. WHISPER_API int whisper_bench_memcpy(int n_threads) {
  3953. fputs(whisper_bench_memcpy_str(n_threads), stderr);
  3954. return 0;
  3955. }
  3956. WHISPER_API const char * whisper_bench_memcpy_str(int n_threads) {
  3957. static std::string s;
  3958. s = "";
  3959. char strbuf[256];
  3960. ggml_time_init();
  3961. size_t n = 20;
  3962. size_t arr = n_threads > 0 ? 1024llu : n_threads; // trick to avoid compiler optimizations
  3963. // 1GB MB array
  3964. const size_t size = arr*1024llu*1024llu;
  3965. // single-thread
  3966. {
  3967. char * src = (char *) malloc(size);
  3968. char * dst = (char *) malloc(size);
  3969. for (size_t i = 0; i < size; i++) src[i] = i;
  3970. memcpy(dst, src, size); // heat-up
  3971. double tsum = 0.0;
  3972. double sum = 0.0;
  3973. for (size_t i = 0; i < n; i++) {
  3974. const int64_t t0 = ggml_time_us();
  3975. memcpy(dst, src, size);
  3976. const int64_t t1 = ggml_time_us();
  3977. tsum += (t1 - t0)*1e-6;
  3978. src[rand() % size] = rand() % 256;
  3979. }
  3980. snprintf(strbuf, sizeof(strbuf), "memcpy: %.2f GB/s (1 thread)\n", (double) (n*size)/(tsum*1024llu*1024llu*1024llu));
  3981. s += strbuf;
  3982. // needed to prevent the compiler from optimizing the memcpy away
  3983. {
  3984. for (size_t i = 0; i < size; i++) sum += dst[i];
  3985. snprintf(strbuf, sizeof(strbuf), "sum: %f\n", sum);
  3986. s += strbuf;
  3987. }
  3988. free(src);
  3989. free(dst);
  3990. }
  3991. return s.c_str();
  3992. }
  3993. WHISPER_API int whisper_bench_ggml_mul_mat(int n_threads) {
  3994. fputs(whisper_bench_ggml_mul_mat_str(n_threads), stderr);
  3995. return 0;
  3996. }
  3997. WHISPER_API const char * whisper_bench_ggml_mul_mat_str(int n_threads) {
  3998. static std::string s;
  3999. s = "";
  4000. char strbuf[256];
  4001. ggml_time_init();
  4002. const int n_max = 128;
  4003. const std::vector<size_t> sizes = {
  4004. 64, 128, 256, 512, 1024, 2048, 4096,
  4005. };
  4006. const size_t N_max = sizes.back();
  4007. // a: N*N*sizeof(float)
  4008. // b: N*N*sizeof(float)
  4009. // c: N*N*sizeof(float)
  4010. // when F16 is used, there is an extra work buffer of size N*N*sizeof(float)
  4011. std::vector<char> buf(4llu*N_max*N_max*sizeof(float) + 4*512);
  4012. // put a bunch of random data in the buffer
  4013. for (size_t i = 0; i < buf.size(); i++) buf[i] = i;
  4014. for (int j = 0; j < (int) sizes.size(); j++) {
  4015. int n_q4_0 = 0;
  4016. int n_q4_1 = 0;
  4017. int n_q5_0 = 0;
  4018. int n_q5_1 = 0;
  4019. int n_q8_0 = 0;
  4020. int n_fp16 = 0;
  4021. int n_fp32 = 0;
  4022. // GFLOPS/s
  4023. double s_q4_0 = 0.0;
  4024. double s_q4_1 = 0.0;
  4025. double s_q5_0 = 0.0;
  4026. double s_q5_1 = 0.0;
  4027. double s_q8_0 = 0.0;
  4028. double s_fp16 = 0.0;
  4029. double s_fp32 = 0.0;
  4030. const size_t N = sizes[j];
  4031. for (int k = 0; k < 7; ++k) {
  4032. const ggml_type wtype =
  4033. k == 0 ? GGML_TYPE_Q4_0 :
  4034. k == 1 ? GGML_TYPE_Q4_1 :
  4035. k == 2 ? GGML_TYPE_Q5_0 :
  4036. k == 3 ? GGML_TYPE_Q5_1 :
  4037. k == 4 ? GGML_TYPE_Q8_0 :
  4038. k == 5 ? GGML_TYPE_F16 : GGML_TYPE_F32;
  4039. double & s = k == 0 ? s_q4_0 : k == 1 ? s_q4_1 : k == 2 ? s_q5_0 : k == 3 ? s_q5_1 : k == 4 ? s_q8_0 : k == 5 ? s_fp16 : /*k == 6*/ s_fp32;
  4040. int & n = k == 0 ? n_q4_0 : k == 1 ? n_q4_1 : k == 2 ? n_q5_0 : k == 3 ? n_q5_1 : k == 4 ? n_q8_0 : k == 5 ? n_fp16 : /*k == 6*/ n_fp32;
  4041. struct ggml_init_params gparams = {
  4042. /*.mem_size =*/ buf.size(),
  4043. /*.mem_buffer =*/ buf.data(),
  4044. /*.no_alloc =*/ false,
  4045. };
  4046. struct ggml_context * ctx0 = ggml_init(gparams);
  4047. struct ggml_tensor * a = ggml_new_tensor_2d(ctx0, wtype, N, N);
  4048. struct ggml_tensor * b = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, N, N);
  4049. struct ggml_tensor * c = ggml_mul_mat(ctx0, a, b);
  4050. struct ggml_cgraph gf = ggml_build_forward(c);
  4051. double tsum = 0.0;
  4052. // heat-up
  4053. ggml_graph_compute_with_ctx(ctx0, &gf, n_threads);
  4054. for (int i = 0; i < n_max; ++i) {
  4055. const int64_t t0 = ggml_time_us();
  4056. ggml_graph_compute_with_ctx(ctx0, &gf, n_threads);
  4057. const int64_t t1 = ggml_time_us();
  4058. tsum += (t1 - t0)*1e-6;
  4059. n++;
  4060. if (tsum > 1.0 && n >= 3) {
  4061. break;
  4062. }
  4063. }
  4064. ggml_free(ctx0);
  4065. s = ((2.0*N*N*N*n)/tsum)*1e-9;
  4066. }
  4067. // Q4_0 | Q4_1
  4068. snprintf(strbuf, sizeof(strbuf), "%4zu x %4zu: Q4_0 %7.1f GFLOPS (%3d runs) | Q4_1 %7.1f GFLOPS (%3d runs)\n",
  4069. N, N, s_q4_0, n_q4_0, s_q4_1, n_q4_1);
  4070. s += strbuf;
  4071. // Q5_0 | Q5_1 | Q8_0
  4072. snprintf(strbuf, sizeof(strbuf), "%4zu x %4zu: Q5_0 %7.1f GFLOPS (%3d runs) | Q5_1 %7.1f GFLOPS (%3d runs) | Q8_0 %7.1f GFLOPS (%3d runs)\n",
  4073. N, N, s_q5_0, n_q5_0, s_q5_1, n_q5_1, s_q8_0, n_q8_0);
  4074. s += strbuf;
  4075. // F16 | F32
  4076. snprintf(strbuf, sizeof(strbuf), "%4zu x %4zu: F16 %7.1f GFLOPS (%3d runs) | F32 %7.1f GFLOPS (%3d runs)\n",
  4077. N, N, s_fp16, n_fp16, s_fp32, n_fp32);
  4078. s += strbuf;
  4079. }
  4080. return s.c_str();
  4081. }
  4082. // =================================================================================================
  4083. // =================================================================================================
  4084. //
  4085. // Experimental stuff below
  4086. //
  4087. // Not sure if these should be part of the library at all, because the quality of the results is not
  4088. // guaranteed. Might get removed at some point unless a robust algorithm implementation is found
  4089. //
  4090. // =================================================================================================
  4091. //
  4092. // token-level timestamps
  4093. //
  4094. static int timestamp_to_sample(int64_t t, int n_samples) {
  4095. return std::max(0, std::min((int) n_samples - 1, (int) ((t*WHISPER_SAMPLE_RATE)/100)));
  4096. }
  4097. static int64_t sample_to_timestamp(int i_sample) {
  4098. return (100ll*i_sample)/WHISPER_SAMPLE_RATE;
  4099. }
  4100. // a cost-function / heuristic that is high for text that takes longer to pronounce
  4101. // obviously, can be improved
  4102. static float voice_length(const std::string & text) {
  4103. float res = 0.0f;
  4104. for (char c : text) {
  4105. if (c == ' ') {
  4106. res += 0.01f;
  4107. } else if (c == ',') {
  4108. res += 2.00f;
  4109. } else if (c == '.') {
  4110. res += 3.00f;
  4111. } else if (c == '!') {
  4112. res += 3.00f;
  4113. } else if (c == '?') {
  4114. res += 3.00f;
  4115. } else if (c >= '0' && c <= '9') {
  4116. res += 3.00f;
  4117. } else {
  4118. res += 1.00f;
  4119. }
  4120. }
  4121. return res;
  4122. }
  4123. // average the fabs of the signal
  4124. static std::vector<float> get_signal_energy(const float * signal, int n_samples, int n_samples_per_half_window) {
  4125. const int hw = n_samples_per_half_window;
  4126. std::vector<float> result(n_samples);
  4127. for (int i = 0; i < n_samples; i++) {
  4128. float sum = 0;
  4129. for (int j = -hw; j <= hw; j++) {
  4130. if (i + j >= 0 && i + j < n_samples) {
  4131. sum += fabs(signal[i + j]);
  4132. }
  4133. }
  4134. result[i] = sum/(2*hw + 1);
  4135. }
  4136. return result;
  4137. }
  4138. static void whisper_exp_compute_token_level_timestamps(
  4139. struct whisper_context & ctx,
  4140. struct whisper_state & state,
  4141. int i_segment,
  4142. float thold_pt,
  4143. float thold_ptsum) {
  4144. auto & segment = state.result_all[i_segment];
  4145. auto & tokens = segment.tokens;
  4146. const int n_samples = state.energy.size();
  4147. if (n_samples == 0) {
  4148. log("%s: no signal data available\n", __func__);
  4149. return;
  4150. }
  4151. const int64_t t0 = segment.t0;
  4152. const int64_t t1 = segment.t1;
  4153. const int n = tokens.size();
  4154. if (n == 0) {
  4155. return;
  4156. }
  4157. if (n == 1) {
  4158. tokens[0].t0 = t0;
  4159. tokens[0].t1 = t1;
  4160. return;
  4161. }
  4162. auto & t_beg = state.t_beg;
  4163. auto & t_last = state.t_last;
  4164. auto & tid_last = state.tid_last;
  4165. for (int j = 0; j < n; ++j) {
  4166. auto & token = tokens[j];
  4167. if (j == 0) {
  4168. if (token.id == whisper_token_beg(&ctx)) {
  4169. tokens[j ].t0 = t0;
  4170. tokens[j ].t1 = t0;
  4171. tokens[j + 1].t0 = t0;
  4172. t_beg = t0;
  4173. t_last = t0;
  4174. tid_last = whisper_token_beg(&ctx);
  4175. } else {
  4176. tokens[j ].t0 = t_last;
  4177. }
  4178. }
  4179. const int64_t tt = t_beg + 2*(token.tid - whisper_token_beg(&ctx));
  4180. tokens[j].id = token.id;
  4181. tokens[j].tid = token.tid;
  4182. tokens[j].p = token.p;
  4183. tokens[j].pt = token.pt;
  4184. tokens[j].ptsum = token.ptsum;
  4185. tokens[j].vlen = voice_length(whisper_token_to_str(&ctx, token.id));
  4186. if (token.pt > thold_pt && token.ptsum > thold_ptsum && token.tid > tid_last && tt <= t1) {
  4187. if (j > 0) {
  4188. tokens[j - 1].t1 = tt;
  4189. }
  4190. tokens[j].t0 = tt;
  4191. tid_last = token.tid;
  4192. }
  4193. }
  4194. tokens[n - 2].t1 = t1;
  4195. tokens[n - 1].t0 = t1;
  4196. tokens[n - 1].t1 = t1;
  4197. t_last = t1;
  4198. // find intervals of tokens with unknown timestamps
  4199. // fill the timestamps by proportionally splitting the interval based on the token voice lengths
  4200. {
  4201. int p0 = 0;
  4202. int p1 = 0;
  4203. while (true) {
  4204. while (p1 < n && tokens[p1].t1 < 0) {
  4205. p1++;
  4206. }
  4207. if (p1 >= n) {
  4208. p1--;
  4209. }
  4210. //printf("p0=%d p1=%d t0=%lld t1=%lld\n", p0, p1, tokens[p0].t0, tokens[p1].t1);
  4211. if (p1 > p0) {
  4212. double psum = 0.0;
  4213. for (int j = p0; j <= p1; j++) {
  4214. psum += tokens[j].vlen;
  4215. }
  4216. //printf("analyzing %d - %d, psum = %f\n", p0, p1, psum);
  4217. const double dt = tokens[p1].t1 - tokens[p0].t0;
  4218. // split the time proportionally to the voice length
  4219. for (int j = p0 + 1; j <= p1; j++) {
  4220. const double ct = tokens[j - 1].t0 + dt*tokens[j - 1].vlen/psum;
  4221. tokens[j - 1].t1 = ct;
  4222. tokens[j ].t0 = ct;
  4223. }
  4224. }
  4225. p1++;
  4226. p0 = p1;
  4227. if (p1 >= n) {
  4228. break;
  4229. }
  4230. }
  4231. }
  4232. // fix up (just in case)
  4233. for (int j = 0; j < n - 1; j++) {
  4234. if (tokens[j].t1 < 0) {
  4235. tokens[j + 1].t0 = tokens[j].t1;
  4236. }
  4237. if (j > 0) {
  4238. if (tokens[j - 1].t1 > tokens[j].t0) {
  4239. tokens[j].t0 = tokens[j - 1].t1;
  4240. tokens[j].t1 = std::max(tokens[j].t0, tokens[j].t1);
  4241. }
  4242. }
  4243. }
  4244. // VAD
  4245. // expand or contract tokens based on voice activity
  4246. {
  4247. const int hw = WHISPER_SAMPLE_RATE/8;
  4248. for (int j = 0; j < n; j++) {
  4249. if (tokens[j].id >= whisper_token_eot(&ctx)) {
  4250. continue;
  4251. }
  4252. int s0 = timestamp_to_sample(tokens[j].t0, n_samples);
  4253. int s1 = timestamp_to_sample(tokens[j].t1, n_samples);
  4254. const int ss0 = std::max(s0 - hw, 0);
  4255. const int ss1 = std::min(s1 + hw, n_samples);
  4256. const int ns = ss1 - ss0;
  4257. float sum = 0.0f;
  4258. for (int k = ss0; k < ss1; k++) {
  4259. sum += state.energy[k];
  4260. }
  4261. const float thold = 0.5*sum/ns;
  4262. {
  4263. int k = s0;
  4264. if (state.energy[k] > thold && j > 0) {
  4265. while (k > 0 && state.energy[k] > thold) {
  4266. k--;
  4267. }
  4268. tokens[j].t0 = sample_to_timestamp(k);
  4269. if (tokens[j].t0 < tokens[j - 1].t1) {
  4270. tokens[j].t0 = tokens[j - 1].t1;
  4271. } else {
  4272. s0 = k;
  4273. }
  4274. } else {
  4275. while (state.energy[k] < thold && k < s1) {
  4276. k++;
  4277. }
  4278. s0 = k;
  4279. tokens[j].t0 = sample_to_timestamp(k);
  4280. }
  4281. }
  4282. {
  4283. int k = s1;
  4284. if (state.energy[k] > thold) {
  4285. while (k < n_samples - 1 && state.energy[k] > thold) {
  4286. k++;
  4287. }
  4288. tokens[j].t1 = sample_to_timestamp(k);
  4289. if (j < ns - 1 && tokens[j].t1 > tokens[j + 1].t0) {
  4290. tokens[j].t1 = tokens[j + 1].t0;
  4291. } else {
  4292. s1 = k;
  4293. }
  4294. } else {
  4295. while (state.energy[k] < thold && k > s0) {
  4296. k--;
  4297. }
  4298. s1 = k;
  4299. tokens[j].t1 = sample_to_timestamp(k);
  4300. }
  4301. }
  4302. }
  4303. }
  4304. // fixed token expand (optional)
  4305. //{
  4306. // const int t_expand = 0;
  4307. // for (int j = 0; j < n; j++) {
  4308. // if (j > 0) {
  4309. // tokens[j].t0 = std::max(0, (int) (tokens[j].t0 - t_expand));
  4310. // }
  4311. // if (j < n - 1) {
  4312. // tokens[j].t1 = tokens[j].t1 + t_expand;
  4313. // }
  4314. // }
  4315. //}
  4316. // debug info
  4317. //for (int j = 0; j < n; ++j) {
  4318. // const auto & token = tokens[j];
  4319. // const auto tt = token.pt > thold_pt && token.ptsum > 0.01 ? whisper_token_to_str(&ctx, token.tid) : "[?]";
  4320. // printf("%s: %10s %6.3f %6.3f %6.3f %6.3f %5d %5d '%s'\n", __func__,
  4321. // tt, token.p, token.pt, token.ptsum, token.vlen, (int) token.t0, (int) token.t1, whisper_token_to_str(&ctx, token.id));
  4322. // if (tokens[j].id >= whisper_token_eot(&ctx)) {
  4323. // continue;
  4324. // }
  4325. //}
  4326. }
  4327. void whisper_set_log_callback(whisper_log_callback callback) {
  4328. whisper_log = callback;
  4329. }