Debian Codegraph @

lualib/lua_ffi/linalg.lua

raw
1 --[[
2 Copyright (c) 2022, Vsevolod Stakhov <[email protected]>
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 ]]--
16
17 --[[[
18 -- @module lua_ffi/linalg
19 -- This module contains ffi interfaces to linear algebra routines
20 --]]
21
22 local ffi = require 'ffi'
23
24 local exports = {}
25
26 ffi.cdef [[
27 void kad_sgemm_simple(int trans_A, int trans_B, int M, int N, int K, const float *A, const float *B, float *C);
28 bool kad_ssyev_simple (int N, float *A, float *output);
29 ]]
30
31 local function table_to_ffi(a, m, n)
32 local a_conv = ffi.new("float[?]", m * n)
33 for i = 1, m or #a do
34 for j = 1, n or #a[1] do
35 a_conv[(i - 1) * n + (j - 1)] = a[i][j]
36 end
37 end
38 return a_conv
39 end
40
41 local function ffi_to_table(a, m, n)
42 local res = {}
43
44 for i = 0, m - 1 do
45 res[i + 1] = {}
46 for j = 0, n - 1 do
47 res[i + 1][j + 1] = a[i * n + j]
48 end
49 end
50
51 return res
52 end
53
54 exports.sgemm = function(a, m, b, n, k, trans_a, trans_b)
55 if type(a) == 'table' then
56 -- Need to convert, slow!
57 a = table_to_ffi(a, m, k)
58 end
59 if type(b) == 'table' then
60 b = table_to_ffi(b, k, n)
61 end
62 local res = ffi.new("float[?]", m * n)
63 ffi.C.kad_sgemm_simple(trans_a or 0, trans_b or 0, m, n, k, ffi.cast('const float*', a),
64 ffi.cast('const float*', b), ffi.cast('float*', res))
65 return res
66 end
67
68 exports.eigen = function(a, n)
69 if type(a) == 'table' then
70 -- Need to convert, slow!
71 n = n or #a
72 a = table_to_ffi(a, n, n)
73 end
74
75 local res = ffi.new("float[?]", n)
76
77 if ffi.C.kad_ssyev_simple(n, ffi.cast('float*', a), res) then
78 return res, a
79 end
80
81 return nil
82 end
83
84 exports.ffi_to_table = ffi_to_table
85 exports.table_to_ffi = table_to_ffi
86
87 return exports