remotecontrol.go 6.3 KB

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