Debian Codegraph @

melder/MAT.cpp

raw symbols SCIP
1 /* MAT.cpp
2 *
3 * Copyright (C) 2017-2021,2025,2026 Paul Boersma
4 *
5 * This code is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or (at
8 * your option) any later version.
9 *
10 * This code is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 * See the GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this work. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #include "melder.h"
20 #include "../dwsys/NUM2.h"
21 //#include "../external/gsl/gsl_blas.h"
22
23 #ifdef macintosh
24 #include "macport_on.h"
25 #include <Accelerate/Accelerate.h>
26 #undef trace
27 #import <MetalPerformanceShaders/MetalPerformanceShaders.h>
28 #include <OpenCL/opencl.h>
29 #include "macport_off.h"
30 #endif
31
32 void centreEachColumn_MAT_inout (MATVU const& x) noexcept {
33 for (integer icol = 1; icol <= x.ncol; icol ++) {
34 const double columnMean = NUMmean (x.column (icol));
35 for (integer irow = 1; irow <= x.nrow; irow ++)
36 x [irow] [icol] -= columnMean;
37 }
38 }
39
40 void centreEachRow_MAT_inout (MATVU const& x) noexcept {
41 for (integer irow = 1; irow <= x.nrow; irow ++)
42 centre_VEC_inout (x [irow]);
43 }
44
45 void doubleCentre_MAT_inout (MATVU const& x) noexcept {
46 centreEachRow_MAT_inout (x);
47 centreEachColumn_MAT_inout (x);
48 }
49
50 void mtm_MAT_out (MATVU const& target, constMATVU const& x) noexcept {
51 Melder_assert (target.nrow == x.ncol);
52 Melder_assert (target.ncol == x.ncol);
53 #if 0
54 for (integer irow = 1; irow <= target.nrow; irow ++) {
55 for (integer icol = irow; icol <= target.ncol; icol ++) {
56 longdouble t = 0.0;
57 for (integer k = 1; k <= x.nrow; k ++)
58 t += x [k] [irow] * x [k] [icol];
59 target [irow] [icol] = target [icol] [irow] = double (t);
60 }
61 }
62 #elif 0
63 for (integer irow = 1; irow <= target.nrow; irow ++) {
64 for (integer icol = irow; icol <= target.ncol; icol ++) {
65 PAIRWISE_SUM (longdouble, sum, integer, x.nrow,
66 const double *px1 = & x [1] [irow];
67 const double *px2 = & x [1] [icol],
68 longdouble (*px1) * longdouble (*px2),
69 (px1 += x.rowStride, px2 += x.rowStride)
70 )
71 target [irow] [icol] = target [icol] [irow] = double (sum);
72 }
73 }
74 #else
75 for (integer irow = 1; irow <= target.nrow; irow ++)
76 for (integer icol = irow; icol <= target.ncol; icol ++)
77 target [irow] [icol] = 0.0;
78 for (integer k = 1; k <= x.nrow; k ++)
79 for (integer irow = 1; irow <= target.nrow; irow ++)
80 for (integer icol = irow; icol <= target.ncol; icol ++)
81 target [irow] [icol] += x [k] [irow] * x [k] [icol];
82 for (integer irow = 2; irow <= target.nrow; irow ++)
83 for (integer icol = 1; icol < irow; icol ++)
84 target [irow] [icol] = target [icol] [irow];
85 #endif
86 }
87
88 void _mul_MAT_out (MATVU const& target, constMATVU const& x, constMATVU const& y) noexcept {
89 /*
90 Precise matrix multiplication, using pairwise summation.
91 */
92 if (x.colStride == 1) {
93 if (y.rowStride == 1) {
94 /*
95 Appropriate for Target := X.Y',
96 if X and Y are packed row-major matrices.
97 The speed is 0.142, 0.716, 1.32, 1.64, 2.33, 2.22, 2.08, 2.31, 2.18, 1.89, 1.77, 1.53 Gflop/s
98 for size = 1, 3, 10, 20, 50, 100, 200, 500, 1000, 2000, 3000, 5000.
99 */
100 for (integer irow = 1; irow <= target.nrow; irow ++) {
101 for (integer icol = 1; icol <= target.ncol; icol ++) {
102 PAIRWISE_SUM (longdouble, sum, integer, x.ncol,
103 const double *px = & x [irow] [1];
104 const double *py = & y [1] [icol],
105 longdouble (*px) * longdouble (*py),
106 (px += 1, py += 1)
107 )
108 target [irow] [icol] = double (sum);
109 }
110 }
111 } else {
112 /*
113 Appropriate for Target := X.Y,
114 if X and Y are packed row-major matrices.
115 The speed is 0.143, 0.684, 1.20, 1.64, 2.24, 2.04, 1.44, 1.22, 0.56, 0.114 Gflop/s
116 for size = 1, 3, 10, 20, 50, 100, 200, 500, 1000, 2000.
117 */
118 for (integer irow = 1; irow <= target.nrow; irow ++) {
119 for (integer icol = 1; icol <= target.ncol; icol ++) {
120 PAIRWISE_SUM (longdouble, sum, integer, x.ncol,
121 const double *px = & x [irow] [1];
122 const double *py = & y [1] [icol],
123 longdouble (*px) * longdouble (*py),
124 (px += 1, py += y.rowStride)
125 )
126 target [irow] [icol] = double (sum);
127 }
128 }
129 }
130 } else if (y.rowStride == 1) {
131 /*
132 Appropriate for Target := X'.Y',
133 if X and Y are packed row-major matrices.
134 The speed is 0.136, 0.666, 1.22, 1.65, 2.36, 1.96, 1.62, 1.24, 0.69, 0.118 Gflop/s
135 for size = 1, 3, 10, 20, 50, 100, 200, 500, 1000, 2000.
136 */
137 for (integer irow = 1; irow <= target.nrow; irow ++) {
138 for (integer icol = 1; icol <= target.ncol; icol ++) {
139 PAIRWISE_SUM (longdouble, sum, integer, x.ncol,
140 const double *px = & x [irow] [1];
141 const double *py = & y [1] [icol],
142 longdouble (*px) * longdouble (*py),
143 (px += x.colStride, py += 1)
144 )
145 target [irow] [icol] = double (sum);
146 }
147 }
148 } else {
149 /*
150 Appropriate for Target := X'.Y,
151 if X and Y are packed row-major matrices.
152 The speed is 0.143, 0.572, 1.10, 1.43, 1.71, 1.70, 1.29, 0.71, 0.067 Gflop/s
153 for size = 1, 3, 10, 20, 50, 100, 200, 500, 1000.
154 */
155 for (integer irow = 1; irow <= target.nrow; irow ++) {
156 for (integer icol = 1; icol <= target.ncol; icol ++) {
157 PAIRWISE_SUM (longdouble, sum, integer, x.ncol,
158 const double *px = & x [irow] [1];
159 const double *py = & y [1] [icol],
160 longdouble (*px) * longdouble (*py),
161 (px += x.colStride, py += y.rowStride)
162 )
163 target [irow] [icol] = double (sum);
164 }
165 }
166 }
167 }
168
169 void _mul_forceAllocation_MAT_out (MATVU const& target, constMATVU x, constMATVU y) {
170 /*
171 As seen above, the only multiplication that stays fast for large sizes,
172 if X and Y are packed row-major matrices, is X.Y';
173 this is because both x.colStride and y.rowStride are 1 in that case.
174 It may therefore be useful to convert any matrix X that has
175 a column stride unequal to 1, and any matrix Y that has a row stride
176 unequal to 1, to matrices that do have these desirable properties.
177
178 For the X.Y case, where X and Y are packed row-major matrices,
179 the speed is 0.084, 0.124, 0.91, 1.56, 2.26, 2.18, 2.12, 2.25, 2.23, 1.85, 1.78, 1.57 Gflop/s
180 for size = 1, 3, 10, 20, 50, 100, 200, 500, 1000, 2000, 3000, 5000.
181
182 For the X.Y' case, where X and Y are packed row-major matrices, there is no allocation, and
183 the speed is 0.084, 0.610, 1.26, 1.69, 2.32, 2.20, 2.12, 2.28, 2.24, 1.91, 1.76, 1.53 Gflop/s
184 for size = 1, 3, 10, 20, 50, 100, 200, 500, 1000, 2000, 3000, 5000.
185
186 For the X'.Y case, where X and Y are packed row-major matrices,
187 the speed is 0.082, 0.068, 0.73, 1.42, 2.20, 2.14, 2.09, 2.27, 2.21, 1.84, 1.77, 1.53 Gflop/s
188 for size = 1, 3, 10, 20, 50, 100, 200, 500, 1000, 2000, 3000, 5000.
189
190 For the X'.Y' case, where X and Y are packed row-major matrices,
191 the speed is 0.082, 0.117, 0.90, 1.57, 2.25, 2.19, 2.12, 2.23, 2.09, 1.92, 1.69, 1.48 Gflop/s
192 for size = 1, 3, 10, 20, 50, 100, 200, 500, 1000, 2000, 3000, 5000.
193 */
194 autoMAT tmpX, tmpY; // the scope shall extend to the end of the function
195 if (x.colStride != 1) {
196 tmpX = copy_MAT (x);
197 x = tmpX.all();
198 Melder_assert (x.colStride == 1);
199 }
200 if (y.rowStride != 1) {
201 tmpY = transpose_MAT (y);
202 y = tmpY.transpose();
203 Melder_assert (y.rowStride == 1);
204 }
205 for (integer irow = 1; irow <= target.nrow; irow ++) {
206 for (integer icol = 1; icol <= target.ncol; icol ++) {
207 PAIRWISE_SUM (longdouble, sum, integer, x.ncol,
208 const double *px = & x [irow] [1];
209 const double *py = & y [1] [icol],
210 longdouble (*px) * longdouble (*py),
211 (px += 1, py += 1)
212 )
213 target [irow] [icol] = double (sum);
214 }
215 }
216 }
217
218 void _mul_allowAllocation_MAT_out (MATVU const& target, constMATVU x, constMATVU y) {
219 /*
220 The faster of _mul_MAT_out and _mul_forceAllocation_MAT_out.
221 Allocation takes place only for larger matrices, e.g. from size 47 on
222 (100,000 flops).
223
224 For the X.Y case, where X and Y are packed row-major matrices,
225 the speed is 0.204, 1.130, 3.74, 3.47, 4.77, 3.81, 4.05, 4.26, 3.92, 2.82, 2.83, 2.80 Gflop/s on 2.9 GHz i9
226 the speed is 0.158, 1.452, 3.70, 4.40, 6.01, 4.55, 4.56, 4.76, 4.84, 3.23, 3.23, 3.26 Gflop/s with SSE 4.2
227 the speed is 0.135, 1.483, 3.85, 4.80, 5.60, 4.49, 4.43, 4.52, 5.05, 3.31, 3.19, 3.25 Gflop/s with AVX2
228 the speed is 0.087, 0.574, 1.18, 1.61, 2.25, 2.14, 2.11, 2.23, 2.23, 1.88, 1.74, 1.53 Gflop/s
229 for size = 1, 3, 10, 20, 50, 100, 200, 500, 1000, 2000, 3000, 5000.
230
231 For the X.Y' case, where X and Y are packed row-major matrices, there is never allocation, and
232 the speed is 0.088, 0.577, 1.28, 1.67, 2.27, 2.18, 2.12, 2.28, 2.20, 1.96, 1.78, 1.57 Gflop/s
233 for size = 1, 3, 10, 20, 50, 100, 200, 500, 1000, 2000, 3000, 5000.
234
235 For the X'.Y case, where X and Y are packed row-major matrices,
236 the speed is 0.084, 0.547, 1.12, 1.44, 2.20, 2.15, 2.04, 2.25, 2.18, 1.92, 1.74, 1.48 Gflop/s
237 for size = 1, 3, 10, 20, 50, 100, 200, 500, 1000, 2000, 3000, 5000.
238
239 For the X'.Y' case, where X and Y are packed row-major matrices,
240 the speed is 0.084, 0.553, 1.18, 1.63, 2.31, 2.12, 2.12, 2.25, 2.16, 1.90, 1.79, 1.50 Gflop/s
241 for size = 1, 3, 10, 20, 50, 100, 200, 500, 1000, 2000, 3000, 5000.
242 */
243 if (x.colStride == 1) {
244 if (y.rowStride == 1) {
245 for (integer irow = 1; irow <= target.nrow; irow ++) {
246 for (integer icol = 1; icol <= target.ncol; icol ++) {
247 PAIRWISE_SUM (longdouble, sum, integer, x.ncol,
248 const double *px = & x [irow] [1];
249 const double *py = & y [1] [icol],
250 longdouble (*px) * longdouble (*py),
251 (px += 1, py += 1)
252 )
253 target [irow] [icol] = double (sum);
254 }
255 }
256 } else {
257 if (double (target.nrow) * double (target.ncol) * double (x.ncol) > 1e5) {
258 autoMAT tmpY = transpose_MAT (y);
259 y = tmpY.transpose();
260 Melder_assert (y.rowStride == 1);
261 for (integer irow = 1; irow <= target.nrow; irow ++) {
262 for (integer icol = 1; icol <= target.ncol; icol ++) {
263 PAIRWISE_SUM (longdouble, sum, integer, x.ncol,
264 const double *px = & x [irow] [1];
265 const double *py = & y [1] [icol],
266 longdouble (*px) * longdouble (*py),
267 (px += 1, py += 1)
268 )
269 target [irow] [icol] = double (sum);
270 }
271 }
272 } else {
273 for (integer irow = 1; irow <= target.nrow; irow ++) {
274 for (integer icol = 1; icol <= target.ncol; icol ++) {
275 PAIRWISE_SUM (longdouble, sum, integer, x.ncol,
276 const double *px = & x [irow] [1];
277 const double *py = & y [1] [icol],
278 longdouble (*px) * longdouble (*py),
279 (px += 1, py += y.rowStride)
280 )
281 target [irow] [icol] = double (sum);
282 }
283 }
284 }
285 }
286 } else if (y.rowStride == 1) {
287 if (double (target.nrow) * double (target.ncol) * double (x.ncol) > 1e5) {
288 autoMAT tmpX = copy_MAT (x);
289 x = tmpX.all();
290 Melder_assert (x.colStride == 1);
291 for (integer irow = 1; irow <= target.nrow; irow ++) {
292 for (integer icol = 1; icol <= target.ncol; icol ++) {
293 PAIRWISE_SUM (longdouble, sum, integer, x.ncol,
294 const double *px = & x [irow] [1];
295 const double *py = & y [1] [icol],
296 longdouble (*px) * longdouble (*py),
297 (px += 1, py += 1)
298 )
299 target [irow] [icol] = double (sum);
300 }
301 }
302 } else {
303 for (integer irow = 1; irow <= target.nrow; irow ++) {
304 for (integer icol = 1; icol <= target.ncol; icol ++) {
305 PAIRWISE_SUM (longdouble, sum, integer, x.ncol,
306 const double *px = & x [irow] [1];
307 const double *py = & y [1] [icol],
308 longdouble (*px) * longdouble (*py),
309 (px += x.colStride, py += 1)
310 )
311 target [irow] [icol] = double (sum);
312 }
313 }
314 }
315 } else {
316 if (double (target.nrow) * double (target.ncol) * double (x.ncol) > 1e5) {
317 autoMAT tmpX = copy_MAT (x);
318 x = tmpX.all();
319 Melder_assert (x.colStride == 1);
320 autoMAT tmpY = transpose_MAT (y);
321 y = tmpY.transpose();
322 Melder_assert (y.rowStride == 1);
323 for (integer irow = 1; irow <= target.nrow; irow ++) {
324 for (integer icol = 1; icol <= target.ncol; icol ++) {
325 PAIRWISE_SUM (longdouble, sum, integer, x.ncol,
326 const double *px = & x [irow] [1];
327 const double *py = & y [1] [icol],
328 longdouble (*px) * longdouble (*py),
329 (px += 1, py += 1)
330 )
331 target [irow] [icol] = double (sum);
332 }
333 }
334 } else {
335 for (integer irow = 1; irow <= target.nrow; irow ++) {
336 for (integer icol = 1; icol <= target.ncol; icol ++) {
337 PAIRWISE_SUM (longdouble, sum, integer, x.ncol,
338 const double *px = & x [irow] [1];
339 const double *py = & y [1] [icol],
340 longdouble (*px) * longdouble (*py),
341 (px += x.colStride, py += y.rowStride)
342 )
343 target [irow] [icol] = double (sum);
344 }
345 }
346 }
347 }
348 }
349
350 static inline void MATmul_rough_naiveReferenceImplementation (MATVU const& target, constMATVU const& x, constMATVU const& y) noexcept {
351 /*
352 If x.colStride == size and y.colStride == 1,
353 this version is 0.073, 1.32, 1.17, 0.58 Gflop/s for size = 1,10,100,1000.
354 */
355 for (integer irow = 1; irow <= target.nrow; irow ++) {
356 for (integer icol = 1; icol <= target.ncol; icol ++) {
357 target [irow] [icol] = 0.0;
358 for (integer i = 1; i <= x.ncol; i ++)
359 target [irow] [icol] += x [irow] [i] * y [i] [icol];
360 }
361 }
362 }
363 void _mul_fast_MAT_out (MATVU const& target, constMATVU const& x, constMATVU const& y) noexcept {
364 if ((false)) {
365 MATmul_rough_naiveReferenceImplementation (target, x, y);
366 } else if (y.colStride == 1) {
367 /*
368 This case is appropriate for the multiplication of full matrices
369 X.Y
370 or
371 X'.Y
372
373 The speed for X.Y is 0.053, 1.37, 3.14, 2.99, 2.38, 2.06, 1.70 Gflop/s
374 for size = 1, 10, 100, 1000, 2000, 3000, 5000.
375 The speed for X'.Y is 0.063, 1.37, 3.11, 2.72 Gflop/s for size = 1,10,100,1000.
376
377 The trick is to have the inner loop run along two fastest indices;
378 for target as well as y, this fastest index is the last index.
379 Note that the multiplication factor within the inner loop is constant,
380 so we move it out of the loop (by hand, in case the compiler doesn't do it).
381 */
382 #if 1
383 for (integer irow = 1; irow <= target.nrow; irow ++) {
384 VECVU const targetrow = target [irow];
385 for (integer icol = 1; icol <= target.ncol; icol ++)
386 targetrow [icol] = 0.0;
387 for (integer i = 1; i <= x.ncol; i ++) {
388 const double xcell = x [irow] [i];
389 constVECVU const yrow = y [i];
390 for (integer icol = 1; icol <= target.ncol; icol ++)
391 targetrow [icol] += xcell * yrow [icol];
392 }
393 }
394 #elif 0
395 /*
396 Using 64-bit BLAS from Apple's Accelerate framework.
397 The speed for X.Y is 0.037, 1.51, 3.40, 2.40, 1.82, 1.64, 1.04 Gflop/s
398 for size = 1, 10, 100, 1000, 2000, 3000, 5000.
399 This is not really faster than our own simple implementation
400 (perhaps 32-bit BLAS is faster, because it can use more flops per cycle).
401 */
402 cblas_dgemm (CblasRowMajor, CblasNoTrans, CblasNoTrans,
403 target.nrow, target.ncol, x.ncol,
404 1.0,
405 & x [1] [1], x.rowStride,
406 & y [1] [1], y.rowStride,
407 0.0,
408 & target [1] [1], target.rowStride
409 );
410 #else
411 /*
412 An implementation that is notationally ideal.
413 Does the compiler manage to move the constant parts
414 of the expression outside the loop?
415
416 The speed for X.Y is 0.056, 1.08, 2.99, 2.87 Gflop/s for size = 1,10,100,1000.
417 */
418 for (integer irow = 1; irow <= target.nrow; irow ++) {
419 for (integer icol = 1; icol <= target.ncol; icol ++)
420 target [irow] [icol] = 0.0;
421 for (integer i = 1; i <= x.ncol; i ++)
422 for (integer icol = 1; icol <= target.ncol; icol ++)
423 target [irow] [icol] += x [irow] [i] * y [i] [icol];
424 }
425 #endif
426 } else if (y.rowStride == 1) {
427 if (x.colStride == 1) {
428 /*
429 This case will be appropriate for the multiplication of full matrices
430 X.Y'
431 The speed is 0.064, 1.18, 1.67, 1.69 Gflop/s for size = 1,10,100,1000.
432 */
433 _mul_MAT_out (target, x, y);
434 } else {
435 /*
436 This case will be appropriate for the multiplication of full matrices
437 X'.Y'
438
439 So we will make this fast by making the target matrix column-major.
440 The speed will be 0.065, 1.27, 1.45, 1.21 Gflop/s for size = 1,10,100,1000.
441 However, this will work only once an automatrix has row and column strides;
442 until that time we cannot really modify the structure of `target`.
443
444 For the moment, the target has to stay row-major.
445 The speed is 0.064, 1.21, 1.41, 0.43 Gflop/s for size = 1,10,100,1000.
446
447 The trick is to have the inner loop run along two fastest indices;
448 for both target (in future) and y, this fastest index is the first index.
449 */
450 //target.rowStride = 1;
451 //target.colStride = target.nrow;
452 for (integer icol = 1; icol <= target.ncol; icol ++) {
453 VECVU const targetcolumn = target.column (icol);
454 for (integer irow = 1; irow <= target.nrow; irow ++)
455 targetcolumn [irow] = 0.0;
456 for (integer i = 1; i <= x.ncol; i ++) {
457 constVECVU const ycolumn = y.column (i);
458 for (integer irow = 1; irow <= target.nrow; irow ++)
459 targetcolumn [irow] += x [irow] [i] * ycolumn [irow];
460 }
461 }
462 }
463 } else {
464 /*
465 A rare case: the strides of y are both greater than 1.
466 We do not bother to optimize these cases yet.
467 */
468 MATmul_rough_naiveReferenceImplementation (target, x, y);
469 }
470 }
471
472 void MATmul_forceMetal_ (MATVU const& target, constMATVU const& x, constMATVU const& y) {
473 #ifdef macintosh
474 if (@available (macOS 10.13, *)) {
475 /*
476 The speed is 0.000'005, 0.004, 1.86, 17.1, 13.8, 58, 41.4, 76, 42.5, 88, 63, 120, 255, 337, 525, 577, 620, 734, 769, 798, 894, 857, 868, 900, 872, 875, 956, 914 Gflop/s AMD Radeon Pro Vega 20 (4 GB)
477 The speed is 0.000'007, 0.006, 2.37, 20.3, 15.7, 42, 35.7, 73, 54.3, 90, 72, 118, 245, 349, 575, 667, 1024, 1028, 1090, 1175, 1220, 1206, 1249, 1285, 1265, 1260, 1302, 1311, 1336, 1192, 1226 Gflop/s AMD Radeon RX Vega 56 (BlackMagic, 8 GB)
478 for size = 1, 10, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 2000, 3000, 5000, 7000, 10000, 12000, 15000, 17000, 18000, 18500, 18700, 18800, 18900, 19000, 20000, 21000, 22000, 25000, 30000.
479 */
480 static bool gpuInited = false;
481 static id <MTLDevice> gpuDevice;
482 static id <MTLCommandQueue> gpuQueue;
483 if (! gpuInited) {
484 NSArray <id<MTLDevice>> *gpuDeviceList = MTLCopyAllDevices ();
485 NSUInteger numberOfGpuDevices = [gpuDeviceList count];
486 Melder_casual (U"Found ", numberOfGpuDevices, U" GPU devices.");
487 if (numberOfGpuDevices < 2) {
488 /*
489 Easy choice.
490 */
491 gpuDevice = MTLCreateSystemDefaultDevice ();
492 } else {
493 int externalGpuDeviceNumber = -1, discreteGpuDeviceNumber = -1;
494 for (NSUInteger idevice = 0; idevice < numberOfGpuDevices; idevice ++) {
495 id <MTLDevice> device = [gpuDeviceList objectAtIndex: idevice];
496 autostring32 deviceName = Melder_8to32_e ([[device name] UTF8String]);
497 Melder_casual (U"GPU device ", idevice, U": ", deviceName.get());
498 if (device. removable)
499 externalGpuDeviceNumber = int (idevice);
500 else if (! device. lowPower)
501 discreteGpuDeviceNumber = int (idevice);
502 }
503 if (externalGpuDeviceNumber != -1)
504 gpuDevice = [gpuDeviceList objectAtIndex: NSUInteger (externalGpuDeviceNumber)];
505 else if (discreteGpuDeviceNumber != -1)
506 gpuDevice = [gpuDeviceList objectAtIndex: NSUInteger (discreteGpuDeviceNumber)];
507 else
508 gpuDevice = MTLCreateSystemDefaultDevice (); // unlikely fallback
509 }
510 autostring32 deviceName = Melder_8to32_e ([[gpuDevice name] UTF8String]);
511 Melder_casual (U"GPU device for computing: ", deviceName.get());
512 gpuInited = true;
513 gpuQueue = [gpuDevice newCommandQueue];
514 }
515 //Melder_casual (U"start ", Melder_stopwatch ());
516 MPSMatrixMultiplication *matrixMultiplication = [[MPSMatrixMultiplication alloc]
517 initWithDevice: gpuDevice
518 resultRows: integer_to_uinteger_a (target.nrow)
519 resultColumns: integer_to_uinteger_a (target.ncol)
520 interiorColumns: integer_to_uinteger_a (x.ncol)
521 ];
522 Melder_assert (matrixMultiplication != nil);
523
524 uinteger xRowStrideInBytes = [MPSMatrixDescriptor rowBytesForColumns: uinteger (x.ncol) dataType: MPSDataTypeFloat32];
525 uinteger xRowStrideInFloats = xRowStrideInBytes / sizeof (float);
526 autovector <float> x32 = newvectorzero <float> (integer (uinteger (x.nrow) * xRowStrideInFloats));
527 for (integer irow = 1; irow <= x.nrow; irow ++) {
528 float *prow = & x32 [1] + uinteger (irow - 1) * xRowStrideInFloats;
529 for (integer icol = 1; icol <= x.ncol; icol ++)
530 *prow ++ = float (x [irow] [icol]);
531 }
532
533 uinteger yRowStrideInBytes = [MPSMatrixDescriptor rowBytesForColumns: uinteger (y.ncol) dataType: MPSDataTypeFloat32];
534 uinteger yRowStrideInFloats = yRowStrideInBytes / sizeof (float);
535 autovector <float> y32 = newvectorzero <float> (integer (uinteger (y.nrow) * yRowStrideInFloats));
536 for (integer irow = 1; irow <= y.nrow; irow ++) {
537 float *prow = & y32 [1] + uinteger (irow - 1) * yRowStrideInFloats;
538 for (integer icol = 1; icol <= y.ncol; icol ++)
539 *prow ++ = float (y [irow] [icol]);
540 }
541
542 uinteger targetRowStrideInBytes = [MPSMatrixDescriptor rowBytesForColumns: uinteger (y.ncol) dataType: MPSDataTypeFloat32];
543 uinteger targetRowStrideInFloats = targetRowStrideInBytes / sizeof (float);
544 autovector <float> target32 = newvectorzero <float> (integer (uinteger (target.nrow) * targetRowStrideInFloats));
545
546 uinteger x32length = uinteger (x.nrow) * xRowStrideInBytes;
547 id <MTLBuffer> bufferX = [gpuDevice newBufferWithBytes: & x32 [1] length: x32length options: MTLResourceStorageModeManaged];
548 Melder_assert (bufferX != nil);
549
550 uinteger y32length = uinteger (y.nrow) * yRowStrideInBytes;
551 id <MTLBuffer> bufferY = [gpuDevice newBufferWithBytes: & y32 [1] length: y32length options: MTLResourceStorageModeManaged];
552 Melder_assert (bufferY != nil);
553
554 uinteger target32length = uinteger (target.nrow) * targetRowStrideInBytes;
555 id <MTLBuffer> bufferTarget = [gpuDevice newBufferWithBytes: & target32 [1] length: target32length options: MTLResourceStorageModeShared];
556 Melder_assert (bufferTarget != nil);
557 //Melder_casual (U"to GPU ", Melder_stopwatch ());
558
559 MPSMatrixDescriptor *descriptorX =
560 [MPSMatrixDescriptor matrixDescriptorWithRows: uinteger (x.nrow)
561 columns: uinteger (x.ncol)
562 rowBytes: xRowStrideInBytes
563 dataType: MPSDataTypeFloat32];
564 MPSMatrixDescriptor *descriptorY =
565 [MPSMatrixDescriptor matrixDescriptorWithRows: uinteger (y.nrow)
566 columns: uinteger (y.ncol)
567 rowBytes: yRowStrideInBytes
568 dataType: MPSDataTypeFloat32];
569 MPSMatrixDescriptor *descriptorTarget =
570 [MPSMatrixDescriptor matrixDescriptorWithRows: uinteger (target.nrow)
571 columns: uinteger (target.ncol)
572 rowBytes: targetRowStrideInBytes
573 dataType: MPSDataTypeFloat32];
574
575 MPSMatrix *mpsX = [[MPSMatrix alloc] initWithBuffer: bufferX descriptor: descriptorX];
576 Melder_assert (mpsX != nil);
577 MPSMatrix *mpsY = [[MPSMatrix alloc] initWithBuffer: bufferY descriptor: descriptorY];
578 Melder_assert (mpsY != nil);
579 MPSMatrix *mpsTarget = [[MPSMatrix alloc] initWithBuffer: bufferTarget descriptor: descriptorTarget];
580 Melder_assert (mpsTarget != nil);
581
582 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
583 id <MTLCommandBuffer> commandBuffer = [gpuQueue commandBuffer]; // autoreleased
584 [matrixMultiplication encodeToCommandBuffer: commandBuffer
585 leftMatrix: mpsX
586 rightMatrix: mpsY
587 resultMatrix: mpsTarget];
588 [commandBuffer commit];
589 /*
590 For testing.
591 */
592 constexpr integer numberOfTimes = 0;
593 id <MTLCommandBuffer> commandBuffers [numberOfTimes];
594 for (integer itime = 0; itime < numberOfTimes; itime ++) {
595 commandBuffers [itime] = [gpuQueue commandBuffer];
596 [matrixMultiplication encodeToCommandBuffer: commandBuffers [itime]
597 leftMatrix: mpsX
598 rightMatrix: mpsTarget
599 resultMatrix: mpsY];
600 [matrixMultiplication encodeToCommandBuffer: commandBuffers [itime]
601 leftMatrix: mpsX
602 rightMatrix: mpsY
603 resultMatrix: mpsTarget];
604 [commandBuffers [itime] commit];
605 }
606 [commandBuffer waitUntilCompleted];
607 for (integer itime = 0; itime < numberOfTimes; itime ++) {
608 [commandBuffers [itime] waitUntilCompleted];
609 }
610 //Melder_casual (U"in GPU ", Melder_stopwatch ());
611 NSError *error = [commandBuffer error];
612 if (error) {
613 /*
614 Save the error messages before the release of `commandBuffer` invalidates `error`.
615 */
616 autostring32 localizedDescription = Melder_8to32_e ([[error localizedDescription] UTF8String]);
617 autostring32 localizedFailureReason = Melder_8to32_e ([[error localizedFailureReason] UTF8String]);
618 autostring32 localizedRecoverySuggestion = Melder_8to32_e ([[error localizedRecoverySuggestion] UTF8String]);
619 [bufferX release];
620 [bufferY release];
621 [bufferTarget release];
622 [matrixMultiplication release];
623 [mpsX release];
624 [mpsY release];
625 [mpsTarget release];
626 [pool release]; // this releases `commandBuffer`
627 Melder_throw (U"Matrix multiplication in Metal: Error during execution: ",
628 localizedDescription.get(), localizedFailureReason.get(), localizedRecoverySuggestion.get());
629 }
630 [error release];
631 const float *const rawPointer = (const float *) [bufferTarget contents];
632 for (integer irow = 1; irow <= target.nrow; irow ++) {
633 const float * prow = rawPointer + uinteger (irow - 1) * targetRowStrideInFloats;
634 for (integer icol = 1; icol <= target.ncol; icol ++) {
635 const double value = double (*prow ++);
636 target [irow] [icol] = value;
637 }
638 }
639 //Melder_casual (U"from GPU ", Melder_stopwatch ());
640 [bufferX release];
641 [bufferY release];
642 [bufferTarget release];
643 [matrixMultiplication release];
644 [mpsX release];
645 [mpsY release];
646 [mpsTarget release];
647 //[descriptorX release]; // apparently the MPSMatrix objects have become owners?
648 //[descriptorY release];
649 //[descriptorTarget release];
650 [pool release]; // this releases `commandBuffer`
651 /*
652 Check the result.
653 */
654 //return;
655 const integer numberOfChecks = Melder_iround (pow (target.nrow * target.ncol, 0.33333));
656 integer numberOfUnexpectedZeroes = 0;
657 for (integer icheck = 1; icheck <= numberOfChecks; icheck ++) {
658 const integer rowNumber = NUMrandomInteger (1, target.nrow);
659 const integer columnNumber = NUMrandomInteger (1, target.ncol);
660 const double targetValue = target [rowNumber] [columnNumber];
661 double checkedValue = 0.0;
662 for (integer i = 1; i <= x.ncol; i ++)
663 checkedValue += x [rowNumber] [i] * y [i] [columnNumber];
664 if (checkedValue != 0.0) {
665 //Melder_require (targetValue != 0.0,
666 // U"GPU matrix multiplication incorrect: unexpected zero at row ", rowNumber, U" and column ", columnNumber, U": value should be ", checkedValue, U".");
667 if (targetValue == 0.0) {
668 numberOfUnexpectedZeroes ++;
669 } else {
670 const double relativeError = fabs (checkedValue / targetValue - 1.0);
671 if (relativeError > 10.0) Melder_casual
672 (U"GPU matrix multiplication warning: unexpected imprecision of ", relativeError, U".");
673 }
674 }
675 }
676 if (numberOfUnexpectedZeroes > 0) Melder_casual
677 (U"GPU matrix multiplication warning: found ", numberOfUnexpectedZeroes, U" unexpected zeroes, out of ", numberOfChecks, U".");
678 return;
679 }
680 #else
681 mul_MAT_out (target, x, y);
682 #endif
683 }
684
685 void MATmul_forceOpenCL_ (MATVU const& target, constMATVU const& x, constMATVU const& y) {
686 #ifdef macintosh
687 static bool gpuInited = false;
688 static cl_context openclContext = nullptr;
689 static cl_command_queue commandQueue = nullptr;
690 static cl_kernel kernel = nullptr;
691 if (! gpuInited) {
692 cl_platform_id platformIDs = nullptr;
693 cl_uint numberOfPlatforms;
694 cl_int status = clGetPlatformIDs (1, & platformIDs, & numberOfPlatforms);
695 cl_device_id deviceIDs = nullptr;
696 cl_uint numberOfDevices;
697 status = clGetDeviceIDs (platformIDs, CL_DEVICE_TYPE_GPU, 1, & deviceIDs, & numberOfDevices);
698 openclContext = clCreateContext (nullptr, 1, & deviceIDs, nullptr, nullptr, & status);
699 commandQueue = clCreateCommandQueue (openclContext, deviceIDs, 0, & status);
700 conststring8 sourceText = "__kernel void vector_add(__global const int *A, __global const int *B, __global int *C) {"
701
702 /* Get the index of the current element to be processed */
703 "int i = get_global_id(0);"
704
705 /* Do the operation */
706 "C[i] = A[i] + B[i];"
707 "}";
708 size_t sourceSize = strlen (sourceText);
709 cl_program program = clCreateProgramWithSource (openclContext, 1,
710 (const char **) & sourceText, (const size_t *) & sourceSize, & status);
711 status = clBuildProgram (program, 1, & deviceIDs, nullptr, nullptr, nullptr);
712 kernel = clCreateKernel (program, "MATmul_opencl", & status);
713 }
714 #if 0
715 // Create memory buffers on the device for each vector
716 cl_mem a_mem_obj = clCreateBuffer (context, CL_MEM_READ_ONLY,
717 LIST_SIZE * sizeof(int), NULL, &ret);
718 cl_mem b_mem_obj = clCreateBuffer (context, CL_MEM_READ_ONLY,
719 LIST_SIZE * sizeof(int), NULL, &ret);
720 cl_mem c_mem_obj = clCreateBuffer (context, CL_MEM_WRITE_ONLY,
721 LIST_SIZE * sizeof(int), NULL, &ret);
722 // Copy the lists A and B to their respective memory buffers
723 ret = clEnqueueWriteBuffer(command_queue, a_mem_obj, CL_TRUE, 0,
724 LIST_SIZE * sizeof(int), A, 0, NULL, NULL);
725 ret = clEnqueueWriteBuffer(command_queue, b_mem_obj, CL_TRUE, 0,
726 LIST_SIZE * sizeof(int), B, 0, NULL, NULL);
727 // Set the arguments of the kernel
728 ret = clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&a_mem_obj);
729 ret = clSetKernelArg(kernel, 1, sizeof(cl_mem), (void *)&b_mem_obj);
730 ret = clSetKernelArg(kernel, 2, sizeof(cl_mem), (void *)&c_mem_obj);
731
732 // Execute the OpenCL kernel on the list
733 size_t global_item_size = LIST_SIZE; // Process the entire lists
734 size_t local_item_size = 64; // Divide work items into groups of 64
735 ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL,
736 &global_item_size, &local_item_size, 0, NULL, NULL);
737
738 // Read the memory buffer C on the device to the local variable C
739 int *C = (int*)malloc(sizeof(int)*LIST_SIZE);
740 ret = clEnqueueReadBuffer(command_queue, c_mem_obj, CL_TRUE, 0,
741 LIST_SIZE * sizeof(int), C, 0, NULL, NULL);
742
743 // Display the result to the screen
744 for(i = 0; i < LIST_SIZE; i++)
745 printf("%d + %d = %d\n", A[i], B[i], C[i]);
746 // Clean up
747 ret = clFlush(command_queue);
748 ret = clFinish(command_queue);
749 ret = clReleaseMemObject(a_mem_obj);
750 ret = clReleaseMemObject(b_mem_obj);
751 ret = clReleaseMemObject(c_mem_obj);
752 free(A);
753 free(B);
754 free(C);
755 #endif
756 #else
757 mul_MAT_out (target, x, y);
758 #endif
759 }
760
761 void outer_MAT_out (MATVU const& target, constVECVU const& x, constVECVU const& y) {
762 for (integer irow = 1; irow <= x.size; irow ++)
763 for (integer icol = 1; icol <= y.size; icol ++)
764 target [irow] [icol] = x [irow] * y [icol];
765 }
766 autoMAT outer_MAT (constVECVU const& x, constVECVU const& y) {
767 autoMAT result = raw_MAT (x.size, y.size);
768 outer_MAT_out (result.get(), x, y);
769 return result;
770 }
771
772 autoMAT peaks_MAT (constVECVU const& x, bool includeEdges, int interpolate, bool sortByHeight) {
773 if (x.size < 2) includeEdges = false;
774 integer numberOfPeaks = 0;
775 for (integer i = 2; i < x.size; i ++)
776 if (x [i] > x [i - 1] && x [i] >= x [i + 1])
777 numberOfPeaks ++;
778 if (includeEdges) {
779 if (x [1] > x [2])
780 numberOfPeaks ++;
781 if (x [x.size] > x [x.size - 1])
782 numberOfPeaks ++;
783 }
784 autoMAT result = raw_MAT (2, numberOfPeaks);
785 integer peakNumber = 0;
786 if (includeEdges && x [1] > x [2]) {
787 result [1] [++ peakNumber] = 1;
788 result [2] [peakNumber] = x [1];
789 }
790 for (integer i = 2; i < x.size; i ++) {
791 if (x [i] > x [i - 1] && x [i] >= x [i + 1]) {
792 ++ peakNumber;
793 if (interpolate != 0) { // this is not a boolean; there could follow more options
794 /*
795 Parabolic interpolation.
796 */
797 const double dy = 0.5 * (x [i + 1] - x [i - 1]);
798 const double d2y = (x [i] - x [i - 1]) + (x [i] - x [i + 1]);
799 Melder_assert (d2y > 0.0);
800 result [1] [peakNumber] = (double) i + dy / d2y;
801 result [2] [peakNumber] = x [i] + 0.5 * dy * (dy / d2y);
802 } else {
803 /*
804 Don't interpolate: choose the nearest index.
805 */
806 result [1] [peakNumber] = i;
807 result [2] [peakNumber] = x [i];
808 }
809 }
810 }
811 if (includeEdges && x [x.size] > x [x.size - 1]) {
812 result [1] [++ peakNumber] = x.size;
813 result [2] [peakNumber] = x [x.size];
814 }
815 Melder_assert (peakNumber == numberOfPeaks);
816 if (sortByHeight) {
817 for (integer i = 1; i <= numberOfPeaks; i ++)
818 result [2] [i] *= -1.0;
819 NUMsortTogether (result.row (2), result.row (1));
820
821 for (integer i = 1; i <= numberOfPeaks; i ++)
822 result [2] [i] *= -1.0;
823 }
824 return result;
825 }
826
827 void power_MAT_out (MATVU const& target, constMATVU const& mat, double power) {
828 for (integer irow = 1; irow <= target.nrow; irow ++)
829 power_VEC_out (target.row (irow), mat.row (irow), power);
830 }
831
832 autoMAT splitByLinesAndWhitespace_MAT (conststring32 string) {
833 if (! string)
834 return autoMAT(); // accept null pointer input
835
836 /*
837 The following algorithm has been based on Matrix_readFromRawTextFile().
838 */
839 const char32 *p = & string [0];
840
841 /*
842 Count columns.
843 */
844 integer numberOfColumns = 0;
845 for (;;) {
846 char32 kar = * (p ++);
847 if (kar == U'\0' || Melder_isVerticalSpace (kar))
848 break;
849 if (Melder_isHorizontalSpace (kar))
850 continue;
851 numberOfColumns ++;
852 do {
853 kar = * (p ++);
854 } while (kar != U'\0' && ! Melder_isHorizontalOrVerticalSpace (kar));
855 if (kar == U'\0' || Melder_isVerticalSpace (kar))
856 break;
857 }
858 if (numberOfColumns == 0)
859 return autoMAT();
860
861 /*
862 Count cells.
863 */
864 const integer numberOfCells = NUMnumberOfTokens (string);
865
866 /*
867 Check if all columns are complete.
868 */
869 if (numberOfCells == 0 || numberOfCells % numberOfColumns != 0)
870 Melder_throw (U"The number of cells (", numberOfCells, U") is not a multiple of the number of columns (", numberOfColumns, U").");
871
872 /*
873 Create matrix.
874 */
875 const integer numberOfRows = numberOfCells / numberOfColumns;
876 autoMAT result (numberOfRows, numberOfColumns, MelderArray::kInitializationType::ZERO);
877
878 /*
879 Read cells.
880 */
881 integer irow = 1, icol = 0;
882 p = & string [0];
883 for (;;) {
884 Melder_skipHorizontalOrVerticalSpace (& p);
885 if (*p == U'\0')
886 break;
887 const char32 *beginOfInk = p;
888 p ++; // step over first nonspace
889 p = Melder_findEndOfInk (p);
890 if (++ icol > numberOfColumns) {
891 irow ++;
892 icol = 1;
893 }
894 result [irow] [icol] = Melder_atof (beginOfInk);
895 }
896 return result;
897 }
898
899 /* End of file MAT.cpp */