9mark9 commited on
Commit
2d470dc
·
verified ·
1 Parent(s): 6b7fc8d

Go server: the policy update replays the whole slate and credits only shown slots; prefix lists are bit-identical, restart test added

Browse files
README.md CHANGED
@@ -524,7 +524,8 @@ the cross-encoder reorders them and the top 5 are shown. **Feedback only changes
524
  with Explore on** (a test checks that explore-off feedback leaves the policy update count unchanged). With Explore off,
525
  feedback is recorded as per-memory usefulness only, and the app's starting weights (the server defaults) give that
526
  feature (utility) no weight, so it does not change the order. Feedback credits only the 5 memories shown, not the 15 candidates the
527
- reranker discarded. With Explore on, results vary from run to run and the reranker is skipped.
 
528
 
529
  With the reranker, each line shows its raw relevance logit (higher is more relevant; not a probability). Without
530
  it, the number is the server's weighted sum of ranking features.
 
524
  with Explore on** (a test checks that explore-off feedback leaves the policy update count unchanged). With Explore off,
525
  feedback is recorded as per-memory usefulness only, and the app's starting weights (the server defaults) give that
526
  feature (utility) no weight, so it does not change the order. Feedback credits only the 5 memories shown, not the 15 candidates the
527
+ reranker discarded. The server's policy update replays the whole drawn slate and adds learning only for the shown slots, so a shown list
528
+ that is not the first slots no longer biases it; every stored result here sent the full list or none, so none changed. With Explore on, results vary from run to run and the reranker is skipped.
529
 
530
  With the reranker, each line shows its raw relevance logit (higher is more relevant; not a probability). Without
531
  it, the number is the server's weighted sum of ranking features.
src/internal/memory/durability_test.go CHANGED
@@ -425,3 +425,54 @@ func TestCompactionDoesNotWriteThroughAPlantedLink(t *testing.T) {
425
  t.Fatalf("journal is not a regular file after compaction: %v %v", info, err)
426
  }
427
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
425
  t.Fatalf("journal is not a regular file after compaction: %v %v", info, err)
426
  }
427
  }
428
+
429
+ func TestFeedbackShownNonPrefixSurvivesRestart(t *testing.T) {
430
+ path := filepath.Join(t.TempDir(), "store.journal")
431
+ s := open(t, Options{JournalPath: path})
432
+ for i := range 5 {
433
+ remember(t, s, Memory{Text: fmt.Sprintf("topic note %d", i), Embedding: []float32{float32(i), 1}})
434
+ }
435
+ r := recall(t, s, Query{Text: "topic note", Embedding: []float32{1, 1}, K: 3, Explore: true})
436
+ if len(r.Memories) != 3 {
437
+ t.Fatalf("got %d memories, want 3", len(r.Memories))
438
+ }
439
+ p := s.waiting[r.ID].Value.(*pending)
440
+ want := *s.policy
441
+ want.UpdateShown(p.features, p.slate, []bool{true, false, true}, .8, []float64{1, 0})
442
+ before := s.policy.Weights
443
+ // Reverse the supplied IDs to verify rewards still follow slate order.
444
+ if err := s.FeedbackShown(r.ID, .8, []string{r.Memories[0].ID}, []string{r.Memories[2].ID, r.Memories[0].ID}); err != nil {
445
+ t.Fatal(err)
446
+ }
447
+ if *s.policy != want || s.policy.Weights == before {
448
+ t.Fatalf("policy did not apply the masked update: got %+v, want %+v", *s.policy, want)
449
+ }
450
+ sp := s.spaces["ns"]
451
+ for _, e := range sp.entries {
452
+ wantRecalls, wantReward := 0, 0.0
453
+ if e.ID == r.Memories[0].ID || e.ID == r.Memories[2].ID {
454
+ wantRecalls = 1
455
+ }
456
+ if e.ID == r.Memories[0].ID {
457
+ wantReward = 1
458
+ }
459
+ if int(e.recalls) != wantRecalls || e.rewardSum != wantReward {
460
+ t.Fatalf("credit for %s = %d, %v; want %d, %v", e.ID, e.recalls, e.rewardSum, wantRecalls, wantReward)
461
+ }
462
+ }
463
+ if err := s.Close(); err != nil {
464
+ t.Fatal(err)
465
+ }
466
+ reopened := open(t, Options{JournalPath: path})
467
+ got := reopened.policy
468
+ if got.Weights != want.Weights || got.Baseline != want.Baseline || got.ItemBaseline != want.ItemBaseline || got.Updates != want.Updates {
469
+ t.Fatalf("learned state after restart = %+v, want %+v", *got, want)
470
+ }
471
+ for id, doc := range sp.byID {
472
+ before := sp.entries[doc]
473
+ after := reopened.spaces["ns"].entries[reopened.spaces["ns"].byID[id]]
474
+ if after.recalls != before.recalls || after.rewardSum != before.rewardSum {
475
+ t.Fatalf("credit changed after restart for %s: got %d, %v; want %d, %v", id, after.recalls, after.rewardSum, before.recalls, before.rewardSum)
476
+ }
477
+ }
478
+ }
src/internal/memory/store.go CHANGED
@@ -710,6 +710,7 @@ func (s *Store) FeedbackShown(recallID string, reward float64, useful, shown []s
710
  }
