-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathpredictor.go
187 lines (155 loc) · 5.08 KB
/
predictor.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
package optimus
import (
"context"
"fmt"
"math/big"
"sync"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/sonm-io/core/blockchain"
"github.com/sonm-io/core/insonmnia/benchmarks"
"github.com/sonm-io/core/insonmnia/dwh"
"github.com/sonm-io/core/proto"
"github.com/sonm-io/core/util"
"go.uber.org/zap"
"golang.org/x/sync/errgroup"
)
type engineFactory func(worker WorkerManagementClientAPI) (*workerEngine, error)
func predictionEngineConfig(cfg marketplaceConfig, bruteThreshold uint) *workerConfig {
priceThresholdValue := &RelativePriceThreshold{
Int: big.NewInt(int64(5.0 * 1000)),
}
return &workerConfig{
PrivateKey: cfg.PrivateKey,
Epoch: 60 * time.Second,
OrderDuration: 24 * time.Hour,
DryRun: false,
Identity: sonm.IdentityLevel_ANONYMOUS,
PriceThreshold: priceThreshold{
PriceThreshold: priceThresholdValue,
},
StaleThreshold: 5 * time.Minute,
PreludeTimeout: 30 * time.Second,
Optimization: OptimizationConfig{
Model: optimizationMethodFactory{
OptimizationMethodFactory: &defaultPredictionOptimizationMethodFactory{
BruteThreshold: bruteThreshold,
},
},
},
}
}
type PredictorConfig struct {
Blockchain *blockchain.Config
DWH *dwh.DWHConfig
Marketplace marketplaceConfig
BruteThreshold uint `yaml:"brute_threshold" default:"6"`
}
type PredictorService struct {
cfg *PredictorConfig
log *zap.SugaredLogger
mu sync.RWMutex
market blockchain.MarketAPI
marketCache *MarketCache
benchmarks benchmarks.BenchList
regression *regressionClassifier
classification *OrderClassification
engineFactory engineFactory
}
// NewPredictorService constructs a new order price predictor service.
// Returns nil when nil "cfg" is passed.
func NewPredictorService(cfg *PredictorConfig, eth blockchain.API, benchmarkList benchmarks.BenchList, dwh sonm.DWHClient, log *zap.SugaredLogger) *PredictorService {
if cfg == nil {
return nil
}
regression := ®ressionClassifier{
model: &SCAKKTModel{
MaxIterations: 1e7,
Log: log,
},
}
engineConfig := predictionEngineConfig(cfg.Marketplace, cfg.BruteThreshold)
blacklist := newEmptyBlacklist()
marketCache := newMarketCache(newMarketScanner(cfg.Marketplace, dwh), cfg.Marketplace.Interval)
benchmarkMapping := benchmarks.NewArrayMapping(benchmarkList, benchmarkList.Max())
tagger := newTagger("predictor")
engineFactory := func(worker WorkerManagementClientAPI) (*workerEngine, error) {
return newWorkerEngine(engineConfig, common.Address{}, common.Address{}, blacklist, worker, eth, marketCache, benchmarkMapping, tagger, log)
}
m := &PredictorService{
cfg: cfg,
log: log,
market: eth.Market(),
marketCache: marketCache,
benchmarks: benchmarkList,
regression: regression,
engineFactory: engineFactory,
}
return m
}
func (m *PredictorService) Serve(ctx context.Context) error {
return m.serve(ctx)
}
func (m *PredictorService) serve(ctx context.Context) error {
m.log.Info("serving order price predictor")
defer m.log.Info("stopped serving order price predictor")
wg, ctx := errgroup.WithContext(ctx)
wg.Go(func() error {
return m.serveMarketplace(ctx)
})
return wg.Wait()
}
func (m *PredictorService) serveMarketplace(ctx context.Context) error {
registry := newRegistry()
defer registry.Close()
dwh, err := registry.NewDWH(ctx, m.cfg.Marketplace.Endpoint, m.cfg.Marketplace.PrivateKey.Unwrap())
if err != nil {
return err
}
marketCache := newMarketCache(newMarketScanner(m.cfg.Marketplace, dwh), m.cfg.Marketplace.Interval)
timer := util.NewImmediateTicker(m.cfg.Marketplace.Interval)
defer timer.Stop()
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-timer.C:
if err := m.executeRegression(ctx, marketCache); err != nil {
m.log.Warnw("failed to perform regression analysis", zap.Error(err))
}
}
}
}
func (m *PredictorService) executeRegression(ctx context.Context, marketCache *MarketCache) error {
m.log.Info("performing regression analysis")
orders, err := marketCache.ExecutedOrders(ctx, sonm.OrderType_BID)
if err != nil {
return fmt.Errorf("failed to fetch active orders: %v", err)
}
// This is the hack, which mathematicians call "tuning regression parameters".
// We have some benchmark cross-correlated, which results in bad fitting, for
// example GPU count, correlated to hashrate etc. To avoid this we just
// reset them to zero, which forces the model to exclude them from
// training.
for _, order := range orders {
order.GetOrder().GetBenchmarks().SetCPUCores(0)
order.GetOrder().GetBenchmarks().SetGPUCount(0)
}
classification, err := m.regression.ClassifyExt(orders)
if err != nil {
m.log.Warnw("failed to classify active orders", zap.Error(err))
return err
}
m.updateClassification(classification)
return nil
}
func (m *PredictorService) updateClassification(classification *OrderClassification) {
m.mu.Lock()
defer m.mu.Unlock()
m.classification = classification
}
func (m *PredictorService) Classification() *OrderClassification {
m.mu.RLock()
defer m.mu.RUnlock()
return m.classification
}