tfLite.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. // Copyright 2022 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package main
  15. import (
  16. "fmt"
  17. "github.com/lf-edge/ekuiper/pkg/api"
  18. "github.com/lf-edge/ekuiper/pkg/cast"
  19. "github.com/mattn/go-tflite"
  20. )
  21. type Tffunc struct {
  22. }
  23. // Validate the arguments.
  24. // args[0]: string, model name which maps to a path
  25. // args[1 to n]: tensors
  26. func (f *Tffunc) Validate(args []interface{}) error {
  27. if len(args) < 2 {
  28. return fmt.Errorf("tensorflow function must have at least 2 parameters but got %d", len(args))
  29. }
  30. return nil
  31. }
  32. func (f *Tffunc) IsAggregate() bool {
  33. return false
  34. }
  35. func (f *Tffunc) Exec(args []interface{}, ctx api.FunctionContext) (interface{}, bool) {
  36. model, ok := args[0].(string)
  37. if !ok {
  38. return fmt.Errorf("tensorflow function first parameter must be a string, but got %[1]T(%[1]v)", args[0]), false
  39. }
  40. interpreter, err := ipManager.GetOrCreate(model)
  41. if err != nil {
  42. return err, false
  43. }
  44. inputCount := interpreter.GetInputTensorCount()
  45. if len(args)-1 != inputCount {
  46. return fmt.Errorf("tensorflow function requires %d tensors but got %d", inputCount, len(args)-1), false
  47. }
  48. ctx.GetLogger().Debugf("tensorflow function %s with %d tensors", model, inputCount)
  49. // Set input tensors
  50. for i := 1; i < len(args); i++ {
  51. input := interpreter.GetInputTensor(i - 1)
  52. var arg []interface{}
  53. switch v := args[i].(type) {
  54. case []byte:
  55. if int(input.ByteSize()) != len(v) {
  56. return fmt.Errorf("tensorflow function input tensor %d has %d bytes but got %d", i-1, input.ByteSize(), len(v)), false
  57. }
  58. input.CopyFromBuffer(v)
  59. continue
  60. case []interface{}: // only supports one dimensional arg. Even dim 0 must be an array of 1 element
  61. arg = v
  62. default:
  63. return fmt.Errorf("tensorflow function parameter %d must be a bytea or array of bytea, but got %[1]T(%[1]v)", i), false
  64. }
  65. paraLen := 1
  66. for j := 0; j < input.NumDims(); j++ {
  67. paraLen = paraLen * input.Dim(j)
  68. }
  69. ctx.GetLogger().Debugf("receive tensor %v, require %d length", arg, paraLen)
  70. if paraLen != len(arg) {
  71. return fmt.Errorf("tensorflow function input tensor %d must have %d elements but got %d", i-1, paraLen, len(arg)), false
  72. }
  73. switch input.Type() {
  74. case tflite.Float32:
  75. v, err := cast.ToFloat32Slice(arg, cast.CONVERT_SAMEKIND)
  76. if err != nil {
  77. return fmt.Errorf("invalid %d parameter, expect float32 but got %[2]T(%[2]v) with err %v", i, args[i], err), false
  78. }
  79. err = input.SetFloat32s(v)
  80. if err != nil {
  81. return nil, false
  82. }
  83. case tflite.Int64:
  84. v, err := cast.ToInt64Slice(arg, cast.CONVERT_SAMEKIND)
  85. if err != nil {
  86. return fmt.Errorf("invalid %d parameter, expect int64 but got %[2]T(%[2]v) with err %v", i, args[i], err), false
  87. }
  88. err = input.SetInt64s(v)
  89. if err != nil {
  90. return nil, false
  91. }
  92. case tflite.Int32:
  93. v, err := cast.ToTypedSlice(args, func(input interface{}, sn cast.Strictness) (interface{}, error) {
  94. return cast.ToInt32(input, sn)
  95. }, "int32", cast.CONVERT_SAMEKIND)
  96. if err != nil {
  97. return fmt.Errorf("invalid %d parameter, expect int32 but got %[2]T(%[2]v) with err %v", i, args[i], err), false
  98. }
  99. err = input.SetInt32s(v.([]int32))
  100. if err != nil {
  101. return nil, false
  102. }
  103. case tflite.Int16:
  104. v, err := cast.ToTypedSlice(args, func(input interface{}, sn cast.Strictness) (interface{}, error) {
  105. return cast.ToInt16(input, sn)
  106. }, "int16", cast.CONVERT_SAMEKIND)
  107. if err != nil {
  108. return fmt.Errorf("invalid %d parameter, expect int16 but got %[2]T(%[2]v) with err %v", i, args[i], err), false
  109. }
  110. err = input.SetInt16s(v.([]int16))
  111. if err != nil {
  112. return nil, false
  113. }
  114. case tflite.Int8:
  115. v, err := cast.ToTypedSlice(args, func(input interface{}, sn cast.Strictness) (interface{}, error) {
  116. return cast.ToInt8(input, sn)
  117. }, "int8", cast.CONVERT_SAMEKIND)
  118. if err != nil {
  119. return fmt.Errorf("invalid %d parameter, expect int8 but got %[2]T(%[2]v) with err %v", i, args[i], err), false
  120. }
  121. err = input.SetInt8s(v.([]int8))
  122. if err != nil {
  123. return nil, false
  124. }
  125. case tflite.UInt8:
  126. v, err := cast.ToBytes(args, cast.CONVERT_SAMEKIND)
  127. if err != nil {
  128. return fmt.Errorf("invalid %d parameter, expect uint8 but got %[2]T(%[2]v) with err %v", i, args[i], err), false
  129. }
  130. err = input.SetUint8s(v)
  131. if err != nil {
  132. return nil, false
  133. }
  134. default:
  135. return fmt.Errorf("invalid %d parameter, unsupported type %v in the model", i, input.Type()), false
  136. }
  137. }
  138. status := interpreter.Invoke()
  139. if status != tflite.OK {
  140. return fmt.Errorf("invoke failed"), false
  141. }
  142. outputCount := interpreter.GetOutputTensorCount()
  143. results := make([]interface{}, outputCount)
  144. for i := 0; i < outputCount; i++ {
  145. output := interpreter.GetOutputTensor(i)
  146. //outputSize := output.Dim(output.NumDims() - 1)
  147. //b := make([]byte, outputSize)
  148. //status = output.CopyToBuffer(&b[0])
  149. //if status != tflite.OK {
  150. // return fmt.Errorf("output failed"), false
  151. //}
  152. //results[i] = b
  153. t := output.Type()
  154. switch t {
  155. case tflite.Float32:
  156. results[i] = output.Float32s()
  157. case tflite.Int64:
  158. results[i] = output.Int64s()
  159. case tflite.Int32:
  160. results[i] = output.Int32s()
  161. case tflite.Int16:
  162. results[i] = output.Int16s()
  163. case tflite.Int8:
  164. results[i] = output.Int8s()
  165. case tflite.UInt8:
  166. results[i] = output.UInt8s()
  167. default:
  168. return fmt.Errorf("invalid %d parameter, unsupported type %v in the model", i, t), false
  169. }
  170. }
  171. return results, true
  172. }
  173. var TfLite Tffunc