Elffuss BraidHub

kikocis/kleidiai public

main · 47.4 KiBRawPermalink
1//
2// SPDX-FileCopyrightText: Copyright 2025-2026 Arm Limited and/or its affiliates <open-source-office@arm.com>
3//
4// SPDX-License-Identifier: Apache-2.0
5//
6
7#pragma once
8
9#include <atomic>
10#include <cinttypes>
11#include <cstdint>
12#include <cstdio>
13
14#include <time.h>
15
16#include "cache_stats.hpp"
17
18#include "gemm_lib.hpp"
19#include "kai/ops/bfloat.hpp"
20
21#ifndef _GNU_SOURCE
22# define _GNU_SOURCE
23#endif
24
25#ifdef BARE_METAL
26#ifndef __aarch64__
27static unsigned int s;
28#endif // __aarch64__
29
30static void enable_cyclecounter() {
31#ifdef __aarch64__
32 uint64_t tmp;
33
34 __asm __volatile (
35 "mrs %[tmp], pmcr_el0\n"
36 "orr %[tmp], %[tmp], #1\n"
37 "msr pmcr_el0, %[tmp]\n"
38 "mrs %[tmp], pmcntenset_el0\n"
39 "orr %[tmp], %[tmp], #1<<31\n"
40 "msr pmcntenset_el0, %[tmp]\n"
41 : [tmp] "=r" (tmp)
42 );
43#else
44 s = clock();
45#endif
46}
47
48static void disable_cyclecounter() {
49#ifdef __aarch64__
50 uint64_t tmp;
51
52 __asm __volatile (
53 "mov %[tmp], #0x3f\n"
54 "orr %[tmp], %[tmp], #1<<31\n"
55 "msr pmcntenclr_el0, %[tmp]\n"
56 : [tmp] "=r" (tmp)
57 );
58#endif
59}
60
61static inline uint64_t get_cyclecounter() {
62#ifdef __aarch64__
63 uint64_t retval;
64
65 __asm __volatile (
66 "mrs %[retval], pmccntr_el0\n"
67 : [retval] "=r" (retval));
68
69 return retval;
70#else
71 return clock()-s;
72#endif
73}
74#else
75
76/* Prototypes from perf.cpp */
77void start_counter(int fd);
78long long get_counter(int fd);
79long long stop_counter(int fd);
80int open_instruction_counter(void);
81int open_cycle_counter(void);
82
83#endif
84
85class run_timer {
86private:
87 uint64_t total=0;
88 uint64_t first=0;
89 uint64_t best=0;
90 unsigned int runs=0;
91 unsigned int run_delay=0;
92 unsigned int min_ms=0;
93
94 uint64_t macs;
95
96 uint64_t grand_total=0;
97 unsigned int grand_total_iters=0;
98
99 uint64_t best_batch_total;
100 unsigned int best_batch_iters=0;
101
102#ifdef CYCLE_TIMING
103 const char *time_units = "cycles";
104 const char *rate_units = "MACs/cycle";
105#else
106 const char *time_units = "ns";
107 const char *rate_units = "GMAC/sec";
108#endif
109
110public:
111 run_timer(unsigned int run_delay, unsigned int min_ms) : run_delay(run_delay), min_ms(min_ms) { }
112
113 ~run_timer() {
114#ifndef SILENT
115 if (grand_total_iters <= 1) {
116 return;
117 }
118
119 if (min_ms==0) {
120 if (grand_total_iters > 1) {
121 printf("%u total runs, %" PRId64 " total %s, %.2f average %s, %" PRId64 " lowest %s.\n",grand_total_iters,grand_total,time_units,(float)grand_total/grand_total_iters,time_units,best,time_units);
122 }
123 if (grand_total_iters > 2) {
124 printf(" %.2f average %s (excluding first run)\n",(float)(grand_total-first)/(grand_total_iters-1),time_units);
125 }
126 return;
127 }
128
129 printf("Grand total: %u iterations, %" PRId64 " %s, %.1f average %s, %.2f %s.\n",grand_total_iters,grand_total,time_units,(float)grand_total/grand_total_iters,time_units,(float)(macs * grand_total_iters) / grand_total,rate_units);
130 printf("Best batch: %u iterations, %" PRId64" %s, %.1f average %s, %.2f %s.\n",best_batch_iters,best_batch_total,time_units,(float)best_batch_total/best_batch_iters,time_units,(float)(macs * best_batch_iters) / best_batch_total,rate_units);
131 printf("Best single iteration: %" PRId64" %s, %.2f %s\n",best,time_units,(float)macs/best,rate_units);
132#endif
133 }
134
135 // Do we need more iterations in this run?
136 // "Total" will actually measure either ns or cycles, so in cycle mode "ms" means "millions of cycles".
137 bool need_more() {
138 if (runs==0 || total < (min_ms * 1000000)) {
139 return true;
140 }
141
142 grand_total += total;
143 grand_total_iters += runs;
144
145 // In "single run" mode, produce the same output as before
146 if (min_ms==0) {
147#ifndef SILENT
148 printf("Benchmark: %" PRId64 " %s, %f %s.\n",total,time_units,(float)macs/total,rate_units);
149#endif // !SILENT
150 total=0;
151 runs=0;
152 return false;
153 }
154
155 // In "multi run" mode, produce a summary for this batch of runs.
156#ifndef SILENT
157 printf("%u runs, %f avg %s, %f avg %s.\n",runs,(float)total/runs,time_units,(float)(macs * runs)/total,rate_units);
158#endif // !SILENT
159
160 if (best_batch_iters == 0 || ((float)total / runs) < ((float)best_batch_total / best_batch_iters)) {
161 best_batch_total = total;
162 best_batch_iters = runs;
163 }
164
165 total=0;
166 runs=0;
167
168 return false;
169 }
170
171 template <typename T>
172 void operator()(const char *name, uint64_t macs, T func) {
173 this->macs = macs;
174
175 uint64_t res;
176#ifdef CYCLE_TIMING
177#ifdef BARE_METAL
178 uint64_t start, end;
179
180 enable_cyclecounter();
181
182 start = get_cyclecounter();
183 func();
184 end = get_cyclecounter();
185 disable_cyclecounter();
186
187 res=end-start;
188#else
189 int cyclefd = open_cycle_counter();
190
191 start_counter(cyclefd);
192 func();
193 res=stop_counter(cyclefd);
194
195 // If run_delay is defined, wait for a bit here.
196 sleep(run_delay);
197
198 close(cyclefd);
199#endif
200#else
201 struct timespec ts1, ts2;
202
203#ifdef __APPLE__
204 clock_gettime(CLOCK_MONOTONIC_RAW, &ts1);
205 func();
206 clock_gettime(CLOCK_MONOTONIC_RAW, &ts2);
207#else
208 clock_gettime(CLOCK_MONOTONIC, &ts1);
209 func();
210 clock_gettime(CLOCK_MONOTONIC, &ts2);
211#endif // __APPLE__
212
213 res=(ts2.tv_sec - ts1.tv_sec) * 1000000000 + (ts2.tv_nsec - ts1.tv_nsec);
214 // If run_delay is defined, wait for a bit here.
215 sleep(run_delay);
216#endif
217 total += res;
218 if (first==0) {
219 first = res;
220 }
221 if (best==0 or res < best) {
222 best = res;
223 }
224 runs++;
225 }
226};
227
228// Need "cache stats" class similar to run timer
229//
230// - Core class with aggregated stats, averages, etc.
231// - Per thread subclass that manages events, reads each iteration and combines on to aggregated stats
232// - For each iteration
233
234/*
235 * Wrapper to allow "legacy" or "new" kernels to be used by the test/benchmark functions.
236 *
237 * This is the "legacy" version - extract M, N, K from the GemmProblem and pass to kernel constructor.
238 */
239template<bool legacy, QuantizationType quantized, bool perchannel, typename T>
240struct TestKernel {
241 template <typename To, typename Tr>
242 static T get(To A, To B, Tr C, Tr bias, GemmProblem *p, int nthreads, bool do_init) {
243 return T(A,B,C,p->output_width,p->output_channels,p->input_channels,nthreads,do_init);
244 }
245
246 /* This method makes no sense for legacy kernels (there is only one
247 * kernel which is directly implemented. */
248 static void print_kernels(GemmProblem *p, unsigned int nthreads) {
249 printf("Legacy kernel - can't list kernels.\n");
250 }
251};
252
253/*
254 * This is the "new" version - pass GemmProblem directly to the kernel constructor.
255 */
256template<bool perchannel, typename T>
257struct TestKernel<false, QuantizationType::NONE, perchannel, T> {
258 template <typename To, typename Tr>
259 static T get(To A, To B, Tr C, Tr bias, GemmProblem *p, int nthreads, bool do_init) {
260 return T(A,B,C,bias,p,nthreads,do_init);
261 }
262
263 static void print_kernels(GemmProblem *p, unsigned int nthreads) {
264 T::print_kernels(p, nthreads);
265 }
266};
267
268template<bool perchannel, typename T>
269struct TestKernel<false, QuantizationType::FLOAT, perchannel, T> {
270 template <typename To, typename Tw, typename Tr>
271 static T get(std::shared_ptr<Matrix<To>> &A, std::shared_ptr<Matrix<Tw>> &B, std::shared_ptr<Matrix<Tr>> &C,
272 std::shared_ptr<Matrix<Tr>> &bias, GemmProblem *p, int nthreads, bool do_init) {
273 QuantizeParameters<To> qp_A = QuantizeParameters<To>(0, std::pair<float, float>(p->after_relu ? 0.0f : -1.0f, 6.0f));
274 QuantizeParameters<To> qp_B = QuantizeParameters<To>(0, std::pair<float, float>(-1.0f, 1.0f));
275 kai::ops::DequantizeFloat scale(qp_A.m_scale * qp_B.m_scale);
276 return T(A,B,C,bias,scale,p,nthreads,do_init);
277 }
278
279 static void print_kernels(GemmProblem *p, unsigned int nthreads) {
280 T::print_kernels(p, nthreads);
281 }
282};
283
284/* This is the quantized version. */
285template<bool perchannel, typename T>
286struct TestKernel<false, QuantizationType::INTEGER, perchannel, T> {
287 template <typename To, typename Tw, typename Tr>
288 static T get(std::shared_ptr<Matrix<To>> &A, std::shared_ptr<Matrix<Tw>> &B, std::shared_ptr<Matrix<Tr>> &C,
289 std::shared_ptr<Matrix<Tr>> &bias, GemmProblem *p, int nthreads, bool do_init) {
290 unsigned int quantize_sets = perchannel ? p->output_channels : 1;
291
292 /* Invent some dummy quantize parameters */
293 bool do_relu = (p->act.type == Activation::Type::ReLU || p->act.type == Activation::Type::BoundedReLU);
294
295 auto bias_real = std::make_shared<Matrix<int32_t>>(1, p->output_channels, p->output_channels, 1, p->multis);
296
297 if (bias) {
298 bias_real->Copy(bias);
299 } else {
300 bias_real.reset();
301 }
302
303 QuantizeParameters<To> qp_A = QuantizeParameters<To>(std::pair<float, float>(p->after_relu ? 0.0f : -1.0f, 6.0f));
304 std::vector<QuantizeParameters<Tw> > qp_B;
305 for (unsigned int i=0; i<quantize_sets; i++) {
306 if (perchannel) {
307 qp_B.emplace_back(QuantizeParameters<Tw>(0, std::pair<float, float>(-1.0f, 1.0f)));
308 } else {
309 qp_B.emplace_back(QuantizeParameters<Tw>(std::pair<float, float>(-1.0f, 1.0f)));
310 }
311 }
312 QuantizeParameters<Tr> qp_C = QuantizeParameters<Tr>(std::pair<float, float>(do_relu ? 0.0f : -6.0f, 6.0f));
313
314 return T(A,B,C,bias_real,qp_A,qp_B,qp_C,p,nthreads,do_init);
315 }
316
317 static void print_kernels(GemmProblem *p, unsigned int nthreads) {
318 T::print_kernels(p, nthreads);
319 }
320};
321
322/*
323 * This function benchmarks a kernel class, as included above.
324 *
325 * The kernel to be benchmarked is templated on the kernel class.
326 *
327 * The output is ignored, so for safety the kernel will need some mechanism
328 * such as a volatile asm statement to prevent the compiler optimizing it
329 * out.
330 */
331template <typename T, bool legacy, QuantizationType quantized, bool perchannel>
332void benchmark(GemmProblem *p, int iterations, int nthreads, int run_delay, mapfn cpuid_map, const char *kernel_name) {
333 const int total_threads = nthreads * p->n_teams;
334 uint64_t mac_count = (int64_t)p->output_height*p->output_width*p->kernel_height*p->kernel_width*p->output_channels*(p->input_channels/p->groups)*p->batches*p->multis*p->n_teams;
335 cache_stats cs(total_threads);
336
337 if (p->add_problem) {
338 mac_count /= p->input_channels;
339 }
340
341 // Each team has its own set of operand matrices, and it's own instance
342 // of the test kernel. Deal with that in this class.
343 struct team_data {
344 GemmProblem * &p;
345 int nthreads;
346
347 std::shared_ptr<Matrix <typename T::lhs_operand_type> > A;
348 std::shared_ptr<Matrix <typename T::rhs_operand_type> > B;
349 std::shared_ptr<Matrix <typename T::result_type> > C;
350 std::shared_ptr<Matrix <typename T::result_type> > bias;
351
352 T kern;
353
354 static std::shared_ptr<Matrix <typename T::lhs_operand_type> > get_a_matrix(const GemmProblem *p, std::shared_ptr<Matrix <typename T::lhs_operand_type> > from = nullptr) {
355 auto A = std::make_shared<Matrix <typename T::lhs_operand_type> >((p->input_height * p->input_width), p->input_channels, std::max(p->input_channels, p->a_stride), p->batches, p->multis);
356
357#ifndef BARE_METAL
358 if (from) {
359 A->Copy(from);
360 } else {
361 A->Randomize();
362 }
363#endif
364
365 return A;
366 }
367
368 static std::shared_ptr<Matrix <typename T::rhs_operand_type> > get_b_matrix(const GemmProblem *p, std::shared_ptr<Matrix <typename T::rhs_operand_type> > from = nullptr) {
369 auto gemm_k = (p->input_channels / p->groups) * p->kernel_height * p->kernel_width;
370 auto B = std::make_shared<Matrix <typename T::rhs_operand_type> >(gemm_k, p->output_channels, std::max(p->output_channels, p->b_stride), 1, p->multis);
371
372#ifndef BARE_METAL
373 if (from) {
374 B->Copy(from);
375 } else {
376 B->Randomize();
377 }
378#endif
379
380 return B;
381 }
382
383 static std::shared_ptr<Matrix <typename T::result_type> > get_bias(const GemmProblem *p, std::shared_ptr<Matrix <typename T::result_type> > from = nullptr) {
384 if (!p->use_bias) {
385 return nullptr;
386 }
387
388 auto bias = std::make_shared<Matrix <typename T::result_type> >(1, p->output_channels, p->output_channels, 1, p->multis);
389
390#ifndef BARE_METAL
391 if (from) {
392 bias->Copy(from);
393 } else {
394 bias->Randomize();
395 }
396#endif
397 return bias;
398 }
399
400 static bool init_needed() {
401#ifdef BARE_METAL
402 return false;
403#else
404 return true;
405#endif
406 }
407
408 team_data(GemmProblem *&p, int nthreads) :
409 p(p), nthreads(nthreads),
410 A(get_a_matrix(p)), B(get_b_matrix(p)),
411 C(std::make_shared<Matrix <typename T::result_type> >((p->output_height * p->output_width), p->output_channels, p->output_channels, p->batches, p->multis)),
412 bias(get_bias(p)),
413 kern(TestKernel<legacy, quantized, perchannel, T>::get(A, B, C, bias, p, nthreads, init_needed()))
414 {
415 }
416
417 team_data(GemmProblem *&p, int nthreads, team_data &from) :
418 p(p), nthreads(nthreads),
419 A(get_a_matrix(p, from.A)), B(get_b_matrix(p, from.B)),
420 C(std::make_shared<Matrix <typename T::result_type> >((p->output_height * p->output_width), p->output_channels, p->output_channels, p->batches, p->multis)),
421 bias(get_bias(p, from.bias)),
422 kern(TestKernel<legacy, quantized, perchannel, T>::get(A, B, C, bias, p, nthreads, init_needed()))
423 {
424 }
425 };
426
427 int m_round = T::get_m_block();
428 int n_round = T::get_n_block();
429 int k_round = T::get_k_block();
430
431 // Round requested sizes to something the kernel can do.
432 if (m_round > 1 || n_round > 1 || k_round > 1) {
433 assert(p->is_basic_gemm());
434
435 p->output_width=p->input_width = round_up_to_nearest_multiple(p->input_width, m_round);
436 p->output_channels = round_up_to_nearest_multiple(p->output_channels, n_round);
437 p->input_channels = round_up_to_nearest_multiple(p->input_channels, k_round);
438 }
439
440 std::vector<team_data> teams;
441 run_timer thetimer(run_delay, p->min_ms);
442
443#ifdef TEST_TEAMS
444 // In team test mode, copy the data for subsequent teams from team 0.
445 // That way we can check that the results at the end are the same.
446 teams.emplace_back(p, nthreads);
447 for (int i=1; i<p->n_teams; i++) {
448 teams.emplace_back(p, nthreads, teams[0]);
449 }
450#else
451 // In normal mode, each team generates its own data.
452 for (int i=0; i<p->n_teams; i++) {
453 teams.emplace_back(p, nthreads);
454 }
455#endif
456
457 // For the benchmark, print something out to confirm sizes. This can be
458 // checked against "golden" output to make sure we're not running
459 // unexpected sizes.
460#ifndef SILENT
461 if (p->is_basic_gemm()) {
462 printf("Starting MM benchmark: threads=%d teams=%d iterations=%d batches=%lld multis=%lld M=%lld N=%lld K=%lld\n", nthreads, p->n_teams, iterations, (long long)p->batches, (long long)p->multis, (long long)p->output_width, (long long)p->output_channels, (long long)p->input_channels);
463 } else {
464 printf("Starting Conv2D benchmark: threads=%d teams=%d iterations=%d batches=%lld multis=%lld input=%lldx%lld, input channels=%lld, "
465 "kernel=%lldx%lld, stride=%lldx%lld, dilation=%lldx%lld, output=%lldx%lld, output channels=%lld\n",
466 nthreads, p->n_teams, iterations, (long long)p->batches, (long long)p->multis, (long long)p->input_height, (long long)p->input_width,
467 (long long)p->input_channels,
468 (long long)p->kernel_height, (long long)p->kernel_width,
469 (long long)p->out_stride_h, (long long)p->out_stride_w,
470 (long long)p->in_stride_h, (long long)p->in_stride_w,
471 (long long)p->output_height, (long long)p->output_width,
472 (long long)p->output_channels);
473 }
474#endif
475
476
477#ifdef THREADS
478#define COMPLETER_STRIDE 1
479 if (total_threads > 1) {
480 // In multithreaded mode, we start up the extra threads and have them indicate they are waiting first.
481 // The actual timed operation consists of: Releasing the waiters, doing the thread 0 work and joining the worker threads.
482 std::atomic_int waiters(0);
483 int *completed_buffer = (int *)malloc(COMPLETER_STRIDE * total_threads * sizeof(int));
484 volatile int *completed = completed_buffer;
485 std::vector<std::thread> thethreads;
486 volatile int go=0;
487#ifdef BIND_THREADS
488 unsigned int maxcpus = std::thread::hardware_concurrency();
489#endif
490 volatile int reset=0;
491 volatile int finished=0;
492
493
494 for (int i=1; i<total_threads; i++) {
495 thethreads.emplace_back( [&](int myid) {
496#ifdef BIND_THREADS
497 if (cpuid_map) {
498 // Bind thread to relevant CPU.
499 cpu_set_t set;
500
501 CPU_ZERO(&set);
502 CPU_SET(cpuid_map(myid, maxcpus), &set);
503
504 if (sched_setaffinity(0, sizeof(set), &set)) {
505 perror("Error setting worker thread affinity");
506 }
507 }
508#endif
509 int myteam = myid / nthreads;
510 int mythread = myid % nthreads;
511
512 auto csd = cs.get_thread_entry(myid);
513 if (p->cache_stats) {
514 csd->init();
515 }
516
517 // Worker threads will loop forever until "finished" gets set.
518 for (;;) {
519 completed[myid * COMPLETER_STRIDE] = 0;
520
521 __asm __volatile ("dsb sy");
522
523 waiters++;
524
525
526 while (go==0) ;
527
528 if (finished) {
529 break;
530 }
531
532 if (p->cache_stats) {
533 csd->start_count();
534 teams[myteam].kern.Run(mythread);
535 csd->stop_count();
536 } else {
537 teams[myteam].kern.Run(mythread);
538 }
539
540 completed[myid * COMPLETER_STRIDE] = 1;
541
542
543 while (reset==0) ;
544 }
545 }, i);
546 }
547
548#ifdef BIND_THREADS
549 if (cpuid_map) {
550 // Bind main thread
551 cpu_set_t set;
552 CPU_ZERO(&set);
553 CPU_SET(cpuid_map(0, maxcpus), &set);
554 if(sched_setaffinity(0, sizeof(set), &set)) {
555 perror("Error setting main thread affinity");
556 }
557 }
558#endif
559
560 auto csd = cs.get_thread_entry(0);
561 if (p->cache_stats) {
562 csd->init();
563 }
564
565 for (int it=0; it<iterations; it++) {
566 while (thetimer.need_more()) {
567 while (waiters < (total_threads-1) ) {
568
569 }
570
571 reset=0;
572 waiters=0;
573 __asm __volatile ("dsb sy");
574
575
576 thetimer("Benchmark", mac_count, [&](void) {
577 go=1;
578
579 if (p->cache_stats) {
580 csd->start_count();
581 teams[0].kern.Run(0);
582 csd->stop_count();
583 } else {
584 teams[0].kern.Run(0);
585 }
586
587
588 for (int i=1; i<total_threads; i++) {
589 while (!completed[i * COMPLETER_STRIDE]) {
590 /* spin until thread complete */
591 }
592 }
593 });
594
595 csd->stop_count();
596
597 go=0;
598 __asm __volatile ("dsb sy");
599
600 reset=1;
601 }
602 if (p->cache_stats) {
603 cs.report_summary();
604 }
605 }
606
607 /* Make the worked threads exit */
608 {
609 finished=1;
610 __asm __volatile ("dsb sy");
611 go=1;
612 }
613
614 /* Clear up worker threads. */
615 for (int i=1; i<total_threads; i++) {
616 thethreads[i-1].join();
617 }
618
619 free(completed_buffer);
620 } else {
621#else /* THREADS */
622 if (1) {
623#endif /* THREADS */
624#ifdef BIND_THREADS
625 if (cpuid_map) {
626 // If bind is selected, bind even in single thread mode.
627 unsigned int maxcpus = std::thread::hardware_concurrency();
628 cpu_set_t set;
629 CPU_ZERO(&set);
630 CPU_SET(cpuid_map(0, maxcpus), &set);
631 if(sched_setaffinity(0, sizeof(set), &set)) {
632 perror("Error setting main thread affinity");
633 }
634 }
635#endif
636 auto csd = cs.get_thread_entry(0);
637 if (p->cache_stats) {
638 csd->init();
639 }
640
641 for (int it=0; it<iterations; it++) {
642 while(thetimer.need_more()) {
643 thetimer("Benchmark", mac_count, [&](void) {
644 if (p->cache_stats) {
645 csd->start_count();
646 teams[0].kern.Run(0);
647 csd->stop_count();
648 } else {
649 teams[0].kern.Run(0);
650 }
651 });
652 }
653 if (p->cache_stats) {
654 cs.report_summary();
655 }
656 }
657 }
658
659#ifdef TEST_TEAMS
660 // Make sure all the teams got the same result.
661 if (p->n_teams > 1) {
662 for (int t=1; t<p->n_teams; t++) {
663 teams[0].C->Compare(teams[t].C);
664 }
665 }
666#endif
667}
668
669// Helper class to generate test data such that no rounding needs to occur.
670// This means results should be the same regardless of accumulation order
671// (which is not guaranteed and varies by kernel and blocking strategy).
672//
673// For the most part this uses integers as it is easier to reason about.
674//
675// Work out how many useful mantissa bits can be stored in the result (i.e.
676// what size integer the result type can reliably represent exactly - for FP
677// types this includes the implicit 1 bit before the binary point), and how
678// many results will be accumulated. This gives a number of bits that each
679// result can have, which can then be divided between the LHS and RHS
680// operands.
681//
682// When the reference result is computed, the positive and negative
683// contributions to each result are accumulated separately and checked that
684// they are smaller than the maximum representable integer mentioned above.
685// This means that no precision can be lost by rounding regardless of how
686// the sum is reassociated.
687//
688// Some configurations require more precision in accumulation than the final
689// result (e.g. FP16 operands and result, FP32 accumulation). For these,
690// use fractional bits in the operands to make sure the accumulation is
691// being done properly.
692template<typename Tres>
693class test_data_helper {
694private:
695 int acc_operand_bits;
696 int res_operand_bits;
697
698 int lhs_acc_bits;
699 int lhs_res_bits;
700
701 int rhs_acc_bits;
702 int rhs_res_bits;
703
704 int acc_mantissa_bits;
705 int res_mantissa_bits;
706
707public:
708 test_data_helper(GemmProblem* p) {
709 const int64_t kernel_hwi = p->kernel_height * p->kernel_width * (p->input_channels / p->groups);
710
711 if (std::is_same<Tres, bfloat16>::value) {
712 // BF16 result implies BF16 operands
713 // Fast mode implies BF16 accumulation, otherwise it's FP32
714 res_mantissa_bits = 6;
715 if (p->fast_mode) {
716 acc_mantissa_bits = 6;
717 } else {
718 acc_mantissa_bits = 24;
719 }
720 } else if (std::is_same<Tres, __fp16>::value) {
721 // FP16 result - in fast mode accumulation can also be FP16,
722 // otherwise it's required to be FP32.
723 res_mantissa_bits = 11;
724 if (p->fast_mode) {
725 acc_mantissa_bits = 11;
726 } else {
727 acc_mantissa_bits = 24;
728 }
729 } else if (std::is_same<Tres, float>::value) {
730 // FP32 result implies FP32 accumulation.
731 acc_mantissa_bits = 24;
732 res_mantissa_bits = 24;
733 } else if (std::is_same<Tres, double>::value) {
734 acc_mantissa_bits = 53;
735 res_mantissa_bits = 53;
736 } else { // Assume these are (U)INT32
737 // Default case - mostly integer types.
738 acc_mantissa_bits = 30;
739 res_mantissa_bits = 30;
740 }
741
742 // If bias is to be used, it counts as one additional result so
743 // account for that here.
744 const int64_t acc_depth = kernel_hwi + ((p->use_bias || p->accumulate) ? 1 : 0);
745
746 // How many of those bits will be used up by accumulation?
747 int accu_bits = 1;
748 while ((1 << accu_bits) < acc_depth) {
749 accu_bits++;
750 }
751
752 // How many bits are left over for operands? Must have at least
753 // one.
754 //
755 // Note that in extreme cases where operands end up being 1 bit
756 // wide, most of the results end up being zero so significantly more
757 // accumulations can be made safely. There's no attempt to model
758 // this - there is the safety check later that the total
759 // accumulation isn't too large.
760 acc_operand_bits = std::max(1, acc_mantissa_bits - accu_bits);
761 res_operand_bits = std::max(1, res_mantissa_bits - accu_bits);
762
763 // Divide this amongst LHS and RHS
764 lhs_acc_bits = std::max(1, (acc_operand_bits+1) / 2);
765 rhs_acc_bits = std::max(1, (acc_operand_bits - lhs_acc_bits));
766
767 lhs_res_bits = std::max(1, (res_operand_bits+1) / 2);
768 rhs_res_bits = std::max(1, (res_operand_bits - lhs_res_bits));
769
770#ifndef SILENT
771 printf("Generating test data: %d accumulator mantissa bits, %d result mantissa bits, %" PRId64 " total accumulations, %d accumulation bits\n", acc_mantissa_bits, res_mantissa_bits, acc_depth, accu_bits);
772 printf("Accumulation: %d bits available, %d lhs, %d rhs\n", acc_operand_bits, lhs_acc_bits, rhs_acc_bits);
773 printf("Result: %d bits available, %d lhs, %d rhs\n", res_operand_bits, lhs_res_bits, rhs_res_bits);
774#endif
775 }
776
777 float lhs_quant_scale() {
778 float max_v = float(1 << lhs_res_bits);
779 return max_v / 128.0f;
780 }
781
782 float rhs_quant_scale() {
783 float max_v = float(1 << rhs_res_bits);
784 return max_v / 128.0f;
785 }
786
787 template<typename T1>
788 void populate_lhs(std::shared_ptr<Matrix <T1>> lhs) {
789 lhs->RandomizeBits(lhs_acc_bits, lhs_res_bits);
790 }
791
792 template<typename T1>
793 void populate_rhs(std::shared_ptr<Matrix <T1>> rhs) {
794 rhs->RandomizeBits(rhs_acc_bits, rhs_res_bits);
795 }
796
797 template <typename T1>
798 void populate_bias(std::shared_ptr<Matrix <T1>> bias) {
799 bias->RandomizeBits(acc_operand_bits, res_operand_bits);
800 }
801
802 void check_max_val(uint64_t max_val) {
803 if (max_val > (1ULL << res_mantissa_bits)) {
804 printf("Accumulated value too large - test data not reassociation safe.\n");
805 printf("Aborting.");
806 exit(1);
807 }
808 }
809};
810
811
812template<typename T_ref, typename T_test>
813void test_dequantized(GemmProblem *p, int iterations, int nthreads, const char *kernel_name, FILE *dump_in) {
814 const int64_t input_hw = p->input_height * p->input_width;
815 const int64_t output_hw = p->output_height * p->output_width;
816 const int64_t kernel_hwi = p->kernel_height * p->kernel_width * (p->input_channels / p->groups);
817
818 // Define quantize parameter types
819 using QType_ol = QuantizeParameters<typename T_test::lhs_operand_type, typename T_ref::lhs_operand_type>;
820 using QType_or = QuantizeParameters<typename T_test::rhs_operand_type, typename T_ref::rhs_operand_type>;
821
822 QType_ol A_qp;
823 QType_or B_qp;
824
825 auto A_q = std::make_shared<Matrix <typename T_test::lhs_operand_type> >(input_hw, p->input_channels, p->input_channels, p->batches, p->multis);
826 auto B_q = std::make_shared<Matrix <typename T_test::rhs_operand_type> >(kernel_hwi, p->output_channels, p->output_channels, 1, p->multis);
827
828 auto C_in = std::make_shared<Matrix <typename T_ref::result_type> >(output_hw, p->output_channels, p->output_channels, p->batches, p->multis);
829 auto C_r = std::make_shared<Matrix <typename T_test::result_type> >(output_hw, p->output_channels, p->output_channels, p->batches, p->multis);
830 auto C_fr = std::make_shared<Matrix <typename T_ref::result_type> >(output_hw, p->output_channels, p->output_channels, p->batches, p->multis);
831
832
833 std::shared_ptr<Matrix <typename T_ref::result_type> > bias_f = nullptr;
834
835 if (dump_in) {
836 A_q->read_dump(dump_in);
837 B_q->read_dump(dump_in);
838
839 if(p->use_bias) {
840 bias_f = std::make_shared<Matrix <typename T_ref::result_type> >(1, p->output_channels, p->output_channels, 1, p->multis);
841 bias_f->read_dump(dump_in);
842 }
843
844 C_fr->read_dump(dump_in);
845
846 fread(&A_qp, sizeof(QType_ol), 1, dump_in);
847 fread(&B_qp, sizeof(QType_or), 1, dump_in);
848 } else {
849 auto A_f = std::make_shared<Matrix <typename T_ref::lhs_operand_type> >(input_hw, p->input_channels, p->input_channels, p->batches, p->multis);
850 auto B_f = std::make_shared<Matrix <typename T_ref::rhs_operand_type> >(kernel_hwi, p->output_channels, p->output_channels, 1, p->multis);
851
852 if (p->use_bias) {
853 bias_f = std::make_shared<Matrix <typename T_ref::result_type> >(1, p->output_channels, p->output_channels, 1, p->multis);
854 }
855
856 test_data_helper<typename T_ref::result_type> test_data(p);
857
858 test_data.populate_lhs(A_f);
859
860 if (p->after_relu) {
861 // Activate the incoming data
862 auto ptr_multi = A_f->data;
863 for (int m = 0; m < A_f->multis; m++) {
864 auto ptr_batch = ptr_multi;
865 ptr_multi += A_f->multi_stride;
866
867 for (int b = 0; b < A_f->batches; b++) {
868 auto ptr_row = ptr_batch;
869 ptr_batch += A_f->batch_stride;
870
871 for (int y = 0; y < A_f->M; y++) {
872 for (int x = 0; x < A_f->N; x++) {
873 ptr_row[x] = std::max<typename T_ref::lhs_operand_type>(0, ptr_row[x]);
874 }
875 ptr_row += A_f->stride;
876 }
877 }
878 }
879 }
880
881 test_data.populate_rhs(B_f);
882
883 if (p->use_bias) {
884 test_data.populate_bias(bias_f);
885 }
886
887 if (p->accumulate) {
888 test_data.populate_bias(C_in);
889 C_fr->Copy(C_in);
890 }
891
892 // Use case for testing here is dynamic quantization
893 // where scaling factor is multiplication of scaling
894 // factors for activations and weights. Activations
895 // can have non-zero zero point but that is not handled
896 // by gemm-linux so we set it to zero here
897 A_qp = QType_ol(test_data.lhs_quant_scale(), 0);
898 B_qp = QType_or(test_data.rhs_quant_scale(), 0);
899
900 A_f->QuantizeRound(A_qp);
901 B_f->QuantizeRound(B_qp);
902
903 GemmProblem p2 = *p;
904 p2.kernel_filter="";
905 p2.fast_mode=0;
906
907 T_ref kern_ref(A_f, B_f, C_fr, bias_f, &p2, nthreads, true);
908#ifdef THREADS
909 if (nthreads > 1) {
910 std::vector<std::thread> thethreads;
911 for (int i=1; i<nthreads; i++) {
912 thethreads.emplace_back( [&kern_ref](int myid) { kern_ref.Run(myid); }, i );
913 }
914 kern_ref.Run(0);
915 for (int i=1; i<nthreads; i++) {
916 thethreads[i-1].join();
917 }
918 } else {
919#else
920 if (1) {
921#endif
922 kern_ref.Run(0);
923 }
924
925 A_q->Quantize(A_f, A_qp);
926 B_q->Quantize(B_f, B_qp);
927
928 }
929
930 kai::ops::DequantizeFloat scale(A_qp.m_scale * B_qp.m_scale);
931 std::cout << "Scaling factor is: " << scale.scale << std::endl;
932 T_test kern_test(A_q, B_q, C_r, bias_f, scale, p, nthreads, true);
933 bool compare_ok = false;
934 for(int it=0; it<iterations;it++) {
935 if (p->accumulate) {
936 C_r->Copy(C_in);
937 }
938#ifdef THREADS
939 if (nthreads > 1) {
940 std::vector<std::thread> thethreads;
941 for (int i=1; i<nthreads; i++) {
942 thethreads.emplace_back( [&kern_test](int myid) { kern_test.Run(myid); }, i );
943 }
944 kern_test.Run(0);
945 for (int i=1; i<nthreads; i++) {
946 thethreads[i-1].join();
947 }
948 } else {
949#else
950 if (1) {
951#endif
952 kern_test.Run(0);
953 }
954 if(dump_in) {
955 C_fr->Compare(C_r, 0);
956 } else {
957 compare_ok = C_fr->Compare(C_r);
958 }
959 }
960
961 if(compare_ok && p->dump_file != "") {
962 FILE *fp = write_dump(p, p->dump_file.c_str());
963
964 A_q->dump_out(fp);
965 B_q->dump_out(fp);
966 if(p->use_bias) {
967 bias_f->dump_out(fp);
968 }
969 C_r->dump_out(fp);
970
971 fwrite(&A_qp, sizeof(QType_ol), 1, fp);
972 fwrite(&B_qp, sizeof(QType_or), 1, fp);
973
974 fclose(fp);
975 }
976
977
978}
979
980template<typename T_ref, typename T_test, bool per_channel=false>
981void test_quantized(GemmProblem *p, int iterations, int nthreads, const char *kernel_name, FILE *dump_in) {
982
983 const int64_t input_hw = p->input_height * p->input_width;
984 const int64_t output_hw = p->output_height * p->output_width;
985 const int64_t kernel_hwi = p->kernel_height * p->kernel_width * (p->input_channels / p->groups);
986
987 // Define quantize parameter types
988 using QType_o = QuantizeParameters<typename T_test::lhs_operand_type, typename T_ref::lhs_operand_type>;
989 using QType_w = QuantizeParameters<typename T_test::rhs_operand_type, typename T_ref::rhs_operand_type>;
990 using QType_r = QuantizeParameters<typename T_test::result_type, typename T_ref::result_type>;
991 using QType_i = QuantizeParameters<int32_t, typename T_ref::result_type>;
992
993 QType_o A_qp;
994 std::vector<QType_w> B_qp;
995 QType_r C_qp;
996
997 // Define quantized matrices
998 auto A_q = std::make_shared<Matrix <typename T_test::lhs_operand_type> >(input_hw, p->input_channels, p->input_channels, p->batches, p->multis);
999 auto B_q = std::make_shared<Matrix <typename T_test::rhs_operand_type> >(kernel_hwi, p->output_channels, p->output_channels, 1, p->multis);
1000 auto Cin_q = std::make_shared<Matrix <typename T_test::result_type> >(output_hw, p->output_channels, p->output_channels, p->batches, p->multis); // For ADD problems, "Cin" is quantized to operand type.
1001 auto C_q = std::make_shared<Matrix <typename T_test::result_type> >(output_hw, p->output_channels, p->output_channels, p->batches, p->multis);
1002 auto C_qr = std::make_shared<Matrix <typename T_test::result_type> >(output_hw, p->output_channels, p->output_channels, p->batches, p->multis);
1003
1004 std::shared_ptr<Matrix <int32_t> > bias_q = nullptr;
1005
1006 if (dump_in) {
1007 A_q->read_dump(dump_in);
1008 B_q->read_dump(dump_in);
1009
1010 if (p->use_bias) {
1011 bias_q = std::make_shared<Matrix <int32_t> >(1, p->output_channels, p->output_channels, 1, p->multis);
1012 bias_q->read_dump(dump_in);
1013 }
1014
1015 C_qr->read_dump(dump_in);
1016
1017 fread(&A_qp, sizeof(QType_o), 1, dump_in);
1018
1019 A_qp.print("LHS");
1020
1021 const int64_t l = per_channel ? p->output_channels : 1;
1022
1023 for (int64_t i=0; i<l; i++) {
1024 QType_w q;
1025 fread(&q, sizeof(QType_w), 1, dump_in);
1026
1027 q.print("RHS");
1028
1029 B_qp.push_back(q);
1030 }
1031
1032 fread(&C_qp, sizeof(QType_r), 1, dump_in);
1033
1034 C_qp.print("Result");
1035 } else {
1036 auto A_f = std::make_shared<Matrix <typename T_ref::lhs_operand_type> >(input_hw, p->input_channels, p->input_channels, p->batches, p->multis);
1037 auto B_f = std::make_shared<Matrix <typename T_ref::rhs_operand_type> >(kernel_hwi, p->output_channels, p->output_channels, 1, p->multis);
1038 auto Cin_f = std::make_shared<Matrix <typename T_ref::result_type> >(output_hw, p->output_channels, p->output_channels, p->batches, p->multis);
1039 auto Cr_f = std::make_shared<Matrix <typename T_ref::result_type> >(output_hw, p->output_channels, p->output_channels, p->batches, p->multis);
1040
1041 std::shared_ptr<Matrix <typename T_ref::result_type> > bias_f = nullptr;
1042
1043 if (p->use_bias) {
1044 bias_f = std::make_shared<Matrix <typename T_ref::result_type> >(1, p->output_channels, p->output_channels, 1, p->multis);
1045 bias_q = std::make_shared<Matrix <int32_t> >(1, p->output_channels, p->output_channels, 1, p->multis);
1046 }
1047
1048 /* Use reference kernel to generate (generally FP) reference results. */
1049 A_f->Randomize();
1050
1051 if (p->after_relu) {
1052 // Activate the incoming data
1053 auto ptr_multi = A_f->data;
1054 for (int m = 0; m < A_f->multis; m++) {
1055 auto ptr_batch = ptr_multi;
1056 ptr_multi += A_f->multi_stride;
1057
1058 for (int b = 0; b < A_f->batches; b++) {
1059 auto ptr_row = ptr_batch;
1060 ptr_batch += A_f->batch_stride;
1061
1062 for (int y = 0; y < A_f->M; y++) {
1063 for (int x = 0; x < A_f->N; x++) {
1064 ptr_row[x] = std::max<typename T_ref::lhs_operand_type>(0, ptr_row[x]);
1065 }
1066 ptr_row += A_f->stride;
1067 }
1068 }
1069 }
1070 }
1071
1072 if (p->add_problem) {
1073 if (p->use_bias) {
1074 B_f->Randomize();
1075 } else {
1076 B_f->AllOne();
1077 }
1078 Cin_f->Randomize();
1079 } else {
1080 B_f->Randomize();
1081 }
1082
1083 if (p->use_bias) {
1084 bias_f->Randomize();
1085 }
1086
1087 /* Now work out quantization parameters */
1088 /* A is always per layer regardless. */
1089 A_qp = QType_o(A_f->get_range()[0]);
1090
1091 /* For add problems - "Cin" quantization is also always per layer. */
1092 QType_r Cin_qp(Cin_f->get_range()[0]);
1093
1094 /* B might be per channel or per layer - B_ranges will be returned at the appropriate length (either 1 or #channels). */
1095 auto B_ranges = B_f->template get_range<per_channel>();
1096
1097 /* Compute a set of quantize parameters for each range supplied */
1098 for (auto &&i : B_ranges) {
1099 if (per_channel) {
1100 int zero_pt = 0;
1101 if (std::is_same<typename T_test::rhs_operand_type, uint8_t>::value) {
1102 zero_pt = 128;
1103 }
1104 B_qp.emplace_back(zero_pt, i, std::is_same<typename T_test::rhs_operand_type, int8_t>::value ? -127 : std::numeric_limits<typename T_test::rhs_operand_type>::min());
1105 } else {
1106 B_qp.emplace_back(i, std::is_same<typename T_test::rhs_operand_type, int8_t>::value ? -127 : std::numeric_limits<typename T_test::rhs_operand_type>::min());
1107 }
1108 }
1109
1110 /* Same for the bias */
1111 std::vector<QType_i> bias_qp;
1112 for (auto &&i : B_qp) {
1113 bias_qp.emplace_back(A_qp, i);
1114 }
1115
1116 A_f->QuantizeRound(A_qp);
1117 B_f->QuantizeRound(B_qp);
1118
1119 if (p->add_problem) {
1120 Cin_f->QuantizeRound(Cin_qp);
1121 Cr_f->Copy(Cin_f);
1122 }
1123
1124 if (p->use_bias) {
1125 bias_f->QuantizeRound(bias_qp);
1126 }
1127
1128 GemmProblem p2 = *p;
1129 p2.kernel_filter="";
1130 p2.fast_mode=0;
1131
1132 T_ref kern_ref(A_f, B_f, Cr_f, bias_f, &p2, nthreads, true);
1133
1134 /* Run multithreaded if requested */
1135#ifdef THREADS
1136 if (nthreads > 1) {
1137 std::vector<std::thread> thethreads;
1138 for (int i=1; i<nthreads; i++) {
1139 thethreads.emplace_back( [&kern_ref](int myid) { kern_ref.Run(myid); }, i );
1140 }
1141 kern_ref.Run(0);
1142 for (int i=1; i<nthreads; i++) {
1143 thethreads[i-1].join();
1144 }
1145 } else {
1146#else
1147 if (1) {
1148#endif
1149 kern_ref.Run(0);
1150 }
1151
1152 C_qp = QType_r(Cr_f->get_range()[0]);
1153
1154 // Generate reference quantized output
1155 C_qr->Quantize(Cr_f, C_qp);
1156
1157 // Prepare to run the test kernel - quantize the inputs and bias.
1158 A_q->Quantize(A_f, A_qp);
1159 B_q->Quantize(B_f, B_qp);
1160
1161 if (p->add_problem) {
1162 Cin_q->Quantize(Cin_f, Cin_qp);
1163 // For add problems, we (ab)use the array of quantize parameters for B to store the C input quantize parameters.
1164 // This is OK as per-channel add quantization is not supported.
1165 B_qp.emplace_back(*reinterpret_cast<QType_w *>(&Cin_qp));
1166 }
1167
1168 if (p->use_bias) {
1169 bias_q->Quantize(bias_f, bias_qp);
1170 }
1171 }
1172
1173 T_test kern_test(A_q, B_q, C_q, bias_q, A_qp, B_qp, C_qp, p, nthreads, true);
1174 bool compare_ok = false;
1175
1176 for (int it=0; it<iterations; it++) {
1177 C_q->Copy(Cin_q);
1178#ifdef THREADS
1179 if (nthreads > 1) {
1180 std::vector<std::thread> thethreads;
1181 for (int i=1; i<nthreads; i++) {
1182 thethreads.emplace_back( [&kern_test](int myid) { kern_test.Run(myid); }, i );
1183 }
1184 kern_test.Run(0);
1185 for (int i=1; i<nthreads; i++) {
1186 thethreads[i-1].join();
1187 }
1188 } else {
1189#else
1190 if (1) {
1191#endif
1192 kern_test.Run(0);
1193 }
1194
1195 // Compare the result to the quantized reference. Tolerate off-by-one errors, unless we are reading a dump.
1196 // Note this deliberately doesn't set compare_ok so you can't read and create a dump at the same time.
1197 if (dump_in) {
1198 C_qr->Compare(C_q, 0);
1199 } else {
1200 compare_ok = C_qr->Compare(C_q, 1);
1201 }
1202 }
1203
1204 if (compare_ok && p->dump_file != "") {
1205 FILE *fp = write_dump(p, p->dump_file.c_str());
1206
1207 A_q->dump_out(fp);
1208 B_q->dump_out(fp);
1209 if (p->use_bias) {
1210 bias_q->dump_out(fp);
1211 }
1212 C_q->dump_out(fp);
1213
1214 fwrite(&A_qp, sizeof(QType_o), 1, fp);
1215
1216 const int64_t l = per_channel ? p->output_channels : 1;
1217
1218 for (int64_t i=0; i<l; i++) {
1219 fwrite(&(B_qp[i]), sizeof(QType_w), 1, fp);
1220 }
1221
1222 fwrite(&C_qp, sizeof(QType_r), 1, fp);
1223
1224 fclose(fp);
1225 }
1226}
1227
1228/*
1229 * This function runs two kernels and compares their output.
1230 *
1231 * Generally this is used to check that an optimized kernel produces the
1232 * same output as an unoptimized reference kernel.
1233 *
1234 * Templated on the reference kernel and test kernel.
1235 */
1236template<typename T_ref, typename T_test, bool legacy>
1237void test(GemmProblem *p, int iterations, int nthreads, const char *kernel_name, FILE *dump_in) {
1238 // Only test kernels with the same operand and result types.
1239 static_assert(std::is_same<typename T_ref::operand_type, typename T_test::lhs_operand_type>::value, "Kernels must use same operand type.");
1240 static_assert(std::is_same<typename T_ref::result_type, typename T_test::result_type>::value, "Kernels must use same result type.");
1241
1242 // Assume reference kernel can deal with any size, just get rounding values from test kernel.
1243 int m_round = T_test::get_m_block();
1244 int n_round = T_test::get_n_block();
1245 int k_round = T_test::get_k_block();
1246
1247 // Round requested sizes to something both kernels can do.
1248 if (m_round != 1 || n_round != 1 || k_round != 1) {
1249 assert(p->is_basic_gemm());
1250
1251 p->output_width=p->input_width = round_up_to_nearest_multiple(p->output_width, m_round);
1252 p->output_channels = round_up_to_nearest_multiple(p->output_channels, n_round);
1253 p->input_channels = round_up_to_nearest_multiple(p->input_channels, k_round);
1254 }
1255
1256 const int64_t input_hw = p->input_height * p->input_width;
1257 const int64_t kernel_hwi = p->kernel_height * p->kernel_width * (p->input_channels / p->groups);
1258 const int64_t output_hw = p->output_height * p->output_width;
1259
1260 auto A = std::make_shared<Matrix <typename T_ref::operand_type> >(input_hw, p->input_channels, std::max(p->input_channels, p->a_stride), p->batches, p->multis);
1261 auto B = std::make_shared<Matrix <typename T_ref::operand_type> >(kernel_hwi, p->output_channels, std::max(p->output_channels, p->b_stride), 1, p->multis);
1262 auto C = std::make_shared<Matrix <typename T_ref::result_type> >(output_hw, p->output_channels, p->output_channels, p->batches, p->multis);
1263 auto C1 = std::make_shared<Matrix <typename T_ref::result_type> >(output_hw, p->output_channels, p->output_channels, p->batches, p->multis);
1264 auto C2 = std::make_shared<Matrix <typename T_test::result_type> >(output_hw, p->output_channels, p->output_channels, p->batches, p->multis);
1265
1266 std::shared_ptr<Matrix <typename T_test::result_type> > bias;
1267
1268 if (dump_in) {
1269 // If provided, read references from input dump file
1270 A->read_dump(dump_in);
1271 B->read_dump(dump_in);
1272
1273 if (p->use_bias) {
1274 bias = std::make_shared<Matrix <typename T_test::result_type> >(1, p->output_channels, p->output_channels, 1, p->multis);
1275 bias->read_dump(dump_in);
1276 }
1277
1278 C1->read_dump(dump_in);
1279 } else {
1280 test_data_helper<typename T_ref::result_type> test_data(p);
1281
1282 if (p->use_bias) {
1283 bias = std::make_shared<Matrix <typename T_test::result_type> >(1, p->output_channels, p->output_channels, 1, p->multis);
1284
1285 test_data.populate_bias(bias);
1286 }
1287
1288 test_data.populate_lhs(A);
1289
1290 if (p->add_problem) {
1291 if (p->use_bias) {
1292 B->Randomize();
1293 } else {
1294 B->AllOne();
1295 }
1296 C->Randomize();
1297 C1->Copy(C);
1298 } else {
1299 test_data.populate_rhs(B);
1300 if (p->accumulate) {
1301 test_data.populate_bias(C);
1302 C1->Copy(C);
1303 }
1304 }
1305
1306 // FP32 fast mode means the operands can be cast to BF16 - mask them
1307 // off here so the reference will match.
1308 if (std::is_same<typename T_ref::operand_type, float>::value && p->fast_mode) {
1309 A->template Mask<uint32_t>(0xffff0000);
1310 B->template Mask<uint32_t>(0xffff0000);
1311 }
1312
1313 T_ref kern_ref(A, B, C1, bias, p, true);
1314
1315 // The reference kernel returns the largest absolute positive or
1316 // negative contribution to any individual result, which is used to
1317 // check that the accumulator can't possibly get out of range and
1318 // start rounding. If the check fails, abort the test.
1319 int64_t max_val = kern_ref.Run();
1320 test_data.check_max_val(max_val);
1321 }
1322
1323 T_test kern_test=TestKernel<legacy, QuantizationType::NONE, false, T_test>::get(A, B, C2, bias, p, nthreads, true);
1324
1325 bool compare_ok=false;
1326
1327 for (int it=0; it<iterations; it++) {
1328 C2->Copy(C);
1329#ifdef THREADS
1330 if (nthreads > 1) {
1331 std::vector<std::thread> thethreads;
1332 for (int i=1; i<nthreads; i++) {
1333 thethreads.emplace_back( [&kern_test](int myid) { kern_test.Run(myid); }, i );
1334 }
1335 kern_test.Run(0);
1336 for (int i=1; i<nthreads; i++) {
1337 thethreads[i-1].join();
1338 }
1339 } else {
1340#else /* THREADS */
1341 if(1) {
1342#endif
1343 kern_test.Run(0);
1344 }
1345
1346 if (dump_in) {
1347 C1->Compare(C2, 0);
1348 } else {
1349 compare_ok = C1->Compare(C2);
1350 }
1351 }
1352
1353 if (compare_ok && p->dump_file != "") {
1354 FILE *fp = write_dump(p, p->dump_file.c_str());
1355
1356 A->dump_out(fp);
1357 B->dump_out(fp);
1358 if (p->use_bias) {
1359 bias->dump_out(fp);
1360 }
1361 C2->dump_out(fp);
1362
1363 fclose(fp);
1364 }
1365}
1366
1367template<typename T, bool legacy>
1368void print_kernels(GemmProblem *p, unsigned int nthreads) {
1369 TestKernel<legacy, QuantizationType::NONE, false, T>::print_kernels(p, nthreads);
1370}