remotecontrol.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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. neuralnetwork "../neuralnetwork"
  37. "gonum.org/v1/gonum/mat"
  38. grpc "google.golang.org/grpc"
  39. training "../training"
  40. )
  41. type RemoteControl struct {
  42. nn *neuralnetwork.NeuralNetwork
  43. activationsQueue chan *LayerMatrix
  44. biasesQueue chan *LayerMatrix
  45. weightsQueue chan *LayerMatrix
  46. stateQueue chan int
  47. mutex sync.Mutex
  48. config *Configuration
  49. }
  50. func (rw *RemoteControl) Init(nn *neuralnetwork.NeuralNetwork) {
  51. rw.nn = nn
  52. rw.activationsQueue = make(chan *LayerMatrix, 5)
  53. rw.biasesQueue = make(chan *LayerMatrix, 5)
  54. rw.weightsQueue = make(chan *LayerMatrix, 5)
  55. rw.stateQueue = make(chan int, 2)
  56. rw.config = &Configuration{}
  57. for _, size := range rw.nn.Sizes {
  58. rw.config.Sizes = append(rw.config.Sizes, int32(size))
  59. }
  60. }
  61. func (rw *RemoteControl) UpdateActivations(l int, a *mat.Dense) {
  62. matrix := NewLayerMatrix(l, a, LayerMatrix_Activations)
  63. select {
  64. case rw.activationsQueue <- matrix:
  65. default:
  66. }
  67. }
  68. func (rw *RemoteControl) UpdateBiases(l int, biases *mat.Dense) {
  69. matrix := NewLayerMatrix(l, biases, LayerMatrix_Biases)
  70. select {
  71. case rw.biasesQueue <- matrix:
  72. default:
  73. }
  74. }
  75. func (rw *RemoteControl) UpdateWeights(l int, weights *mat.Dense) {
  76. matrix := NewLayerMatrix(l, weights, LayerMatrix_Weights)
  77. select {
  78. case rw.weightsQueue <- matrix:
  79. default:
  80. }
  81. }
  82. func (rw *RemoteControl) UpdateState(state int) {
  83. select {
  84. case rw.stateQueue <- state:
  85. default:
  86. }
  87. }
  88. func NewLayerMatrix(l int, dense *mat.Dense, contentType LayerMatrix_ContentType) (matrix *LayerMatrix) {
  89. buffer, err := dense.MarshalBinary()
  90. if err != nil {
  91. log.Fatalln("Invalid dense is provided for remote control")
  92. }
  93. matrix = &LayerMatrix{
  94. Matrix: &Matrix{
  95. Matrix: buffer,
  96. },
  97. Layer: int32(l),
  98. ContentType: contentType,
  99. }
  100. return
  101. }
  102. func (rw *RemoteControl) GetConfiguration(context.Context, *None) (*Configuration, error) {
  103. return rw.config, nil
  104. }
  105. func (rw *RemoteControl) Activations(_ *None, srv RemoteControl_ActivationsServer) error {
  106. ctx := srv.Context()
  107. for {
  108. select {
  109. case <-ctx.Done():
  110. return ctx.Err()
  111. default:
  112. }
  113. msg := <-rw.activationsQueue
  114. fmt.Println("Send Activations")
  115. srv.Send(msg)
  116. }
  117. }
  118. func (rw *RemoteControl) Biases(_ *None, srv RemoteControl_BiasesServer) error {
  119. ctx := srv.Context()
  120. for {
  121. select {
  122. case <-ctx.Done():
  123. return ctx.Err()
  124. default:
  125. }
  126. msg := <-rw.biasesQueue
  127. fmt.Println("Send Biases")
  128. srv.Send(msg)
  129. }
  130. }
  131. func (rw *RemoteControl) Weights(_ *None, srv RemoteControl_WeightsServer) error {
  132. ctx := srv.Context()
  133. for {
  134. select {
  135. case <-ctx.Done():
  136. return ctx.Err()
  137. default:
  138. }
  139. msg := <-rw.weightsQueue
  140. fmt.Println("Send Weights")
  141. srv.Send(msg)
  142. }
  143. }
  144. func (rw *RemoteControl) State(_ *None, srv RemoteControl_StateServer) error {
  145. ctx := srv.Context()
  146. for {
  147. select {
  148. case <-ctx.Done():
  149. return ctx.Err()
  150. default:
  151. }
  152. state := <-rw.stateQueue
  153. msg := &NetworkState{
  154. State: NetworkState_State(state),
  155. }
  156. fmt.Printf("Send state %v %v\n", msg, state)
  157. srv.Send(msg)
  158. }
  159. }
  160. func (rw *RemoteControl) Predict(context.Context, *Matrix) (*Matrix, error) {
  161. return nil, status.Error(codes.Unimplemented, "Not implemented")
  162. }
  163. func (rw *RemoteControl) DummyStart(context.Context, *None) (*None, error) {
  164. go func() {
  165. rw.mutex.Lock()
  166. defer rw.mutex.Unlock()
  167. // trainer := training.NewMNISTReader("./minst.data", "./mnist.labels")
  168. trainer := training.NewTextDataReader("wine.data", 5)
  169. rw.nn.Train(trainer, 500)
  170. // for i := 0; i < nn.Count; i++ {
  171. // if i > 0 {
  172. // fmt.Printf("Weights after:\n%v\n\n", mat.Formatted(nn.Weights[i], mat.Prefix(""), mat.Excerpt(0)))
  173. // fmt.Printf("Biases after:\n%v\n\n", mat.Formatted(nn.Biases[i], mat.Prefix(""), mat.Excerpt(0)))
  174. // fmt.Printf("Z after:\n%v\n\n", mat.Formatted(nn.Z[i], mat.Prefix(""), mat.Excerpt(0)))
  175. // }
  176. // fmt.Printf("A after:\n%v\n\n", mat.Formatted(nn.A[i], mat.Prefix(""), mat.Excerpt(0)))
  177. // }
  178. outFile, err := os.OpenFile("./data", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
  179. if err != nil {
  180. log.Fatal(err)
  181. }
  182. defer outFile.Close()
  183. rw.nn.SaveState(outFile)
  184. outFile.Close()
  185. rw.UpdateState(neuralnetwork.StateLearning)
  186. defer rw.UpdateState(neuralnetwork.StateIdle)
  187. failCount := 0
  188. trainer.Reset()
  189. for trainer.NextValidator() {
  190. dataSet, expect := trainer.GetValidator()
  191. index, _ := rw.nn.Predict(dataSet)
  192. //TODO: remove this is not used for visualization
  193. time.Sleep(400 * time.Millisecond)
  194. if expect.At(index, 0) != 1.0 {
  195. failCount++
  196. // fmt.Printf("Fail: %v, %v\n\n", trainer.ValidationIndex(), expect.At(index, 0))
  197. }
  198. if !trainer.NextValidator() {
  199. fmt.Printf("Fail count: %v\n\n", failCount)
  200. failCount = 0
  201. trainer.Reset()
  202. }
  203. }
  204. fmt.Printf("Fail count: %v\n\n", failCount)
  205. failCount = 0
  206. trainer.Reset()
  207. rw.UpdateState(neuralnetwork.StateIdle)
  208. }()
  209. return &None{}, nil
  210. }
  211. func (rw *RemoteControl) Run() {
  212. grpcServer := grpc.NewServer()
  213. RegisterRemoteControlServer(grpcServer, rw)
  214. lis, err := net.Listen("tcp", "localhost:65001")
  215. if err != nil {
  216. fmt.Printf("Failed to listen: %v\n", err)
  217. }
  218. fmt.Printf("Listen localhost:65001\n")
  219. if err := grpcServer.Serve(lis); err != nil {
  220. fmt.Printf("Failed to serve: %v\n", err)
  221. }
  222. }