migraphx.hpp 45.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015-2022 Advanced Micro Devices, Inc. All rights reserved.
 *
 * 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.
 */
Paul Fultz II's avatar
Paul Fultz II committed
24
25
26
#ifndef MIGRAPHX_GUARD_API_RTGLIB_MIGRAPHX_HPP
#define MIGRAPHX_GUARD_API_RTGLIB_MIGRAPHX_HPP

27
#include "migraphx.h"
28
#include <algorithm>
29
#include <cstring>
30
#include <initializer_list>
Paul Fultz II's avatar
Paul Fultz II committed
31
32
#include <migraphx/migraphx.h>
#include <memory>
33
#include <numeric>
Paul Fultz II's avatar
Paul Fultz II committed
34
#include <exception>
35
#include <array>
Paul Fultz II's avatar
Paul Fultz II committed
36
37
#include <vector>
#include <cassert>
Shucai Xiao's avatar
Shucai Xiao committed
38
#include <iostream>
Paul Fultz II's avatar
Paul Fultz II committed
39
40

namespace migraphx {
41
#ifndef DOXYGEN
Paul Fultz II's avatar
Paul Fultz II committed
42
inline namespace api { // NOLINT
43
#endif
Paul Fultz II's avatar
Paul Fultz II committed
44

45
46
47
48
49
50
51
52
53
54
#ifdef __has_cpp_attribute
#if __has_cpp_attribute(deprecated)
#define MIGRAPHX_DEPRECATED(...) [[deprecated(__VA_ARGS__)]]
#endif
#endif

#ifndef MIGRAPHX_DEPRECATED
#define MIGRAPHX_DEPRECATED(...)
#endif

55
56
57
58
59
60
61
62
63
64
template <int N>
struct rank : rank<N - 1>
{
};

template <>
struct rank<0>
{
};

65
66
67
68
template <class PrivateMigraphTypeNameProbe>
std::string compute_type_name()
{
    std::string name;
69
#if defined(_MSC_VER) && !defined(__clang__)
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
    name = typeid(PrivateMigraphTypeNameProbe).name();
    name = name.substr(7);
#else
    const char parameter_name[] = "PrivateMigraphTypeNameProbe ="; // NOLINT

    name = __PRETTY_FUNCTION__;

    auto begin  = name.find(parameter_name) + sizeof(parameter_name);
#if(defined(__GNUC__) && !defined(__clang__) && __GNUC__ == 4 && __GNUC_MINOR__ < 7)
    auto length = name.find_last_of(",") - begin;
#else
    auto length = name.find_first_of("];", begin) - begin;
#endif
    name        = name.substr(begin, length);
#endif
    return name;
}

template <class T>
const std::string& get_type_name()
{
    static const std::string name = compute_type_name<T>();
    return name;
}

template <class T>
const std::string& get_type_name(const T&)
{
    return get_type_name<T>();
}

Paul Fultz II's avatar
Paul Fultz II committed
101
102
103
104
template <class T, class F, class... Ts>
T* make(F f, Ts&&... xs)
{
    T* result = nullptr;
105
    auto e    = f(&result, std::forward<Ts>(xs)...);
Paul Fultz II's avatar
Paul Fultz II committed
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
    if(e != migraphx_status_success)
        throw std::runtime_error("Failed to call function");
    return result;
}

template <class F, class... Ts>
void call(F f, Ts&&... xs)
{
    auto e = f(std::forward<Ts>(xs)...);
    if(e != migraphx_status_success)
        throw std::runtime_error("Failed to call function");
}

template <class F, class Iterator = std::size_t>
struct iota_iterator
{
    Iterator index;
    F f;

    using difference_type   = std::ptrdiff_t;
    using reference         = decltype(f(std::declval<Iterator>()));
    using value_type        = typename std::remove_reference<reference>::type;
    using pointer           = typename std::add_pointer<value_type>::type;
    using iterator_category = std::input_iterator_tag;

    iota_iterator& operator+=(int n)
    {
        index += n;
        return *this;
    }

    iota_iterator& operator-=(int n)
    {
        index += n;
        return *this;
    }

    iota_iterator& operator++()
    {
        index++;
        return *this;
    }

    iota_iterator& operator--()
    {
        index--;
        return *this;
    }

    iota_iterator operator++(int) // NOLINT
    {
        iota_iterator it = *this;
        index++;
        return it;
    }

    iota_iterator operator--(int) // NOLINT
    {
        iota_iterator it = *this;
        index--;
        return it;
    }
    // TODO: operator->
169
    reference operator*() const { return f(index); }
Paul Fultz II's avatar
Paul Fultz II committed
170

171
172
173
174
    friend iota_iterator operator+(iota_iterator x, iota_iterator y)
    {
        return iota_iterator(x.index + y.index, x.f);
    }
Paul Fultz II's avatar
Paul Fultz II committed
175

176
177
178
179
    friend iota_iterator operator-(iota_iterator x, iota_iterator y)
    {
        return iota_iterator(x.index - y.index, x.f);
    }
Paul Fultz II's avatar
Paul Fultz II committed
180

181
    friend bool operator==(iota_iterator x, iota_iterator y) { return x.index == y.index; }
Paul Fultz II's avatar
Paul Fultz II committed
182

183
184
    friend bool operator!=(iota_iterator x, iota_iterator y) { return x.index != y.index; }
};
Paul Fultz II's avatar
Paul Fultz II committed
185
186
187
188
189
190
191
192
193

template <class Derived>
struct array_base
{
    const Derived& derived() const { return static_cast<const Derived&>(*this); }

    template <class T>
    using value_type_t = decltype(std::declval<T>()[0]);

194
195
196
197
198
199
200
201
202
203
    struct iterator_read
    {
        const Derived* self;
        template <class D = Derived>
        value_type_t<D> operator()(size_t pidx) const
        {
            return (*self)[pidx];
        }
    };

Paul Fultz II's avatar
Paul Fultz II committed
204
    template <class T>
205
206
207
    using iterator_t = iota_iterator<iterator_read>;

    bool empty() const { return derived().size() == 0; }
Paul Fultz II's avatar
Paul Fultz II committed
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223

    template <class D = Derived>
    value_type_t<D> front() const
    {
        return derived()[0];
    }

    template <class D = Derived>
    value_type_t<D> back() const
    {
        return derived()[derived().size() - 1];
    }

    template <class D = Derived>
    iterator_t<D> begin() const
    {
224
        return {0, {&derived()}};
Paul Fultz II's avatar
Paul Fultz II committed
225
226
227
228
229
    }

    template <class D = Derived>
    iterator_t<D> end() const
    {
230
        return {derived().size(), {&derived()}};
Paul Fultz II's avatar
Paul Fultz II committed
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
#if defined(__GNUC__) && !defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wnon-template-friend"
#endif

template <class T>
struct holder
{
    // Friend injection
    friend auto migraphx_adl_handle_lookup(holder<T>);
    // Function left unimplemented since its only used in non-evaluated
    // context
    T get() const;
};

template <class C, class T>
struct handle_lookup
{
    friend auto migraphx_adl_handle_lookup(holder<T>) { return holder<C>{}; }
};

#if defined(__GNUC__) && !defined(__clang__)
#pragma GCC diagnostic pop
#endif

template <class T>
using as_handle = decltype(
    migraphx_adl_handle_lookup(holder<std::remove_cv_t<std::remove_pointer_t<T>>>{}).get());

Paul Fultz II's avatar
Paul Fultz II committed
263
264
265
266
267
268
269
struct own
{
};
struct borrow
{
};

270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
template <class T>
struct share
{
    share(std::shared_ptr<T> p) : ptr(std::move(p)) {}

    template <class U>
    std::shared_ptr<U> alias(U* p) const
    {
        return std::shared_ptr<U>{ptr, p};
    }

    private:
    std::shared_ptr<T> ptr;
};

285
286
template <class Derived, class T, class D, D Deleter, class A, A Assigner>
struct handle_base : handle_lookup<Derived, std::remove_cv_t<T>>
Paul Fultz II's avatar
Paul Fultz II committed
287
{
288
    using handle_type = T;
Paul Fultz II's avatar
Paul Fultz II committed
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
    handle_base() : m_handle(nullptr) {}
    template <class F, class... Ts>
    void make_handle(F f, Ts&&... xs)
    {
        using type = typename std::remove_cv<T>::type;
        set_handle(make<type>(f, std::forward<Ts>(xs)...), own{});
    }

    const std::shared_ptr<T>& get_handle() const { return m_handle; }

    T* get_handle_ptr() const
    {
        assert(m_handle != nullptr);
        return get_handle().get();
    }

    template <class U>
    void set_handle(U* ptr, own)
    {
        m_handle = std::shared_ptr<U>{ptr, Deleter};
    }

    template <class U>
    void set_handle(U* ptr, borrow)
    {
        m_handle = std::shared_ptr<U>{ptr, [](U*) {}};
    }

317
318
319
320
321
322
323
324
    template <class U, class V>
    void set_handle(U* ptr, share<V> b)
    {
        m_handle = std::shared_ptr<T>{ptr, [b](U*) {}};
    }

    share<T> share_handle() const { return {m_handle}; }

325
326
327
328
329
330
    template <class U>
    void assign_to_handle(U* x)
    {
        Assigner(x, this->get_handle_ptr());
    }

Paul Fultz II's avatar
Paul Fultz II committed
331
332
333
334
    protected:
    std::shared_ptr<T> m_handle;
};

335
336
337
338
339
340
341
342
343
344
345
// NOLINTNEXTLINE
#define MIGRAPHX_HANDLE_CONSTRUCTOR(name)                                                          \
    template <class HandleType,                                                                    \
              class Lifetime,                                                                      \
              class =                                                                              \
                  typename std::enable_if<std::is_convertible<HandleType*, handle_type*>{}>::type> \
    name(HandleType* p, Lifetime lifetime)                                                         \
    {                                                                                              \
        this->set_handle(p, std::move(lifetime));                                                  \
    }

346
347
348
349
350
template <size_t N>
struct out_params
{
};

351
352
353
354
355
356
357
template <class Base>
struct interface_base : Base
{
    interface_base() : Base() {}

    protected:
    template <class F>
358
    static migraphx_status try_(F f, char* ex_msg = nullptr, size_t ex_msg_size = 0) // NOLINT
359
360
361
362
363
364
    {
        try
        {
            f();
            return migraphx_status_success;
        }
365
366
367
368
369
370
371
372
373
        catch(const std::exception& ex)
        {
            if(ex_msg)
            {
                std::strncpy(ex_msg, ex.what(), ex_msg_size);
                ex_msg[ex_msg_size - 1] = '\0';
            }
            return migraphx_status_unknown_error;
        }
374
375
376
377
378
379
380
381
382
383
384
385
386
387
        catch(...)
        {
            return migraphx_status_unknown_error;
        }
    }

    template <class F, class T, class... Ts>
    void make_interface(F f, T& obj, Ts&&... xs)
    {
        auto copy = [](void** out, void* input) {
            return try_([&] {
                T** y = reinterpret_cast<T**>(out);
                T* x  = reinterpret_cast<T*>(input);
                assert(x != nullptr and y != nullptr and *y == nullptr);
Paul Fultz II's avatar
Paul Fultz II committed
388
                // cppcheck-suppress useSmartPointer
389
390
391
392
393
394
395
396
397
398
399
400
401
                *y = new T(*x); // NOLINT
            });
        };
        auto del = [](void* input) {
            return try_([&] {
                T* x = reinterpret_cast<T*>(input);
                delete x; // NOLINT
            });
        };
        this->make_handle(f, &obj, copy, del, std::forward<Ts>(xs)...);
    }

    template <class T, class Setter, class F>
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
    void set_fp(Setter setter, F pf, out_params<2>)
    {
        static F f = pf;
        (void)f; // avoid warning on gcc
        call(setter,
             this->get_handle_ptr(),
             [](auto out1, auto out2, void* obj, char* ex_msg, size_t ex_msg_size, auto... xs)
                 -> migraphx_status {
                 return try_([&] { call_cast_arg<T>(rank<2>{}, f, out1, out2, obj, xs...); },
                             ex_msg,
                             ex_msg_size);
             });
    }

    template <class T, class Setter, class F>
    void set_fp(Setter setter, F pf, out_params<1>)
418
419
420
    {
        static F f = pf;
        (void)f; // avoid warning on gcc
421
422
423
424
425
426
427
        call(setter,
             this->get_handle_ptr(),
             [](auto out, void* obj, char* ex_msg, size_t ex_msg_size, auto... xs)
                 -> migraphx_status {
                 return try_(
                     [&] { call_cast_arg<T>(rank<1>{}, f, out, obj, xs...); }, ex_msg, ex_msg_size);
             });
428
429
430
    }

    template <class T, class Setter, class F>
431
432
433
434
435
436
437
438
439
440
441
442
443
444
    void set_fp(Setter setter, F pf, out_params<0>)
    {
        static F f = pf;
        (void)f; // avoid warning on gcc
        call(setter,
             this->get_handle_ptr(),
             [](void* obj, char* ex_msg, size_t ex_msg_size, auto... xs) -> migraphx_status {
                 return try_(
                     [&] { call_cast_arg<T>(rank<0>{}, f, obj, xs...); }, ex_msg, ex_msg_size);
             });
    }

    template <class T, class Setter, class F, class Out>
    void set_auto_fp(Setter setter, F f, Out nums)
445
    {
446
447
448
449
450
451
        return set_fp<T>(
            setter,
            [=](T& obj, auto out1, auto out2, auto... xs) {
                auto_invoke(f, out1, out2, obj, auto_convert_param(rank<2>{}, xs)...);
            },
            nums);
452
453
454
455
456
457
458
459
460
    }

    struct no_out_arg
    {
    };

    template <class T, class F, class X, class... Xs, class = std::enable_if_t<std::is_void<X>{}>>
    static void call_cast_arg(rank<0>, F f, X* obj, Xs... xs)
    {
461
        f(reinterpret_cast<T*>(obj), no_out_arg{}, no_out_arg{}, xs...);
462
463
464
465
466
467
468
469
470
471
    }

    template <class T,
              class F,
              class R,
              class X,
              class... Xs,
              class = std::enable_if_t<std::is_void<X>{}>>
    static void call_cast_arg(rank<1>, F f, R result, X* obj, Xs... xs)
    {
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
        f(*reinterpret_cast<T*>(obj), result, no_out_arg{}, xs...);
    }

    template <class T,
              class F,
              class R1,
              class R2,
              class X,
              class... Xs,
              class = std::enable_if_t<std::is_void<X>{}>>
    static void call_cast_arg(rank<2>, F f, R1 result1, R2 result2, X* obj, Xs... xs)
    {
        f(*reinterpret_cast<T*>(obj), result1, result2, xs...);
    }

    template <class F, class T1, class T2, class... Ts>
    void auto_invoke(F f, T1* out1, T2* out2, Ts&&... xs)
    {
        auto_assign(rank<2>{}, out1, out2, f(std::forward<Ts>(xs)...));
491
492
493
    }

    template <class F, class T, class... Ts>
494
    void auto_invoke(F f, T* out, no_out_arg, Ts&&... xs)
495
    {
496
        auto_assign(rank<1>{}, out, f(std::forward<Ts>(xs)...));
497
498
499
    }

    template <class F, class T, class... Ts>
500
    void auto_invoke(F f, no_out_arg, no_out_arg, Ts&&... xs)
501
502
503
504
505
506
507
508
509
510
    {
        f(std::forward<Ts>(xs)...);
    }

    template <class T, class = std::enable_if_t<std::is_fundamental<T>{} or std::is_enum<T>{}>>
    T auto_convert_param(rank<0>, T x)
    {
        return x;
    }

511
512
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
513
514
515
516
517
    template <class T>
    auto auto_convert_param(rank<1>, T x) -> decltype(as_handle<T>{x})
    {
        return as_handle<T>{x};
    }
518
#pragma GCC diagnostic pop
519
520
521
522
523
524
525
526
527
528

    template <class T>
    auto auto_convert_param(rank<2>, T x) -> decltype(as_handle<T>{x, borrow{}})
    {
        return as_handle<T>{x, borrow{}};
    }

    template <class T, class U>
    void auto_assign(rank<0>, T* out, U x)
    {
529
        *out = x;
530
531
532
533
534
535
536
    }

    template <class T, class U>
    auto auto_assign(rank<1>, T* out, U x) -> decltype(x.assign_to_handle(out))
    {
        x.assign_to_handle(out);
    }
537
538
539
540
541
542
543

    template <class T1, class T2, class U, class = std::enable_if_t<std::is_same<T2, size_t>{}>>
    auto auto_assign(rank<2>, T1* out_ptr, T2* out_size, U x)
    {
        *out_size = std::min(*out_size, x.size());
        std::copy_n(x.begin(), *out_size, out_ptr);
    }
544
545
546
};

// NOLINTNEXTLINE
547
548
549
550
551
#define MIGRAPHX_INTERFACE_LIFT(n_out, T, prefix, name) \
    this->set_auto_fp<T>(                               \
        &migraphx_##prefix##_set_##name,                \
        [](T& x, auto... xs) { return x.name(xs...); }, \
        out_params<n_out>{})
552
553
554
555
556
557

template <class Base, class T>
using require_interface =
    std::enable_if_t<std::is_base_of<Base, T>{} and not std::is_same<T, Base>{} and
                     std::is_copy_constructible<T>{} and std::is_final<T>{}>;

558
559
560
#ifdef DOXYGEN
#define MIGRAPHX_DETAIL_HANDLE_BASE(name, const_) handle_base<>
#else
561
#define MIGRAPHX_DETAIL_HANDLE_BASE(name, const_)       \
562
563
    handle_base<name,                                   \
                const_ migraphx_##name,                 \
564
565
566
567
                decltype(&migraphx_##name##_destroy),   \
                migraphx_##name##_destroy,              \
                decltype(&migraphx_##name##_assign_to), \
                migraphx_##name##_assign_to>
568
#endif
Paul Fultz II's avatar
Paul Fultz II committed
569
570
571
572
573
// NOLINTNEXTLINE
#define MIGRAPHX_HANDLE_BASE(name) MIGRAPHX_DETAIL_HANDLE_BASE(name, )
// NOLINTNEXTLINE
#define MIGRAPHX_CONST_HANDLE_BASE(name) MIGRAPHX_DETAIL_HANDLE_BASE(name, const)

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
/**
 * Container to hold optimal dynamic dimension values.
 */
struct optimals : MIGRAPHX_HANDLE_BASE(optimals)
{
    MIGRAPHX_HANDLE_CONSTRUCTOR(optimals)

    optimals(std::initializer_list<size_t> init_list)
    {
        this->make_handle(&migraphx_optimals_create, init_list.begin(), init_list.size());
    }
};

/**
 * @brief Dynamic dimension object.
 * @details minimum, maximum, and optimal dimensions
 */
struct dynamic_dimension : MIGRAPHX_CONST_HANDLE_BASE(dynamic_dimension)
{
    MIGRAPHX_HANDLE_CONSTRUCTOR(dynamic_dimension)

    dynamic_dimension(size_t min, size_t max)
    {
        this->make_handle(&migraphx_dynamic_dimension_create_min_max, min, max);
    }

    dynamic_dimension(size_t min, size_t max, const optimals& opts)
    {
        this->make_handle(
            &migraphx_dynamic_dimension_create_min_max_optimals, min, max, opts.get_handle_ptr());
    }

    bool is_fixed() const
    {
        bool result = false;
        call(&migraphx_dynamic_dimension_is_fixed, &result, this->get_handle_ptr());
        return result;
    }

    friend bool operator==(const dynamic_dimension& x, const dynamic_dimension& y)
    {
        bool pout;
        call(&migraphx_dynamic_dimension_equal, &pout, x.get_handle_ptr(), y.get_handle_ptr());
        return pout;
    }

    friend bool operator!=(const dynamic_dimension& x, const dynamic_dimension& y)
    {
        return not(x == y);
    }
};

/**
 * Container to hold dynamic_dimension objects.
 */
struct dynamic_dimensions : MIGRAPHX_HANDLE_BASE(dynamic_dimensions)
{
    MIGRAPHX_HANDLE_CONSTRUCTOR(dynamic_dimensions)

    template <class... Ts>
    dynamic_dimensions(Ts... xs)
    {
        std::array<const_migraphx_dynamic_dimension_t, sizeof...(Ts)> a{xs.get_handle_ptr()...};
        this->make_handle(&migraphx_dynamic_dimensions_create, a.data(), a.size());
    }

    size_t size() const
    {
        size_t pout;
        call(&migraphx_dynamic_dimensions_size, &pout, this->get_handle_ptr());
        return pout;
    }

    dynamic_dimension operator[](size_t pidx) const
    {
        const_migraphx_dynamic_dimension_t pout;
        call(&migraphx_dynamic_dimensions_get, &pout, this->get_handle_ptr(), pidx);
        return {pout, this->share_handle()};
    }
};

655
656
657
658
/**
 * @brief Describe shape of tensor
 * @details A shape consists of a data type, lengths of multi-dimension tensor, and strides
 */
Paul Fultz II's avatar
Paul Fultz II committed
659
660
661
662
struct shape : MIGRAPHX_CONST_HANDLE_BASE(shape)
{
    shape() {}

663
    MIGRAPHX_DEPRECATED("Contructor without lifetime annotation is deprecated.")
Paul Fultz II's avatar
Paul Fultz II committed
664
665
    shape(const migraphx_shape* p) { this->set_handle(p, borrow{}); }

Umang Yadav's avatar
Umang Yadav committed
666
    MIGRAPHX_HANDLE_CONSTRUCTOR(shape)
Paul Fultz II's avatar
Paul Fultz II committed
667

668
    /// Construct a scalar shape
669
670
671
672
673
    shape(migraphx_shape_datatype_t type)
    {
        this->make_handle(&migraphx_shape_create_scalar, type);
    }

674
675
    /// Construct a shape with its type and lengths. The strides are
    /// automatically computed assumming a packed layout.
Paul Fultz II's avatar
Paul Fultz II committed
676
677
678
679
680
    shape(migraphx_shape_datatype_t type, std::vector<size_t> plengths)
    {
        this->make_handle(&migraphx_shape_create, type, plengths.data(), plengths.size());
    }

681
682
683
684
685
686
687
    // Force all calls of the format `shape( type_t, { size_t compatibles } )` to map to
    // shape(type_t, std::vector<std::size_t> l)
    shape(migraphx_shape_datatype_t t, std::initializer_list<std::size_t> d)
        : shape::shape(t, std::vector<std::size_t>{d.begin(), d.end()})
    {
    }

688
689
690
    shape(migraphx_shape_datatype_t type,
          std::vector<size_t> plengths,
          std::vector<size_t> pstrides)
691
    {
692
693
694
695
696
697
        this->make_handle(&migraphx_shape_create_with_strides,
                          type,
                          plengths.data(),
                          plengths.size(),
                          pstrides.data(),
                          pstrides.size());
698
699
    }

700
701
702
703
704
    shape(migraphx_shape_datatype_t type, const dynamic_dimensions& dyn_dims)
    {
        this->make_handle(&migraphx_shape_create_dynamic, type, dyn_dims.get_handle_ptr());
    }

Paul Fultz II's avatar
Paul Fultz II committed
705
706
707
708
709
    std::vector<size_t> lengths() const
    {
        const size_t* pout;
        size_t pout_size;
        call(&migraphx_shape_lengths, &pout, &pout_size, this->get_handle_ptr());
710
        return {pout, pout + pout_size};
Paul Fultz II's avatar
Paul Fultz II committed
711
712
713
714
715
716
717
    }

    std::vector<size_t> strides() const
    {
        const size_t* pout;
        size_t pout_size;
        call(&migraphx_shape_strides, &pout, &pout_size, this->get_handle_ptr());
718
        return {pout, pout + pout_size};
Paul Fultz II's avatar
Paul Fultz II committed
719
720
    }

721
722
723
724
725
726
727
728
    /// Get the dynamic dimensions of the shape
    dynamic_dimensions dyn_dims() const
    {
        migraphx_dynamic_dimensions_t pout;
        call(&migraphx_shape_dyn_dims, &pout, this->get_handle_ptr());
        return {pout, own{}};
    }

Paul Fultz II's avatar
Paul Fultz II committed
729
730
731
732
733
734
735
    migraphx_shape_datatype_t type() const
    {
        migraphx_shape_datatype_t pout;
        call(&migraphx_shape_type, &pout, this->get_handle_ptr());
        return pout;
    }

736
737
738
739
740
741
742
    size_t elements() const
    {
        size_t pout;
        call(&migraphx_shape_elements, &pout, this->get_handle_ptr());
        return pout;
    }

Paul Fultz II's avatar
Paul Fultz II committed
743
744
745
746
747
748
749
    size_t bytes() const
    {
        size_t pout;
        call(&migraphx_shape_bytes, &pout, this->get_handle_ptr());
        return pout;
    }

750
751
752
753
754
755
756
    bool standard() const
    {
        bool result = false;
        call(&migraphx_shape_standard, &result, this->get_handle_ptr());
        return result;
    }

757
758
759
760
761
762
763
764
    /// Is the shape dynamic
    bool dynamic() const
    {
        bool result = false;
        call(&migraphx_shape_dynamic, &result, this->get_handle_ptr());
        return result;
    }

765
766
767
768
769
770
771
772
    // map element index to space index
    size_t index(size_t i) const
    {
        size_t result;
        call(&migraphx_shape_index, &result, this->get_handle_ptr(), i);
        return result;
    }

Paul Fultz II's avatar
Paul Fultz II committed
773
774
775
776
777
778
779
    friend bool operator==(const shape& px, const shape& py)
    {
        bool pout;
        call(&migraphx_shape_equal, &pout, px.get_handle_ptr(), py.get_handle_ptr());
        return pout;
    }

780
    friend bool operator!=(const shape& px, const shape& py) { return not(px == py); }
Paul Fultz II's avatar
Paul Fultz II committed
781
782
};

783
784
785
786
787
788
/**
 * @brief Arguments to be passed to an migraphx arguments
 *
 * An `argument` represents a raw buffer of data with a shape.
 *
 */
Paul Fultz II's avatar
Paul Fultz II committed
789
790
791
792
struct argument : MIGRAPHX_CONST_HANDLE_BASE(argument)
{
    argument() {}

Umang Yadav's avatar
Umang Yadav committed
793
    MIGRAPHX_HANDLE_CONSTRUCTOR(argument)
Paul Fultz II's avatar
Paul Fultz II committed
794

795
    MIGRAPHX_DEPRECATED("Contructor without lifetime annotation is deprecated.")
Paul Fultz II's avatar
Paul Fultz II committed
796
797
    argument(const migraphx_argument* p) { this->set_handle(p, borrow{}); }

798
799
800
801
802
    argument(shape pshape)
    {
        this->make_handle(&migraphx_argument_create_empty, pshape.get_handle_ptr());
    }

Paul Fultz II's avatar
Paul Fultz II committed
803
804
805
806
807
808
809
810
811
    argument(shape pshape, void* pbuffer)
    {
        this->make_handle(&migraphx_argument_create, pshape.get_handle_ptr(), pbuffer);
    }

    shape get_shape() const
    {
        const_migraphx_shape_t pout;
        call(&migraphx_argument_shape, &pout, this->get_handle_ptr());
812
        return {pout, this->share_handle()};
Paul Fultz II's avatar
Paul Fultz II committed
813
814
815
816
817
818
819
820
821
    }

    char* data() const
    {
        char* pout;
        call(&migraphx_argument_buffer, &pout, this->get_handle_ptr());
        return pout;
    }

822
823
824
    template <typename T>
    std::vector<T> as_vector() const
    {
825
826
827
828
829
830
831
832
833
        auto ss           = this->get_shape();
        auto num_elements = ss.elements();
        std::vector<T> res(num_elements);
        T* buffer_ptr = reinterpret_cast<T*>(this->data());
        for(size_t i = 0; i < num_elements; i++)
        {
            res[i] = buffer_ptr[ss.index(i)];
        }
        return res;
834
835
    }

836
    /// Generate an argument using random data
Paul Fultz II's avatar
Paul Fultz II committed
837
838
    static argument generate(shape ps, size_t pseed = 0)
    {
839
840
        return {make<migraphx_argument>(&migraphx_argument_generate, ps.get_handle_ptr(), pseed),
                own{}};
Paul Fultz II's avatar
Paul Fultz II committed
841
842
843
844
845
846
847
848
849
    }

    friend bool operator==(const argument& px, const argument& py)
    {
        bool pout;
        call(&migraphx_argument_equal, &pout, px.get_handle_ptr(), py.get_handle_ptr());
        return pout;
    }

850
    friend bool operator!=(const argument& px, const argument& py) { return not(px == py); }
Paul Fultz II's avatar
Paul Fultz II committed
851
852
};

853
/// A target for compilation
Paul Fultz II's avatar
Paul Fultz II committed
854
855
856
857
struct target : MIGRAPHX_HANDLE_BASE(target)
{
    target() {}

Umang Yadav's avatar
Umang Yadav committed
858
    MIGRAPHX_HANDLE_CONSTRUCTOR(target)
Paul Fultz II's avatar
Paul Fultz II committed
859

860
    /// Construct a target from its name
Paul Fultz II's avatar
Paul Fultz II committed
861
862
863
864
865
866
867
    target(const char* name) { this->make_handle(&migraphx_target_create, name); }
};

struct program_parameter_shapes : MIGRAPHX_HANDLE_BASE(program_parameter_shapes)
{
    program_parameter_shapes() {}

Umang Yadav's avatar
Umang Yadav committed
868
    MIGRAPHX_HANDLE_CONSTRUCTOR(program_parameter_shapes)
Paul Fultz II's avatar
Paul Fultz II committed
869
870
871
872
873
874
875
876
877
878
879
880

    size_t size() const
    {
        size_t pout;
        call(&migraphx_program_parameter_shapes_size, &pout, this->get_handle_ptr());
        return pout;
    }

    shape operator[](const char* pname) const
    {
        const_migraphx_shape_t pout;
        call(&migraphx_program_parameter_shapes_get, &pout, this->get_handle_ptr(), pname);
881
        return {pout, this->share_handle()};
Paul Fultz II's avatar
Paul Fultz II committed
882
883
884
885
886
    }

    std::vector<const char*> names() const
    {
        std::vector<const char*> result(this->size());
887
        if(not result.empty())
Shucai Xiao's avatar
Shucai Xiao committed
888
889
890
        {
            call(&migraphx_program_parameter_shapes_names, result.data(), this->get_handle_ptr());
        }
Paul Fultz II's avatar
Paul Fultz II committed
891
892
893
894
        return result;
    }
};

895
/// A class to construct the inputs parameters for a program
Paul Fultz II's avatar
Paul Fultz II committed
896
897
struct program_parameters : MIGRAPHX_HANDLE_BASE(program_parameters)
{
Umang Yadav's avatar
Umang Yadav committed
898
    MIGRAPHX_HANDLE_CONSTRUCTOR(program_parameters)
Paul Fultz II's avatar
Paul Fultz II committed
899

900
    MIGRAPHX_DEPRECATED("Contructor without lifetime annotation is deprecated.")
Shucai Xiao's avatar
Shucai Xiao committed
901
902
    program_parameters(migraphx_program_parameters* p) { this->set_handle(p, borrow{}); }

Paul Fultz II's avatar
Paul Fultz II committed
903
904
    program_parameters() { this->make_handle(&migraphx_program_parameters_create); }

905
    /// Construct the parameters from initializer_list
906
907
908
909
910
911
912
    program_parameters(std::initializer_list<std::pair<std::string, argument>> l)
    {
        this->make_handle(&migraphx_program_parameters_create);
        for(auto&& p : l)
            this->add(p.first.c_str(), p.second);
    }

913
    /// Add a new parameter
Paul Fultz II's avatar
Paul Fultz II committed
914
915
916
917
918
919
920
921
922
923
924
    void add(const char* pname, const argument& pargument) const
    {
        call(&migraphx_program_parameters_add,
             this->get_handle_ptr(),
             pname,
             pargument.get_handle_ptr());
    }
};

struct arguments : MIGRAPHX_HANDLE_BASE(arguments), array_base<arguments>
{
Umang Yadav's avatar
Umang Yadav committed
925
    MIGRAPHX_HANDLE_CONSTRUCTOR(arguments)
Paul Fultz II's avatar
Paul Fultz II committed
926
927
928
929
930
931
932
933
934
935
936
937

    size_t size() const
    {
        size_t pout;
        call(&migraphx_arguments_size, &pout, this->get_handle_ptr());
        return pout;
    }

    argument operator[](size_t pidx) const
    {
        const_migraphx_argument_t pout;
        call(&migraphx_arguments_get, &pout, this->get_handle_ptr(), pidx);
938
        return {pout, this->share_handle()};
Paul Fultz II's avatar
Paul Fultz II committed
939
940
941
942
943
    }
};

struct shapes : MIGRAPHX_HANDLE_BASE(shapes), array_base<shapes>
{
Umang Yadav's avatar
Umang Yadav committed
944
    MIGRAPHX_HANDLE_CONSTRUCTOR(shapes)
Paul Fultz II's avatar
Paul Fultz II committed
945
946
947
948
949
950
951
952
953
954
955
956

    size_t size() const
    {
        size_t pout;
        call(&migraphx_shapes_size, &pout, this->get_handle_ptr());
        return pout;
    }

    shape operator[](size_t pidx) const
    {
        const_migraphx_shape_t pout;
        call(&migraphx_shapes_get, &pout, this->get_handle_ptr(), pidx);
957
        return {pout, this->share_handle()};
Paul Fultz II's avatar
Paul Fultz II committed
958
959
960
    }
};

961
962
struct operation : MIGRAPHX_HANDLE_BASE(operation)
{
Umang Yadav's avatar
Umang Yadav committed
963
    MIGRAPHX_HANDLE_CONSTRUCTOR(operation)
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980

    template <class... Ts>
    operation(const char* name, const char* attributes = nullptr, Ts... xs)
    {
        this->make_handle(&migraphx_operation_create, name, attributes, xs...);
    }

    std::string name()
    {
        std::array<char, 1024> out_name;
        call(&migraphx_operation_name, out_name.data(), 1024, this->get_handle_ptr());
        return {out_name.data()};
    }
};

struct instruction : MIGRAPHX_CONST_HANDLE_BASE(instruction)
{
Umang Yadav's avatar
Umang Yadav committed
981
    MIGRAPHX_HANDLE_CONSTRUCTOR(instruction)
982
983
984
985
};

struct instructions : MIGRAPHX_HANDLE_BASE(instructions)
{
Umang Yadav's avatar
Umang Yadav committed
986
    MIGRAPHX_HANDLE_CONSTRUCTOR(instructions)
987
988
989
990
991
992
993
994
995
996
997
998
999

    template <class... Ts>
    instructions(Ts... xs)
    {
        std::array<const_migraphx_instruction_t, sizeof...(Ts)> a{xs.get_handle_ptr()...};
        this->make_handle(&migraphx_instructions_create, a.data(), a.size());
    }
};

struct module;

struct modules : MIGRAPHX_HANDLE_BASE(modules)
{
Umang Yadav's avatar
Umang Yadav committed
1000
    MIGRAPHX_HANDLE_CONSTRUCTOR(modules)
1001
1002
1003
1004

    template <class... Ts>
    modules(Ts... xs)
    {
1005
        std::array<migraphx_module_t, sizeof...(Ts)> a = {xs.get_handle_ptr()...};
1006
1007
1008
1009
        this->make_handle(&migraphx_modules_create, a.data(), a.size());
    }
};

Shucai Xiao's avatar
Shucai Xiao committed
1010
1011
struct module
{
1012
1013
    MIGRAPHX_DEPRECATED("Constructor without lifetime annotation is deprecated.")
    module(migraphx_module* m) : mm(std::shared_ptr<migraphx_module*>(), m) {}
1014

1015
    module(migraphx_module* m, borrow) : mm(std::shared_ptr<migraphx_module*>(), m) {}
Shucai Xiao's avatar
Shucai Xiao committed
1016

1017
1018
1019
1020
1021
1022
    template <class T>
    module(migraphx_module* m, share<T> b) : mm(b.alias(m))
    {
    }

    void print() const { call(&migraphx_module_print, mm.get()); }
1023
1024
1025
1026
1027
1028

    instruction add_instruction(const migraphx::operation& op, const migraphx::instructions& args)
    {
        migraphx_instruction_t op_ins;
        call(&migraphx_module_add_instruction,
             &op_ins,
1029
             mm.get(),
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
             op.get_handle_ptr(),
             args.get_handle_ptr());
        return instruction(op_ins, own{});
    }

    instruction add_instruction(const migraphx::operation& op,
                                const migraphx::instructions& args,
                                const migraphx::modules& module_args)
    {
        migraphx_instruction_t op_ins;
        call(&migraphx_module_add_instruction_with_mod_args,
             &op_ins,
1042
             mm.get(),
1043
1044
1045
1046
1047
1048
             op.get_handle_ptr(),
             args.get_handle_ptr(),
             module_args.get_handle_ptr());
        return instruction(op_ins, own{});
    }

1049
1050
1051
1052
1053
1054
1055
1056
1057
    template <typename T>
    instruction add_literal(const migraphx::shape& s, T* buffer)
    {
        migraphx_instruction_t literal_ins;
        const auto* buffer_ptr = reinterpret_cast<const char*>(buffer);
        call(&migraphx_module_add_literal, &literal_ins, mm.get(), s.get_handle_ptr(), buffer_ptr);
        return instruction(literal_ins, own{});
    }

1058
1059
1060
    instruction add_parameter(const std::string& name, shape s)
    {
        migraphx_instruction_t param_ins;
1061
1062
        call(
            &migraphx_module_add_parameter, &param_ins, mm.get(), name.c_str(), s.get_handle_ptr());
1063
1064
1065
1066
1067
1068
        return instruction(param_ins, own{});
    }

    instruction add_return(const migraphx::instructions& args)
    {
        migraphx_instruction_t ret_ins;
1069
        call(&migraphx_module_add_return, &ret_ins, mm.get(), args.get_handle_ptr());
1070
1071
        return instruction(ret_ins, own{});
    }
1072

1073
1074
1075
1076
1077
1078
1079
    instruction add_allocation(const migraphx::shape& s)
    {
        migraphx_instruction_t ret_ins;
        call(&migraphx_module_add_allocation, &ret_ins, mm.get(), s.get_handle_ptr());
        return instruction(ret_ins, own{});
    }

1080
1081
1082
1083
    migraphx_module_t get_handle_ptr() const { return mm.get(); }

    private:
    std::shared_ptr<migraphx_module> mm;
Shucai Xiao's avatar
Shucai Xiao committed
1084
1085
};

1086
struct context : handle_lookup<context, migraphx_context>
kahmed10's avatar
kahmed10 committed
1087
{
1088
    context(migraphx_context* p, borrow) : ctx(std::shared_ptr<migraphx_context*>(), p) {}
kahmed10's avatar
kahmed10 committed
1089

1090
1091
1092
1093
1094
1095
    template <class T>
    context(migraphx_context* p, share<T> b) : ctx(b.alias(p))
    {
    }

    void finish() const { call(&migraphx_context_finish, ctx.get()); }
1096
1097
1098
1099
1100

    template <class T>
    T get_queue()
    {
        void* out;
1101
        call(&migraphx_context_get_queue, &out, ctx.get());
1102
1103
1104
        // TODO: check type here
        return reinterpret_cast<T>(out);
    }
1105
1106
1107

    private:
    std::shared_ptr<migraphx_context> ctx;
kahmed10's avatar
kahmed10 committed
1108
1109
};

1110
1111
1112
1113
struct compile_options : MIGRAPHX_HANDLE_BASE(compile_options)
{
    compile_options() { this->make_handle(&migraphx_compile_options_create); }

Umang Yadav's avatar
Umang Yadav committed
1114
    MIGRAPHX_HANDLE_CONSTRUCTOR(compile_options)
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130

    /// For targets with offloaded memory(such as the gpu), this will insert
    /// instructions during compilation to copy the input parameters to the
    /// offloaded memory and to copy the final result from the offloaded
    /// memory back to main memory.
    void set_offload_copy(bool value = true)
    {
        call(&migraphx_compile_options_set_offload_copy, this->get_handle_ptr(), value);
    }

    /// Optimize math functions to use faster approximate versions. There may
    /// be slight accuracy degredation when enabled.
    void set_fast_math(bool value = true)
    {
        call(&migraphx_compile_options_set_fast_math, this->get_handle_ptr(), value);
    }
1131
1132
1133
1134
1135
1136

    /// Set or un-set exhaustive search to find fastest kernel
    void set_exhaustive_tune_flag(bool value = true)
    {
        call(&migraphx_compile_options_set_exhaustive_tune_flag, this->get_handle_ptr(), value);
    }
1137
1138
};

1139
/// A program represents the all computation graphs to be compiled and executed
Paul Fultz II's avatar
Paul Fultz II committed
1140
1141
struct program : MIGRAPHX_HANDLE_BASE(program)
{
1142
    program() { this->make_handle(&migraphx_program_create); }
Paul Fultz II's avatar
Paul Fultz II committed
1143

Umang Yadav's avatar
Umang Yadav committed
1144
    MIGRAPHX_HANDLE_CONSTRUCTOR(program)
Paul Fultz II's avatar
Paul Fultz II committed
1145

1146
    /// Compile the program for a specific target to be ran on
1147
    void compile(const target& ptarget, const compile_options& poptions) const
Paul Fultz II's avatar
Paul Fultz II committed
1148
    {
1149
1150
1151
1152
        call(&migraphx_program_compile,
             this->get_handle_ptr(),
             ptarget.get_handle_ptr(),
             poptions.get_handle_ptr());
Paul Fultz II's avatar
Paul Fultz II committed
1153
1154
    }

1155
    /// Compile the program for a specific target to be ran on
Paul Fultz II's avatar
Paul Fultz II committed
1156
1157
    void compile(const target& ptarget) const
    {
1158
1159
1160
1161
        call(&migraphx_program_compile,
             this->get_handle_ptr(),
             ptarget.get_handle_ptr(),
             migraphx::compile_options{}.get_handle_ptr());
Paul Fultz II's avatar
Paul Fultz II committed
1162
1163
    }

1164
    /// Return the shapes for the input parameters
Paul Fultz II's avatar
Paul Fultz II committed
1165
1166
1167
1168
1169
1170
1171
    program_parameter_shapes get_parameter_shapes() const
    {
        migraphx_program_parameter_shapes_t pout;
        call(&migraphx_program_get_parameter_shapes, &pout, this->get_handle_ptr());
        return program_parameter_shapes(pout, own{});
    }

1172
    /// Get the shapes of all the outputs returned by this program
Paul Fultz II's avatar
Paul Fultz II committed
1173
1174
1175
1176
1177
1178
1179
    shapes get_output_shapes() const
    {
        migraphx_shapes_t pout;
        call(&migraphx_program_get_output_shapes, &pout, this->get_handle_ptr());
        return shapes(pout, own{});
    }

1180
    /// Run the program using the inputs passed in
Paul Fultz II's avatar
Paul Fultz II committed
1181
1182
1183
1184
1185
1186
1187
    arguments eval(const program_parameters& pparams) const
    {
        migraphx_arguments_t pout;
        call(&migraphx_program_run, &pout, this->get_handle_ptr(), pparams.get_handle_ptr());
        return arguments(pout, own{});
    }

1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
    template <class Stream>
    /// Overloaded to allow for execution_environment input
    arguments run_async(const program_parameters& pparams, Stream* s) const
    {
        migraphx_arguments_t pout;
        call(&migraphx_program_run_async,
             &pout,
             this->get_handle_ptr(),
             pparams.get_handle_ptr(),
             s,
             get_type_name<Stream>().c_str());
        return arguments(pout, own{});
    }

Paul Fultz II's avatar
Paul Fultz II committed
1202
1203
    void print() const { call(&migraphx_program_print, this->get_handle_ptr()); }

1204
1205
1206
1207
1208
1209
    program sort()
    {
        call(&migraphx_program_sort, this->get_handle_ptr());
        return *this;
    }

Paul Fultz II's avatar
Paul Fultz II committed
1210
1211
1212
1213
1214
1215
1216
    friend bool operator==(const program& px, const program& py)
    {
        bool pout;
        call(&migraphx_program_equal, &pout, px.get_handle_ptr(), py.get_handle_ptr());
        return pout;
    }

Shucai Xiao's avatar
Shucai Xiao committed
1217
1218
1219
1220
    module get_main_module()
    {
        migraphx_module_t p_modu;
        call(&migraphx_program_get_main_module, &p_modu, this->get_handle_ptr());
1221
        return module{p_modu, this->share_handle()};
Shucai Xiao's avatar
Shucai Xiao committed
1222
1223
    }

1224
    context experimental_get_context()
kahmed10's avatar
kahmed10 committed
1225
1226
    {
        migraphx_context_t ctx;
1227
        call(&migraphx_program_experimental_get_context, &ctx, this->get_handle_ptr());
1228
        return context{ctx, this->share_handle()};
kahmed10's avatar
kahmed10 committed
1229
1230
    }

1231
    module create_module(const std::string& name)
1232
    {
1233
1234
        migraphx_module_t p_modu;
        call(&migraphx_program_create_module, &p_modu, this->get_handle_ptr(), name.data());
1235
        return module{p_modu, this->share_handle()};
1236
1237
    }

1238
    friend bool operator!=(const program& px, const program& py) { return not(px == py); }
1239
1240
};

1241
1242
1243
// options for migraphx file format options
struct file_options : MIGRAPHX_HANDLE_BASE(file_options)
{
Umang Yadav's avatar
Umang Yadav committed
1244
    MIGRAPHX_HANDLE_CONSTRUCTOR(file_options)
1245
1246
1247
1248
1249
1250
1251
1252
1253
    file_options() { this->make_handle(&migraphx_file_options_create); }

    // set file format
    void set_file_format(const char* format)
    {
        call(&migraphx_file_options_set_file_format, this->get_handle_ptr(), format);
    }
};

1254
/// Load a saved migraphx program from a file
1255
inline program load(const char* filename, const file_options& options)
1256
{
1257
1258
    return program(make<migraphx_program>(&migraphx_load, filename, options.get_handle_ptr()),
                   own{});
1259
1260
}

1261
/// Load a saved migraphx program from a file
1262
1263
inline program load(const char* filename)
{
1264
1265
1266
    return program(
        make<migraphx_program>(&migraphx_load, filename, migraphx::file_options{}.get_handle_ptr()),
        own{});
1267
1268
}

1269
/// Save a program to a file
1270
inline void save(const program& p, const char* filename, const file_options& options)
1271
{
1272
    call(&migraphx_save, p.get_handle_ptr(), filename, options.get_handle_ptr());
1273
1274
}

1275
/// Save a program to a file
1276
1277
inline void save(const program& p, const char* filename)
{
1278
    call(&migraphx_save, p.get_handle_ptr(), filename, migraphx::file_options{}.get_handle_ptr());
1279
1280
}

1281
/// Options for parsing onnx options
1282
struct onnx_options : MIGRAPHX_HANDLE_BASE(onnx_options)
Paul Fultz II's avatar
Paul Fultz II committed
1283
{
1284
1285
    onnx_options() { this->make_handle(&migraphx_onnx_options_create); }

Umang Yadav's avatar
Umang Yadav committed
1286
    MIGRAPHX_HANDLE_CONSTRUCTOR(onnx_options)
1287

1288
    /// Make onnx parser treat an inputs with a certain dimensions
1289
1290
1291
1292
1293
1294
1295
1296
1297
    void set_input_parameter_shape(const std::string& name, std::vector<std::size_t> dim)
    {
        call(&migraphx_onnx_options_set_input_parameter_shape,
             this->get_handle_ptr(),
             name.c_str(),
             dim.data(),
             dim.size());
    }

1298
1299
1300
1301
1302
1303
1304
1305
    void set_dyn_input_parameter_shape(const std::string& name, const dynamic_dimensions& dyn_dims)
    {
        call(&migraphx_onnx_options_set_dyn_input_parameter_shape,
             this->get_handle_ptr(),
             name.c_str(),
             dyn_dims.get_handle_ptr());
    }

kahmed10's avatar
kahmed10 committed
1306
    /// When there is a dimension parameter, then use this default value
1307
1308
1309
1310
    void set_default_dim_value(unsigned int value)
    {
        call(&migraphx_onnx_options_set_default_dim_value, this->get_handle_ptr(), value);
    }
Shucai Xiao's avatar
Shucai Xiao committed
1311

1312
1313
1314
1315
1316
1317
1318
    void set_default_dyn_dim_value(const dynamic_dimension& dd)
    {
        call(&migraphx_onnx_options_set_default_dyn_dim_value,
             this->get_handle_ptr(),
             dd.get_handle_ptr());
    }

Shucai Xiao's avatar
Shucai Xiao committed
1319
1320
1321
1322
1323
    /// Set default max iteration number for the loop operator
    void set_default_loop_iterations(int64_t value)
    {
        call(&migraphx_onnx_options_set_default_loop_iterations, this->get_handle_ptr(), value);
    }
1324
1325
1326
1327
1328
1329

    /// Set max iteration limit for the loop operator
    void set_limit_loop_iterations(int64_t value)
    {
        call(&migraphx_onnx_options_set_limit_loop_iterations, this->get_handle_ptr(), value);
    }
1330
1331
};

1332
/// Parse an onnx file into a migraphx program
1333
1334
1335
1336
inline program parse_onnx(const char* filename, const migraphx::onnx_options& options)
{
    return program(make<migraphx_program>(&migraphx_parse_onnx, filename, options.get_handle_ptr()),
                   own{});
Paul Fultz II's avatar
Paul Fultz II committed
1337
1338
}

1339
/// Parse an onnx file into a migraphx program
Paul Fultz II's avatar
Paul Fultz II committed
1340
1341
inline program parse_onnx(const char* filename)
{
1342
1343
1344
    migraphx::onnx_options options;
    return program(make<migraphx_program>(&migraphx_parse_onnx, filename, options.get_handle_ptr()),
                   own{});
Paul Fultz II's avatar
Paul Fultz II committed
1345
1346
}

1347
/// Parse a buffer of memory as an onnx file
1348
1349
inline program
parse_onnx_buffer(const void* data, size_t size, const migraphx::onnx_options& options)
Paul Fultz II's avatar
Paul Fultz II committed
1350
{
1351
1352
1353
    return program(
        make<migraphx_program>(&migraphx_parse_onnx_buffer, data, size, options.get_handle_ptr()),
        own{});
Paul Fultz II's avatar
Paul Fultz II committed
1354
1355
}

1356
/// Parse a buffer of memory as an onnx file
Paul Fultz II's avatar
Paul Fultz II committed
1357
1358
inline program parse_onnx_buffer(const void* data, size_t size)
{
1359
1360
1361
1362
    migraphx::onnx_options options;
    return program(
        make<migraphx_program>(&migraphx_parse_onnx_buffer, data, size, options.get_handle_ptr()),
        own{});
Paul Fultz II's avatar
Paul Fultz II committed
1363
1364
}

1365
/// Parse a buffer of memory as an onnx file
1366
inline program parse_onnx_buffer(const std::string& buffer, const migraphx::onnx_options& options)
Paul Fultz II's avatar
Paul Fultz II committed
1367
1368
{
    return program(
1369
1370
        make<migraphx_program>(
            &migraphx_parse_onnx_buffer, buffer.data(), buffer.size(), options.get_handle_ptr()),
Paul Fultz II's avatar
Paul Fultz II committed
1371
1372
1373
        own{});
}

1374
/// Parse a buffer of memory as an onnx file
Paul Fultz II's avatar
Paul Fultz II committed
1375
1376
inline program parse_onnx_buffer(const std::string& buffer)
{
1377
    migraphx::onnx_options options;
Paul Fultz II's avatar
Paul Fultz II committed
1378
    return program(
1379
1380
        make<migraphx_program>(
            &migraphx_parse_onnx_buffer, buffer.data(), buffer.size(), options.get_handle_ptr()),
Paul Fultz II's avatar
Paul Fultz II committed
1381
1382
1383
        own{});
}

kahmed10's avatar
kahmed10 committed
1384
1385
1386
1387
1388
/// Options for parsing tf options
struct tf_options : MIGRAPHX_HANDLE_BASE(tf_options)
{
    tf_options() { this->make_handle(&migraphx_tf_options_create); }

Umang Yadav's avatar
Umang Yadav committed
1389
    MIGRAPHX_HANDLE_CONSTRUCTOR(tf_options)
kahmed10's avatar
kahmed10 committed
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437

    /// Make tf parser treat an inputs with a certain dimensions
    void set_input_parameter_shape(const std::string& name, std::vector<std::size_t> dim)
    {
        call(&migraphx_tf_options_set_input_parameter_shape,
             this->get_handle_ptr(),
             name.c_str(),
             dim.data(),
             dim.size());
    }

    /// Change data layout to NHWC (default is NCHW)
    void set_nhwc(bool is_nhwc = true)
    {
        call(&migraphx_tf_options_set_nhwc, this->get_handle_ptr(), is_nhwc);
    }

    /// When there is a dimension parameter, then use this default value
    void set_default_dim_value(unsigned int value)
    {
        call(&migraphx_tf_options_set_default_dim_value, this->get_handle_ptr(), value);
    }

    /// Set output node names to return specific outputs from graph
    void set_output_names(std::vector<const char*> names)
    {
        call(&migraphx_tf_options_set_output_names,
             this->get_handle_ptr(),
             names.data(),
             names.size());
    }
};

/// Parse a tf file into a migraphx program
inline program parse_tf(const char* filename, const migraphx::tf_options& options)
{
    return program(make<migraphx_program>(&migraphx_parse_tf, filename, options.get_handle_ptr()),
                   own{});
}

/// Parse a tf file into a migraphx program
inline program parse_tf(const char* filename)
{
    migraphx::tf_options options;
    return program(make<migraphx_program>(&migraphx_parse_tf, filename, options.get_handle_ptr()),
                   own{});
}

Shucai Xiao's avatar
Shucai Xiao committed
1438
1439
1440
1441
struct quantize_op_names : MIGRAPHX_HANDLE_BASE(quantize_op_names)
{
    quantize_op_names() { this->make_handle(&migraphx_quantize_op_names_create); }

Umang Yadav's avatar
Umang Yadav committed
1442
    MIGRAPHX_HANDLE_CONSTRUCTOR(quantize_op_names)
Shucai Xiao's avatar
Shucai Xiao committed
1443
1444
1445
1446
1447
1448
1449

    void add(const std::string& name)
    {
        call(&migraphx_quantize_op_names_add, this->get_handle_ptr(), name.c_str());
    }
};

1450
/// Quantize program to use fp16
Shucai Xiao's avatar
Shucai Xiao committed
1451
1452
1453
1454
1455
inline void quantize_fp16(const program& prog, const quantize_op_names& names)
{
    call(&migraphx_quantize_fp16_with_op_names, prog.get_handle_ptr(), names.get_handle_ptr());
}

1456
/// Quantize program to use fp16
Shucai Xiao's avatar
Shucai Xiao committed
1457
1458
1459
1460
1461
inline void quantize_fp16(const program& prog)
{
    call(&migraphx_quantize_fp16, prog.get_handle_ptr());
}

1462
/// Options to be passed when quantizing for int8
Shucai Xiao's avatar
Shucai Xiao committed
1463
1464
1465
1466
struct quantize_int8_options : MIGRAPHX_HANDLE_BASE(quantize_int8_options)
{
    quantize_int8_options() { this->make_handle(&migraphx_quantize_int8_options_create); }

Umang Yadav's avatar
Umang Yadav committed
1467
    MIGRAPHX_HANDLE_CONSTRUCTOR(quantize_int8_options)
Shucai Xiao's avatar
Shucai Xiao committed
1468

1469
    /// Add an operator that should be quantized
Shucai Xiao's avatar
Shucai Xiao committed
1470
1471
1472
1473
1474
    void add_op_name(const std::string& name)
    {
        call(&migraphx_quantize_int8_options_add_op_name, this->get_handle_ptr(), name.c_str());
    }

1475
    /// Add calibrartion data to be used for quantizing
Shucai Xiao's avatar
Shucai Xiao committed
1476
1477
1478
1479
1480
1481
1482
1483
    void add_calibration_data(const program_parameters& pp)
    {
        call(&migraphx_quantize_int8_options_add_calibration_data,
             this->get_handle_ptr(),
             pp.get_handle_ptr());
    }
};

1484
/// Quantize program to use int8
Shucai Xiao's avatar
Shucai Xiao committed
1485
1486
1487
1488
1489
1490
1491
1492
1493
inline void
quantize_int8(const program& prog, const target& ptarget, const quantize_int8_options& options)
{
    call(&migraphx_quantize_int8,
         prog.get_handle_ptr(),
         ptarget.get_handle_ptr(),
         options.get_handle_ptr());
}

1494
1495
struct experimental_custom_op_base
{
1496
1497
1498
1499
1500
    experimental_custom_op_base()                                   = default;
    experimental_custom_op_base(const experimental_custom_op_base&) = default;
    experimental_custom_op_base& operator=(const experimental_custom_op_base&) = default;
    virtual ~experimental_custom_op_base()                                     = default;

1501
1502
1503
    virtual std::string name() const                                            = 0;
    virtual argument compute(context ctx, shape output, arguments inputs) const = 0;
    virtual shape compute_shape(shapes inputs) const                            = 0;
1504
1505
1506
    virtual std::vector<size_t> output_alias(shapes) const { return {}; }
    // TODO: Return target string instead of bool
    virtual bool runs_on_offload_target() const = 0;
1507
1508
1509
1510
1511
1512
1513
};

struct experimental_custom_op : interface_base<MIGRAPHX_HANDLE_BASE(experimental_custom_op)>
{
    template <class T>
    experimental_custom_op(T& obj)
    {
1514
1515
1516
1517
        this->make_interface(&migraphx_experimental_custom_op_create,
                             obj,
                             get_type_name(obj).c_str(),
                             obj.name().c_str());
1518
1519
1520
1521
        MIGRAPHX_INTERFACE_LIFT(1, T, experimental_custom_op, compute_shape);
        MIGRAPHX_INTERFACE_LIFT(1, T, experimental_custom_op, compute);
        MIGRAPHX_INTERFACE_LIFT(2, T, experimental_custom_op, output_alias);
        MIGRAPHX_INTERFACE_LIFT(1, T, experimental_custom_op, runs_on_offload_target);
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
    }

    void register_op() { call(&migraphx_experimental_custom_op_register, this->get_handle_ptr()); }
};

template <class T, class = require_interface<experimental_custom_op_base, T>>
void register_experimental_custom_op(T& obj)
{
    experimental_custom_op op{obj};
    op.register_op();
}

1534
#ifndef DOXYGEN
Paul Fultz II's avatar
Paul Fultz II committed
1535
} // namespace api
1536
#endif
Paul Fultz II's avatar
Paul Fultz II committed
1537
1538
1539
} // namespace migraphx

#endif