-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
gd.cc
1554 lines (1394 loc) · 53.4 KB
/
gd.cc
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) by respective owners including Yahoo!, Microsoft, and
// individual contributors. All rights reserved. Released under a BSD (revised)
// license as described in the file LICENSE.
#include "vw/core/array_parameters.h"
#include "vw/core/array_parameters_dense.h"
#include "vw/core/crossplat_compat.h"
#include "vw/core/feature_group.h"
#include "vw/core/global_data.h"
#include "vw/core/learner.h"
#include "vw/core/loss_functions.h"
#include "vw/core/prediction_type.h"
#include "vw/core/setup_base.h"
#include <cfloat>
#if !defined(VW_NO_INLINE_SIMD)
# if !defined(__SSE2__) && (defined(_M_AMD64) || defined(_M_X64))
# define __SSE2__
# endif
# if defined(__ARM_NEON__)
# include <arm_neon.h>
# elif defined(__SSE2__)
# include <xmmintrin.h>
# endif
#endif
#include "vw/core/accumulate.h"
#include "vw/core/debug_log.h"
#include "vw/core/label_parser.h"
#include "vw/core/parse_regressor.h"
#include "vw/core/reductions/gd.h"
#include "vw/core/shared_data.h"
#include "vw/core/vw.h"
#include "vw/core/vw_versions.h"
#undef VW_DEBUG_LOG
#define VW_DEBUG_LOG vw_dbg::GD
#include "vw/io/logger.h"
using namespace VW::LEARNER;
using namespace VW::config;
constexpr double L1_STATE_DEFAULT = 0.;
constexpr double L2_STATE_DEFAULT = 1.;
namespace
{
template <typename WeightsT>
void merge_weights_simple(size_t length, const std::vector<std::reference_wrapper<const WeightsT>>& source,
const std::vector<float>& per_model_weighting, WeightsT& weights)
{
for (size_t i = 0; i < source.size(); i++)
{
const auto& this_source = source[i].get();
for (size_t j = 0; j < length; j++)
{ weights.strided_index(j) += (this_source.strided_index(j) * per_model_weighting[i]); }
}
}
void merge_weights_with_save_resume(size_t length,
const std::vector<std::reference_wrapper<const dense_parameters>>& source,
const std::vector<float>& /*per_model_weighting*/, VW::workspace& output_workspace, dense_parameters& weights)
{
// Adaptive totals
std::vector<float> adaptive_totals(length, 0.f);
for (const auto& model : source)
{
const auto& this_model = model.get();
for (size_t i = 0; i < length; i++) { adaptive_totals[i] += (&(this_model[i << weights.stride_shift()]))[1]; }
}
for (size_t i = 0; i < source.size(); i++)
{ VW::details::do_weighting(output_workspace.normalized_idx, length, adaptive_totals.data(), weights); }
// Weights have already been reweighted, so just accumulate.
for (const auto& model_num : source)
{
const auto& this_source = model_num.get();
// Intentionally add irrespective of stride.
const auto full_weights_size = length << weights.stride_shift();
for (uint64_t i = 0; i < full_weights_size; i++) { weights[i] += this_source[i]; }
}
}
template <typename WeightsT>
void copy_weights(WeightsT& dest, const WeightsT& source, size_t length)
{
const size_t full_weights_size = length << dest.stride_shift();
for (size_t i = 0; i < full_weights_size; i++) { dest[i] = source[i]; }
}
} // namespace
// todo:
// 4. Factor various state out of VW::workspace&
namespace GD
{
void sync_weights(VW::workspace& all);
inline float quake_inv_sqrt(float x)
{
// Carmack/Quake/SGI fast method:
float xhalf = 0.5f * x;
static_assert(sizeof(int) == sizeof(float), "Floats and ints are converted between, they must be the same size.");
int i = reinterpret_cast<int&>(x); // store floating-point bits in integer
i = 0x5f3759d5 - (i >> 1); // initial guess for Newton's method
x = reinterpret_cast<float&>(i); // convert new bits into float
x = x * (1.5f - xhalf * x * x); // One round of Newton's method
return x;
}
static inline float inv_sqrt(float x)
{
#if !defined(VW_NO_INLINE_SIMD)
# if defined(__ARM_NEON__)
// Propagate into vector
float32x2_t v1 = vdup_n_f32(x);
// Estimate
float32x2_t e1 = vrsqrte_f32(v1);
// N-R iteration 1
float32x2_t e2 = vmul_f32(e1, vrsqrts_f32(v1, vmul_f32(e1, e1)));
// N-R iteration 2
float32x2_t e3 = vmul_f32(e2, vrsqrts_f32(v1, vmul_f32(e2, e2)));
// Extract result
return vget_lane_f32(e3, 0);
# elif defined(__SSE2__)
__m128 eta = _mm_load_ss(&x);
eta = _mm_rsqrt_ss(eta);
_mm_store_ss(&x, eta);
# else
x = quake_inv_sqrt(x);
# endif
#else
x = quake_inv_sqrt(x);
#endif
return x;
}
VW_WARNING_STATE_PUSH
VW_WARNING_DISABLE_COND_CONST_EXPR
template <bool sqrt_rate, bool feature_mask_off, size_t adaptive, size_t normalized, size_t spare>
inline void update_feature(float& update, float x, float& fw)
{
VW::weight* w = &fw;
bool modify = x < FLT_MAX && x > -FLT_MAX && (feature_mask_off || fw != 0.);
if (modify)
{
if VW_STD17_CONSTEXPR (spare != 0) { x *= w[spare]; }
w[0] += update * x;
}
}
// this deals with few nonzero features vs. all nonzero features issues.
template <bool sqrt_rate, size_t adaptive, size_t normalized>
float average_update(float total_weight, float normalized_sum_norm_x, float neg_norm_power)
{
if VW_STD17_CONSTEXPR (normalized != 0)
{
if (sqrt_rate)
{
float avg_norm = (total_weight / normalized_sum_norm_x);
if (adaptive) { return std::sqrt(avg_norm); }
else
{
return avg_norm;
}
}
else
{
return powf((normalized_sum_norm_x / total_weight), neg_norm_power);
}
}
return 1.f;
}
template <bool sqrt_rate, bool feature_mask_off, size_t adaptive, size_t normalized, size_t spare>
void train(gd& g, VW::example& ec, float update)
{
if VW_STD17_CONSTEXPR (normalized != 0) { update *= g.update_multiplier; }
VW_DBG(ec) << "gd: train() spare=" << spare << std::endl;
foreach_feature<float, update_feature<sqrt_rate, feature_mask_off, adaptive, normalized, spare>>(*g.all, ec, update);
}
void end_pass(gd& g)
{
VW::workspace& all = *g.all;
if (!all.save_resume) { sync_weights(all); }
if (all.all_reduce != nullptr)
{
if (all.weights.adaptive) { accumulate_weighted_avg(all, all.weights); }
else
{
accumulate_avg(all, all.weights, 0);
}
}
all.eta *= all.eta_decay_rate;
if (all.save_per_pass) { save_predictor(all, all.final_regressor_name, all.current_pass); }
if (!all.holdout_set_off)
{
if (VW::details::summarize_holdout_set(all, g.no_win_counter))
{ finalize_regressor(all, all.final_regressor_name); }
if ((g.early_stop_thres == g.no_win_counter) &&
((all.check_holdout_every_n_passes <= 1) || ((all.current_pass % all.check_holdout_every_n_passes) == 0)))
{ set_done(all); }
}
}
void merge(const std::vector<float>& per_model_weighting, const std::vector<const VW::workspace*>& all_workspaces,
const std::vector<GD::gd*>& all_data, VW::workspace& output_workspace, GD::gd& output_data)
{
const size_t length = static_cast<size_t>(1) << output_workspace.num_bits;
// Weight aggregation is based on same method as allreduce.
if (output_workspace.weights.sparse)
{
std::vector<std::reference_wrapper<const sparse_parameters>> source;
source.reserve(all_workspaces.size());
for (const auto* workspace : all_workspaces) { source.emplace_back(workspace->weights.sparse_weights); }
if (output_workspace.weights.adaptive) { THROW("Sparse parameters not supported for merging with save_resume"); }
else
{
merge_weights_simple(length, source, per_model_weighting, output_workspace.weights.sparse_weights);
}
}
else
{
std::vector<std::reference_wrapper<const dense_parameters>> source;
source.reserve(all_workspaces.size());
for (const auto* workspace : all_workspaces) { source.emplace_back(workspace->weights.dense_weights); }
if (output_workspace.weights.adaptive)
{
merge_weights_with_save_resume(
length, source, per_model_weighting, output_workspace, output_workspace.weights.dense_weights);
}
else
{
merge_weights_simple(length, source, per_model_weighting, output_workspace.weights.dense_weights);
}
}
for (size_t i = 0; i < output_data.per_model_states.size(); i++)
{
for (const auto* source_data_obj : all_data)
{
// normalized_sum_norm_x is additive
output_data.per_model_states[i].normalized_sum_norm_x +=
source_data_obj->per_model_states[i].normalized_sum_norm_x;
// total_weight is additive
output_data.per_model_states[i].total_weight += source_data_obj->per_model_states[i].total_weight;
}
}
}
void add(const VW::workspace& /* ws1 */, const GD::gd& data1, const VW::workspace& ws2, GD::gd& data2,
VW::workspace& ws_out, GD::gd& data_out)
{
const size_t length = static_cast<size_t>(1) << ws_out.num_bits;
// When adding, output the weights from the model delta (2nd arugment to addition)
if (ws_out.weights.sparse) { copy_weights(ws_out.weights.sparse_weights, ws2.weights.sparse_weights, length); }
else
{
copy_weights(ws_out.weights.dense_weights, ws2.weights.dense_weights, length);
}
for (size_t i = 0; i < data_out.per_model_states.size(); i++)
{
// normalized_sum_norm_x is additive
data_out.per_model_states[i].normalized_sum_norm_x =
data1.per_model_states[i].normalized_sum_norm_x + data2.per_model_states[i].normalized_sum_norm_x;
// total_weight is additive
data_out.per_model_states[i].total_weight =
data1.per_model_states[i].total_weight + data2.per_model_states[i].total_weight;
}
}
void subtract(const VW::workspace& ws1, const GD::gd& data1, const VW::workspace& /* ws2 */, GD::gd& data2,
VW::workspace& ws_out, GD::gd& data_out)
{
const size_t length = static_cast<size_t>(1) << ws_out.num_bits;
// When subtracting, output the weights from the newer model (1st arugment to subtraction)
if (ws_out.weights.sparse) { copy_weights(ws_out.weights.sparse_weights, ws1.weights.sparse_weights, length); }
else
{
copy_weights(ws_out.weights.dense_weights, ws1.weights.dense_weights, length);
}
for (size_t i = 0; i < data_out.per_model_states.size(); i++)
{
// normalized_sum_norm_x is additive
data_out.per_model_states[i].normalized_sum_norm_x =
data1.per_model_states[i].normalized_sum_norm_x - data2.per_model_states[i].normalized_sum_norm_x;
// total_weight is additive
data_out.per_model_states[i].total_weight =
data1.per_model_states[i].total_weight - data2.per_model_states[i].total_weight;
}
}
#include <algorithm>
class string_value
{
public:
float v;
std::string s;
friend bool operator<(const string_value& first, const string_value& second);
};
bool operator<(const string_value& first, const string_value& second) { return fabsf(first.v) > fabsf(second.v); }
class audit_results
{
public:
VW::workspace& all;
const uint64_t offset;
std::vector<VW::audit_strings> components;
std::vector<string_value> results;
audit_results(VW::workspace& p_all, const size_t p_offset) : all(p_all), offset(p_offset) {}
};
inline void audit_interaction(audit_results& dat, const VW::audit_strings* f)
{
if (f == nullptr)
{
if (!dat.components.empty()) { dat.components.pop_back(); }
return;
}
if (!f->is_empty()) { dat.components.push_back(*f); }
}
inline void audit_feature(audit_results& dat, const float ft_weight, const uint64_t ft_idx)
{
parameters& weights = dat.all.weights;
uint64_t index = ft_idx & weights.mask();
size_t stride_shift = weights.stride_shift();
std::ostringstream tempstream;
for (size_t i = 0; i < dat.components.size(); i++)
{
if (i > 0) { tempstream << "*"; }
tempstream << VW::to_string(dat.components[i]);
}
if (dat.all.audit)
{
tempstream << ':' << (index >> stride_shift) << ':' << ft_weight << ':'
<< trunc_weight(weights[index], static_cast<float>(dat.all.sd->gravity)) *
static_cast<float>(dat.all.sd->contraction);
if (weights.adaptive)
{ // adaptive
tempstream << '@' << (&weights[index])[1];
}
string_value sv = {weights[index] * ft_weight, tempstream.str()};
dat.results.push_back(sv);
}
if ((dat.all.current_pass == 0 || dat.all.training == false) && dat.all.hash_inv)
{
const auto strided_index = index >> stride_shift;
if (dat.all.index_name_map.count(strided_index) == 0)
{
VW::details::invert_hash_info info;
info.weight_components = dat.components;
info.offset = dat.offset;
info.stride_shift = stride_shift;
dat.all.index_name_map.insert(std::make_pair(strided_index, info));
}
}
}
void print_lda_features(VW::workspace& all, VW::example& ec)
{
parameters& weights = all.weights;
uint32_t stride_shift = weights.stride_shift();
size_t count = 0;
for (features& fs : ec) { count += fs.size(); }
// TODO: Where should audit stuff output to?
for (features& fs : ec)
{
for (const auto& f : fs.audit_range())
{
std::cout << '\t' << VW::to_string(*f.audit()) << ':' << ((f.index() >> stride_shift) & all.parse_mask) << ':'
<< f.value();
for (size_t k = 0; k < all.lda; k++) { std::cout << ':' << (&weights[f.index()])[k]; }
}
}
std::cout << " total of " << count << " features." << std::endl;
}
void print_features(VW::workspace& all, VW::example& ec)
{
if (all.lda > 0) { print_lda_features(all, ec); }
else
{
audit_results dat(all, ec.ft_offset);
for (features& fs : ec)
{
if (fs.space_names.size() > 0)
{
for (const auto& f : fs.audit_range())
{
audit_interaction(dat, f.audit());
audit_feature(dat, f.value(), f.index() + ec.ft_offset);
audit_interaction(dat, nullptr);
}
}
else
{
for (const auto& f : fs) { audit_feature(dat, f.value(), f.index() + ec.ft_offset); }
}
}
size_t num_interacted_features = 0;
INTERACTIONS::generate_interactions<audit_results, const uint64_t, audit_feature, true, audit_interaction>(
all, ec, dat, num_interacted_features);
stable_sort(dat.results.begin(), dat.results.end());
if (all.audit)
{
for (string_value& sv : dat.results)
{
all.audit_writer->write("\t", 1);
all.audit_writer->write(sv.s.data(), sv.s.size());
}
all.audit_writer->write("\n", 1);
}
}
}
void print_audit_features(VW::workspace& all, VW::example& ec)
{
if (all.audit) { print_result_by_ref(all.audit_writer.get(), ec.pred.scalar, -1, ec.tag, all.logger); }
fflush(stdout);
print_features(all, ec);
}
float finalize_prediction(shared_data* sd, VW::io::logger& logger, float ret)
{
if (std::isnan(ret))
{
ret = 0.;
logger.err_warn("NAN prediction in example {0}, forcing {1}", sd->example_number + 1, ret);
return ret;
}
if (ret > sd->max_label) { return sd->max_label; }
if (ret < sd->min_label) { return sd->min_label; }
return ret;
}
class trunc_data
{
public:
float prediction;
float gravity;
};
inline void vec_add_trunc(trunc_data& p, const float fx, float& fw)
{
p.prediction += trunc_weight(fw, p.gravity) * fx;
}
inline float trunc_predict(VW::workspace& all, VW::example& ec, double gravity, size_t& num_interacted_features)
{
const auto& simple_red_features = ec.ex_reduction_features.template get<VW::simple_label_reduction_features>();
trunc_data temp = {simple_red_features.initial, static_cast<float>(gravity)};
foreach_feature<trunc_data, vec_add_trunc>(all, ec, temp, num_interacted_features);
return temp.prediction;
}
inline void vec_add_print(float& p, const float fx, float& fw)
{
// TODO: partial line logging. This function isn't actually called from anywhere though?
p += fw * fx;
std::cerr << " + " << fw << "*" << fx;
}
template <bool l1, bool audit>
void predict(gd& g, base_learner&, VW::example& ec)
{
VW_DBG(ec) << "gd.predict(): ex#=" << ec.example_counter << ", offset=" << ec.ft_offset << std::endl;
VW::workspace& all = *g.all;
size_t num_interacted_features = 0;
if (l1) { ec.partial_prediction = trunc_predict(all, ec, all.sd->gravity, num_interacted_features); }
else
{
ec.partial_prediction = inline_predict(all, ec, num_interacted_features);
}
ec.num_features_from_interactions = num_interacted_features;
ec.partial_prediction *= static_cast<float>(all.sd->contraction);
ec.pred.scalar = finalize_prediction(all.sd, all.logger, ec.partial_prediction);
VW_DBG(ec) << "gd: predict() " << VW::debug::scalar_pred_to_string(ec) << VW::debug::features_to_string(ec)
<< std::endl;
if (audit) { print_audit_features(all, ec); }
}
template <class T>
inline void vec_add_trunc_multipredict(multipredict_info<T>& mp, const float fx, uint64_t fi)
{
size_t index = fi;
for (size_t c = 0; c < mp.count; c++, index += mp.step)
{ mp.pred[c].scalar += fx * trunc_weight(mp.weights[index], mp.gravity); }
}
template <bool l1, bool audit>
void multipredict(gd& g, base_learner&, VW::example& ec, size_t count, size_t step, VW::polyprediction* pred,
bool finalize_predictions)
{
VW::workspace& all = *g.all;
for (size_t c = 0; c < count; c++)
{
const auto& simple_red_features = ec.ex_reduction_features.template get<VW::simple_label_reduction_features>();
pred[c].scalar = simple_red_features.initial;
}
size_t num_features_from_interactions = 0;
if (g.all->weights.sparse)
{
multipredict_info<sparse_parameters> mp = {
count, step, pred, g.all->weights.sparse_weights, static_cast<float>(all.sd->gravity)};
if (l1)
{
foreach_feature<multipredict_info<sparse_parameters>, uint64_t, vec_add_trunc_multipredict>(
all, ec, mp, num_features_from_interactions);
}
else
{
foreach_feature<multipredict_info<sparse_parameters>, uint64_t, vec_add_multipredict>(
all, ec, mp, num_features_from_interactions);
}
}
else
{
multipredict_info<dense_parameters> mp = {
count, step, pred, g.all->weights.dense_weights, static_cast<float>(all.sd->gravity)};
if (l1)
{
foreach_feature<multipredict_info<dense_parameters>, uint64_t, vec_add_trunc_multipredict>(
all, ec, mp, num_features_from_interactions);
}
else
{
foreach_feature<multipredict_info<dense_parameters>, uint64_t, vec_add_multipredict>(
all, ec, mp, num_features_from_interactions);
}
}
ec.num_features_from_interactions = num_features_from_interactions;
if (all.sd->contraction != 1.)
{
for (size_t c = 0; c < count; c++) { pred[c].scalar *= static_cast<float>(all.sd->contraction); }
}
if (finalize_predictions)
{
for (size_t c = 0; c < count; c++) { pred[c].scalar = finalize_prediction(all.sd, all.logger, pred[c].scalar); }
}
if (audit)
{
for (size_t c = 0; c < count; c++)
{
ec.pred.scalar = pred[c].scalar;
print_audit_features(all, ec);
ec.ft_offset += static_cast<uint64_t>(step);
}
ec.ft_offset -= static_cast<uint64_t>(step * count);
}
}
class power_data
{
public:
float minus_power_t;
float neg_norm_power;
};
template <bool sqrt_rate, size_t adaptive, size_t normalized>
inline float compute_rate_decay(power_data& s, float& fw)
{
VW::weight* w = &fw;
float rate_decay = 1.f;
if (adaptive)
{
if (sqrt_rate) { rate_decay = inv_sqrt(w[adaptive]); }
else
{
rate_decay = powf(w[adaptive], s.minus_power_t);
}
}
if VW_STD17_CONSTEXPR (normalized != 0)
{
if (sqrt_rate)
{
float inv_norm = 1.f / w[normalized];
if (adaptive) { rate_decay *= inv_norm; }
else
{
rate_decay *= inv_norm * inv_norm;
}
}
else
{
rate_decay *= powf(w[normalized] * w[normalized], s.neg_norm_power);
}
}
return rate_decay;
}
class norm_data
{
public:
float grad_squared;
float pred_per_update;
float norm_x;
power_data pd;
float extra_state[4];
VW::io::logger* logger;
};
constexpr float X_MIN = 1.084202e-19f;
constexpr float X2_MIN = X_MIN * X_MIN;
constexpr float X2_MAX = FLT_MAX;
template <bool sqrt_rate, bool feature_mask_off, size_t adaptive, size_t normalized, size_t spare, bool stateless>
inline void pred_per_update_feature(norm_data& nd, float x, float& fw)
{
bool modify = feature_mask_off || fw != 0.;
if (modify)
{
VW::weight* w = &fw;
float x2 = x * x;
if (x2 < X2_MIN)
{
x = (x > 0) ? X_MIN : -X_MIN;
x2 = X2_MIN;
}
if (stateless) // we must not modify the parameter state so introduce a shadow version.
{
nd.extra_state[0] = w[0];
nd.extra_state[adaptive] = w[adaptive];
nd.extra_state[normalized] = w[normalized];
w = nd.extra_state;
}
if (adaptive) { w[adaptive] += nd.grad_squared * x2; }
if VW_STD17_CONSTEXPR (normalized != 0)
{
float x_abs = fabsf(x);
if (x_abs > w[normalized]) // new scale discovered
{
if (w[normalized] >
0.) // If the normalizer is > 0 then rescale the weight so it's as if the new scale was the old scale.
{
if (sqrt_rate)
{
float rescale = w[normalized] / x_abs;
w[0] *= (adaptive ? rescale : rescale * rescale);
}
else
{
float rescale = x_abs / w[normalized];
w[0] *= powf(rescale * rescale, nd.pd.neg_norm_power);
}
}
w[normalized] = x_abs;
}
float norm_x2 = x2 / (w[normalized] * w[normalized]);
if (x2 > X2_MAX)
{
norm_x2 = 1;
assert(nd.logger != nullptr);
nd.logger->err_error("The features have too much magnitude");
}
nd.norm_x += norm_x2;
}
w[spare] = compute_rate_decay<sqrt_rate, adaptive, normalized>(nd.pd, w[0]);
nd.pred_per_update += x2 * w[spare];
}
}
bool global_print_features = false;
template <bool sqrt_rate, bool feature_mask_off, bool adax, size_t adaptive, size_t normalized, size_t spare,
bool stateless>
float get_pred_per_update(gd& g, VW::example& ec)
{
// We must traverse the features in _precisely_ the same order as during training.
auto& ld = ec.l.simple;
VW::workspace& all = *g.all;
float grad_squared = ec.weight;
if (!adax) { grad_squared *= all.loss->get_square_grad(ec.pred.scalar, ld.label); }
if (grad_squared == 0 && !stateless) { return 1.; }
norm_data nd = {grad_squared, 0., 0., {g.neg_power_t, g.neg_norm_power}, {0}, &g.all->logger};
foreach_feature<norm_data,
pred_per_update_feature<sqrt_rate, feature_mask_off, adaptive, normalized, spare, stateless>>(all, ec, nd);
if VW_STD17_CONSTEXPR (normalized != 0)
{
if (!stateless)
{
g.per_model_states[0].normalized_sum_norm_x += (static_cast<double>(ec.weight)) * nd.norm_x;
g.per_model_states[0].total_weight += ec.weight;
g.update_multiplier =
average_update<sqrt_rate, adaptive, normalized>(static_cast<float>(g.per_model_states[0].total_weight),
static_cast<float>(g.per_model_states[0].normalized_sum_norm_x), g.neg_norm_power);
}
else
{
float nsnx = (static_cast<float>(g.per_model_states[0].normalized_sum_norm_x)) + ec.weight * nd.norm_x;
float tw = static_cast<float>(g.per_model_states[0].total_weight) + ec.weight;
g.update_multiplier = average_update<sqrt_rate, adaptive, normalized>(tw, nsnx, g.neg_norm_power);
}
nd.pred_per_update *= g.update_multiplier;
}
return nd.pred_per_update;
}
template <bool sqrt_rate, bool feature_mask_off, bool adax, size_t adaptive, size_t normalized, size_t spare,
bool stateless>
float sensitivity(gd& g, VW::example& ec)
{
if VW_STD17_CONSTEXPR (adaptive || normalized)
{ return get_pred_per_update<sqrt_rate, feature_mask_off, adax, adaptive, normalized, spare, stateless>(g, ec); }
else
{
_UNUSED(g);
return ec.get_total_sum_feat_sq();
}
}
VW_WARNING_STATE_POP
template <size_t adaptive>
float get_scale(gd& g, VW::example& /* ec */, float weight)
{
float update_scale = g.all->eta * weight;
if (!adaptive)
{
float t = static_cast<float>(
g.all->sd->t + weight - g.all->sd->weighted_holdout_examples - g.all->sd->weighted_unlabeled_examples);
update_scale *= powf(t, g.neg_power_t);
}
return update_scale;
}
template <bool sqrt_rate, bool feature_mask_off, bool adax, size_t adaptive, size_t normalized, size_t spare>
float sensitivity(gd& g, base_learner& /* base */, VW::example& ec)
{
return get_scale<adaptive>(g, ec, 1.) *
sensitivity<sqrt_rate, feature_mask_off, adax, adaptive, normalized, spare, true>(g, ec);
}
template <bool sparse_l2, bool invariant, bool sqrt_rate, bool feature_mask_off, bool adax, size_t adaptive,
size_t normalized, size_t spare>
float compute_update(gd& g, VW::example& ec)
{
// invariant: not a test label, importance weight > 0
const auto& ld = ec.l.simple;
VW::workspace& all = *g.all;
float update = 0.;
ec.updated_prediction = ec.pred.scalar;
if (all.loss->get_loss(all.sd, ec.pred.scalar, ld.label) > 0.)
{
float pred_per_update = sensitivity<sqrt_rate, feature_mask_off, adax, adaptive, normalized, spare, false>(g, ec);
float update_scale = get_scale<adaptive>(g, ec, ec.weight);
if (invariant) { update = all.loss->get_update(ec.pred.scalar, ld.label, update_scale, pred_per_update); }
else
{
update = all.loss->get_unsafe_update(ec.pred.scalar, ld.label, update_scale);
}
// changed from ec.partial_prediction to ld.prediction
ec.updated_prediction += pred_per_update * update;
if (all.reg_mode && std::fabs(update) > 1e-8)
{
double dev1 = all.loss->first_derivative(all.sd, ec.pred.scalar, ld.label);
double eta_bar = (fabs(dev1) > 1e-8) ? (-update / dev1) : 0.0;
if (fabs(dev1) > 1e-8) { all.sd->contraction *= (1. - all.l2_lambda * eta_bar); }
update /= static_cast<float>(all.sd->contraction);
all.sd->gravity += eta_bar * all.l1_lambda;
}
}
if (sparse_l2) { update -= g.sparse_l2 * ec.pred.scalar; }
if (std::isnan(update))
{
g.all->logger.err_warn("update is NAN, replacing with 0");
update = 0.;
}
return update;
}
template <bool sparse_l2, bool invariant, bool sqrt_rate, bool feature_mask_off, bool adax, size_t adaptive,
size_t normalized, size_t spare>
void update(gd& g, base_learner&, VW::example& ec)
{
// invariant: not a test label, importance weight > 0
float update;
if ((update = compute_update<sparse_l2, invariant, sqrt_rate, feature_mask_off, adax, adaptive, normalized, spare>(
g, ec)) != 0.)
{ train<sqrt_rate, feature_mask_off, adaptive, normalized, spare>(g, ec, update); }
if (g.all->sd->contraction < 1e-9 || g.all->sd->gravity > 1e3)
{ // updating weights now to avoid numerical instability
sync_weights(*g.all);
}
} // namespace GD
// NO_SANITIZE_UNDEFINED needed in learn functions because
// base_learner& base might be a reference created from nullptr
template <bool sparse_l2, bool invariant, bool sqrt_rate, bool feature_mask_off, bool adax, size_t adaptive,
size_t normalized, size_t spare>
void NO_SANITIZE_UNDEFINED learn(gd& g, base_learner& base, VW::example& ec)
{
// invariant: not a test label, importance weight > 0
assert(ec.l.simple.label != FLT_MAX);
assert(ec.weight > 0.);
g.predict(g, base, ec);
update<sparse_l2, invariant, sqrt_rate, feature_mask_off, adax, adaptive, normalized, spare>(g, base, ec);
}
void sync_weights(VW::workspace& all)
{
// todo, fix length dependence
if (all.sd->gravity == 0. && all.sd->contraction == 1.)
{ // to avoid unnecessary weight synchronization
return;
}
if (all.weights.sparse)
{
for (VW::weight& w : all.weights.sparse_weights)
{ w = trunc_weight(w, static_cast<float>(all.sd->gravity)) * static_cast<float>(all.sd->contraction); }
}
else
{
for (VW::weight& w : all.weights.dense_weights)
{ w = trunc_weight(w, static_cast<float>(all.sd->gravity)) * static_cast<float>(all.sd->contraction); }
}
all.sd->gravity = 0.;
all.sd->contraction = 1.;
}
size_t write_index(io_buf& model_file, std::stringstream& msg, bool text, uint32_t num_bits, uint64_t i)
{
size_t brw;
uint32_t old_i = 0;
msg << i;
if (num_bits < 31)
{
old_i = static_cast<uint32_t>(i);
brw = bin_text_write_fixed(model_file, reinterpret_cast<char*>(&old_i), sizeof(old_i), msg, text);
}
else
{
brw = bin_text_write_fixed(model_file, reinterpret_cast<char*>(&i), sizeof(i), msg, text);
}
return brw;
}
std::string to_string(const VW::details::invert_hash_info& info)
{
std::ostringstream ss;
for (size_t i = 0; i < info.weight_components.size(); i++)
{
if (i > 0) { ss << "*"; }
ss << VW::to_string(info.weight_components[i]);
}
if (info.offset != 0)
{
// otherwise --oaa output no features for class > 0.
ss << '[' << (info.offset >> info.stride_shift) << ']';
}
return ss.str();
}
template <class T>
void save_load_regressor(VW::workspace& all, io_buf& model_file, bool read, bool text, T& weights)
{
size_t brw = 1;
if (all.print_invert) // write readable model with feature names
{
std::stringstream msg;
for (auto it = weights.begin(); it != weights.end(); ++it)
{
const auto weight_value = *it;
if (*it != 0.f)
{
const auto weight_index = it.index() >> weights.stride_shift();
const auto map_it = all.index_name_map.find(weight_index);
if (map_it != all.index_name_map.end())
{
msg << to_string(map_it->second);
bin_text_write_fixed(model_file, nullptr /*unused*/, 0 /*unused*/, msg, true);
}
msg << ":" << weight_index << ":" << weight_value << "\n";
bin_text_write_fixed(model_file, nullptr /*unused*/, 0 /*unused*/, msg, true);
}
}
return;
}
uint64_t i = 0;
uint32_t old_i = 0;
uint64_t length = static_cast<uint64_t>(1) << all.num_bits;
if (read)
{
do
{
brw = 1;
if (all.num_bits < 31) // backwards compatible
{
brw = model_file.bin_read_fixed(reinterpret_cast<char*>(&old_i), sizeof(old_i));
i = old_i;
}
else
{
brw = model_file.bin_read_fixed(reinterpret_cast<char*>(&i), sizeof(i));
}
if (brw > 0)
{
if (i >= length)
THROW("Model content is corrupted, weight vector index " << i << " must be less than total vector length "
<< length);
VW::weight* v = &weights.strided_index(i);
brw += model_file.bin_read_fixed(reinterpret_cast<char*>(&(*v)), sizeof(*v));
}
} while (brw > 0);
}
else // write
{
for (typename T::iterator v = weights.begin(); v != weights.end(); ++v)
{
if (*v != 0.)
{
i = v.index() >> weights.stride_shift();
std::stringstream msg;
brw = write_index(model_file, msg, text, all.num_bits, i);
msg << ":" << *v << "\n";
brw += bin_text_write_fixed(model_file, (char*)&(*v), sizeof(*v), msg, text);
}
}
}
}
void save_load_regressor(VW::workspace& all, io_buf& model_file, bool read, bool text)
{
if (all.weights.sparse) { save_load_regressor(all, model_file, read, text, all.weights.sparse_weights); }
else
{
save_load_regressor(all, model_file, read, text, all.weights.dense_weights);
}
}
template <class T>
void save_load_online_state_weights(VW::workspace& all, io_buf& model_file, bool read, bool text, gd* g,
std::stringstream& msg, uint32_t ftrl_size, T& weights)
{
uint64_t length = static_cast<uint64_t>(1) << all.num_bits;
uint64_t i = 0;
uint32_t old_i = 0;
size_t brw = 1;
if (read)
{
do
{
brw = 1;
if (all.num_bits < 31) // backwards compatible
{
brw = model_file.bin_read_fixed(reinterpret_cast<char*>(&old_i), sizeof(old_i));
i = old_i;
}
else
{
brw = model_file.bin_read_fixed(reinterpret_cast<char*>(&i), sizeof(i));
}
if (brw > 0)
{
if (i >= length)
THROW("Model content is corrupted, weight vector index " << i << " must be less than total vector length "