ml: split oversized Rust files under the 500-line limit
- Commit
9bb3a824f662837a51d0caa88e83b753cd3a48c2- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-01 20:25 UTC (4 days ago)
- Parents
169291c
logmel_extra.rs (1419), post/whisper.rs (505) and nets/mod.rs (503) exceeded the 500-line rustFileLength limit. logmel_extra: the two 512-entry generated reference arrays move into four half-array part files spliced into the same test module; the three call sites reassemble them with ref_tone()/ref_noise() helpers returning the identical values in the identical order. whisper: the test modules move verbatim to whisper_part1.rs. nets: the Kind enum (with its existing mod_part variant includes) moves verbatim to mod_kind.rs. No production code or public surface changes. Verified: cargo fmt -p modelrunner -- --check clean and cargo test -p modelrunner --locked green (871 passed).
Diff
library/ml/src/main/rust/src/logmel_extra.rs
diff --git a/library/ml/src/main/rust/src/logmel_extra.rs b/library/ml/src/main/rust/src/logmel_extra.rsindex d2a3c09fc0..b18915cd98 100644--- a/library/ml/src/main/rust/src/logmel_extra.rs+++ b/library/ml/src/main/rust/src/logmel_extra.rs@@ -157,1036 +157,12 @@ mod tests { const REF_TONE_PEAKS: [(f32, usize); 2] = [(440.0, 24), (3000.0, 84)]; const REF_TONE_ROWS: [usize; 4] = [0, 1, 24, 48];- const REF_TONE: [f32; 512] = [- -6.90775528,- 0.115827199,- -1.06805375,- -0.0724676845,- -0.579895123,- -0.149364395,- -0.424133554,- -0.0588712061,- -0.428997638,- 0.147787389,- -0.642566798,- 0.409517059,- -0.868085589,- 0.593130053,- -0.183939812,- 0.34937896,- 0.562275919,- 0.0398005584,- 1.02395619,- 0.999261697,- 0.914881349,- 1.95192199,- 1.67790951,- 1.69352427,- 2.14447997,- 1.94184339,- 1.62844189,- 1.52479659,- 1.42117224,- 0.74515439,- 0.394147496,- 0.260734278,- 0.178749723,- 0.0674562358,- -0.0150409755,- -0.256665607,- -0.334908578,- -0.435699747,- -0.520541992,- -0.589211344,- -0.66819431,- -0.750326441,- -0.815489239,- -0.883209669,- -0.956651697,- -1.01698204,- -1.07886302,- -1.14543634,- -1.13696147,- -1.20969287,- -1.31822,- -1.36944691,- -1.42619708,- -1.36606606,- -1.48341503,- -1.58692714,- -1.55163227,- -1.57785272,- -1.73619893,- -1.61648144,- -1.7938643,- -1.74851742,- -1.83480949,- -1.82771636,- -1.93152539,- -1.86072234,- -2.01453578,- -1.96488454,- -2.00926571,- -2.08384392,- -2.10392157,- -2.07873197,- -2.15758267,- -2.19004352,- -2.21475497,- -2.24153389,- -2.26783785,- -2.29451349,- -2.32237855,- -2.35181284,- -2.38151641,- -2.40997411,- -2.40428144,- -2.4524257,- -2.49143255,- -2.49515089,- -2.51192471,- -2.57442439,- -2.53519116,- -2.61393293,- -2.5913303,- -2.63230757,- -2.66188279,- -2.66104912,- -2.68091736,- -2.71299548,- -2.72909053,- -2.74445454,- -2.75889241,- -2.77404933,- -2.78855932,- -2.79292525,- -2.80988817,- -2.83484042,- -2.83490985,- -2.85288264,- -2.85863856,- -2.8844114,- -2.87086295,- -2.89247025,- -2.89615177,- -2.89963932,- -2.90695398,- -2.91304301,- -2.9124707,- -2.91660401,- -2.91565386,- -2.91360068,- -2.92245588,- -2.90633718,- -2.90850119,- -2.9073133,- -2.89970452,- -2.88150091,- -2.87202889,- -2.86415029,- -2.853362,- -2.84045739,- -6.90775528,- -4.65611132,- -5.62751148,- -4.5591449,- -5.00596243,- -5.5100319,- -5.70980346,- -4.24566536,- -4.58543404,- -3.82250231,- -4.56020615,- -4.70522507,- -4.77003484,- -2.64922969,- -3.57746049,- -3.05855604,- -2.47976547,- -2.49894849,- -0.912939311,- -1.84327256,- -1.02851594,- 1.70733085,- 2.13949372,- 2.2225578,- 2.83419559,- 2.50478316,- 1.91048069,- 1.44675972,- -0.34279279,- -0.874517245,- -2.03942984,- -2.76091039,- -2.48075038,- -2.7853359,- -4.69180295,- -3.43929625,- -3.98041825,- -4.41029802,- -4.29839117,- -4.67756535,- -5.06616811,- -4.79163073,- -5.29869545,- -5.44900782,- -5.29334276,- -5.69860867,- -5.50009208,- -5.98632057,- -5.75970969,- -5.84671191,- -6.27880693,- -5.98457004,- -6.20975043,- -6.07110791,- -6.4370089,- -6.2359509,- -6.51350736,- -6.30297615,- -6.56992109,- -6.40081456,- -6.65377476,- -6.46026562,- -6.61139045,- -6.54663581,- -6.63051666,- -6.55011453,- -6.57727284,- -6.73777063,- -6.66740709,- -6.67554278,- -6.65441085,- -6.63014329,- -6.73774554,- -6.7546344,- -6.74631943,- -6.72924573,- -6.75748402,- -6.7220948,- -6.73905053,- -6.72265757,- -6.76001633,- -6.80378287,- -6.73752404,- -6.63060642,- -6.58241795,- -6.65284146,- -6.59562971,- -6.59617064,- -6.63020131,- -6.70710833,- -6.74550524,- -6.66915066,- -6.57474808,- -6.68339872,- -6.5673124,- -6.54983683,- -6.71811914,- -6.79949987,- -6.70218286,- -6.70691925,- -6.6384433,- -6.62030962,- -6.71844089,- -6.67216013,- -6.53747239,- -6.70122882,- -6.45529997,- -6.48885351,- -6.55622319,- -6.71100603,- -6.87667325,- -6.8001267,- -6.63361946,- -6.64282407,- -6.65873675,- -6.63061303,- -6.72918397,- -6.68290798,- -6.78946612,- -6.8554214,- -6.71872078,- -6.58337544,- -6.51836034,- -6.5185381,- -6.56079497,- -6.66141415,- -6.59964943,- -6.73885207,- -6.90775528,- -4.65611132,- -5.62751148,- -4.5591449,- -5.00596243,- -5.5100319,- -5.70980346,- -4.24566536,- -4.58543404,- -3.82250231,- -4.56020615,- -4.70522507,- -4.77003484,- -2.64922969,- -3.57746049,- -3.05855604,- -2.47976547,- -2.49894849,- -0.912939311,- -1.84327256,- -1.02851594,- 1.70733085,- 2.13949372,- 2.2225578,- 2.83419559,- 2.50478316,- 1.91048069,- 1.44675972,- -0.34279279,- -0.874517245,- -2.03942984,- -2.76091039,- -2.48075038,- -2.7853359,- -4.69180295,- -3.43929625,- -3.98041825,- -4.41029802,- -4.29839117,- -4.67756535,- -5.06616811,- -4.79163073,- -5.29869545,- -5.44900782,- -5.29334276,- -5.69860867,- -5.50009208,- -5.98632057,- -5.75970969,- -5.84671191,- -6.27880693,- -5.98457004,- -6.20975043,- -6.07110791,- -6.4370089,- -6.2359509,- -6.51350736,- -6.30297615,- -6.56992109,- -6.40081456,- -6.65377476,- -6.46026562,- -6.61139045,- -6.54663581,- -6.63051666,- -6.55011453,- -6.57727284,- -6.73777063,- -6.66740709,- -6.67554278,- -6.65441085,- -6.63014329,- -6.73774554,- -6.7546344,- -6.74631943,- -6.72924573,- -6.75748402,- -6.7220948,- -6.73905053,- -6.72265757,- -6.76001633,- -6.80378287,- -6.73752404,- -6.63060642,- -6.58241795,- -6.65284146,- -6.59562971,- -6.59617064,- -6.63020131,- -6.70710833,- -6.74550524,- -6.66915066,- -6.57474808,- -6.68339872,- -6.5673124,- -6.54983683,- -6.71811914,- -6.79949987,- -6.70218286,- -6.70691925,- -6.6384433,- -6.62030962,- -6.71844089,- -6.67216013,- -6.53747239,- -6.70122882,- -6.45529997,- -6.48885351,- -6.55622319,- -6.71100603,- -6.87667325,- -6.8001267,- -6.63361946,- -6.64282407,- -6.65873675,- -6.63061303,- -6.72918397,- -6.68290798,- -6.78946612,- -6.8554214,- -6.71872078,- -6.58337544,- -6.51836034,- -6.5185381,- -6.56079497,- -6.66141415,- -6.59964943,- -6.73885207,- -6.90775528,- -5.43430991,- -6.20086499,- -4.62803009,- -5.07061493,- -5.13152463,- -5.35443793,- -4.43647034,- -4.76987631,- -3.78939909,- -4.52880651,- -5.11961842,- -4.85207485,- -2.67149517,- -3.55777431,- -3.03857705,- -2.50109228,- -2.50796896,- -0.913459768,- -1.83769021,- -1.02664702,- 1.70711166,- 2.1394735,- 2.2225655,- 2.83426269,- 2.5047514,- 1.91043715,- 1.44672776,- -0.341273456,- -0.874609093,- -2.04205802,- -2.76172443,- -2.47608344,- -2.78715955,- -4.6223419,- -3.43363688,- -3.98654568,- -4.38636953,- -4.28232112,- -4.6957205,- -5.06525589,- -4.77859238,- -5.28897561,- -5.40555845,- -5.29026167,- -5.64257055,- -5.47103912,- -6.07087758,- -5.7389326,- -5.81006153,- -6.18180225,- -6.00023735,- -6.21922259,- -6.01856939,- -6.52176237,- -6.22756894,- -6.43485284,- -6.29922816,- -6.501708,- -6.36634489,- -6.66667204,- -6.45177775,- -6.55811221,- -6.5906188,- -6.56682383,- -6.62064125,- -6.59443061,- -6.63285366,- -6.68491175,- -6.69541035,- -6.5974781,- -6.64739983,- -6.67687621,- -6.73910907,- -6.7578857,- -6.72785535,- -6.72309734,- -6.76123424,- -6.67039045,- -6.7320537,- -6.73594146,- -6.74778075,- -6.6890395,- -6.56922507,- -6.52279446,- -6.69970616,- -6.63538608,- -6.52795799,- -6.71534309,- -6.6620974,- -6.74572103,- -6.69865406,- -6.68634566,- -6.68879468,- -6.60756899,- -6.65205342,- -6.77496086,- -6.78324427,- -6.75474105,- -6.78491151,- -6.67778655,- -6.59274778,- -6.7075291,- -6.63448385,- -6.57934407,- -6.68796156,- -6.43142549,- -6.52693545,- -6.60821634,- -6.74302647,- -6.87290217,- -6.80890484,- -6.67827595,- -6.6603476,- -6.71498439,- -6.6608397,- -6.74891252,- -6.63900668,- -6.78401111,- -6.86265983,- -6.74454433,- -6.61858598,- -6.57601562,- -6.51464453,- -6.52192414,- -6.67624931,- -6.63910373,- -6.72816021,- ];+ include!("logmel_tone_parta.rs");+ include!("logmel_tone_partb.rs"); const REF_NOISE_ROWS: [usize; 4] = [0, 8, 15, 24];- const REF_NOISE: [f32; 512] = [- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- -6.90775528,- 1.10368136,- -0.0814687455,- 1.18202222,- 0.674086119,- 1.30129663,- 1.02624601,- 1.4524591,- 1.08196194,- 1.6379237,- 0.846763823,- 1.85114717,- 0.530636709,- 1.92044629,- 0.951061124,- 1.48471737,- 1.37009364,- 0.650846822,- 1.01417987,- 0.22201124,- 0.139279812,- 1.18808022,- 0.574680968,- 0.424914831,- 0.22058273,- 0.113414088,- 0.150786986,- 0.273043266,- 0.384116904,- 0.864815001,- 1.17220472,- 1.38234196,- 1.48726779,- 1.48036444,- 1.36981318,- 0.961658482,- 0.844450304,- 0.811346843,- 0.825339854,- 0.943593318,- 1.2384294,- 1.59435408,- 1.85768936,- 1.96375025,- 1.87575362,- 1.52852439,- 0.937431863,- 1.01648087,- 1.41454351,- 1.38462487,- 1.21851481,- 1.41491013,- 1.78540707,- 2.08907059,- 1.77041892,- 1.63332333,- 2.24898452,- 2.35208938,- 1.82497342,- 1.57739994,- 1.472043,- 1.16403082,- 1.25804223,- 2.10748137,- 2.17740656,- 2.31560231,- 2.13056412,- 2.0669558,- 1.62463526,- 1.48559566,- 1.80291051,- 1.65150581,- 1.2070903,- 1.72513116,- 2.1434589,- 2.12243146,- 1.86699741,- 1.80286593,- 2.24133256,- 2.28873325,- 2.43386085,- 2.47732807,- 2.11692482,- 1.86431426,- 2.26296959,- 2.49227331,- 2.53309138,- 2.07920803,- 1.91913626,- 2.49835249,- 2.25290271,- 2.86032799,- 2.86453007,- 2.60138521,- 2.43487509,- 2.04221069,- 2.24315863,- 2.70849792,- 2.90600308,- 2.5122749,- 2.04626767,- 2.12480033,- 2.87349127,- 3.18223522,- 2.76795935,- 3.17666739,- 2.59372021,- 2.72476791,- 2.72237905,- 2.90858874,- 3.32568608,- 3.13743899,- 2.87503886,- 3.12455491,- 2.84583319,- 2.98574442,- 2.77865769,- 2.82812897,- 3.23171531,- 2.42764119,- 2.89097404,- 3.80546637,- 3.72956156,- 2.46200432,- 2.69400862,- 3.34537222,- 3.68703694,- 3.47869273,- -6.90775528,- 0.944442284,- -0.240577768,- 0.707485446,- 0.199672627,- 0.950376262,- 0.67536187,- 1.45139987,- 1.08090281,- 1.82543814,- 1.03423818,- 2.02309156,- 0.648418319,- 1.92957094,- 0.723801306,- 1.25741677,- 0.785234708,- 0.177248691,- 0.950747631,- 1.07027545,- 0.96658239,- 1.84467192,- 1.2785895,- 1.17575768,- 1.21716859,- -0.568228925,- 0.283787541,- 0.704287979,- 1.28814448,- 1.46601122,- 1.53164587,- 1.65516025,- 1.75704134,- 1.88596485,- 1.79015978,- -0.232729794,- 1.34874015,- 1.66544841,- 1.68353777,- 1.82191276,- 1.84125591,- 1.44541715,- 1.66734955,- 2.1610481,- 1.98555211,- 0.963465872,- 0.712782743,- 1.23280785,- 1.09228866,- 1.31659001,- 2.03394253,- 2.16801097,- 1.91847052,- 1.83041111,- 1.92029882,- 1.57462854,- 1.20577947,- 1.90371749,- 2.20457276,- 2.0846581,- 0.98126909,- 1.47201995,- 0.923291883,- 1.61406793,- 1.9038384,- 1.90532967,- 0.852779096,- 1.95396745,- 2.95504988,- 2.56921351,- 1.86088402,- 2.17758421,- 1.52289866,- 1.64660618,- 1.56663085,- 1.7623093,- 2.67332155,- 2.26657505,- 1.20436693,- 2.28920396,- 2.04821167,- 1.20994831,- 1.9821323,- 2.39779743,- 2.22081177,- 3.10762213,- 3.52155513,- 3.11711862,- 2.14912058,- 2.3550525,- 2.74247214,- 2.35738456,- 2.13669781,- 2.46743167,- 2.51903451,- 2.83621559,- 2.8998643,- 2.74527928,- 2.51664694,- 2.68731401,- 3.39449417,- 3.088192,- 2.85220926,- 2.76926481,- 2.92501036,- 2.88903299,- 2.1410271,- 2.21367984,- 2.83281509,- 3.45324587,- 3.59365658,- 3.44009302,- 3.05991417,- 3.32672779,- 2.9884109,- 3.28850967,- 3.27938096,- 3.01106143,- 3.1954184,- 3.20814465,- 2.88880901,- 3.43842899,- 3.56019078,- 3.27743988,- 3.32378077,- 2.78003804,- 2.96784355,- 2.92626806,- -6.90775528,- -2.26631649,- -3.43053069,- -2.15721297,- -2.65964245,- -1.97505696,- -2.24791384,- -1.72195466,- -2.09004977,- -1.41681153,- -2.2032428,- -1.10317784,- -2.39653447,- -0.979414164,- -1.89243813,- -1.36137054,- -1.30048067,- -1.92092619,- -1.19552141,- -1.85291016,- -1.99138858,- -1.51244246,- -2.16368066,- -2.15524959,- -1.72651471,- -1.67229377,- -1.72528515,- -1.6050164,- -1.22832591,- -1.27990656,- -1.33675256,- -1.27773879,- -1.21123841,- -1.09113021,- -0.831334945,- -0.797652096,- -0.625521629,- -0.459714969,- -0.306204938,- -0.167639677,- -0.043781348,- 0.0675428575,- 0.169324755,- 0.264250146,- 0.353771875,- 0.437662502,- 0.51417416,- 0.580625603,- 0.703345605,- 0.732887108,- 0.701890286,- 0.693898148,- 0.663203598,- 0.718444668,- 0.56180894,- 0.396997334,- 0.341744625,- 0.222713103,- 0.00416862684,- 0.145333058,- 0.0583857485,- 0.223517597,- 0.242345051,- 0.323900959,- 0.251236721,- 0.307995468,- 0.0971015817,- 0.0541065972,- -0.121382175,- -0.322781969,- -0.434618284,- -0.430318174,- -0.390338684,- -0.170094731,- 0.106434164,- 0.354501114,- 0.554151242,- 0.727916742,- 0.899566575,- 1.05214408,- 1.1355343,- 1.09836048,- 0.923068107,- 0.54951349,- 0.45663018,- 0.743732003,- 0.914747991,- 0.900887774,- 0.997810383,- 1.05480506,- 1.18897317,- 1.16634209,- 1.1076565,- 1.1406831,- 1.23330539,- 1.28007508,- 1.23651587,- 1.11211923,- 1.00977277,- 1.05343845,- 1.19540931,- 1.22296633,- 0.862892132,- -0.0284080496,- 0.729135883,- 1.22668576,- 1.23423492,- 0.930077611,- 0.437421798,- 0.160740667,- 0.704537754,- 1.10118228,- 1.2987806,- 1.49952509,- 1.70381572,- 1.69405181,- 1.87872772,- 2.25066366,- 2.23662378,- 1.73064319,- 0.890180346,- 1.02435653,- 1.37649953,- 1.57099457,- 1.63290953,- 1.52072455,- 1.41955117,- 1.60426133,- ];+ include!("logmel_noise_parta.rs");+ include!("logmel_noise_partb.rs"); /// between the two `sin`s cannot reach the comparison. fn tone(count: usize, hz: f64, amplitude: f64) -> Vec<f32> {@@ -1218,6 +194,16 @@ mod tests { .collect() } + /// The 512 reference values, reassembled from their two halves.+ fn ref_tone() -> Vec<f32> {+ REF_TONE_A.iter().chain(REF_TONE_B.iter()).copied().collect()+ }++ /// The 512 reference values, reassembled from their two halves.+ fn ref_noise() -> Vec<f32> {+ REF_NOISE_A.iter().chain(REF_NOISE_B.iter()).copied().collect()+ }+ fn run(waveform: &[f32]) -> Vec<f32> { let mut out = Vec::new(); let frames = LogMel::new().spectrogram(waveform, &mut out);@@ -1375,11 +361,13 @@ mod tests { // comes in lower. As of writing: 7.60e-4 of log, at the tone's channel 111, where the // reference is -6.800 and the mel value behind it is 1.1e-4; and 2.24e-7 of the frame // peak, at the tone's own peak channel, which is under two ulps of f32.+ let ref_tone = ref_tone();+ let ref_noise = ref_noise(); let mut worst = (0.0f32, "", 0usize, 0usize, 0.0f32); let mut worst_mel = (0.0f32, "", 0usize, 0usize, 0.0f32); for (case, waveform, rows, want) in [- ("tone", tone(8000, 440.0, 8192.0), REF_TONE_ROWS.as_slice(), REF_TONE.as_slice()),- ("noise", noise_burst(5000), REF_NOISE_ROWS.as_slice(), REF_NOISE.as_slice()),+ ("tone", tone(8000, 440.0, 8192.0), REF_TONE_ROWS.as_slice(), ref_tone.as_slice()),+ ("noise", noise_burst(5000), REF_NOISE_ROWS.as_slice(), ref_noise.as_slice()), ] { let frames = run(&waveform); for (probe, row) in rows.iter().enumerate() {@@ -1404,10 +392,12 @@ mod tests { #[test] fn the_reference_signals_exercise_the_range_rather_than_the_floor() {+ let ref_tone = ref_tone();+ let ref_noise = ref_noise(); // A comparison of two floors passes while measuring nothing. The tone is spectrally // sparse on purpose, so most of its 128 channels *are* at the floor and the bar is that // enough of them are not; the noise burst has to be almost entirely above it.- for (want, above) in [(REF_TONE.as_slice(), 100), (REF_NOISE.as_slice(), 300)] {+ for (want, above) in [(ref_tone.as_slice(), 100), (ref_noise.as_slice(), 300)] { let low = want.iter().copied().fold(f32::INFINITY, f32::min); let high = want.iter().copied().fold(f32::NEG_INFINITY, f32::max); assert_eq!(low, MEL_FLOOR.ln(), "the empty channel should sit at the floor");
library/ml/src/main/rust/src/logmel_noise_parta.rs
diff --git a/library/ml/src/main/rust/src/logmel_noise_parta.rs b/library/ml/src/main/rust/src/logmel_noise_parta.rsnew file mode 100644index 0000000000..d1d199fb22--- /dev/null+++ b/library/ml/src/main/rust/src/logmel_noise_parta.rs@@ -0,0 +1,258 @@+ const REF_NOISE_A: [f32; 256] = [+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ -6.90775528,+ 1.10368136,+ -0.0814687455,+ 1.18202222,+ 0.674086119,+ 1.30129663,+ 1.02624601,+ 1.4524591,+ 1.08196194,+ 1.6379237,+ 0.846763823,+ 1.85114717,+ 0.530636709,+ 1.92044629,+ 0.951061124,+ 1.48471737,+ 1.37009364,+ 0.650846822,+ 1.01417987,+ 0.22201124,+ 0.139279812,+ 1.18808022,+ 0.574680968,+ 0.424914831,+ 0.22058273,+ 0.113414088,+ 0.150786986,+ 0.273043266,+ 0.384116904,+ 0.864815001,+ 1.17220472,+ 1.38234196,+ 1.48726779,+ 1.48036444,+ 1.36981318,+ 0.961658482,+ 0.844450304,+ 0.811346843,+ 0.825339854,+ 0.943593318,+ 1.2384294,+ 1.59435408,+ 1.85768936,+ 1.96375025,+ 1.87575362,+ 1.52852439,+ 0.937431863,+ 1.01648087,+ 1.41454351,+ 1.38462487,+ 1.21851481,+ 1.41491013,+ 1.78540707,+ 2.08907059,+ 1.77041892,+ 1.63332333,+ 2.24898452,+ 2.35208938,+ 1.82497342,+ 1.57739994,+ 1.472043,+ 1.16403082,+ 1.25804223,+ 2.10748137,+ 2.17740656,+ 2.31560231,+ 2.13056412,+ 2.0669558,+ 1.62463526,+ 1.48559566,+ 1.80291051,+ 1.65150581,+ 1.2070903,+ 1.72513116,+ 2.1434589,+ 2.12243146,+ 1.86699741,+ 1.80286593,+ 2.24133256,+ 2.28873325,+ 2.43386085,+ 2.47732807,+ 2.11692482,+ 1.86431426,+ 2.26296959,+ 2.49227331,+ 2.53309138,+ 2.07920803,+ 1.91913626,+ 2.49835249,+ 2.25290271,+ 2.86032799,+ 2.86453007,+ 2.60138521,+ 2.43487509,+ 2.04221069,+ 2.24315863,+ 2.70849792,+ 2.90600308,+ 2.5122749,+ 2.04626767,+ 2.12480033,+ 2.87349127,+ 3.18223522,+ 2.76795935,+ 3.17666739,+ 2.59372021,+ 2.72476791,+ 2.72237905,+ 2.90858874,+ 3.32568608,+ 3.13743899,+ 2.87503886,+ 3.12455491,+ 2.84583319,+ 2.98574442,+ 2.77865769,+ 2.82812897,+ 3.23171531,+ 2.42764119,+ 2.89097404,+ 3.80546637,+ 3.72956156,+ 2.46200432,+ 2.69400862,+ 3.34537222,+ 3.68703694,+ 3.47869273,+ ];
library/ml/src/main/rust/src/logmel_noise_partb.rs
diff --git a/library/ml/src/main/rust/src/logmel_noise_partb.rs b/library/ml/src/main/rust/src/logmel_noise_partb.rsnew file mode 100644index 0000000000..9cd6ccdcdc--- /dev/null+++ b/library/ml/src/main/rust/src/logmel_noise_partb.rs@@ -0,0 +1,258 @@+ const REF_NOISE_B: [f32; 256] = [+ -6.90775528,+ 0.944442284,+ -0.240577768,+ 0.707485446,+ 0.199672627,+ 0.950376262,+ 0.67536187,+ 1.45139987,+ 1.08090281,+ 1.82543814,+ 1.03423818,+ 2.02309156,+ 0.648418319,+ 1.92957094,+ 0.723801306,+ 1.25741677,+ 0.785234708,+ 0.177248691,+ 0.950747631,+ 1.07027545,+ 0.96658239,+ 1.84467192,+ 1.2785895,+ 1.17575768,+ 1.21716859,+ -0.568228925,+ 0.283787541,+ 0.704287979,+ 1.28814448,+ 1.46601122,+ 1.53164587,+ 1.65516025,+ 1.75704134,+ 1.88596485,+ 1.79015978,+ -0.232729794,+ 1.34874015,+ 1.66544841,+ 1.68353777,+ 1.82191276,+ 1.84125591,+ 1.44541715,+ 1.66734955,+ 2.1610481,+ 1.98555211,+ 0.963465872,+ 0.712782743,+ 1.23280785,+ 1.09228866,+ 1.31659001,+ 2.03394253,+ 2.16801097,+ 1.91847052,+ 1.83041111,+ 1.92029882,+ 1.57462854,+ 1.20577947,+ 1.90371749,+ 2.20457276,+ 2.0846581,+ 0.98126909,+ 1.47201995,+ 0.923291883,+ 1.61406793,+ 1.9038384,+ 1.90532967,+ 0.852779096,+ 1.95396745,+ 2.95504988,+ 2.56921351,+ 1.86088402,+ 2.17758421,+ 1.52289866,+ 1.64660618,+ 1.56663085,+ 1.7623093,+ 2.67332155,+ 2.26657505,+ 1.20436693,+ 2.28920396,+ 2.04821167,+ 1.20994831,+ 1.9821323,+ 2.39779743,+ 2.22081177,+ 3.10762213,+ 3.52155513,+ 3.11711862,+ 2.14912058,+ 2.3550525,+ 2.74247214,+ 2.35738456,+ 2.13669781,+ 2.46743167,+ 2.51903451,+ 2.83621559,+ 2.8998643,+ 2.74527928,+ 2.51664694,+ 2.68731401,+ 3.39449417,+ 3.088192,+ 2.85220926,+ 2.76926481,+ 2.92501036,+ 2.88903299,+ 2.1410271,+ 2.21367984,+ 2.83281509,+ 3.45324587,+ 3.59365658,+ 3.44009302,+ 3.05991417,+ 3.32672779,+ 2.9884109,+ 3.28850967,+ 3.27938096,+ 3.01106143,+ 3.1954184,+ 3.20814465,+ 2.88880901,+ 3.43842899,+ 3.56019078,+ 3.27743988,+ 3.32378077,+ 2.78003804,+ 2.96784355,+ 2.92626806,+ -6.90775528,+ -2.26631649,+ -3.43053069,+ -2.15721297,+ -2.65964245,+ -1.97505696,+ -2.24791384,+ -1.72195466,+ -2.09004977,+ -1.41681153,+ -2.2032428,+ -1.10317784,+ -2.39653447,+ -0.979414164,+ -1.89243813,+ -1.36137054,+ -1.30048067,+ -1.92092619,+ -1.19552141,+ -1.85291016,+ -1.99138858,+ -1.51244246,+ -2.16368066,+ -2.15524959,+ -1.72651471,+ -1.67229377,+ -1.72528515,+ -1.6050164,+ -1.22832591,+ -1.27990656,+ -1.33675256,+ -1.27773879,+ -1.21123841,+ -1.09113021,+ -0.831334945,+ -0.797652096,+ -0.625521629,+ -0.459714969,+ -0.306204938,+ -0.167639677,+ -0.043781348,+ 0.0675428575,+ 0.169324755,+ 0.264250146,+ 0.353771875,+ 0.437662502,+ 0.51417416,+ 0.580625603,+ 0.703345605,+ 0.732887108,+ 0.701890286,+ 0.693898148,+ 0.663203598,+ 0.718444668,+ 0.56180894,+ 0.396997334,+ 0.341744625,+ 0.222713103,+ 0.00416862684,+ 0.145333058,+ 0.0583857485,+ 0.223517597,+ 0.242345051,+ 0.323900959,+ 0.251236721,+ 0.307995468,+ 0.0971015817,+ 0.0541065972,+ -0.121382175,+ -0.322781969,+ -0.434618284,+ -0.430318174,+ -0.390338684,+ -0.170094731,+ 0.106434164,+ 0.354501114,+ 0.554151242,+ 0.727916742,+ 0.899566575,+ 1.05214408,+ 1.1355343,+ 1.09836048,+ 0.923068107,+ 0.54951349,+ 0.45663018,+ 0.743732003,+ 0.914747991,+ 0.900887774,+ 0.997810383,+ 1.05480506,+ 1.18897317,+ 1.16634209,+ 1.1076565,+ 1.1406831,+ 1.23330539,+ 1.28007508,+ 1.23651587,+ 1.11211923,+ 1.00977277,+ 1.05343845,+ 1.19540931,+ 1.22296633,+ 0.862892132,+ -0.0284080496,+ 0.729135883,+ 1.22668576,+ 1.23423492,+ 0.930077611,+ 0.437421798,+ 0.160740667,+ 0.704537754,+ 1.10118228,+ 1.2987806,+ 1.49952509,+ 1.70381572,+ 1.69405181,+ 1.87872772,+ 2.25066366,+ 2.23662378,+ 1.73064319,+ 0.890180346,+ 1.02435653,+ 1.37649953,+ 1.57099457,+ 1.63290953,+ 1.52072455,+ 1.41955117,+ 1.60426133,+ ];
library/ml/src/main/rust/src/logmel_tone_parta.rs
diff --git a/library/ml/src/main/rust/src/logmel_tone_parta.rs b/library/ml/src/main/rust/src/logmel_tone_parta.rsnew file mode 100644index 0000000000..c406b873f8--- /dev/null+++ b/library/ml/src/main/rust/src/logmel_tone_parta.rs@@ -0,0 +1,258 @@+ const REF_TONE_A: [f32; 256] = [+ -6.90775528,+ 0.115827199,+ -1.06805375,+ -0.0724676845,+ -0.579895123,+ -0.149364395,+ -0.424133554,+ -0.0588712061,+ -0.428997638,+ 0.147787389,+ -0.642566798,+ 0.409517059,+ -0.868085589,+ 0.593130053,+ -0.183939812,+ 0.34937896,+ 0.562275919,+ 0.0398005584,+ 1.02395619,+ 0.999261697,+ 0.914881349,+ 1.95192199,+ 1.67790951,+ 1.69352427,+ 2.14447997,+ 1.94184339,+ 1.62844189,+ 1.52479659,+ 1.42117224,+ 0.74515439,+ 0.394147496,+ 0.260734278,+ 0.178749723,+ 0.0674562358,+ -0.0150409755,+ -0.256665607,+ -0.334908578,+ -0.435699747,+ -0.520541992,+ -0.589211344,+ -0.66819431,+ -0.750326441,+ -0.815489239,+ -0.883209669,+ -0.956651697,+ -1.01698204,+ -1.07886302,+ -1.14543634,+ -1.13696147,+ -1.20969287,+ -1.31822,+ -1.36944691,+ -1.42619708,+ -1.36606606,+ -1.48341503,+ -1.58692714,+ -1.55163227,+ -1.57785272,+ -1.73619893,+ -1.61648144,+ -1.7938643,+ -1.74851742,+ -1.83480949,+ -1.82771636,+ -1.93152539,+ -1.86072234,+ -2.01453578,+ -1.96488454,+ -2.00926571,+ -2.08384392,+ -2.10392157,+ -2.07873197,+ -2.15758267,+ -2.19004352,+ -2.21475497,+ -2.24153389,+ -2.26783785,+ -2.29451349,+ -2.32237855,+ -2.35181284,+ -2.38151641,+ -2.40997411,+ -2.40428144,+ -2.4524257,+ -2.49143255,+ -2.49515089,+ -2.51192471,+ -2.57442439,+ -2.53519116,+ -2.61393293,+ -2.5913303,+ -2.63230757,+ -2.66188279,+ -2.66104912,+ -2.68091736,+ -2.71299548,+ -2.72909053,+ -2.74445454,+ -2.75889241,+ -2.77404933,+ -2.78855932,+ -2.79292525,+ -2.80988817,+ -2.83484042,+ -2.83490985,+ -2.85288264,+ -2.85863856,+ -2.8844114,+ -2.87086295,+ -2.89247025,+ -2.89615177,+ -2.89963932,+ -2.90695398,+ -2.91304301,+ -2.9124707,+ -2.91660401,+ -2.91565386,+ -2.91360068,+ -2.92245588,+ -2.90633718,+ -2.90850119,+ -2.9073133,+ -2.89970452,+ -2.88150091,+ -2.87202889,+ -2.86415029,+ -2.853362,+ -2.84045739,+ -6.90775528,+ -4.65611132,+ -5.62751148,+ -4.5591449,+ -5.00596243,+ -5.5100319,+ -5.70980346,+ -4.24566536,+ -4.58543404,+ -3.82250231,+ -4.56020615,+ -4.70522507,+ -4.77003484,+ -2.64922969,+ -3.57746049,+ -3.05855604,+ -2.47976547,+ -2.49894849,+ -0.912939311,+ -1.84327256,+ -1.02851594,+ 1.70733085,+ 2.13949372,+ 2.2225578,+ 2.83419559,+ 2.50478316,+ 1.91048069,+ 1.44675972,+ -0.34279279,+ -0.874517245,+ -2.03942984,+ -2.76091039,+ -2.48075038,+ -2.7853359,+ -4.69180295,+ -3.43929625,+ -3.98041825,+ -4.41029802,+ -4.29839117,+ -4.67756535,+ -5.06616811,+ -4.79163073,+ -5.29869545,+ -5.44900782,+ -5.29334276,+ -5.69860867,+ -5.50009208,+ -5.98632057,+ -5.75970969,+ -5.84671191,+ -6.27880693,+ -5.98457004,+ -6.20975043,+ -6.07110791,+ -6.4370089,+ -6.2359509,+ -6.51350736,+ -6.30297615,+ -6.56992109,+ -6.40081456,+ -6.65377476,+ -6.46026562,+ -6.61139045,+ -6.54663581,+ -6.63051666,+ -6.55011453,+ -6.57727284,+ -6.73777063,+ -6.66740709,+ -6.67554278,+ -6.65441085,+ -6.63014329,+ -6.73774554,+ -6.7546344,+ -6.74631943,+ -6.72924573,+ -6.75748402,+ -6.7220948,+ -6.73905053,+ -6.72265757,+ -6.76001633,+ -6.80378287,+ -6.73752404,+ -6.63060642,+ -6.58241795,+ -6.65284146,+ -6.59562971,+ -6.59617064,+ -6.63020131,+ -6.70710833,+ -6.74550524,+ -6.66915066,+ -6.57474808,+ -6.68339872,+ -6.5673124,+ -6.54983683,+ -6.71811914,+ -6.79949987,+ -6.70218286,+ -6.70691925,+ -6.6384433,+ -6.62030962,+ -6.71844089,+ -6.67216013,+ -6.53747239,+ -6.70122882,+ -6.45529997,+ -6.48885351,+ -6.55622319,+ -6.71100603,+ -6.87667325,+ -6.8001267,+ -6.63361946,+ -6.64282407,+ -6.65873675,+ -6.63061303,+ -6.72918397,+ -6.68290798,+ -6.78946612,+ -6.8554214,+ -6.71872078,+ -6.58337544,+ -6.51836034,+ -6.5185381,+ -6.56079497,+ -6.66141415,+ -6.59964943,+ -6.73885207,+ ];
library/ml/src/main/rust/src/logmel_tone_partb.rs
diff --git a/library/ml/src/main/rust/src/logmel_tone_partb.rs b/library/ml/src/main/rust/src/logmel_tone_partb.rsnew file mode 100644index 0000000000..ef8c9008f7--- /dev/null+++ b/library/ml/src/main/rust/src/logmel_tone_partb.rs@@ -0,0 +1,258 @@+ const REF_TONE_B: [f32; 256] = [+ -6.90775528,+ -4.65611132,+ -5.62751148,+ -4.5591449,+ -5.00596243,+ -5.5100319,+ -5.70980346,+ -4.24566536,+ -4.58543404,+ -3.82250231,+ -4.56020615,+ -4.70522507,+ -4.77003484,+ -2.64922969,+ -3.57746049,+ -3.05855604,+ -2.47976547,+ -2.49894849,+ -0.912939311,+ -1.84327256,+ -1.02851594,+ 1.70733085,+ 2.13949372,+ 2.2225578,+ 2.83419559,+ 2.50478316,+ 1.91048069,+ 1.44675972,+ -0.34279279,+ -0.874517245,+ -2.03942984,+ -2.76091039,+ -2.48075038,+ -2.7853359,+ -4.69180295,+ -3.43929625,+ -3.98041825,+ -4.41029802,+ -4.29839117,+ -4.67756535,+ -5.06616811,+ -4.79163073,+ -5.29869545,+ -5.44900782,+ -5.29334276,+ -5.69860867,+ -5.50009208,+ -5.98632057,+ -5.75970969,+ -5.84671191,+ -6.27880693,+ -5.98457004,+ -6.20975043,+ -6.07110791,+ -6.4370089,+ -6.2359509,+ -6.51350736,+ -6.30297615,+ -6.56992109,+ -6.40081456,+ -6.65377476,+ -6.46026562,+ -6.61139045,+ -6.54663581,+ -6.63051666,+ -6.55011453,+ -6.57727284,+ -6.73777063,+ -6.66740709,+ -6.67554278,+ -6.65441085,+ -6.63014329,+ -6.73774554,+ -6.7546344,+ -6.74631943,+ -6.72924573,+ -6.75748402,+ -6.7220948,+ -6.73905053,+ -6.72265757,+ -6.76001633,+ -6.80378287,+ -6.73752404,+ -6.63060642,+ -6.58241795,+ -6.65284146,+ -6.59562971,+ -6.59617064,+ -6.63020131,+ -6.70710833,+ -6.74550524,+ -6.66915066,+ -6.57474808,+ -6.68339872,+ -6.5673124,+ -6.54983683,+ -6.71811914,+ -6.79949987,+ -6.70218286,+ -6.70691925,+ -6.6384433,+ -6.62030962,+ -6.71844089,+ -6.67216013,+ -6.53747239,+ -6.70122882,+ -6.45529997,+ -6.48885351,+ -6.55622319,+ -6.71100603,+ -6.87667325,+ -6.8001267,+ -6.63361946,+ -6.64282407,+ -6.65873675,+ -6.63061303,+ -6.72918397,+ -6.68290798,+ -6.78946612,+ -6.8554214,+ -6.71872078,+ -6.58337544,+ -6.51836034,+ -6.5185381,+ -6.56079497,+ -6.66141415,+ -6.59964943,+ -6.73885207,+ -6.90775528,+ -5.43430991,+ -6.20086499,+ -4.62803009,+ -5.07061493,+ -5.13152463,+ -5.35443793,+ -4.43647034,+ -4.76987631,+ -3.78939909,+ -4.52880651,+ -5.11961842,+ -4.85207485,+ -2.67149517,+ -3.55777431,+ -3.03857705,+ -2.50109228,+ -2.50796896,+ -0.913459768,+ -1.83769021,+ -1.02664702,+ 1.70711166,+ 2.1394735,+ 2.2225655,+ 2.83426269,+ 2.5047514,+ 1.91043715,+ 1.44672776,+ -0.341273456,+ -0.874609093,+ -2.04205802,+ -2.76172443,+ -2.47608344,+ -2.78715955,+ -4.6223419,+ -3.43363688,+ -3.98654568,+ -4.38636953,+ -4.28232112,+ -4.6957205,+ -5.06525589,+ -4.77859238,+ -5.28897561,+ -5.40555845,+ -5.29026167,+ -5.64257055,+ -5.47103912,+ -6.07087758,+ -5.7389326,+ -5.81006153,+ -6.18180225,+ -6.00023735,+ -6.21922259,+ -6.01856939,+ -6.52176237,+ -6.22756894,+ -6.43485284,+ -6.29922816,+ -6.501708,+ -6.36634489,+ -6.66667204,+ -6.45177775,+ -6.55811221,+ -6.5906188,+ -6.56682383,+ -6.62064125,+ -6.59443061,+ -6.63285366,+ -6.68491175,+ -6.69541035,+ -6.5974781,+ -6.64739983,+ -6.67687621,+ -6.73910907,+ -6.7578857,+ -6.72785535,+ -6.72309734,+ -6.76123424,+ -6.67039045,+ -6.7320537,+ -6.73594146,+ -6.74778075,+ -6.6890395,+ -6.56922507,+ -6.52279446,+ -6.69970616,+ -6.63538608,+ -6.52795799,+ -6.71534309,+ -6.6620974,+ -6.74572103,+ -6.69865406,+ -6.68634566,+ -6.68879468,+ -6.60756899,+ -6.65205342,+ -6.77496086,+ -6.78324427,+ -6.75474105,+ -6.78491151,+ -6.67778655,+ -6.59274778,+ -6.7075291,+ -6.63448385,+ -6.57934407,+ -6.68796156,+ -6.43142549,+ -6.52693545,+ -6.60821634,+ -6.74302647,+ -6.87290217,+ -6.80890484,+ -6.67827595,+ -6.6603476,+ -6.71498439,+ -6.6608397,+ -6.74891252,+ -6.63900668,+ -6.78401111,+ -6.86265983,+ -6.74454433,+ -6.61858598,+ -6.57601562,+ -6.51464453,+ -6.52192414,+ -6.67624931,+ -6.63910373,+ -6.72816021,+ ];
library/ml/src/main/rust/src/nets/mod.rs
diff --git a/library/ml/src/main/rust/src/nets/mod.rs b/library/ml/src/main/rust/src/nets/mod.rsindex 6d5afdec27..b9c8eb28aa 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -151,350 +151,7 @@ pub enum Act { } /// Which compute pipeline an [`Op::Dispatch`] wants.-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub enum Kind {- /// Dense, grouped or dilated convolution with a fused activation.- Conv,- /// Transposed convolution. One use, in the selfie net's 2x upsample to 256x256.- ConvTranspose,- /// Max pooling.- MaxPool,- /// Average pooling over an explicit window, floored and unpadded.- ///- /// One use: the pool that turns PP-OCRv5 recognition's `[480, 3, 80]` feature map- /// into the `[480, 1, 40]` sequence its transformer reads, with kernel and stride- /// both `(3, 2)`. The asymmetric window is the reason this carries `kh`/`kw` rather- /// than one size, and the reason it is not [`Kind::GlobalAvgPool`] with a flag — that- /// one reduces all of H and W to a single value and needs no window arithmetic.- AvgPool,- /// Bilinear resize, `half_pixel` coordinates.- Resize,- /// Nearest-neighbour resize, `asymmetric` coordinates and `floor` rounding.- ///- /// SCRFD's feature-pyramid upsamples are `mode=nearest`, which is a different- /// pipeline rather than a flag on [`Kind::Resize`] because the two share no- /// arithmetic: `src = floor(dst * in / out)` against `(dst + 0.5) * in / out - 0.5`.- /// Running an FPN through the bilinear one blurs every lateral it adds.- ResizeNearest,- /// Mean over H and W, keeping C. The squeeze in a squeeze-excite block.- GlobalAvgPool,- /// Elementwise sum of two equal shapes.- Add,- /// `a * b` where `b` is `C x 1 x 1`. The excite in a squeeze-excite block.- MulBroadcast,- /// `a + b` where `b` is `C x 1 x 1`. A per-channel shift.- ///- /// The mirror of [`Kind::MulBroadcast`], and used for one thing: the four timestep- /// conditioning layers of Supertonic's sampler, whose `Linear` from the time embedding the- /// host evaluates because it depends on two scalars. See `shaders/add_bcast.comp`.- AddBroadcast,- /// Elementwise `a * b` over two equal shapes.- Mul,- /// `x * scale + shift`, both scalars. PP-OCRv5's "learnable affine block".- ///- /// One pass over the data for two multiplies. It exists because these sit *after* an- /// activation, so unlike everything else constant in that export they cannot be- /// folded into the preceding convolution's weight.- ///- /// # Why they cannot all fold forward either- ///- /// Pushing one into the *following* convolution looks free: `conv(a * x + t)[m]` is- /// `a * conv(x)[m] + t * sum(W[m])`. That identity holds at an interior pixel and- /// **fails at a border one**, because a padded convolution reads zero outside the- /// input rather than `t`, so the constant's real contribution there is `t` times the- /// sum of only the in-bounds taps. The correction varies per output position, so it is- /// not a bias and there is no fold.- ///- /// `scripts/ml/ppocr_fold.py` therefore folds an affine only into an *unpadded*- /// convolution, which leaves 14 in detection and 16 in recognition — all of them- /// feeding either a padded depthwise or a squeeze-excite's two branches.- ///- /// Getting this wrong is invisible to every structural check: the layer table, the- /// tensor count and the digest are all unchanged, and only the weight *values* differ.- /// `scripts/ml/onnx_parity.py` is what caught it.- Affine,- /// Layer normalisation **over the channel axis**, with a per-channel affine.- ///- /// # Why over channels- ///- /// PP-OCRv5's recogniser is a CNN feeding a small transformer — `d_model` 120, 8- /// heads, two blocks — and this runtime keeps its sequences in the layout the CNN- /// already produces: `[d_model, 1, T]`, features in channels and the sequence along- /// the width. Two things fall out of that and neither is an accident:- ///- /// * **Every linear projection is a 1x1 convolution.** All five feed-forward `Gemm`s- /// and all six attention projections are already expressible, so they need no new- /// pipeline.- /// * **Splitting `d_model` into heads is free.** `[120, 1, T]` read as `[8, 15, T]`- /// is the same bytes in the same order, so there is no `Permute` and no `Reshape`- /// anywhere in the attention — the attention pipelines take the head count in- /// [`Push::group`] and index accordingly.- ///- /// The cost is that the reduction here is strided rather than contiguous. At- /// `d_model` 120 that is 120 loads a stride apart per position, which is nothing- /// against what a contiguous layout would cost in permutes.- LayerNorm,- /// Instance normalisation over the **spatial** axes, with no affine.- ///- /// [`Kind::LayerNorm`] transposed: where that one reduces `C` strided values per- /// position, this reduces one channel's contiguous `H x W` plane — so one- /// invocation per channel, and the whole pass is contiguous reads. Sixteen uses,- /// all MODNet's `IBNorm` second halves (`InstanceNorm2d(affine=False)`), each- /// over one [`Builder::slice_channels`] half rejoined by [`Builder::concat`].- ///- /// No gamma/beta: the export's scale and bias are constant 1 and 0 (verified- /// by `scripts/ml/modnet_fold.py`, which rejects anything else), so there are- /// no weight reads at all — epsilon rides [`Push::param1_bits`] like the other- /// norms'. The batch-norm halves of those same `IBNorm`s are folded into their- /// convolutions by the fold script instead, which is why this is the only new- /// pipeline MODNet needs.- InstanceNorm,- /// Root-mean-square normalisation over the channel axis, with a per-channel gain.- ///- /// [`Kind::LayerNorm`] without the mean subtraction and without beta:- /// `x / sqrt(mean(x^2) + eps) * gamma`. Sixteen uses, all Maia3's `norm1` / `norm2`.- ///- /// Separate from [`Kind::LayerNorm`] rather than a flag on it because the difference- /// is also a difference in *weights read* — one rank-1 tensor rather than two — and- /// [`Kind::weight_reads`] is what `vulkan::segment` uses to decide which slice of the- /// `.maml` a pass has to have resident. A flag would make that arm depend on the push- /// block's contents rather than its kind.- RmsNorm,- /// `S[h][i][j] = scale * sum_d Q[h][d][i] * K[h][d][j]`, attention's score map.- ///- /// Contracts over the *middle* axis of `[heads, head_dim, T]`, which is what makes- /// the head split free — see [`Kind::LayerNorm`]. Takes the head count in- /// [`Push::group`] and `1 / sqrt(head_dim)` in [`Push::param0_bits`].- ///- /// The output is `[heads, T, T]` with the key index innermost, so the row a- /// [`Kind::Softmax`] normalises is contiguous.- AttnScores,- /// Softmax over the last axis, one row at a time.- ///- /// Kept separate from [`Kind::AttnScores`] rather than fused into it. Fusing would- /// save writing a `heads * T * T` intermediate — 100 KiB at the recogniser's sizes,- /// which is not a cost worth a shader that does two things — and would give up the- /// per-score parallelism, since a fused pass has to be one invocation per *row* to- /// see the whole distribution it is normalising.- Softmax,- /// [`Kind::Softmax`] with each row truncated at the diagonal: a **causal** mask.- ///- /// One use, TinyCLIP's text tower, whose three layers attend over all 77 tokens at once and- /// may not read the future. Query `q`'s row is normalised over keys `0 ..= q` and the rest of- /// it is written as zero, so [`Kind::AttnApply`] can multiply the whole row unchanged.- ///- /// A separate pipeline rather than a flag on [`Kind::Softmax`], because that one is shared by- /// PP-OCRv5 recognition, both Supertonic encoders and SMaLL-100 — a push field the bound came- /// from would break four shipping nets at once if it were ever left unset. See- /// `shaders/softmax_causal.comp`.- SoftmaxCausal,- /// [`Kind::Softmax`] over only the leading `prefix + 1` entries of each row.- ///- /// The decode counterpart. Once a decode plan is built once at a maximum context rather than- /// rebuilt per token, a score-map row is as wide as that maximum but only its leading span was- /// written this step; the rest holds whatever the previous step left. Normalising the whole- /// row would fold that stale data into the maximum and the sum.- ///- /// A separate pipeline for the same reason [`Kind::SoftmaxCausal`] is one, and more so: plain- /// [`Kind::Softmax`] is shared by PP-OCRv5 recognition, both Supertonic encoders, whisper,- /// maia and NLLB's own encoder. See `shaders/softmax_prefix.comp`.- SoftmaxPrefix,- /// Write one position into a KV cache at the row [`crate::vulkan::run::StepParams::prefix`]- /// names.- ///- /// The only op whose *destination* is decided at submit time rather than at record time, and- /// the reason a decode plan can be recorded once. See `shaders/cache_write.comp` and- /// [`Builder::cache_write`].- CacheWrite,- /// `tanh(x / cap) * cap`, Gemma's `final_logit_softcapping`. See `shaders/softcap.comp`.- Softcap,- /// The argmax of a logits row: index of the maximum value as a scalar.- ///- /// A device-side greedy sampler. The 262,144-logit host scan costs ~14 ms- /// a token; this reduces on the device and reads back one value instead- /// of 512 KB of logits. See `shaders/argmax.comp`. The full-logits path- /// (Kotlin sampling) is untouched — this serves greedy decoding only.- ///- /// The first of two stages: many workgroups each reduce a slice of the row to a- /// `(value, lo, hi)` partial, and [`Kind::ArgmaxFold`] folds the partials to the- /// winning index. See [`Builder::argmax`].- Argmax,- /// Fold [`Kind::Argmax`]'s partials to the winning index as two fp16 lanes.- ///- /// Reads the `(value, lo, hi)` triples the first stage wrote and stores- /// `lo = id % 2048`, `hi = id / 2048`, keeping the FIRST index on ties.- /// See `shaders/argmax_fold.comp`.- ArgmaxFold,- TopK, // The 64 largest of a row with their ids; see shaders/topk.comp.- /// An [`Act`] applied on its own, for a value no convolution produced. See- /// `shaders/activate.comp`.- ///- /// [`Act::PRelu`] is **not** supported: its slope is a weight tensor, and the one caller- /// this exists for wants `Gelu`. Passing it here silently uses a zero slope, which is a- /// plain `Relu` - so [`Builder::activate`] refuses it rather than letting that happen.- Activate,- /// `activate(gate) * up` over a fused `[gate | up]` projection, replacing two slices, an- /// activation and a multiply. See `shaders/gated_activate.comp`.- GatedActivate,- /// Multiply by a scalar held in the weights. See `shaders/mul_scalar.comp`.- MulScalar,- /// Clamp to a `[min, max]` pair held in the weights. See `shaders/clamp.comp`.- Clamp,- /// `clamp(round(x / scale), -128, 127) * scale`, an int8 round-trip at a- /// per-layer scale. See `shaders/quantize.comp`.- ///- /// S10's live attention quantizes the mixture to int8 before the O projection- /// consumes it; the scale rides the push block like [`Kind::Softcap`]'s cap.- Quantize,- /// Block-quantise an activation to int8 for [`Kind::ConvPointInt4Dot`]. See- /// `shaders/quantize_blocks.comp`.- QuantizeBlocks,- /// [`Kind::ConvPointInt4`] on the int8 dot product, reading the staged activation at- /// [`Push::kw`]. Falls back to the fp32 pipeline on a device without the extension. See- /// `shaders/conv_point_int4_dot.comp`.- ConvPointInt4Dot,- /// `O[h][d][i] = sum_j S[h][i][j] * V[h][d][j]`, attention's weighted sum.- ///- /// `O[h][d][i] = sum_j S[h][i][j] * V[h][d][j]`, attention's weighted sum.- ///- /// Writes `[d_model, 1, T]`, so the head concatenation that normally follows- /// attention is not an op: output channel `c` belongs to head `c / head_dim` and- /// lands where the concatenated result wants it. Head count in [`Push::group`].- AttnApply,- /// [`Kind::AttnScores`] plus a relative-position term, which is nine taps rather than the- /// `[heads, T, 2T-1]` product and skew the export spells out. Table at [`Push::weight`] as- /// `[2 * window + 1, head_dim]`, offset count in [`Push::kw`].- ///- /// Both of Supertonic's encoders use it: `supertonic_text` has four such layers and- /// `supertonic_duration` two, all at `window_size` 4, so `OFFSETS` is 9 in each.- AttnScoresRelative,- /// [`Kind::AttnApply`] plus the value-side relative term. See- /// [`Kind::AttnScoresRelative`].- AttnApplyRelative,- /// Attention scores over a **backward sliding window**, stored as a band, with the relative- /// term and the logit cap fused in. See `shaders/attn_scores_banded.comp`.- ///- /// `[heads, T, band]` rather than `[heads, T, T]`: Gemma 4's audio tower attends- /// `0 <= q - k <= 11`, so a square map computes sixty-two times what it keeps. Band width in- /// [`Push::kh`], relative offsets in [`Push::kw`], table at [`Push::weight`] as- /// `[heads, offsets, head_dim]`, cap in [`Push::param1_bits`].- AttnScoresBanded,- /// [`Kind::AttnScoresBanded`]'s value half: a band of probabilities against a- /// `[d_model, 1, T]` sequence. See `shaders/attn_apply_banded.comp`.- AttnApplyBanded,- /// [`AttnScores`](Kind::AttnScores) for one query against a **position-major** K cache.- ///- /// A decoder step is one query, and its keys live in a cache that a position is appended to- /// every step. `[d_model, 1, T]` makes that append `d_model` scattered two-byte copies, so a- /// cache is `[T, 1, d_model]` instead and reads through this. See- /// `shaders/attn_scores_cached.comp` for why the shared shaders are not extended.- AttnScoresCached,- /// [`AttnApply`](Kind::AttnApply) for one query against a **position-major** V cache.- AttnApplyCached,- /// A `1 x 1` convolution as a tiled matrix multiply, staging weights through shared memory.- ///- /// [`Kind::Conv`] reads each output element''s weights from global memory with no reuse, which- /// costs nothing for a spatial kernel and everything for a wide `1 x 1` over a short- /// sequence - measured at 15.2 GFLOP/s on a Tensor G4 against a device peak of order 1000.- /// This stages a tile of weights once per workgroup instead. `Builder::conv` routes here- /// automatically for an ungrouped `1 x 1`; see `conv_point.comp`.- ///- /// [`Push::count`] is the **tile** count for this kind, not the output element count.- ConvPoint,- /// [`Kind::Conv`] with int8 weights and one dequantisation scale per output channel.- ///- /// Only for a network where the weights dominate the download. The scale multiplies the- /// finished accumulator rather than every tap, so the inner loop costs what fp16 costs;- /// activations stay fp16, which is simpler than the export''s dynamic quantisation and- /// strictly more accurate. [`Push::weight`] is a **word** offset here, not an fp16 one, and- /// [`Push::act_weight`] holds the scale tensor — which is why [`Act::PRelu`] is refused.- ConvInt8,- /// [`Kind::ConvPoint`] with int8 weights: the tiled lowering of [`Kind::ConvInt8`].- ///- /// `Builder::emit` routes an int8 convolution here under exactly the conditions an fp16 one- /// reaches [`Kind::ConvPoint`] under — ungrouped, `1 x 1`, stride 1, unpadded. Without it,- /// quantising Supertonic's sampler would move 92% of its parameters onto the untiled path,- /// which is far slower than the size saving is worth; see `conv_point_int8.comp`.- ///- /// [`Push::count`] is the **tile** count here, as it is for [`Kind::ConvPoint`].- ConvPointInt8,- /// `out[c][t] = table[id(t)][c]`, an embedding lookup.- ///- /// The only op here whose addresses depend on the data. Ids arrive as an ordinary fp16- /// tensor, which is exact for a small vocabulary — fp16 holds every integer to 2048. Table at- /// [`Push::weight`], its row count in [`Push::in_w`], and an out-of-range id clamps rather- /// than reading past the table.- ///- /// # Vocabularies past 2048- ///- /// Above [`EMBED_LANE`] the gaps between representable fp16 integers open up, so a single- /// id lane would silently land on a neighbouring row — Supertonic has 8,322 symbols and- /// SMaLL-100 has 128,112. Those arrive **split across two lanes**, `id = lo + 2048 * hi`,- /// as a `[2, 1, T]` tensor; [`Push::in_c`] carries the lane count. See [`embed_lanes`].- /// [`Kind::ConvPointInt8`] for a single position: a matrix-vector product.- ///- /// The tiled kind's workgroup count is `out_c.div_ceil(16) * positions.div_ceil(16)`, so at one- /// position 15 of every 16 tile columns are padding and 56 of every 64 invocations store- /// nothing. A SMaLL-100 decode step is entirely single-position — 30 projections and a- /// 128,112-class head, 128 times per translation — so that waste lands on the dominant cost.- /// See `shaders/conv_vec_int8.comp`.- ///- /// Chosen automatically by [`Builder`]; no net asks for it.- ConvVecInt8,- /// [`Kind::ConvVecInt8`] with a four-bit kernel and a per-block scale. See- /// `shaders/conv_vec_int4.comp`.- ConvVecInt4,- /// [`Kind::ConvPointInt8`] with a four-bit kernel and a per-block scale. See- /// `shaders/conv_point_int4.comp`.- ConvPointInt4,- /// [`Kind::ConvVecInt8`] with a GGUF Q2_K kernel and a per-superblock `(d, dmin)`- /// scale. See `shaders/conv_vec_q2k.comp`.- ConvVecQ2K,- /// [`Kind::ConvPointInt8`] with a GGUF Q2_K kernel and a per-superblock `(d, dmin)`- /// scale. See `shaders/conv_point_q2k.comp`.- ConvPointQ2K,- /// [`Kind::ConvInt8`] with a GGUF Q2_K kernel: the untiled lowering. See- /// `shaders/conv_q2k.comp`.- ConvQ2K,- Embed,- /// `out[i] = weights[i]`, a learned tensor copied into the arena.- ///- /// The only op that produces a tensor from nothing but the weights file. It exists because- /// [`Kind::AttnScores`] contracts two *arena* tensors, and Supertonic's text encoder attends- /// against 50 style keys that are entirely constant — `tanh(W_key . style_key + b_key)`,- /// which the converter folds to one tensor. See `shaders/constant.comp`.- Constant,- /// Rotary position embedding over a `[C, 1, W]` sequence, the **half**-split convention.- ///- /// `out[j] = x[j] cos - x[j + half] sin` and `out[j + half] = x[j + half] cos + x[j] sin`,- /// within each head. The angle table is the second operand rather than a weight: in this- /// export the angle is `(position / length) * theta`, so it depends on the sequence length- /// and the host rebuilds it per call. See `shaders/rotary.comp` for why the pairing- /// convention matters more than it looks.- Rotary,-}--include!("mod_part1.rs");-include!("mod_part2.rs");-include!("mod_part2b.rs");-include!("mod_part3.rs");-include!("mod_part4.rs");-include!("mod_part4b.rs");-include!("mod_part5.rs");-include!("mod_part6.rs");-include!("mod_part6b.rs");-include!("mod_part7.rs");-include!("mod_part8.rs");-include!("mod_part9.rs");-include!("mod_part9b.rs");-include!("mod_part9c.rs");-include!("mod_part9d.rs");-include!("mod_part10.rs");-include!("mod_part11.rs");-include!("mod_part12.rs");-include!("mod_part13.rs");-include!("mod_part14.rs");-include!("mod_part15.rs");+include!("mod_kind.rs"); #[cfg(test)] #[path = "builder_validation_tests.rs"] mod builder_validation_tests;
library/ml/src/main/rust/src/nets/mod_kind.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_kind.rs b/library/ml/src/main/rust/src/nets/mod_kind.rsnew file mode 100644index 0000000000..3131a5d90c--- /dev/null+++ b/library/ml/src/main/rust/src/nets/mod_kind.rs@@ -0,0 +1,344 @@+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Kind {+ /// Dense, grouped or dilated convolution with a fused activation.+ Conv,+ /// Transposed convolution. One use, in the selfie net's 2x upsample to 256x256.+ ConvTranspose,+ /// Max pooling.+ MaxPool,+ /// Average pooling over an explicit window, floored and unpadded.+ ///+ /// One use: the pool that turns PP-OCRv5 recognition's `[480, 3, 80]` feature map+ /// into the `[480, 1, 40]` sequence its transformer reads, with kernel and stride+ /// both `(3, 2)`. The asymmetric window is the reason this carries `kh`/`kw` rather+ /// than one size, and the reason it is not [`Kind::GlobalAvgPool`] with a flag — that+ /// one reduces all of H and W to a single value and needs no window arithmetic.+ AvgPool,+ /// Bilinear resize, `half_pixel` coordinates.+ Resize,+ /// Nearest-neighbour resize, `asymmetric` coordinates and `floor` rounding.+ ///+ /// SCRFD's feature-pyramid upsamples are `mode=nearest`, which is a different+ /// pipeline rather than a flag on [`Kind::Resize`] because the two share no+ /// arithmetic: `src = floor(dst * in / out)` against `(dst + 0.5) * in / out - 0.5`.+ /// Running an FPN through the bilinear one blurs every lateral it adds.+ ResizeNearest,+ /// Mean over H and W, keeping C. The squeeze in a squeeze-excite block.+ GlobalAvgPool,+ /// Elementwise sum of two equal shapes.+ Add,+ /// `a * b` where `b` is `C x 1 x 1`. The excite in a squeeze-excite block.+ MulBroadcast,+ /// `a + b` where `b` is `C x 1 x 1`. A per-channel shift.+ ///+ /// The mirror of [`Kind::MulBroadcast`], and used for one thing: the four timestep+ /// conditioning layers of Supertonic's sampler, whose `Linear` from the time embedding the+ /// host evaluates because it depends on two scalars. See `shaders/add_bcast.comp`.+ AddBroadcast,+ /// Elementwise `a * b` over two equal shapes.+ Mul,+ /// `x * scale + shift`, both scalars. PP-OCRv5's "learnable affine block".+ ///+ /// One pass over the data for two multiplies. It exists because these sit *after* an+ /// activation, so unlike everything else constant in that export they cannot be+ /// folded into the preceding convolution's weight.+ ///+ /// # Why they cannot all fold forward either+ ///+ /// Pushing one into the *following* convolution looks free: `conv(a * x + t)[m]` is+ /// `a * conv(x)[m] + t * sum(W[m])`. That identity holds at an interior pixel and+ /// **fails at a border one**, because a padded convolution reads zero outside the+ /// input rather than `t`, so the constant's real contribution there is `t` times the+ /// sum of only the in-bounds taps. The correction varies per output position, so it is+ /// not a bias and there is no fold.+ ///+ /// `scripts/ml/ppocr_fold.py` therefore folds an affine only into an *unpadded*+ /// convolution, which leaves 14 in detection and 16 in recognition — all of them+ /// feeding either a padded depthwise or a squeeze-excite's two branches.+ ///+ /// Getting this wrong is invisible to every structural check: the layer table, the+ /// tensor count and the digest are all unchanged, and only the weight *values* differ.+ /// `scripts/ml/onnx_parity.py` is what caught it.+ Affine,+ /// Layer normalisation **over the channel axis**, with a per-channel affine.+ ///+ /// # Why over channels+ ///+ /// PP-OCRv5's recogniser is a CNN feeding a small transformer — `d_model` 120, 8+ /// heads, two blocks — and this runtime keeps its sequences in the layout the CNN+ /// already produces: `[d_model, 1, T]`, features in channels and the sequence along+ /// the width. Two things fall out of that and neither is an accident:+ ///+ /// * **Every linear projection is a 1x1 convolution.** All five feed-forward `Gemm`s+ /// and all six attention projections are already expressible, so they need no new+ /// pipeline.+ /// * **Splitting `d_model` into heads is free.** `[120, 1, T]` read as `[8, 15, T]`+ /// is the same bytes in the same order, so there is no `Permute` and no `Reshape`+ /// anywhere in the attention — the attention pipelines take the head count in+ /// [`Push::group`] and index accordingly.+ ///+ /// The cost is that the reduction here is strided rather than contiguous. At+ /// `d_model` 120 that is 120 loads a stride apart per position, which is nothing+ /// against what a contiguous layout would cost in permutes.+ LayerNorm,+ /// Instance normalisation over the **spatial** axes, with no affine.+ ///+ /// [`Kind::LayerNorm`] transposed: where that one reduces `C` strided values per+ /// position, this reduces one channel's contiguous `H x W` plane — so one+ /// invocation per channel, and the whole pass is contiguous reads. Sixteen uses,+ /// all MODNet's `IBNorm` second halves (`InstanceNorm2d(affine=False)`), each+ /// over one [`Builder::slice_channels`] half rejoined by [`Builder::concat`].+ ///+ /// No gamma/beta: the export's scale and bias are constant 1 and 0 (verified+ /// by `scripts/ml/modnet_fold.py`, which rejects anything else), so there are+ /// no weight reads at all — epsilon rides [`Push::param1_bits`] like the other+ /// norms'. The batch-norm halves of those same `IBNorm`s are folded into their+ /// convolutions by the fold script instead, which is why this is the only new+ /// pipeline MODNet needs.+ InstanceNorm,+ /// Root-mean-square normalisation over the channel axis, with a per-channel gain.+ ///+ /// [`Kind::LayerNorm`] without the mean subtraction and without beta:+ /// `x / sqrt(mean(x^2) + eps) * gamma`. Sixteen uses, all Maia3's `norm1` / `norm2`.+ ///+ /// Separate from [`Kind::LayerNorm`] rather than a flag on it because the difference+ /// is also a difference in *weights read* — one rank-1 tensor rather than two — and+ /// [`Kind::weight_reads`] is what `vulkan::segment` uses to decide which slice of the+ /// `.maml` a pass has to have resident. A flag would make that arm depend on the push+ /// block's contents rather than its kind.+ RmsNorm,+ /// `S[h][i][j] = scale * sum_d Q[h][d][i] * K[h][d][j]`, attention's score map.+ ///+ /// Contracts over the *middle* axis of `[heads, head_dim, T]`, which is what makes+ /// the head split free — see [`Kind::LayerNorm`]. Takes the head count in+ /// [`Push::group`] and `1 / sqrt(head_dim)` in [`Push::param0_bits`].+ ///+ /// The output is `[heads, T, T]` with the key index innermost, so the row a+ /// [`Kind::Softmax`] normalises is contiguous.+ AttnScores,+ /// Softmax over the last axis, one row at a time.+ ///+ /// Kept separate from [`Kind::AttnScores`] rather than fused into it. Fusing would+ /// save writing a `heads * T * T` intermediate — 100 KiB at the recogniser's sizes,+ /// which is not a cost worth a shader that does two things — and would give up the+ /// per-score parallelism, since a fused pass has to be one invocation per *row* to+ /// see the whole distribution it is normalising.+ Softmax,+ /// [`Kind::Softmax`] with each row truncated at the diagonal: a **causal** mask.+ ///+ /// One use, TinyCLIP's text tower, whose three layers attend over all 77 tokens at once and+ /// may not read the future. Query `q`'s row is normalised over keys `0 ..= q` and the rest of+ /// it is written as zero, so [`Kind::AttnApply`] can multiply the whole row unchanged.+ ///+ /// A separate pipeline rather than a flag on [`Kind::Softmax`], because that one is shared by+ /// PP-OCRv5 recognition, both Supertonic encoders and SMaLL-100 — a push field the bound came+ /// from would break four shipping nets at once if it were ever left unset. See+ /// `shaders/softmax_causal.comp`.+ SoftmaxCausal,+ /// [`Kind::Softmax`] over only the leading `prefix + 1` entries of each row.+ ///+ /// The decode counterpart. Once a decode plan is built once at a maximum context rather than+ /// rebuilt per token, a score-map row is as wide as that maximum but only its leading span was+ /// written this step; the rest holds whatever the previous step left. Normalising the whole+ /// row would fold that stale data into the maximum and the sum.+ ///+ /// A separate pipeline for the same reason [`Kind::SoftmaxCausal`] is one, and more so: plain+ /// [`Kind::Softmax`] is shared by PP-OCRv5 recognition, both Supertonic encoders, whisper,+ /// maia and NLLB's own encoder. See `shaders/softmax_prefix.comp`.+ SoftmaxPrefix,+ /// Write one position into a KV cache at the row [`crate::vulkan::run::StepParams::prefix`]+ /// names.+ ///+ /// The only op whose *destination* is decided at submit time rather than at record time, and+ /// the reason a decode plan can be recorded once. See `shaders/cache_write.comp` and+ /// [`Builder::cache_write`].+ CacheWrite,+ /// `tanh(x / cap) * cap`, Gemma's `final_logit_softcapping`. See `shaders/softcap.comp`.+ Softcap,+ /// The argmax of a logits row: index of the maximum value as a scalar.+ ///+ /// A device-side greedy sampler. The 262,144-logit host scan costs ~14 ms+ /// a token; this reduces on the device and reads back one value instead+ /// of 512 KB of logits. See `shaders/argmax.comp`. The full-logits path+ /// (Kotlin sampling) is untouched — this serves greedy decoding only.+ ///+ /// The first of two stages: many workgroups each reduce a slice of the row to a+ /// `(value, lo, hi)` partial, and [`Kind::ArgmaxFold`] folds the partials to the+ /// winning index. See [`Builder::argmax`].+ Argmax,+ /// Fold [`Kind::Argmax`]'s partials to the winning index as two fp16 lanes.+ ///+ /// Reads the `(value, lo, hi)` triples the first stage wrote and stores+ /// `lo = id % 2048`, `hi = id / 2048`, keeping the FIRST index on ties.+ /// See `shaders/argmax_fold.comp`.+ ArgmaxFold,+ TopK, // The 64 largest of a row with their ids; see shaders/topk.comp.+ /// An [`Act`] applied on its own, for a value no convolution produced. See+ /// `shaders/activate.comp`.+ ///+ /// [`Act::PRelu`] is **not** supported: its slope is a weight tensor, and the one caller+ /// this exists for wants `Gelu`. Passing it here silently uses a zero slope, which is a+ /// plain `Relu` - so [`Builder::activate`] refuses it rather than letting that happen.+ Activate,+ /// `activate(gate) * up` over a fused `[gate | up]` projection, replacing two slices, an+ /// activation and a multiply. See `shaders/gated_activate.comp`.+ GatedActivate,+ /// Multiply by a scalar held in the weights. See `shaders/mul_scalar.comp`.+ MulScalar,+ /// Clamp to a `[min, max]` pair held in the weights. See `shaders/clamp.comp`.+ Clamp,+ /// `clamp(round(x / scale), -128, 127) * scale`, an int8 round-trip at a+ /// per-layer scale. See `shaders/quantize.comp`.+ ///+ /// S10's live attention quantizes the mixture to int8 before the O projection+ /// consumes it; the scale rides the push block like [`Kind::Softcap`]'s cap.+ Quantize,+ /// Block-quantise an activation to int8 for [`Kind::ConvPointInt4Dot`]. See+ /// `shaders/quantize_blocks.comp`.+ QuantizeBlocks,+ /// [`Kind::ConvPointInt4`] on the int8 dot product, reading the staged activation at+ /// [`Push::kw`]. Falls back to the fp32 pipeline on a device without the extension. See+ /// `shaders/conv_point_int4_dot.comp`.+ ConvPointInt4Dot,+ /// `O[h][d][i] = sum_j S[h][i][j] * V[h][d][j]`, attention's weighted sum.+ ///+ /// `O[h][d][i] = sum_j S[h][i][j] * V[h][d][j]`, attention's weighted sum.+ ///+ /// Writes `[d_model, 1, T]`, so the head concatenation that normally follows+ /// attention is not an op: output channel `c` belongs to head `c / head_dim` and+ /// lands where the concatenated result wants it. Head count in [`Push::group`].+ AttnApply,+ /// [`Kind::AttnScores`] plus a relative-position term, which is nine taps rather than the+ /// `[heads, T, 2T-1]` product and skew the export spells out. Table at [`Push::weight`] as+ /// `[2 * window + 1, head_dim]`, offset count in [`Push::kw`].+ ///+ /// Both of Supertonic's encoders use it: `supertonic_text` has four such layers and+ /// `supertonic_duration` two, all at `window_size` 4, so `OFFSETS` is 9 in each.+ AttnScoresRelative,+ /// [`Kind::AttnApply`] plus the value-side relative term. See+ /// [`Kind::AttnScoresRelative`].+ AttnApplyRelative,+ /// Attention scores over a **backward sliding window**, stored as a band, with the relative+ /// term and the logit cap fused in. See `shaders/attn_scores_banded.comp`.+ ///+ /// `[heads, T, band]` rather than `[heads, T, T]`: Gemma 4's audio tower attends+ /// `0 <= q - k <= 11`, so a square map computes sixty-two times what it keeps. Band width in+ /// [`Push::kh`], relative offsets in [`Push::kw`], table at [`Push::weight`] as+ /// `[heads, offsets, head_dim]`, cap in [`Push::param1_bits`].+ AttnScoresBanded,+ /// [`Kind::AttnScoresBanded`]'s value half: a band of probabilities against a+ /// `[d_model, 1, T]` sequence. See `shaders/attn_apply_banded.comp`.+ AttnApplyBanded,+ /// [`AttnScores`](Kind::AttnScores) for one query against a **position-major** K cache.+ ///+ /// A decoder step is one query, and its keys live in a cache that a position is appended to+ /// every step. `[d_model, 1, T]` makes that append `d_model` scattered two-byte copies, so a+ /// cache is `[T, 1, d_model]` instead and reads through this. See+ /// `shaders/attn_scores_cached.comp` for why the shared shaders are not extended.+ AttnScoresCached,+ /// [`AttnApply`](Kind::AttnApply) for one query against a **position-major** V cache.+ AttnApplyCached,+ /// A `1 x 1` convolution as a tiled matrix multiply, staging weights through shared memory.+ ///+ /// [`Kind::Conv`] reads each output element''s weights from global memory with no reuse, which+ /// costs nothing for a spatial kernel and everything for a wide `1 x 1` over a short+ /// sequence - measured at 15.2 GFLOP/s on a Tensor G4 against a device peak of order 1000.+ /// This stages a tile of weights once per workgroup instead. `Builder::conv` routes here+ /// automatically for an ungrouped `1 x 1`; see `conv_point.comp`.+ ///+ /// [`Push::count`] is the **tile** count for this kind, not the output element count.+ ConvPoint,+ /// [`Kind::Conv`] with int8 weights and one dequantisation scale per output channel.+ ///+ /// Only for a network where the weights dominate the download. The scale multiplies the+ /// finished accumulator rather than every tap, so the inner loop costs what fp16 costs;+ /// activations stay fp16, which is simpler than the export''s dynamic quantisation and+ /// strictly more accurate. [`Push::weight`] is a **word** offset here, not an fp16 one, and+ /// [`Push::act_weight`] holds the scale tensor — which is why [`Act::PRelu`] is refused.+ ConvInt8,+ /// [`Kind::ConvPoint`] with int8 weights: the tiled lowering of [`Kind::ConvInt8`].+ ///+ /// `Builder::emit` routes an int8 convolution here under exactly the conditions an fp16 one+ /// reaches [`Kind::ConvPoint`] under — ungrouped, `1 x 1`, stride 1, unpadded. Without it,+ /// quantising Supertonic's sampler would move 92% of its parameters onto the untiled path,+ /// which is far slower than the size saving is worth; see `conv_point_int8.comp`.+ ///+ /// [`Push::count`] is the **tile** count here, as it is for [`Kind::ConvPoint`].+ ConvPointInt8,+ /// `out[c][t] = table[id(t)][c]`, an embedding lookup.+ ///+ /// The only op here whose addresses depend on the data. Ids arrive as an ordinary fp16+ /// tensor, which is exact for a small vocabulary — fp16 holds every integer to 2048. Table at+ /// [`Push::weight`], its row count in [`Push::in_w`], and an out-of-range id clamps rather+ /// than reading past the table.+ ///+ /// # Vocabularies past 2048+ ///+ /// Above [`EMBED_LANE`] the gaps between representable fp16 integers open up, so a single+ /// id lane would silently land on a neighbouring row — Supertonic has 8,322 symbols and+ /// SMaLL-100 has 128,112. Those arrive **split across two lanes**, `id = lo + 2048 * hi`,+ /// as a `[2, 1, T]` tensor; [`Push::in_c`] carries the lane count. See [`embed_lanes`].+ /// [`Kind::ConvPointInt8`] for a single position: a matrix-vector product.+ ///+ /// The tiled kind's workgroup count is `out_c.div_ceil(16) * positions.div_ceil(16)`, so at one+ /// position 15 of every 16 tile columns are padding and 56 of every 64 invocations store+ /// nothing. A SMaLL-100 decode step is entirely single-position — 30 projections and a+ /// 128,112-class head, 128 times per translation — so that waste lands on the dominant cost.+ /// See `shaders/conv_vec_int8.comp`.+ ///+ /// Chosen automatically by [`Builder`]; no net asks for it.+ ConvVecInt8,+ /// [`Kind::ConvVecInt8`] with a four-bit kernel and a per-block scale. See+ /// `shaders/conv_vec_int4.comp`.+ ConvVecInt4,+ /// [`Kind::ConvPointInt8`] with a four-bit kernel and a per-block scale. See+ /// `shaders/conv_point_int4.comp`.+ ConvPointInt4,+ /// [`Kind::ConvVecInt8`] with a GGUF Q2_K kernel and a per-superblock `(d, dmin)`+ /// scale. See `shaders/conv_vec_q2k.comp`.+ ConvVecQ2K,+ /// [`Kind::ConvPointInt8`] with a GGUF Q2_K kernel and a per-superblock `(d, dmin)`+ /// scale. See `shaders/conv_point_q2k.comp`.+ ConvPointQ2K,+ /// [`Kind::ConvInt8`] with a GGUF Q2_K kernel: the untiled lowering. See+ /// `shaders/conv_q2k.comp`.+ ConvQ2K,+ Embed,+ /// `out[i] = weights[i]`, a learned tensor copied into the arena.+ ///+ /// The only op that produces a tensor from nothing but the weights file. It exists because+ /// [`Kind::AttnScores`] contracts two *arena* tensors, and Supertonic's text encoder attends+ /// against 50 style keys that are entirely constant — `tanh(W_key . style_key + b_key)`,+ /// which the converter folds to one tensor. See `shaders/constant.comp`.+ Constant,+ /// Rotary position embedding over a `[C, 1, W]` sequence, the **half**-split convention.+ ///+ /// `out[j] = x[j] cos - x[j + half] sin` and `out[j + half] = x[j + half] cos + x[j] sin`,+ /// within each head. The angle table is the second operand rather than a weight: in this+ /// export the angle is `(position / length) * theta`, so it depends on the sequence length+ /// and the host rebuilds it per call. See `shaders/rotary.comp` for why the pairing+ /// convention matters more than it looks.+ Rotary,+}++include!("mod_part1.rs");+include!("mod_part2.rs");+include!("mod_part2b.rs");+include!("mod_part3.rs");+include!("mod_part4.rs");+include!("mod_part4b.rs");+include!("mod_part5.rs");+include!("mod_part6.rs");+include!("mod_part6b.rs");+include!("mod_part7.rs");+include!("mod_part8.rs");+include!("mod_part9.rs");+include!("mod_part9b.rs");+include!("mod_part9c.rs");+include!("mod_part9d.rs");+include!("mod_part10.rs");+include!("mod_part11.rs");+include!("mod_part12.rs");+include!("mod_part13.rs");+include!("mod_part14.rs");+include!("mod_part15.rs");
library/ml/src/main/rust/src/post/whisper.rs
diff --git a/library/ml/src/main/rust/src/post/whisper.rs b/library/ml/src/main/rust/src/post/whisper.rsindex 30cfd48244..c031858157 100644--- a/library/ml/src/main/rust/src/post/whisper.rs+++ b/library/ml/src/main/rust/src/post/whisper.rs@@ -238,268 +238,4 @@ fn argmax(logits: &[f32], suppress: &[u32], also: &[u32]) -> Option<u32> { best.map(|(index, _)| index as u32) } -#[cfg(test)]-#[path = "whisper_check_tests.rs"]-mod whisper_check_tests;--#[cfg(test)]-mod tests {- use super::*;-- /// The real ids, from `generation_config.json`, so the fixtures below are the shipping prompt.- const SOT: u32 = 50_258;- const EOT: u32 = 50_257;- const TRANSCRIBE: u32 = 50_359;- const NO_TIMESTAMPS: u32 = 50_363;- const EN: u32 = 50_259;- const FR: u32 = 50_265;-- fn config() -> Decoding {- Decoding {- start_of_transcript: SOT,- end_of_text: EOT,- transcribe: TRANSCRIBE,- no_timestamps: NO_TIMESTAMPS,- max_length: 448,- languages: vec![EN, FR],- // 220 is the leading space and 50257 the end of text, which is `begin_suppress_tokens`.- suppress: vec![1, 2, 7],- suppress_at_begin: vec![220, EOT],- }- }-- /// Records what the loop asked for, and answers with a scripted sequence of tokens.- struct Scripted {- /// One winning token per *generated* position; the prompt's three discarded steps are not- /// scripted, because their logits are never read.- script: Vec<u32>,- /// Every `(token, step)` the decoder saw, in order.- steps: Vec<(u32, usize)>,- /// The mel the encoder was given, so a test can assert it ran exactly once.- encoded: usize,- /// Scores for the language tokens at step 0, so detection can be steered.- language_scores: Vec<(u32, f32)>,- vocabulary: usize,- }-- impl Nets for Scripted {- fn encode(&mut self, mel: &[f32]) -> Result<(), String> {- assert_eq!(mel.len(), 80 * 3000, "the mel window is a fixed size");- self.encoded += 1;- Ok(())- }-- fn decode_step(&mut self, token: u32, step: usize) -> Result<Vec<f32>, String> {- self.steps.push((token, step));- let mut logits = vec![0.0f32; self.vocabulary];- if step == 0 {- for &(id, score) in &self.language_scores {- logits[id as usize] = score;- }- return Ok(logits);- }- // Positions 1 and 2 are prompt steps whose logits are discarded; position 3 predicts- // the first transcript token, and position `3 + n` the token after the nth.- let wanted = step.saturating_sub(PROMPT_TOKENS - 1);- let token = self.script.get(wanted).copied().unwrap_or(EOT);- logits[token as usize] = 1.0;- Ok(logits)- }- }-- fn scripted(script: &[u32]) -> Scripted {- Scripted {- script: script.to_vec(),- steps: Vec::new(),- encoded: 0,- // English wins unless a test says otherwise.- language_scores: vec![(EN, 2.0), (FR, 1.0)],- vocabulary: 51_865,- }- }-- fn mel() -> Vec<f32> {- vec![0.25; 80 * 3000]- }-- #[test]- fn the_prompt_is_four_tokens_ending_in_no_timestamps() {- // The trap this module exists to document. `<|notimestamps|>` last, at position 3, is what- // keeps the output plain text; dropping it produces `<|0.00|>`-style output that still- // decodes and still reads like a transcript.- let mut nets = scripted(&[100, EOT]);- let out = transcribe(&mut nets, &config(), &mel(), None).expect("transcribes");- assert_eq!(out, vec![100]);- let prompt: Vec<(u32, usize)> = nets.steps.iter().take(PROMPT_TOKENS).copied().collect();- assert_eq!(- prompt,- vec![(SOT, 0), (EN, 1), (TRANSCRIBE, 2), (NO_TIMESTAMPS, 3)],- "{:?}",- nets.steps- );- }-- #[test]- fn the_language_is_detected_from_step_zero_and_needs_no_extra_pass() {- // With only `<|startoftranscript|>` fed, the highest-scoring language token is the answer.- // Step 0 runs either way, so detection is free.- let mut nets = scripted(&[EOT]);- nets.language_scores = vec![(EN, 0.5), (FR, 3.0)];- transcribe(&mut nets, &config(), &mel(), None).expect("transcribes");- assert_eq!(nets.steps[1], (FR, 1));- // One encoder run, and the language was fed exactly once: detection cost no extra pass.- assert_eq!(nets.encoded, 1);- let languages =- nets.steps.iter().filter(|(token, _)| config().languages.contains(token)).count();- assert_eq!(languages, 1, "{:?}", nets.steps);- }-- #[test]- fn a_named_language_wins_over_the_scores() {- // An explicit code beats detection, and the detection logits are simply ignored — which is- // why step 0 still runs.- let mut nets = scripted(&[EOT]);- nets.language_scores = vec![(EN, 9.0), (FR, 0.0)];- transcribe(&mut nets, &config(), &mel(), Some(FR)).expect("transcribes");- assert_eq!(nets.steps[1], (FR, 1));- }-- #[test]- fn a_language_token_the_model_does_not_have_is_refused() {- // The caller resolves a code to a token, so a wrong table there would otherwise feed a text- // id into the prompt and produce confident nonsense.- let mut nets = scripted(&[EOT]);- let error = transcribe(&mut nets, &config(), &mel(), Some(42)).expect_err("a text id");- assert!(error.contains("language tokens"), "{error}");- assert_eq!(nets.encoded, 0, "the encoder ran before the check");- }-- #[test]- fn each_step_feeds_the_previous_token_back_after_the_prompt() {- // Greedy decoding is a chain, and the step numbering continues from the prompt: the first- // generated token is fed at position 4, not at 0.- let mut nets = scripted(&[100, 101, 102, EOT]);- let out = transcribe(&mut nets, &config(), &mel(), Some(EN)).expect("transcribes");- assert_eq!(out, vec![100, 101, 102]);- assert_eq!(- nets.steps,- vec![- (SOT, 0),- (EN, 1),- (TRANSCRIBE, 2),- (NO_TIMESTAMPS, 3),- (100, 4),- (101, 5),- (102, 6),- ]- );- }-- #[test]- fn end_of_text_ends_the_loop_and_is_not_emitted() {- let mut nets = scripted(&[100, 101, EOT, 102]);- let out = transcribe(&mut nets, &config(), &mel(), Some(EN)).expect("transcribes");- assert_eq!(out, vec![100, 101]);- // Four prompt steps plus two generated ones: the step that would have fed `EOT` never ran.- assert_eq!(nets.steps.len(), PROMPT_TOKENS + 2);- }-- #[test]- fn end_of_text_at_the_first_position_is_suppressed() {- // `begin_suppress_tokens` is `[220, 50257]`, so a window with speech in it cannot come back- // empty because the model was unsure. Without it this returns nothing.- let mut nets = scripted(&[EOT]);- // Make `EOT` the strongest and 100 the runner-up at the first position only.- nets.script = vec![EOT];- let mut config = config();- config.suppress_at_begin = vec![220, EOT];- let out = transcribe(&mut nets, &config, &mel(), Some(EN)).expect("transcribes");- // Suppressed, so the loop picks *something* rather than stopping immediately.- assert!(!out.is_empty(), "the first position returned nothing");- assert_ne!(out[0], EOT);- // And a leading space is suppressed there too.- assert_ne!(out[0], 220);- }-- #[test]- fn a_suppressed_id_is_never_emitted_at_any_position() {- let mut config = config();- config.suppress = vec![100];- let mut nets = scripted(&[100, 100, EOT]);- let out = transcribe(&mut nets, &config, &mel(), Some(EN)).expect("transcribes");- assert!(!out.contains(&100), "{out:?}");- }-- #[test]- fn a_decoder_that_never_stops_is_capped() {- // Greedy decoding can loop forever by repeating itself, and the position table is only 448- // deep, so the loop stops rather than running past it.- let mut nets = scripted(&vec![100u32; MAX_NEW_TOKENS + 50]);- let out = transcribe(&mut nets, &config(), &mel(), Some(EN)).expect("transcribes");- assert_eq!(out.len(), MAX_NEW_TOKENS);- // And it did not run a step for a token it had no room to predict from.- assert_eq!(nets.steps.len(), PROMPT_TOKENS + MAX_NEW_TOKENS - 1);- // The last step is at position `3 + 223`, comfortably inside the 448-entry table.- assert!(nets.steps.last().expect("a step").1 < 448);- }-- #[test]- fn a_short_max_length_caps_the_loop_before_the_token_budget_does() {- // `max_length` is the position table, and the prompt spends four of it. A configuration that- // shrank it must shorten the transcript rather than overrun the table.- let mut config = config();- config.max_length = PROMPT_TOKENS + 3;- assert_eq!(config.budget(), 3);- let mut nets = scripted(&[100u32; 50]);- let out = transcribe(&mut nets, &config, &mel(), Some(EN)).expect("transcribes");- assert_eq!(out.len(), 3);- }-- #[test]- fn a_configuration_outside_the_vocabulary_is_refused() {- let vocabulary = 51_865;- config().check(vocabulary).expect("the real ids are in range");-- let mut wrong = config();- wrong.no_timestamps = vocabulary;- let error = wrong.check(vocabulary).expect_err("past the vocabulary");- assert!(error.contains("no_timestamps"), "{error}");-- let mut wrong = config();- wrong.languages.clear();- let error = wrong.check(vocabulary).expect_err("no languages");- assert!(error.contains("language tokens"), "{error}");-- let mut wrong = config();- wrong.max_length = PROMPT_TOKENS;- let error = wrong.check(vocabulary).expect_err("no room");- assert!(error.contains("max_length"), "{error}");- }-- #[test]- fn argmax_takes_the_lowest_index_of_a_tie_and_skips_nan() {- assert_eq!(argmax(&[1.0, 3.0, 3.0, 2.0], &[], &[]), Some(1));- assert_eq!(argmax(&[f32::NAN, 1.0], &[], &[]), Some(1));- assert_eq!(argmax(&[f32::NAN], &[], &[]), None);- assert_eq!(argmax(&[], &[], &[]), None);- // Negative logits are normal — a softmax was never taken.- assert_eq!(argmax(&[-5.0, -1.0, -9.0], &[], &[]), Some(1));- // Suppression applies before the comparison, not after.- assert_eq!(argmax(&[1.0, 9.0, 2.0], &[1], &[]), Some(2));- assert_eq!(argmax(&[1.0, 9.0, 2.0], &[], &[1, 2]), Some(0));- }-- #[test]- fn language_detection_ignores_every_non_language_logit() {- // A text token will always outscore a language token on a real window, so scoring the- // language ids against *each other* is the whole of the method.- let mut logits = vec![0.0f32; 51_865];- logits[100] = 99.0;- logits[EN as usize] = 1.0;- logits[FR as usize] = 2.0;- assert_eq!(best_of(&logits, &[EN, FR]), Some(FR));- // An id past the end is skipped rather than panicking.- assert_eq!(best_of(&logits, &[EN, 99_999]), Some(EN));- assert_eq!(best_of(&logits, &[]), None);- }-}+include!("whisper_part1.rs");
library/ml/src/main/rust/src/post/whisper_part1.rs
diff --git a/library/ml/src/main/rust/src/post/whisper_part1.rs b/library/ml/src/main/rust/src/post/whisper_part1.rsnew file mode 100644index 0000000000..89950c08c9--- /dev/null+++ b/library/ml/src/main/rust/src/post/whisper_part1.rs@@ -0,0 +1,265 @@+#[cfg(test)]+#[path = "whisper_check_tests.rs"]+mod whisper_check_tests;++#[cfg(test)]+mod tests {+ use super::*;++ /// The real ids, from `generation_config.json`, so the fixtures below are the shipping prompt.+ const SOT: u32 = 50_258;+ const EOT: u32 = 50_257;+ const TRANSCRIBE: u32 = 50_359;+ const NO_TIMESTAMPS: u32 = 50_363;+ const EN: u32 = 50_259;+ const FR: u32 = 50_265;++ fn config() -> Decoding {+ Decoding {+ start_of_transcript: SOT,+ end_of_text: EOT,+ transcribe: TRANSCRIBE,+ no_timestamps: NO_TIMESTAMPS,+ max_length: 448,+ languages: vec![EN, FR],+ // 220 is the leading space and 50257 the end of text, which is `begin_suppress_tokens`.+ suppress: vec![1, 2, 7],+ suppress_at_begin: vec![220, EOT],+ }+ }++ /// Records what the loop asked for, and answers with a scripted sequence of tokens.+ struct Scripted {+ /// One winning token per *generated* position; the prompt's three discarded steps are not+ /// scripted, because their logits are never read.+ script: Vec<u32>,+ /// Every `(token, step)` the decoder saw, in order.+ steps: Vec<(u32, usize)>,+ /// The mel the encoder was given, so a test can assert it ran exactly once.+ encoded: usize,+ /// Scores for the language tokens at step 0, so detection can be steered.+ language_scores: Vec<(u32, f32)>,+ vocabulary: usize,+ }++ impl Nets for Scripted {+ fn encode(&mut self, mel: &[f32]) -> Result<(), String> {+ assert_eq!(mel.len(), 80 * 3000, "the mel window is a fixed size");+ self.encoded += 1;+ Ok(())+ }++ fn decode_step(&mut self, token: u32, step: usize) -> Result<Vec<f32>, String> {+ self.steps.push((token, step));+ let mut logits = vec![0.0f32; self.vocabulary];+ if step == 0 {+ for &(id, score) in &self.language_scores {+ logits[id as usize] = score;+ }+ return Ok(logits);+ }+ // Positions 1 and 2 are prompt steps whose logits are discarded; position 3 predicts+ // the first transcript token, and position `3 + n` the token after the nth.+ let wanted = step.saturating_sub(PROMPT_TOKENS - 1);+ let token = self.script.get(wanted).copied().unwrap_or(EOT);+ logits[token as usize] = 1.0;+ Ok(logits)+ }+ }++ fn scripted(script: &[u32]) -> Scripted {+ Scripted {+ script: script.to_vec(),+ steps: Vec::new(),+ encoded: 0,+ // English wins unless a test says otherwise.+ language_scores: vec![(EN, 2.0), (FR, 1.0)],+ vocabulary: 51_865,+ }+ }++ fn mel() -> Vec<f32> {+ vec![0.25; 80 * 3000]+ }++ #[test]+ fn the_prompt_is_four_tokens_ending_in_no_timestamps() {+ // The trap this module exists to document. `<|notimestamps|>` last, at position 3, is what+ // keeps the output plain text; dropping it produces `<|0.00|>`-style output that still+ // decodes and still reads like a transcript.+ let mut nets = scripted(&[100, EOT]);+ let out = transcribe(&mut nets, &config(), &mel(), None).expect("transcribes");+ assert_eq!(out, vec![100]);+ let prompt: Vec<(u32, usize)> = nets.steps.iter().take(PROMPT_TOKENS).copied().collect();+ assert_eq!(+ prompt,+ vec![(SOT, 0), (EN, 1), (TRANSCRIBE, 2), (NO_TIMESTAMPS, 3)],+ "{:?}",+ nets.steps+ );+ }++ #[test]+ fn the_language_is_detected_from_step_zero_and_needs_no_extra_pass() {+ // With only `<|startoftranscript|>` fed, the highest-scoring language token is the answer.+ // Step 0 runs either way, so detection is free.+ let mut nets = scripted(&[EOT]);+ nets.language_scores = vec![(EN, 0.5), (FR, 3.0)];+ transcribe(&mut nets, &config(), &mel(), None).expect("transcribes");+ assert_eq!(nets.steps[1], (FR, 1));+ // One encoder run, and the language was fed exactly once: detection cost no extra pass.+ assert_eq!(nets.encoded, 1);+ let languages =+ nets.steps.iter().filter(|(token, _)| config().languages.contains(token)).count();+ assert_eq!(languages, 1, "{:?}", nets.steps);+ }++ #[test]+ fn a_named_language_wins_over_the_scores() {+ // An explicit code beats detection, and the detection logits are simply ignored — which is+ // why step 0 still runs.+ let mut nets = scripted(&[EOT]);+ nets.language_scores = vec![(EN, 9.0), (FR, 0.0)];+ transcribe(&mut nets, &config(), &mel(), Some(FR)).expect("transcribes");+ assert_eq!(nets.steps[1], (FR, 1));+ }++ #[test]+ fn a_language_token_the_model_does_not_have_is_refused() {+ // The caller resolves a code to a token, so a wrong table there would otherwise feed a text+ // id into the prompt and produce confident nonsense.+ let mut nets = scripted(&[EOT]);+ let error = transcribe(&mut nets, &config(), &mel(), Some(42)).expect_err("a text id");+ assert!(error.contains("language tokens"), "{error}");+ assert_eq!(nets.encoded, 0, "the encoder ran before the check");+ }++ #[test]+ fn each_step_feeds_the_previous_token_back_after_the_prompt() {+ // Greedy decoding is a chain, and the step numbering continues from the prompt: the first+ // generated token is fed at position 4, not at 0.+ let mut nets = scripted(&[100, 101, 102, EOT]);+ let out = transcribe(&mut nets, &config(), &mel(), Some(EN)).expect("transcribes");+ assert_eq!(out, vec![100, 101, 102]);+ assert_eq!(+ nets.steps,+ vec![+ (SOT, 0),+ (EN, 1),+ (TRANSCRIBE, 2),+ (NO_TIMESTAMPS, 3),+ (100, 4),+ (101, 5),+ (102, 6),+ ]+ );+ }++ #[test]+ fn end_of_text_ends_the_loop_and_is_not_emitted() {+ let mut nets = scripted(&[100, 101, EOT, 102]);+ let out = transcribe(&mut nets, &config(), &mel(), Some(EN)).expect("transcribes");+ assert_eq!(out, vec![100, 101]);+ // Four prompt steps plus two generated ones: the step that would have fed `EOT` never ran.+ assert_eq!(nets.steps.len(), PROMPT_TOKENS + 2);+ }++ #[test]+ fn end_of_text_at_the_first_position_is_suppressed() {+ // `begin_suppress_tokens` is `[220, 50257]`, so a window with speech in it cannot come back+ // empty because the model was unsure. Without it this returns nothing.+ let mut nets = scripted(&[EOT]);+ // Make `EOT` the strongest and 100 the runner-up at the first position only.+ nets.script = vec![EOT];+ let mut config = config();+ config.suppress_at_begin = vec![220, EOT];+ let out = transcribe(&mut nets, &config, &mel(), Some(EN)).expect("transcribes");+ // Suppressed, so the loop picks *something* rather than stopping immediately.+ assert!(!out.is_empty(), "the first position returned nothing");+ assert_ne!(out[0], EOT);+ // And a leading space is suppressed there too.+ assert_ne!(out[0], 220);+ }++ #[test]+ fn a_suppressed_id_is_never_emitted_at_any_position() {+ let mut config = config();+ config.suppress = vec![100];+ let mut nets = scripted(&[100, 100, EOT]);+ let out = transcribe(&mut nets, &config, &mel(), Some(EN)).expect("transcribes");+ assert!(!out.contains(&100), "{out:?}");+ }++ #[test]+ fn a_decoder_that_never_stops_is_capped() {+ // Greedy decoding can loop forever by repeating itself, and the position table is only 448+ // deep, so the loop stops rather than running past it.+ let mut nets = scripted(&vec![100u32; MAX_NEW_TOKENS + 50]);+ let out = transcribe(&mut nets, &config(), &mel(), Some(EN)).expect("transcribes");+ assert_eq!(out.len(), MAX_NEW_TOKENS);+ // And it did not run a step for a token it had no room to predict from.+ assert_eq!(nets.steps.len(), PROMPT_TOKENS + MAX_NEW_TOKENS - 1);+ // The last step is at position `3 + 223`, comfortably inside the 448-entry table.+ assert!(nets.steps.last().expect("a step").1 < 448);+ }++ #[test]+ fn a_short_max_length_caps_the_loop_before_the_token_budget_does() {+ // `max_length` is the position table, and the prompt spends four of it. A configuration that+ // shrank it must shorten the transcript rather than overrun the table.+ let mut config = config();+ config.max_length = PROMPT_TOKENS + 3;+ assert_eq!(config.budget(), 3);+ let mut nets = scripted(&[100u32; 50]);+ let out = transcribe(&mut nets, &config, &mel(), Some(EN)).expect("transcribes");+ assert_eq!(out.len(), 3);+ }++ #[test]+ fn a_configuration_outside_the_vocabulary_is_refused() {+ let vocabulary = 51_865;+ config().check(vocabulary).expect("the real ids are in range");++ let mut wrong = config();+ wrong.no_timestamps = vocabulary;+ let error = wrong.check(vocabulary).expect_err("past the vocabulary");+ assert!(error.contains("no_timestamps"), "{error}");++ let mut wrong = config();+ wrong.languages.clear();+ let error = wrong.check(vocabulary).expect_err("no languages");+ assert!(error.contains("language tokens"), "{error}");++ let mut wrong = config();+ wrong.max_length = PROMPT_TOKENS;+ let error = wrong.check(vocabulary).expect_err("no room");+ assert!(error.contains("max_length"), "{error}");+ }++ #[test]+ fn argmax_takes_the_lowest_index_of_a_tie_and_skips_nan() {+ assert_eq!(argmax(&[1.0, 3.0, 3.0, 2.0], &[], &[]), Some(1));+ assert_eq!(argmax(&[f32::NAN, 1.0], &[], &[]), Some(1));+ assert_eq!(argmax(&[f32::NAN], &[], &[]), None);+ assert_eq!(argmax(&[], &[], &[]), None);+ // Negative logits are normal — a softmax was never taken.+ assert_eq!(argmax(&[-5.0, -1.0, -9.0], &[], &[]), Some(1));+ // Suppression applies before the comparison, not after.+ assert_eq!(argmax(&[1.0, 9.0, 2.0], &[1], &[]), Some(2));+ assert_eq!(argmax(&[1.0, 9.0, 2.0], &[], &[1, 2]), Some(0));+ }++ #[test]+ fn language_detection_ignores_every_non_language_logit() {+ // A text token will always outscore a language token on a real window, so scoring the+ // language ids against *each other* is the whole of the method.+ let mut logits = vec![0.0f32; 51_865];+ logits[100] = 99.0;+ logits[EN as usize] = 1.0;+ logits[FR as usize] = 2.0;+ assert_eq!(best_of(&logits, &[EN, FR]), Some(FR));+ // An id past the end is skipped rather than panicking.+ assert_eq!(best_of(&logits, &[EN, 99_999]), Some(EN));+ assert_eq!(best_of(&logits, &[]), None);+ }+}