-
Notifications
You must be signed in to change notification settings - Fork 5
/
utility.hpp
3270 lines (2855 loc) · 107 KB
/
utility.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ************************************************************************
* Copyright (c) <2021> Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* ************************************************************************ */
#ifndef _UTILITY_
#define _UTILITY_
#include "rocblas.h"
#include <cmath>
#include <fstream>
#include <immintrin.h>
#include <iomanip>
#include <iostream>
#include <random>
#include <sys/time.h>
#include <vector>
#include <mutex>
#include <condition_variable>
#include <future>
#include <queue>
#include <fcntl.h>
#include <type_traits>
#include <sys/stat.h>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
// clang-format off
// return letter N,T,C in place of rocblas_operation enum
constexpr char rocblas_transpose_letter(rocblas_operation trans)
{
switch(trans)
{
case rocblas_operation_none: return 'N';
case rocblas_operation_transpose: return 'T';
case rocblas_operation_conjugate_transpose: return 'C';
}
return ' ';
}
// return letter L, R, B in place of rocblas_side enum
constexpr char rocblas_side_letter(rocblas_side side)
{
switch(side)
{
case rocblas_side_left: return 'L';
case rocblas_side_right: return 'R';
case rocblas_side_both: return 'B';
}
return ' ';
}
// return letter U, L, B in place of rocblas_fill enum
constexpr char rocblas_fill_letter(rocblas_fill fill)
{
switch(fill)
{
case rocblas_fill_upper: return 'U';
case rocblas_fill_lower: return 'L';
case rocblas_fill_full: return 'F';
}
return ' ';
}
// return letter N, U in place of rocblas_diagonal enum
constexpr char rocblas_diag_letter(rocblas_diagonal diag)
{
switch(diag)
{
case rocblas_diagonal_non_unit: return 'N';
case rocblas_diagonal_unit: return 'U';
}
return ' ';
}
// return precision string for rocblas_datatype
constexpr const char* rocblas_datatype_string(rocblas_datatype type)
{
switch(type)
{
case rocblas_datatype_f16_r: return "f16_r";
case rocblas_datatype_f32_r: return "f32_r";
case rocblas_datatype_f64_r: return "f64_r";
case rocblas_datatype_f16_c: return "f16_c";
case rocblas_datatype_f32_c: return "f32_c";
case rocblas_datatype_f64_c: return "f64_c";
case rocblas_datatype_i8_r: return "i8_r";
case rocblas_datatype_u8_r: return "u8_r";
case rocblas_datatype_i32_r: return "i32_r";
case rocblas_datatype_u32_r: return "u32_r";
case rocblas_datatype_i8_c: return "i8_c";
case rocblas_datatype_u8_c: return "u8_c";
case rocblas_datatype_i32_c: return "i32_c";
case rocblas_datatype_u32_c: return "u32_c";
case rocblas_datatype_bf16_r: return "bf16_r";
case rocblas_datatype_bf16_c: return "bf16_c";
case rocblas_datatype_invalid: return "invalid";
}
return "invalid";
}
// return sizeof rocblas_datatype
constexpr size_t rocblas_sizeof_datatype(rocblas_datatype type)
{
switch(type)
{
case rocblas_datatype_f16_r: return 2;
case rocblas_datatype_f32_r: return 4;
case rocblas_datatype_f64_r: return 8;
case rocblas_datatype_f16_c: return 4;
case rocblas_datatype_f32_c: return 8;
case rocblas_datatype_f64_c: return 16;
case rocblas_datatype_i8_r: return 1;
case rocblas_datatype_u8_r: return 1;
case rocblas_datatype_i32_r: return 4;
case rocblas_datatype_u32_r: return 4;
case rocblas_datatype_i8_c: return 2;
case rocblas_datatype_u8_c: return 2;
case rocblas_datatype_i32_c: return 8;
case rocblas_datatype_u32_c: return 8;
case rocblas_datatype_bf16_r: return 2;
case rocblas_datatype_bf16_c: return 4;
}
return 0;
}
// Convert atomics mode to string
constexpr const char* rocblas_atomics_mode_to_string(rocblas_atomics_mode mode)
{
return mode != rocblas_atomics_not_allowed ? "atomics_allowed" : "atomics_not_allowed";
}
// Convert gemm flags to string
constexpr const char* rocblas_gemm_flags_to_string(rocblas_gemm_flags)
{
return "none";
}
#define rocblas_cout (internal_ostream::cout())
#define rocblas_cerr (internal_ostream::cerr())
/***************************************************************************
* The internal_ostream class performs atomic IO on log files, and provides *
* consistent formatting *
***************************************************************************/
class internal_ostream
{
/**************************************************************************
* The worker class sets up a worker thread for writing to log files. Two *
* files are considered the same if they have the same device ID / inode. *
**************************************************************************/
class worker
{
// task_t represents a payload of data and a promise to finish
class task_t
{
std::string str;
std::promise<void> promise;
public:
// The task takes ownership of the string payload
task_t(std::string&& str, std::promise<void>&& promise)
: str(std::move(str))
, promise(std::move(promise))
{
}
auto get_future()
{
return promise.get_future();
}
// Notify the future to wake up
void set_value()
{
promise.set_value();
}
// Size of the string payload
size_t size() const
{
return str.size();
}
// Data of the string payload
const char* data() const
{
return str.data();
}
};
// FILE is used for safety in the presence of signals
FILE* file = nullptr;
// This worker's thread
std::thread thread;
// Condition variable for worker notification
std::condition_variable cond;
// Mutex for this thread's queue
std::mutex mutex;
// Queue of tasks
std::queue<task_t> queue;
// Worker thread which waits for and handles tasks sequentially
void thread_function()
{
// Clear any errors in the FILE
clearerr(file);
// Lock the mutex in preparation for cond.wait
std::unique_lock<std::mutex> lock(mutex);
while(true)
{
// Wait for any data, ignoring spurious wakeups
cond.wait(lock, [&] { return !queue.empty(); });
// With the mutex locked, get and pop data from the front of queue
task_t task = std::move(queue.front());
queue.pop();
// Temporarily unlock queue mutex, unblocking other threads
lock.unlock();
// An empty message indicates the closing of the stream
if(!task.size())
{
// Tell future to wake up
task.set_value();
break;
}
// Write the data
fwrite(task.data(), 1, task.size(), file);
// Detect any error and flush the C FILE stream
if(ferror(file) || fflush(file))
{
perror("Error writing log file");
// Tell future to wake up
task.set_value();
break;
}
// Promise that the data has been written
task.set_value();
// Re-lock the mutex in preparation for cond.wait
lock.lock();
}
}
public:
// Worker constructor creates a worker thread for a raw filehandle
explicit worker(int fd)
{
// The worker duplicates the file descriptor (RAII)
fd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
// If the dup fails or fdopen fails, print error and abort
if(fd == -1 || !(file = fdopen(fd, "a")))
{
perror("fdopen() error");
rocblas_abort();
}
// Create a worker thread, capturing *this
thread = std::thread([=] { thread_function(); });
// Detatch from the worker thread
thread.detach();
}
// Send a string to be written
void send(std::string str)
{
// Create a promise to wait for the operation to complete
std::promise<void> promise;
// The future indicating when the operation has completed
auto future = promise.get_future();
// task_t consists of string and promise
// std::move transfers ownership of str and promise to task
task_t worker_task(std::move(str), std::move(promise));
// Submit the task to the worker assigned to this device/inode
// Hold mutex for as short as possible, to reduce contention
// TODO: Consider whether notification should be done with lock held or released
{
std::lock_guard<std::mutex> lock(mutex);
queue.push(std::move(worker_task));
cond.notify_one();
}
// Wait for the task to be completed, to ensure flushed IO
future.get();
}
// Destroy a worker when all std::shared_ptr references to it are gone
~worker()
{
// Tell worker thread to exit, by sending it an empty string
send({});
// Close the FILE
if(file)
fclose(file);
}
};
// Two filehandles point to the same file if they share the same (std_dev, std_ino).
// Initial slice of struct stat which contains device ID and inode
struct file_id_t
{
dev_t st_dev; // ID of device containing file
ino_t st_ino; // Inode number
};
// Compares device IDs and inodes for map containers
struct file_id_less
{
bool operator()(const file_id_t& lhs, const file_id_t& rhs) const
{
return lhs.st_ino < rhs.st_ino || (lhs.st_ino == rhs.st_ino && lhs.st_dev < rhs.st_dev);
}
};
// Map from file_id to a worker shared_ptr
// Implemented as singleton to avoid the static initialization order fiasco
static auto& map()
{
static std::map<file_id_t, std::shared_ptr<worker>, file_id_less> map;
return map;
}
// Mutex for accessing the map
// Implemented as singleton to avoid the static initialization order fiasco
static auto& map_mutex()
{
static std::recursive_mutex map_mutex;
return map_mutex;
}
// Map from file_id to a worker shared_ptr
// Implemented as singleton to avoid the static initialization order fiasco
static auto& worker_map()
{
static std::map<file_id_t, std::shared_ptr<worker>, file_id_less> file_id_to_worker_map;
return file_id_to_worker_map;
}
// Mutex for accessing the map
// Implemented as singleton to avoid the static initialization order fiasco
static auto& worker_map_mutex()
{
static std::recursive_mutex map_mutex;
return map_mutex;
}
// Output buffer for formatted IO
std::ostringstream os;
// Worker thread for accepting tasks
std::shared_ptr<worker> worker_ptr;
// Flag indicating whether YAML mode is turned on
bool yaml = false;
// Get worker for file descriptor
static std::shared_ptr<worker> get_worker(int fd)
{
// For a file descriptor indicating an error, return a nullptr
if(fd == -1)
return nullptr;
// C++ allows type punning of common initial sequences
union
{
struct stat statbuf;
file_id_t file_id;
};
// Verify common initial sequence
static_assert(std::is_standard_layout<file_id_t>{} && std::is_standard_layout<struct stat>{}
&& offsetof(file_id_t, st_dev) == 0 && offsetof(struct stat, st_dev) == 0
&& offsetof(file_id_t, st_ino) == offsetof(struct stat, st_ino)
&& std::is_same<decltype(file_id_t::st_dev), decltype(stat::st_dev)>{}
&& std::is_same<decltype(file_id_t::st_ino), decltype(stat::st_ino)>{},
"struct stat and file_id_t are not layout-compatible");
// Get the device ID and inode, to detect common files
if(fstat(fd, &statbuf))
{
perror("Error executing fstat()");
return nullptr;
}
// Lock the map from file_id -> std::shared_ptr<internal_ostream::worker>
std::lock_guard<std::recursive_mutex> lock(map_mutex());
// Insert a nullptr map element if file_id doesn't exist in map already
// worker_ptr is a reference to the std::shared_ptr<internal_ostream::worker>
auto& worker_ptr = map().emplace(file_id, nullptr).first->second;
// If a new entry was inserted, or an old entry is empty, create new worker
if(!worker_ptr)
worker_ptr = std::make_shared<worker>(fd);
// Return the existing or new worker matching the file
return worker_ptr;
}
// Private explicit copy constructor duplicates the worker and starts a new buffer
explicit internal_ostream(const internal_ostream& other)
: worker_ptr(other.worker_ptr)
{
}
public:
// Default constructor is a std::ostringstream with no worker
internal_ostream() = default;
// Move constructor
internal_ostream(internal_ostream&&) = default;
// Move assignment
internal_ostream& operator=(internal_ostream&&) & = default;
// Copy assignment is deleted
internal_ostream& operator=(const internal_ostream&) = delete;
// Construct from a file descriptor, which is duped
explicit internal_ostream(int fd)
: worker_ptr(get_worker(fd))
{
if(!worker_ptr)
{
dprintf(STDERR_FILENO, "Error: Bad file descriptor %d\n", fd);
rocblas_abort();
}
}
// Construct from a C filename
explicit internal_ostream(const char* filename)
{
int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_APPEND | O_CLOEXEC, 0644);
worker_ptr = get_worker(fd);
if(!worker_ptr)
{
dprintf(STDERR_FILENO, "Cannot open %s: %m\n", filename);
rocblas_abort();
}
close(fd);
}
// Construct from a std::string filename
explicit internal_ostream(const std::string& filename)
: internal_ostream(filename.c_str())
{
}
// Create a duplicate of this
internal_ostream dup() const
{
if(!worker_ptr)
throw std::runtime_error(
"Attempting to duplicate a internal_ostream without an associated file");
return internal_ostream(*this);
}
// For testing to allow file closing and deletion
static void clear_workers();
// Convert stream output to string
std::string str() const
{
return os.str();
}
// Clear the buffer
void clear()
{
os.clear();
os.str({});
}
// Flush the output
void flush()
{
// Flush only if this stream contains a worker (i.e., is not a string)
if(worker_ptr)
{
// The contents of the string buffer
auto str = os.str();
// Empty string buffers kill the worker thread, so they are not flushed here
if(str.size())
worker_ptr->send(std::move(str));
// Clear the string buffer
clear();
}
}
// Destroy the internal_ostream
virtual ~internal_ostream()
{
flush(); // Flush any pending IO
}
// Implemented as singleton to avoid the static initialization order fiasco
static internal_ostream& cout()
{
thread_local internal_ostream t_cout{STDOUT_FILENO};
return t_cout;
}
// Implemented as singleton to avoid the static initialization order fiasco
static internal_ostream& cerr()
{
thread_local internal_ostream t_cerr{STDERR_FILENO};
return t_cerr;
}
// Abort function which safely flushes all IO
friend void rocblas_abort_once();
/*************************************************************************
* Non-member friend functions for formatted output *
*************************************************************************/
// Default output for non-enumeration types
template <typename T, std::enable_if_t<!std::is_enum<std::decay_t<T>>{}, int> = 0>
friend internal_ostream& operator<<(internal_ostream& os, T&& x)
{
os.os << std::forward<T>(x);
return os;
}
// Default output for enumeration types
template <typename T, std::enable_if_t<std::is_enum<std::decay_t<T>>{}, int> = 0>
friend internal_ostream& operator<<(internal_ostream& os, T&& x)
{
os.os << std::underlying_type_t<std::decay_t<T>>(x);
return os;
}
// Pairs for YAML output
template <typename T1, typename T2>
friend internal_ostream& operator<<(internal_ostream& os, std::pair<T1, T2> p)
{
os << p.first << ": ";
os.yaml = true;
os << p.second;
os.yaml = false;
return os;
}
// Complex output
template <typename T>
friend internal_ostream& operator<<(internal_ostream& os,
const rocblas_complex_num<T>& x)
{
if(os.yaml)
os.os << "'(" << std::real(x) << "," << std::imag(x) << ")'";
else
os.os << x;
return os;
}
// Floating-point output
friend internal_ostream& operator<<(internal_ostream& os, double x)
{
if(!os.yaml)
os.os << x;
else
{
// For YAML, we must output the floating-point value exactly
if(std::isnan(x))
os.os << ".nan";
else if(std::isinf(x))
os.os << (x < 0 ? "-.inf" : ".inf");
else
{
char s[32];
snprintf(s, sizeof(s) - 2, "%.17g", x);
// If no decimal point or exponent, append .0 to indicate floating point
for(char* end = s; *end != '.' && *end != 'e' && *end != 'E'; ++end)
{
if(!*end)
{
end[0] = '.';
end[1] = '0';
end[2] = '\0';
break;
}
}
os.os << s;
}
}
return os;
}
friend internal_ostream& operator<<(internal_ostream& os, rocblas_half half)
{
return os << float(half);
}
friend internal_ostream& operator<<(internal_ostream& os, rocblas_bfloat16 bf16)
{
return os << float(bf16);
}
// Integer output
friend internal_ostream& operator<<(internal_ostream& os, int32_t x)
{
os.os << x;
return os;
}
friend internal_ostream& operator<<(internal_ostream& os, uint32_t x)
{
os.os << x;
return os;
}
friend internal_ostream& operator<<(internal_ostream& os, int64_t x)
{
os.os << x;
return os;
}
friend internal_ostream& operator<<(internal_ostream& os, uint64_t x)
{
os.os << x;
return os;
}
// bool output
friend internal_ostream& operator<<(internal_ostream& os, bool b)
{
if(os.yaml)
os.os << (b ? "true" : "false");
else
os.os << (b ? 1 : 0);
return os;
}
// Character output
friend internal_ostream& operator<<(internal_ostream& os, char c)
{
if(os.yaml)
{
char s[]{c, 0};
os.os << std::quoted(s, '\'');
}
else
os.os << c;
return os;
}
// String output
friend internal_ostream& operator<<(internal_ostream& os, const char* s)
{
if(os.yaml)
os.os << std::quoted(s);
else
os.os << s;
return os;
}
friend internal_ostream& operator<<(internal_ostream& os, const std::string& s)
{
return os << s.c_str();
}
// rocblas_datatype output
friend internal_ostream& operator<<(internal_ostream& os, rocblas_datatype d)
{
os.os << rocblas_datatype_string(d);
return os;
}
// rocblas_operation output
friend internal_ostream& operator<<(internal_ostream& os,
rocblas_operation trans)
{
return os << rocblas_transpose_letter(trans);
}
// rocblas_fill output
friend internal_ostream& operator<<(internal_ostream& os, rocblas_fill fill)
{
return os << rocblas_fill_letter(fill);
}
// rocblas_diagonal output
friend internal_ostream& operator<<(internal_ostream& os, rocblas_diagonal diag)
{
return os << rocblas_diag_letter(diag);
}
// rocblas_side output
friend internal_ostream& operator<<(internal_ostream& os, rocblas_side side)
{
return os << rocblas_side_letter(side);
}
// rocblas_status output
friend internal_ostream& operator<<(internal_ostream& os, rocblas_status status)
{
os.os << rocblas_status_to_string(status);
return os;
}
// atomics mode output
friend internal_ostream& operator<<(internal_ostream& os,
rocblas_atomics_mode mode)
{
os.os << rocblas_atomics_mode_to_string(mode);
return os;
}
// gemm flags output
friend internal_ostream& operator<<(internal_ostream& os,
rocblas_gemm_flags flags)
{
os.os << rocblas_gemm_flags_to_string(flags);
return os;
}
// Transfer internal_ostream to std::ostream
friend std::ostream& operator<<(std::ostream& os, const internal_ostream& str)
{
return os << str.str();
}
// Transfer internal_ostream to internal_ostream
friend internal_ostream& operator<<(internal_ostream& os,
const internal_ostream& str)
{
return os << str.str();
}
// IO Manipulators
friend internal_ostream& operator<<(internal_ostream& os,
std::ostream& (*pf)(std::ostream&))
{
// Turn YAML formatting on or off
if(pf == internal_ostream::yaml_on)
os.yaml = true;
else if(pf == internal_ostream::yaml_off)
os.yaml = false;
else
{
// Output the manipulator to the buffer
os.os << pf;
// If the manipulator is std::endl or std::flush, flush the output
if(pf == static_cast<std::ostream& (*)(std::ostream&)>(std::endl)
|| pf == static_cast<std::ostream& (*)(std::ostream&)>(std::flush))
{
os.flush();
}
}
return os;
}
// YAML Manipulators (only used for their addresses now)
static std::ostream& yaml_on(std::ostream& os);
static std::ostream& yaml_off(std::ostream& os);
};
/*! \brief CPU Timer(in microsecond): synchronize with the default device and return wall time */
double get_time_us(void)
{
hipDeviceSynchronize();
struct timeval tv;
gettimeofday(&tv, NULL);
return (tv.tv_sec * 1000 * 1000) + tv.tv_usec;
};
/* ============================================================================================ */
/* device query and print out their ID and name; return number of compute-capable devices. */
rocblas_int query_device_property()
{
int device_count;
rocblas_status status = (rocblas_status)hipGetDeviceCount(&device_count);
if(status != rocblas_status_success)
{
rocblas_cerr << "Query device error: cannot get device count" << std::endl;
return -1;
}
else
{
rocblas_cout << "Query device success: there are " << device_count << " devices"
<< std::endl;
}
for(rocblas_int i = 0;; i++)
{
rocblas_cout
<< "-------------------------------------------------------------------------------"
<< std::endl;
if(i >= device_count)
break;
hipDeviceProp_t props;
rocblas_status status = (rocblas_status)hipGetDeviceProperties(&props, i);
if(status != rocblas_status_success)
{
rocblas_cerr << "Query device error: cannot get device ID " << i << "'s property"
<< std::endl;
}
else
{
char buf[320];
snprintf(
buf,
sizeof(buf),
"Device ID %d : %s %s\n"
"with %3.1f GB memory, max. SCLK %d MHz, max. MCLK %d MHz, compute capability "
"%d.%d\n"
"maxGridDimX %d, sharedMemPerBlock %3.1f KB, maxThreadsPerBlock %d, warpSize %d\n",
i,
props.name,
props.gcnArchName,
props.totalGlobalMem / 1e9,
(int)(props.clockRate / 1000),
(int)(props.memoryClockRate / 1000),
props.major,
props.minor,
props.maxGridSize[0],
props.sharedMemPerBlock / 1e3,
props.maxThreadsPerBlock,
props.warpSize);
rocblas_cout << buf;
}
}
return device_count;
}
/* set current device to device_id */
void set_device(rocblas_int device_id)
{
rocblas_status status = (rocblas_status)hipSetDevice(device_id);
if(status != rocblas_status_success)
{
printf("Set device error: cannot set device ID %d, there may not be such device ID\n",
(int)device_id);
}
}
inline const char* rocblas_status_to_string(rocblas_status status)
{
switch(status)
{
case rocblas_status_success:
return "rocblas_status_success";
case rocblas_status_invalid_handle:
return "rocblas_status_invalid_handle";
case rocblas_status_not_implemented:
return "rocblas_status_not_implemented";
case rocblas_status_invalid_pointer:
return "rocblas_status_invalid_pointer";
case rocblas_status_invalid_size:
return "rocblas_status_invalid_size";
case rocblas_status_memory_error:
return "rocblas_status_memory_error";
case rocblas_status_internal_error:
return "rocblas_status_internal_error";
default:
return "<undefined rocblas_status value>";
}
}
inline void rocblas_expect_status(rocblas_status status, rocblas_status expect)
{
if(status != expect)
{
std::cerr << "rocBLAS status error: Expected " << rocblas_status_to_string(expect)
<< ", received " << rocblas_status_to_string(status) << std::endl;
if(expect == rocblas_status_success)
exit(EXIT_FAILURE);
}
}
#define CHECK_HIP_ERROR(ERROR) \
do \
{ \
auto error = ERROR; \
if(error != hipSuccess) \
{ \
fprintf(stderr, \
"error: '%s'(%d) at %s:%d\n", \
hipGetErrorString(error), \
error, \
__FILE__, \
__LINE__); \
exit(EXIT_FAILURE); \
} \
} while(0)
#define EXPECT_ROCBLAS_STATUS rocblas_expect_status
#define CHECK_ROCBLAS_ERROR2(STATUS) EXPECT_ROCBLAS_STATUS(STATUS, rocblas_status_success)
#define CHECK_ROCBLAS_ERROR(STATUS) CHECK_ROCBLAS_ERROR2(STATUS)
// gemm
template <typename T>
static rocblas_status (*rocblas_gemm)(rocblas_handle handle,
rocblas_operation transA,
rocblas_operation transB,
rocblas_int m,
rocblas_int n,
rocblas_int k,
const T* alpha,
const T* A,
rocblas_int lda,
const T* B,
rocblas_int ldb,
const T* beta,
T* C,
rocblas_int ldc);
template <>
ROCBLAS_CLANG_STATIC constexpr auto rocblas_gemm<rocblas_half> = rocblas_hgemm;
template <>
ROCBLAS_CLANG_STATIC constexpr auto rocblas_gemm<float> = rocblas_sgemm;
template <>
ROCBLAS_CLANG_STATIC constexpr auto rocblas_gemm<double> = rocblas_dgemm;
// gemm_strided_batched
template <typename T>
static rocblas_status (*rocblas_gemm_strided_batched)(rocblas_handle handle,
rocblas_operation transA,
rocblas_operation transB,
rocblas_int m,
rocblas_int n,
rocblas_int k,
const T* alpha,
const T* A,
rocblas_int lda,
rocblas_stride bsa,
const T* B,
rocblas_int ldb,
rocblas_stride bsb,
const T* beta,
T* C,
rocblas_int ldc,
rocblas_stride bsc,
rocblas_int batch_count);
template <>
ROCBLAS_CLANG_STATIC constexpr auto rocblas_gemm_strided_batched<rocblas_half> = rocblas_hgemm_strided_batched;
template <>
ROCBLAS_CLANG_STATIC constexpr auto rocblas_gemm_strided_batched<float> = rocblas_sgemm_strided_batched;
template <>
ROCBLAS_CLANG_STATIC constexpr auto rocblas_gemm_strided_batched<double> = rocblas_dgemm_strided_batched;
/* ============================================================================================ */
// Random number generator
using rocblas_rng_t = std::mt19937;
extern rocblas_rng_t rocblas_rng, rocblas_seed;
rocblas_rng_t rocblas_rng, rocblas_seed;
// Reset the seed (mainly to ensure repeatability of failures in a given suite)