remotecontrol.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. /*
  2. * MIT License
  3. *
  4. * Copyright (c) 2019 Alexey Edelev <semlanik@gmail.com>
  5. *
  6. * This file is part of NeuralNetwork project https://git.semlanik.org/semlanik/NeuralNetwork
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy of this
  9. * software and associated documentation files (the "Software"), to deal in the Software
  10. * without restriction, including without limitation the rights to use, copy, modify,
  11. * merge, publish, distribute, sublicense, and/or sell copies of the Software, and
  12. * to permit persons to whom the Software is furnished to do so, subject to the following
  13. * conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all copies
  16. * or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  19. * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  20. * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
  21. * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  22. * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  23. * DEALINGS IN THE SOFTWARE.
  24. */
  25. package remotecontrol
  26. import (
  27. context "context"
  28. fmt "fmt"
  29. "log"
  30. "net"
  31. "os"
  32. "sync"
  33. "time"
  34. "google.golang.org/grpc/codes"
  35. status "google.golang.org/grpc/status"
  36. neuralnetworkbase "../neuralnetworkbase"
  37. "gonum.org/v1/gonum/mat"
  38. grpc "google.golang.org/grpc"
  39. teach "../teach"
  40. )
  41. type RemoteControl struct {
  42. nn *neuralnetworkbase.NeuralNetwork
  43. activationsQueue chan *LayerMatrix
  44. biasesQueue chan *LayerMatrix
  45. weightsQueue chan *LayerMatrix
  46. mutex sync.Mutex
  47. }
  48. func (rw *RemoteControl) Init(nn *neuralnetworkbase.NeuralNetwork) {
  49. rw.nn = nn
  50. rw.activationsQueue = make(chan *LayerMatrix, 10)
  51. rw.biasesQueue = make(chan *LayerMatrix, 10)
  52. rw.weightsQueue = make(chan *LayerMatrix, 10)
  53. }
  54. func (rw *RemoteControl) UpdateActivations(l int, a *mat.Dense) {
  55. matrix := NewLayerMatrix(l, a, LayerMatrix_Activations)
  56. select {
  57. case rw.activationsQueue <- matrix:
  58. default:
  59. }
  60. }
  61. func (rw *RemoteControl) UpdateBiases(l int, biases *mat.Dense) {
  62. matrix := NewLayerMatrix(l, biases, LayerMatrix_Biases)
  63. select {
  64. case rw.biasesQueue <- matrix:
  65. default:
  66. }
  67. }
  68. func (rw *RemoteControl) UpdateWeights(l int, weights *mat.Dense) {
  69. matrix := NewLayerMatrix(l, weights, LayerMatrix_Weights)
  70. select {
  71. case rw.weightsQueue <- matrix:
  72. default:
  73. }
  74. }
  75. func NewLayerMatrix(l int, dense *mat.Dense, contentType LayerMatrix_ContentType) (matrix *LayerMatrix) {
  76. buffer, err := dense.MarshalBinary()
  77. if err != nil {
  78. log.Fatalln("Invalid dense is provided for remote control")
  79. }
  80. matrix = &LayerMatrix{
  81. Matrix: &Matrix{
  82. Matrix: buffer,
  83. },
  84. Layer: int32(l),
  85. ContentType: contentType,
  86. }
  87. return
  88. }
  89. func (rw *RemoteControl) GetConfiguration(context.Context, *None) (*Configuration, error) {
  90. config := &Configuration{}
  91. for _, size := range rw.nn.Sizes {
  92. config.Sizes = append(config.Sizes, int32(size))
  93. }
  94. return config, nil
  95. }
  96. func (rw *RemoteControl) Activations(_ *None, srv RemoteControl_ActivationsServer) error {
  97. ctx := srv.Context()
  98. for {
  99. select {
  100. case <-ctx.Done():
  101. return ctx.Err()
  102. default:
  103. }
  104. msg := <-rw.activationsQueue
  105. srv.Send(msg)
  106. }
  107. }
  108. func (rw *RemoteControl) Biases(_ *None, srv RemoteControl_BiasesServer) error {
  109. ctx := srv.Context()
  110. for {
  111. select {
  112. case <-ctx.Done():
  113. return ctx.Err()
  114. default:
  115. }
  116. msg := <-rw.biasesQueue
  117. srv.Send(msg)
  118. }
  119. }
  120. func (rw *RemoteControl) Weights(_ *None, srv RemoteControl_WeightsServer) error {
  121. ctx := srv.Context()
  122. for {
  123. select {
  124. case <-ctx.Done():
  125. return ctx.Err()
  126. default:
  127. }
  128. msg := <-rw.weightsQueue
  129. srv.Send(msg)
  130. }
  131. }
  132. func (rw *RemoteControl) Predict(context.Context, *Matrix) (*Matrix, error) {
  133. return nil, status.Error(codes.Unimplemented, "Not implemented")
  134. }
  135. func (rw *RemoteControl) DummyStart(context.Context, *None) (*None, error) {
  136. go func() {
  137. rw.mutex.Lock()
  138. defer rw.mutex.Unlock()
  139. // teacher := teach.NewMNISTReader("./minst.data", "./mnist.labels")
  140. teacher := teach.NewTextDataReader("wine.data", 5)
  141. rw.nn.Teach(teacher, 500)
  142. // for i := 0; i < nn.Count; i++ {
  143. // if i > 0 {
  144. // fmt.Printf("Weights after:\n%v\n\n", mat.Formatted(nn.Weights[i], mat.Prefix(""), mat.Excerpt(0)))
  145. // fmt.Printf("Biases after:\n%v\n\n", mat.Formatted(nn.Biases[i], mat.Prefix(""), mat.Excerpt(0)))
  146. // fmt.Printf("Z after:\n%v\n\n", mat.Formatted(nn.Z[i], mat.Prefix(""), mat.Excerpt(0)))
  147. // }
  148. // fmt.Printf("A after:\n%v\n\n", mat.Formatted(nn.A[i], mat.Prefix(""), mat.Excerpt(0)))
  149. // }
  150. outFile, err := os.OpenFile("./data", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
  151. if err != nil {
  152. log.Fatal(err)
  153. }
  154. defer outFile.Close()
  155. rw.nn.SaveState(outFile)
  156. outFile.Close()
  157. time.Sleep(5 * time.Second)
  158. failCount := 0
  159. teacher.Reset()
  160. for teacher.NextValidator() {
  161. dataSet, expect := teacher.GetValidator()
  162. index, _ := rw.nn.Predict(dataSet)
  163. //TODO: remove this is not used for visualization
  164. time.Sleep(400 * time.Millisecond)
  165. if expect.At(index, 0) != 1.0 {
  166. failCount++
  167. // fmt.Printf("Fail: %v, %v\n\n", teacher.ValidationIndex(), expect.At(index, 0))
  168. }
  169. if !teacher.NextValidator() {
  170. fmt.Printf("Fail count: %v\n\n", failCount)
  171. failCount = 0
  172. teacher.Reset()
  173. }
  174. }
  175. fmt.Printf("Fail count: %v\n\n", failCount)
  176. failCount = 0
  177. teacher.Reset()
  178. }()
  179. return &None{}, nil
  180. }
  181. func (rw *RemoteControl) Run() {
  182. grpcServer := grpc.NewServer()
  183. RegisterRemoteControlServer(grpcServer, rw)
  184. lis, err := net.Listen("tcp", "localhost:65001")
  185. if err != nil {
  186. fmt.Printf("Failed to listen: %v\n", err)
  187. }
  188. fmt.Printf("Listen localhost:65001\n")
  189. if err := grpcServer.Serve(lis); err != nil {
  190. fmt.Printf("Failed to serve: %v\n", err)
  191. }
  192. }