711
  p := el.Value.(*pending)
712
  slate := p.slate
 
713
  if shown != nil {
714
  if len(shown) == 0 {
715
  return fmt.Errorf("%w: shown must name at least one memory", ErrInvalid)
@@ -722,8 +723,10 @@ func (s *Store) FeedbackShown(recallID string, reward float64, useful, shown []s
722
  remaining[id] = true
723
  }
724
  slate = make([]int, 0, len(shown))
725
- for _, at := range p.slate {
 
726
  if remaining[p.ids[at]] {
 
727
  slate = append(slate, at)
728
  delete(remaining, p.ids[at])
729
  }
@@ -752,7 +755,7 @@ func (s *Store) FeedbackShown(recallID string, reward float64, useful, shown []s
752
 
753
  before := *s.policy
754
  if p.explore {
755
- s.policy.Update(p.features, slate, reward, itemRewards)
756
  }
757
  if s.journal != nil {
758
  err := s.journal.append(record{Learn: &learnEntry{
 
710
  }
711
  p := el.Value.(*pending)
712
  slate := p.slate
713
+ var mask []bool
714
  if shown != nil {
715
  if len(shown) == 0 {
716
  return fmt.Errorf("%w: shown must name at least one memory", ErrInvalid)
 
723
  remaining[id] = true
724
  }
725
  slate = make([]int, 0, len(shown))
726
+ mask = make([]bool, len(p.slate))
727
+ for slot, at := range p.slate {
728
  if remaining[p.ids[at]] {
729
+ mask[slot] = true
730
  slate = append(slate, at)
731
  delete(remaining, p.ids[at])
732
  }
 
755
 
756
  before := *s.policy
757
  if p.explore {
758
+ s.policy.UpdateShown(p.features, p.slate, mask, reward, itemRewards)
759
  }
760
  if s.journal != nil {
761
  err := s.journal.append(record{Learn: &learnEntry{
src/internal/policy/policy.go CHANGED
@@ -121,10 +121,31 @@ func (p *Policy) Sample(cands []Features, k int, rng *rand.Rand) []int {
121
  // with its own reward; otherwise every position shares reward. Slates that
122
  // refer to unknown candidates and non-finite rewards are ignored.
123
  func (p *Policy) Update(cands []Features, slate []int, reward float64, itemRewards []float64) {
 
 
 
 
 
 
124
  if len(slate) == 0 || math.IsNaN(reward) || math.IsInf(reward, 0) {
125
  return
126
  }
127
- if itemRewards != nil && len(itemRewards) != len(slate) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  return
129
  }
130
  chosen := make(map[int]bool, len(slate))
@@ -147,7 +168,19 @@ func (p *Policy) Update(cands []Features, slate []int, reward float64, itemRewar
147
  }
148
  var grad Features
149
  var itemMean float64
 
150
  for slot, pick := range slate {
 
 
 
 
 
 
 
 
 
 
 
151
  probs := p.probabilities(cands, remaining)
152
  at := 0
153
  var expected Features
@@ -165,13 +198,17 @@ func (p *Policy) Update(cands []Features, slate []int, reward float64, itemRewar
165
  share := fromPolicy / (fromPolicy + p.Epsilon/float64(len(remaining)))
166
  advantage := reward - p.Baseline
167
  if itemRewards != nil {
168
- r := clamp01(itemRewards[slot])
169
  advantage = r - p.ItemBaseline
170
- itemMean += r / float64(len(slate))
171
  }
172
  for j := range grad {
173
  grad[j] += advantage * share * (cands[pick][j] - expected[j]) / p.Temperature
174
  }
 
 
 
 
175
  remaining = append(remaining[:at], remaining[at+1:]...)
176
  }
177
 
 
121
  // with its own reward; otherwise every position shares reward. Slates that
122
  // refer to unknown candidates and non-finite rewards are ignored.
123
  func (p *Policy) Update(cands []Features, slate []int, reward float64, itemRewards []float64) {
124
+ p.UpdateShown(cands, slate, nil, reward, itemRewards)
125
+ }
126
+
127
+ // UpdateShown replays every draw, but only shown slots contribute gradients.
128
+ // A nil mask shows all slots; itemRewards follows the shown slots in slate order.
129
+ func (p *Policy) UpdateShown(cands []Features, slate []int, shown []bool, reward float64, itemRewards []float64) {
130
  if len(slate) == 0 || math.IsNaN(reward) || math.IsInf(reward, 0) {
131
  return
132
  }
133
+ shownCount := len(slate)
134
+ if shown != nil {
135
+ if len(shown) != len(slate) {
136
+ return
137
+ }
138
+ shownCount = 0
139
+ for _, show := range shown {
140
+ if show {
141
+ shownCount++
142
+ }
143
+ }
144
+ if shownCount == 0 {
145
+ return
146
+ }
147
+ }
148
+ if itemRewards != nil && len(itemRewards) != shownCount {
149
  return
150
  }
151
  chosen := make(map[int]bool, len(slate))
 
168
  }
169
  var grad Features
170
  var itemMean float64
171
+ itemSlot := 0
172
  for slot, pick := range slate {
173
+ if shown != nil && !shown[slot] {
174
+ // An unshown pick earns no gradient, but it still left the pool
175
+ // before the next draw, so later shown slots see the right pool.
176
+ for i, cand := range remaining {
177
+ if cand == pick {
178
+ remaining = append(remaining[:i], remaining[i+1:]...)
179
+ break
180
+ }
181
+ }
182
+ continue
183
+ }
184
  probs := p.probabilities(cands, remaining)
185
  at := 0
186
  var expected Features
 
198
  share := fromPolicy / (fromPolicy + p.Epsilon/float64(len(remaining)))
199
  advantage := reward - p.Baseline
200
  if itemRewards != nil {
201
+ r := clamp01(itemRewards[itemSlot])
202
  advantage = r - p.ItemBaseline
203
+ itemMean += r / float64(shownCount)
204
  }
205
  for j := range grad {
206
  grad[j] += advantage * share * (cands[pick][j] - expected[j]) / p.Temperature
207
  }
208
+ itemSlot++
209
+ if itemSlot == shownCount {
210
+ break // later picks are all unshown and change nothing
211
+ }
212
  remaining = append(remaining[:at], remaining[at+1:]...)
213
  }
214
 
src/internal/policy/policy_test.go CHANGED
@@ -169,3 +169,80 @@ func TestExplorationFindsCandidatesTheCurrentWeightsIgnore(t *testing.T) {
169
  }
170
  }
171
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
  }
170
  }
171
  }
172
+
173
+ func TestUpdateShown(t *testing.T) {
174
+ cands := []Features{feat(.8, .1, .3), feat(.2, .9, .4), feat(.5, .3, .9), feat(.1, .6, .2), feat(.7, .4, .5)}
175
+ slate := []int{2, 0, 3}
176
+ for _, items := range [][]float64{nil, {.9, .2}} {
177
+ label := "/slate-reward"
178
+ if items != nil {
179
+ label = "/item-rewards"
180
+ }
181
+ for _, tc := range []struct {
182
+ name string
183
+ mask []bool
184
+ filtered []int
185
+ equal bool
186
+ }{
187
+ {"prefix", []bool{true, true, false}, slate[:2], true},
188
+ {"non-prefix", []bool{true, false, true}, []int{2, 3}, false},
189
+ } {
190
+ t.Run(tc.name+label, func(t *testing.T) {
191
+ p := New()
192
+ // Start with nonzero moments to check the entire optimizer state.
193
+ p.Update(cands, slate, .7, nil)
194
+ other := *p
195
+ p.UpdateShown(cands, slate, tc.mask, .8, items)
196
+ other.Update(cands, tc.filtered, .8, items)
197
+ if tc.equal && *p != other {
198
+ t.Fatalf("prefix update differs: got %+v, want %+v", *p, other)
199
+ }
200
+ if !tc.equal && p.Weights == other.Weights {
201
+ t.Fatal("non-prefix update used the filtered draw sequence")
202
+ }
203
+ })
204
+ }
205
+ }
206
+ // A nil mask must reproduce the original Update exactly. These numbers were
207
+ // produced by Update before UpdateShown existed.
208
+ golden := []struct {
209
+ items []float64
210
+ weights Features
211
+ itemBaseline float64
212
+ }{
213
+ {nil, Features{2.019999994349239, 1.980000000548177, 0.019999997028450914}, 0},
214
+ {[]float64{.9, .2, .6}, Features{1.9800000014320265, 1.9800000003771723, 0.01999999953041755}, 0.028333333333333335},
215
+ }
216
+ for _, g := range golden {
217
+ p := New()
218
+ p.UpdateShown(cands, slate, nil, .8, g.items)
219
+ if p.Weights != g.weights || p.Baseline != 0.515 || p.ItemBaseline != g.itemBaseline || p.Updates != 1 {
220
+ t.Fatalf("nil mask drifted from the original Update: %+v", *p)
221
+ }
222
+ }
223
+ }
224
+
225
+ func TestUpdateShownIgnoresInvalidMasks(t *testing.T) {
226
+ cands := []Features{feat(1, 0, 0), feat(0, 1, 0), feat(.5, .5, 1)}
227
+ for _, tc := range []struct {
228
+ name string
229
+ mask []bool
230
+ items []float64
231
+ }{
232
+ {"wrong length", []bool{true}, nil},
233
+ {"empty", []bool{}, nil},
234
+ {"none shown", []bool{false, false, false}, nil},
235
+ {"wrong item count", []bool{true, false, true}, []float64{1, 0, 1}},
236
+ {"empty items", []bool{true, false, true}, []float64{}},
237
+ } {
238
+ t.Run(tc.name, func(t *testing.T) {
239
+ p := New()
240
+ p.Update(cands, []int{0, 1}, .8, nil)
241
+ before := *p
242
+ p.UpdateShown(cands, []int{0, 1, 2}, tc.mask, .8, tc.items)
243
+ if *p != before {
244
+ t.Fatal("invalid mask changed policy")
245
+ }
246
+ })
247
+ }
248
+ }