tfLite.go 5.9 KB

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