remotecontrol.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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 main
  26. import (
  27. context "context"
  28. fmt "fmt"
  29. "log"
  30. "net"
  31. "sync"
  32. "time"
  33. "git.semlanik.org/semlanik/NeuralNetworkVisualization/visualization"
  34. neuralnetwork "git.semlanik.org/semlanik/NeuralNetwork/neuralnetwork"
  35. remotecontrol "git.semlanik.org/semlanik/NeuralNetwork/remotecontrol"
  36. "gonum.org/v1/gonum/mat"
  37. grpc "google.golang.org/grpc"
  38. training "git.semlanik.org/semlanik/NeuralNetwork/training"
  39. )
  40. type RemoteControl struct {
  41. nn *neuralnetwork.NeuralNetwork
  42. activationsQueue chan *remotecontrol.LayerMatrix
  43. biasesQueue chan *remotecontrol.LayerMatrix
  44. weightsQueue chan *remotecontrol.LayerMatrix
  45. stateQueue chan int
  46. mutex sync.Mutex
  47. config *remotecontrol.Configuration
  48. }
  49. func NewRemoteControl() (rw *RemoteControl) {
  50. rw = &RemoteControl{}
  51. rw.activationsQueue = make(chan *remotecontrol.LayerMatrix, 5)
  52. rw.biasesQueue = make(chan *remotecontrol.LayerMatrix, 5)
  53. rw.weightsQueue = make(chan *remotecontrol.LayerMatrix, 5)
  54. rw.stateQueue = make(chan int, 2)
  55. rw.config = &remotecontrol.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, remotecontrol.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, remotecontrol.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, remotecontrol.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 remotecontrol.LayerMatrix_ContentType) (matrix *remotecontrol.LayerMatrix) {
  92. buffer, err := dense.MarshalBinary()
  93. if err != nil {
  94. log.Fatalln("Invalid dense is provided for remote control")
  95. }
  96. matrix = &remotecontrol.LayerMatrix{
  97. Matrix: &remotecontrol.Matrix{
  98. Matrix: buffer,
  99. },
  100. Layer: int32(l),
  101. ContentType: contentType,
  102. }
  103. return
  104. }
  105. func (rw *RemoteControl) GetConfiguration(context.Context, *remotecontrol.None) (*remotecontrol.Configuration, error) {
  106. return rw.config, nil
  107. }
  108. func (rw *RemoteControl) Activations(_ *remotecontrol.None, srv remotecontrol.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(_ *remotecontrol.None, srv remotecontrol.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(_ *remotecontrol.None, srv remotecontrol.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(_ *remotecontrol.None, srv remotecontrol.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 := &remotecontrol.NetworkState{
  154. State: remotecontrol.NetworkState_State(state),
  155. }
  156. srv.Send(msg)
  157. }
  158. }
  159. func (rw *RemoteControl) Run(context.Context, *visualization.None) (*visualization.None, error) {
  160. go func() {
  161. rw.mutex.Lock()
  162. defer rw.mutex.Unlock()
  163. // trainer := training.NewMNISTReader("./minst.data", "./mnist.labels")
  164. trainer := training.NewTextDataReader("wine.data", 5)
  165. rw.nn.Train(trainer, 500)
  166. // for i := 0; i < nn.Count; i++ {
  167. // if i > 0 {
  168. // fmt.Printf("Weights after:\n%v\n\n", mat.Formatted(nn.Weights[i], mat.Prefix(""), mat.Excerpt(0)))
  169. // fmt.Printf("Biases after:\n%v\n\n", mat.Formatted(nn.Biases[i], mat.Prefix(""), mat.Excerpt(0)))
  170. // fmt.Printf("Z after:\n%v\n\n", mat.Formatted(nn.Z[i], mat.Prefix(""), mat.Excerpt(0)))
  171. // }
  172. // fmt.Printf("A after:\n%v\n\n", mat.Formatted(nn.A[i], mat.Prefix(""), mat.Excerpt(0)))
  173. // }
  174. rw.nn.SaveStateToFile("./neuralnetworkdata.nnd")
  175. rw.UpdateState(neuralnetwork.StateLearning)
  176. defer rw.UpdateState(neuralnetwork.StateIdle)
  177. failCount := 0
  178. for i := 0; i < trainer.ValidatorCount(); i++ {
  179. dataSet, expect := trainer.GetValidator(i)
  180. index, _ := rw.nn.Predict(dataSet)
  181. //TODO: remove this if not used for visualization
  182. time.Sleep(400 * time.Millisecond)
  183. if expect.At(index, 0) != 1.0 {
  184. failCount++
  185. // fmt.Printf("Fail: %v, %v\n\n", trainer.ValidationIndex(), expect.At(index, 0))
  186. }
  187. }
  188. fmt.Printf("Fail count: %v\n\n", failCount)
  189. failCount = 0
  190. rw.UpdateState(neuralnetwork.StateIdle)
  191. }()
  192. return &visualization.None{}, nil
  193. }
  194. func (rw *RemoteControl) RunServices() {
  195. go func() {
  196. grpcServer := grpc.NewServer()
  197. remotecontrol.RegisterRemoteControlServer(grpcServer, rw)
  198. lis, err := net.Listen("tcp", "localhost:65001")
  199. if err != nil {
  200. fmt.Printf("Failed to listen: %v\n", err)
  201. }
  202. fmt.Printf("Listen localhost:65001\n")
  203. if err := grpcServer.Serve(lis); err != nil {
  204. fmt.Printf("Failed to serve: %v\n", err)
  205. }
  206. }()
  207. grpcServer := grpc.NewServer()
  208. visualization.RegisterVisualizationServer(grpcServer, rw)
  209. lis, err := net.Listen("tcp", "localhost:65002")
  210. if err != nil {
  211. fmt.Printf("Failed to listen: %v\n", err)
  212. }
  213. fmt.Printf("Listen localhost:65002\n")
  214. if err := grpcServer.Serve(lis); err != nil {
  215. fmt.Printf("Failed to serve: %v\n", err)
  216. }
  217. }
  218. func (rw *RemoteControl) GetSubscriptionFeatures() (feature neuralnetwork.SubscriptionFeatures) {
  219. feature.Clear()
  220. feature.Set(neuralnetwork.ActivationsSubscription)
  221. feature.Set(neuralnetwork.BiasesSubscription)
  222. feature.Set(neuralnetwork.WeightsSubscription)
  223. feature.Set(neuralnetwork.StateSubscription)
  224. return
  225. }
  226. func (rw *RemoteControl) UpdateTraining(t int, epocs int, samplesProcced int, totalSamplesCount int) {
  227. log.Fatal("UpdateTraining training is not implemented but called")
  228. }
  229. func (rw *RemoteControl) UpdateValidation(validatorCount int, failCount int) {
  230. log.Fatal("UpdateValidation training is not implemented but called")
  231. }