-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Expand file tree
/
Copy pathrecsys_two_tower_model.py
More file actions
1771 lines (1539 loc) · 66.8 KB
/
Copy pathrecsys_two_tower_model.py
File metadata and controls
1771 lines (1539 loc) · 66.8 KB
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
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 X.AI Corp.
from __future__ import annotations
import logging
import math
import os
import typing
from dataclasses import dataclass, field
from typing import Literal
import haiku as hk
import jax
import jax.numpy as jnp
import numpy as np
import numpy.typing as npt
from jax import shard_map
from jax.lax import with_sharding_constraint
from jax.sharding import PartitionSpec as P
from xai_configlib import Config, configclass
from xai_proto import recsys_pb2
from xrex.cuda.top_k_by_key import top_k_by_key
from xrex.data.recsys.constants import action_type_map
from xrex.data.recsys.recsys_batch import EmbeddingType
from xrex.data.recsys.safety_filter import (
SafetyFilterMode,
apply_safety_filter,
safety_filter_stats,
)
from xrex.data.retrieval_dataset import RetrievalDataset
from xrex.models.layers import Linear
from xrex.models.model_utils import Parameter, get_parameter
from xrex.models.recsys_attention import RecsysAttentionConfig
from xrex.models.recsys_embedding import (
HashTable,
RecsysEmbeddings,
get_recsys_embed_param_to_jax_array,
)
from xrex.models.recsys_feature_prep import build_feature_prep_inputs
from xrex.models.recsys_model import (
DTYPE_BY_NAME,
MemoryKind,
RecsysAggregatedModel,
RecsysAggregatedModelConfig,
RecsysEmbeddingsParameter,
RecsysFeaturesBatch,
UserFeaturesConfig,
block_history_reduce,
build_user_feature_parts,
build_user_features_token,
cast_jax,
embed_entity_sid,
get_candidate_tweet_counts,
pad_to_next_128_multiple,
right_anchored_rope_positions,
)
from xrex.models.scaling import ScaleConfig
from xrex.models.sharding_context import ShardingContext
from xrex.train.misc import PostEmbeddings
from xrex.utils.utils import Summary
logger = logging.getLogger(__name__)
rank_logger = logging.getLogger("rank")
EPS = 1e-12
INF = 1e12
def _l2_normalize_candidates(embeddings: jax.Array) -> jax.Array:
norm_sq = jnp.sum(embeddings**2, axis=-1, keepdims=True)
norm = jnp.sqrt(jnp.maximum(norm_sq, EPS))
return embeddings / norm
class RecsysCandidateTower(hk.Module):
config: RecsysCandidateModelConfig
sharding_context: ShardingContext
embeddings: jax.Array
post_ids: npt.NDArray[np.int64]
def __init__(
self,
config: RecsysCandidateModelConfig,
sharding_context: ShardingContext,
*,
use_post_embedding: bool = True,
use_post_sid: bool = False,
use_project_then_sum: bool = False,
):
super().__init__(name="candidate_tower")
self.config = config
self.sharding_context = sharding_context
self.use_post_embedding = use_post_embedding
self.use_post_sid = use_post_sid
self.use_project_then_sum = use_project_then_sum
@hk.transparent
def _concat_then_mlp(self, post_author_embedding: jax.Array, head_index: int = 0) -> jax.Array:
if len(post_author_embedding.shape) == 4:
B, C, _, _ = post_author_embedding.shape
post_author_embedding = jnp.reshape(post_author_embedding, (B, C, -1))
else:
B, _, _ = post_author_embedding.shape
post_author_embedding = jnp.reshape(post_author_embedding, (B, -1))
w_init = hk.initializers.VarianceScaling(self.config.scale_config.attn_init_scale**2)
lr_multiplier = self.config.scale_config.hidden_lr_multiplier(self.config.emb_table_width)
init_scale = 1.0
if head_index == 0:
proj_1_name = "candidate_tower_projection_1"
proj_2_name = "candidate_tower_projection_2"
else:
proj_1_name = f"candidate_tower_head_{head_index}_projection_1"
proj_2_name = f"candidate_tower_head_{head_index}_projection_2"
candidate_tower_projection_1 = Linear(
self.config.emb_table_width * 2,
w_init=w_init,
with_bias=False,
pspec=P(None, None),
sharding_context=self.sharding_context,
lr_multiplier=lr_multiplier,
init_scale=init_scale,
name=proj_1_name,
)
candidate_tower_projection_2 = Linear(
self.config.emb_table_width,
w_init=w_init,
with_bias=False,
pspec=P(None, None),
sharding_context=self.sharding_context,
lr_multiplier=lr_multiplier,
init_scale=init_scale,
name=proj_2_name,
)
candidate_embeddings = candidate_tower_projection_2(
jax.nn.silu(candidate_tower_projection_1(inputs=post_author_embedding))
)
return _l2_normalize_candidates(candidate_embeddings)
@hk.transparent
def _project_then_sum(
self,
post_author_embedding: jax.Array,
head_index: int = 0,
) -> jax.Array:
num_item_hashes = self.config.hash_table.hash_keys.num_item_hashes
num_author_hashes = self.config.hash_table.hash_keys.num_author_hashes
use_post = self.use_post_embedding
use_sid = self.use_post_sid
expected_tokens = (
(num_item_hashes if use_post else 0) + num_author_hashes + (1 if use_sid else 0)
)
total_tokens = post_author_embedding.shape[-2]
assert total_tokens == expected_tokens, (
f"project-then-sum expected {expected_tokens} tokens on axis -2 "
f"(use_post_embedding={use_post}, num_item_hashes={num_item_hashes}, "
f"num_author_hashes={num_author_hashes}, use_post_sid={use_sid}), "
f"got {total_tokens}"
)
offset = 0
post_embeddings: jax.Array | None = None
if use_post:
post_embeddings = post_author_embedding[..., offset : offset + num_item_hashes, :]
offset += num_item_hashes
author_embeddings = post_author_embedding[..., offset : offset + num_author_hashes, :]
offset += num_author_hashes
sid_embedding: jax.Array | None = None
if use_sid:
sid_embedding = post_author_embedding[..., offset, :]
offset += 1
W = self.config.emb_table_width
D = self.config.emb_table_width
B = author_embeddings.shape[0]
if author_embeddings.ndim == 4:
out_shape_prefix = (B, author_embeddings.shape[1])
else:
out_shape_prefix = (B,)
embed_init = hk.initializers.VarianceScaling(1.0, mode="fan_out")
lr_multiplier = self.config.scale_config.hidden_lr_multiplier(W)
def _proj_one(emb: jax.Array, name: str) -> jax.Array:
proj = typing.cast(
jax.Array,
get_parameter(
name,
[W, D],
dtype=jnp.float32,
init=lambda shape, dtype: embed_init(list(reversed(shape)), dtype).T,
pspec=P(None, None),
lr_multiplier=lr_multiplier,
),
)
return jnp.dot(emb.astype(proj.dtype), proj).astype(emb.dtype)
head_suffix = "" if head_index == 0 else f"_head_{head_index}"
result = jnp.zeros((*out_shape_prefix, D), dtype=author_embeddings.dtype)
if post_embeddings is not None:
for i in range(num_item_hashes):
h = post_embeddings[..., i, :]
result = result + _proj_one(h, f"cand_post_hash_{i}_proj{head_suffix}")
for i in range(num_author_hashes):
h = author_embeddings[..., i, :]
result = result + _proj_one(h, f"cand_author_hash_{i}_proj{head_suffix}")
if sid_embedding is not None:
result = result + _proj_one(sid_embedding, f"cand_sid_proj{head_suffix}")
return _l2_normalize_candidates(result)
def __call__(self, post_author_embedding: jax.Array, head_index: int = 0) -> jax.Array:
if self.use_project_then_sum:
return self._project_then_sum(post_author_embedding, head_index=head_index)
if self.config.enable_linear_proj:
return self._concat_then_mlp(post_author_embedding, head_index=head_index)
return self._mean_pool(post_author_embedding)
def _mean_pool(self, post_author_embedding: jax.Array) -> jax.Array:
return _l2_normalize_candidates(jnp.mean(post_author_embedding, axis=-2))
@configclass
class RecsysCandidateModelConfig(Config):
hash_table: HashTable
enable_linear_proj: bool = False
emb_table_width: int = 128
scale_config: ScaleConfig = ScaleConfig()
max_posts: int = 10_240_000
num_candidate_heads: int = 1
def make(
self,
sharding_context: ShardingContext,
*,
use_post_embedding: bool = True,
use_post_sid: bool = False,
use_project_then_sum: bool = False,
):
if use_project_then_sum and self.enable_linear_proj:
raise ValueError(
"feature_prep_enabled (candidate project-then-sum) and "
"enable_linear_proj are mutually exclusive; enable at most one "
"candidate-tower combine mode (or neither for mean-pool)."
)
return RecsysCandidateTower(
self,
sharding_context,
use_post_embedding=use_post_embedding,
use_post_sid=use_post_sid,
use_project_then_sum=use_project_then_sum,
)
def make_post_embeddings(self):
all_post_ids = jnp.arange(self.max_posts * 2).reshape(-1, 2).astype(jnp.int32)
all_author_ids = jnp.arange(self.max_posts * 2).reshape(-1, 2).astype(jnp.int32)
all_dataset_types = jnp.full(
(self.max_posts, 1), RetrievalDataset.PAD.value, dtype=jnp.int32
)
scale = 1.0 / math.sqrt(self.emb_table_width)
if os.environ.get("DEBUG_ALLOW_RANDOM_INIT") == "1":
emb_init = jax.random.uniform(
jax.random.PRNGKey(0),
(self.max_posts, self.emb_table_width),
dtype=jnp.bfloat16,
minval=-scale,
maxval=scale,
)
else:
emb_init = jnp.empty((self.max_posts, self.emb_table_width), dtype=jnp.bfloat16)
post_embeddings = Parameter(
x=emb_init,
pspec=P(("expert", "replica"), ("seq", "model")),
)
return PostEmbeddings(
post_ids=all_post_ids,
author_ids=all_author_ids,
embeddings=post_embeddings,
dataset_types=all_dataset_types,
)
def _compute_recall_at_k(
N: int,
pos_scores: jax.Array,
neg_scores: jax.Array,
valid_mask: jax.Array,
implicit_negative_mask: jax.Array,
explicit_negative_mask: jax.Array,
use_in_batch_negatives: bool,
data_axis: tuple,
mesh: jax.sharding.Mesh,
debug_mode: bool = False,
) -> dict[str, jax.Array]:
if use_in_batch_negatives:
@shard_map(
mesh=mesh,
in_specs=(P(data_axis)),
out_specs=(P(data_axis), P(data_axis)),
check_vma=False,
)
def _pos_scores(pos_scores_shard: jax.Array) -> tuple[jax.Array, jax.Array]:
b = pos_scores_shard.shape[0]
pos_scores_shard = pos_scores_shard.reshape((b, b, -1))
off_diag_cols = (jnp.arange(b)[:, None] + jnp.arange(1, b)[None, :]) % b
off_diag_cols = jnp.sort(off_diag_cols, axis=1)
in_batch_negatives = pos_scores_shard[jnp.arange(b)[:, None], off_diag_cols].reshape(
b, -1
)
self_cands = pos_scores_shard[jnp.arange(b), jnp.arange(b)]
return self_cands, in_batch_negatives
pos_scores, inbatch_negatives = _pos_scores(pos_scores)
if N > 0:
neg_scores = jnp.concatenate((inbatch_negatives, neg_scores), axis=-1)
else:
neg_scores = inbatch_negatives
recall_metrics = {}
if not debug_mode:
return recall_metrics
sorted_neg_scores = jnp.sort(neg_scores, axis=-1)
for k in [1, 10, 100, 1000]:
kth_negative_scores = sorted_neg_scores[:, -k]
all_is_in_top_k = pos_scores >= kth_negative_scores[:, None]
is_in_top_k = all_is_in_top_k * valid_mask.astype(jnp.float32)
recall = jnp.where(
jnp.any(valid_mask),
jnp.sum(is_in_top_k.astype(jnp.float32)) / jnp.sum(valid_mask.astype(jnp.float32)),
1.0,
)
recall_metrics[f"InBatchRecall@{k}"] = recall
implicit_negative_in_top_k = all_is_in_top_k * implicit_negative_mask.astype(jnp.float32)
implicit_negative_recall = jnp.where(
jnp.any(implicit_negative_mask),
jnp.sum(implicit_negative_in_top_k.astype(jnp.float32))
/ jnp.sum(implicit_negative_mask.astype(jnp.float32)),
1.0,
)
recall_metrics[f"ImplicitNegativeInBatchRecall@{k}"] = implicit_negative_recall
explicit_negative_in_top_k = all_is_in_top_k * explicit_negative_mask.astype(jnp.float32)
explicit_negative_recall = jnp.where(
jnp.any(explicit_negative_mask),
jnp.sum(explicit_negative_in_top_k.astype(jnp.float32))
/ jnp.sum(explicit_negative_mask.astype(jnp.float32)),
1.0,
)
recall_metrics[f"ExplicitNegativeInBatchRecall@{k}"] = explicit_negative_recall
return recall_metrics
def _compute_score_stats(
self_scores: jax.Array,
global_neg_scores: jax.Array,
valid_positive_mask: jax.Array,
use_in_batch_negatives: bool,
data_axis: tuple,
mesh: jax.sharding.Mesh,
debug_mode: bool = False,
) -> dict[str, jax.Array]:
if use_in_batch_negatives:
@shard_map(
mesh=mesh,
in_specs=(P(data_axis)),
out_specs=(P(data_axis)),
check_vma=False,
)
def _self_scores(self_scores_shard: jax.Array) -> jax.Array:
b = self_scores_shard.shape[0]
self_scores_shard = self_scores_shard.reshape((b, b, -1))
return self_scores_shard[jnp.arange(b), jnp.arange(b)]
self_scores = _self_scores(self_scores)
score_stats = {}
valid_count = jnp.sum(valid_positive_mask.astype(jnp.float32))
valid_offset = 1.0 - (valid_count / valid_positive_mask.size)
score_stats["two_tower_positive_scores_mean"] = jnp.mean(self_scores, where=valid_positive_mask)
score_stats["two_tower_positive_scores_std"] = jnp.std(self_scores, where=valid_positive_mask)
score_stats["two_tower_positive_scores_min"] = jnp.min(
self_scores, where=valid_positive_mask, initial=1.0
)
if debug_mode:
masked_for_sort = jnp.where(valid_positive_mask, self_scores, -INF)
offsets = jnp.asarray([0.05, 0.95, 1.0]) + valid_offset
p5, p95, mx = jnp.quantile(masked_for_sort, offsets, method="higher")
score_stats["two_tower_positive_scores_max"] = mx
score_stats["two_tower_positive_scores_p5"] = p5
score_stats["two_tower_positive_scores_p95"] = p95
score_stats["two_tower_negative_scores_mean"] = global_neg_scores.mean()
score_stats["two_tower_negative_scores_std"] = global_neg_scores.std()
mn, p5, p95, mx = jnp.quantile(global_neg_scores, jnp.asarray([0.0, 0.05, 0.95, 1.0]))
score_stats["two_tower_negative_scores_min"] = mn
score_stats["two_tower_negative_scores_max"] = mx
score_stats["two_tower_negative_scores_p5"] = p5
score_stats["two_tower_negative_scores_p95"] = p95
score_stats["two_tower_postive_minus_negative_scores_mean"] = (
score_stats["two_tower_positive_scores_mean"]
- score_stats["two_tower_negative_scores_mean"]
)
return score_stats
def _compute_retrieval_metrics(
C: int,
N: int,
raw_batch_scores: jax.Array,
raw_global_neg_scores: jax.Array,
self_scores: jax.Array,
global_neg_scores: jax.Array,
valid_positive_mask: jax.Array,
implicit_negative_mask: jax.Array,
explicit_negative_mask: jax.Array,
candidate_padding_mask: jax.Array,
actions: npt.NDArray[np.bool_],
contrastive_loss: jax.Array,
has_hard_negative_actions: jax.Array,
positive_actions: list[int],
hard_negative_actions: list[int],
soft_negative_actions: list[int],
use_in_batch_negatives: bool,
data_axis: tuple,
mesh: jax.sharding.Mesh,
debug_mode: bool = False,
) -> dict[str, jax.Array]:
recall_metrics = _compute_recall_at_k(
N,
raw_batch_scores,
raw_global_neg_scores,
valid_positive_mask,
implicit_negative_mask,
explicit_negative_mask,
use_in_batch_negatives,
data_axis,
mesh,
debug_mode,
)
score_stats = _compute_score_stats(
raw_batch_scores,
raw_global_neg_scores,
valid_positive_mask,
use_in_batch_negatives,
data_axis,
mesh,
debug_mode,
)
config_actions = positive_actions + hard_negative_actions + soft_negative_actions
action_value_to_name = {v: k for k, v in action_type_map.items()}
num_examples_with_action = {
f"num_examples_with_action_{action_value_to_name[action_name]}_per_batch": actions[
:, :C, action_name
]
.astype(jnp.float32)
.sum()
for action_name in config_actions
}
return {
"contrastive_loss": contrastive_loss,
"num_valid_positive_examples_per_batch": jnp.sum(valid_positive_mask.astype(jnp.float32)),
"fraction_valid_positive_examples": jnp.mean(valid_positive_mask.astype(jnp.float32)),
"num_negatives_per_example": jnp.float32(global_neg_scores.shape[-1]),
"num_padding_candidates_per_example": (~candidate_padding_mask)
.astype(jnp.float32)
.sum(axis=-1)
.mean(),
"num_hard_negatives_per_example": (
has_hard_negative_actions & candidate_padding_mask[:, :C]
)
.astype(jnp.float32)
.sum(axis=-1)
.mean(),
**num_examples_with_action,
**recall_metrics,
**score_stats,
}
def compute_retrieval_loss(
batch: RecsysFeaturesBatch,
user_representation: jax.Array,
candidate_representation: jax.Array,
temperature: jax.Array,
data_axis: tuple,
mesh: jax.sharding.Mesh,
num_global_negatives_per_example: int,
candidate_seq_len: int,
use_in_batch_negatives: bool,
positive_actions: list[int],
hard_negative_actions: list[int],
soft_negative_actions: list[int],
logq_correction_scale: float,
enable_fake_positives: bool = False,
debug_mode: bool = False,
apply_u2u_and_i2i_loss: bool = True,
ads_only_candidates: bool = False,
safety_filter_mode: SafetyFilterMode = "off",
safety_filter_bits: int = 0b11,
safety_filter_soft_weight: float = 0.0,
safety_filter_apply_to_candidates: bool = False,
) -> tuple[jax.Array, dict[str, jax.Array]]:
B, L, _ = candidate_representation.shape
N = num_global_negatives_per_example
C = candidate_seq_len
assert L == C + N, (
f"candidate_representation.shape[1] ({candidate_representation.shape[1]}) must be candidate_seq_len ({C}) + num_global_negatives_per_example ({N})"
)
@shard_map(
mesh=mesh,
in_specs=(P(data_axis), P(data_axis), P(data_axis)),
out_specs=(P(data_axis), P(data_axis)),
check_vma=False,
)
def _sharded_full_matmul(
local_user: jax.Array, local_candidate: jax.Array, padding_mask: jax.Array
) -> tuple[jax.Array, jax.Array]:
local_B = local_user.shape[0]
if use_in_batch_negatives:
inbatch_cand = local_candidate[:, :C, :].reshape((local_B * C, -1))
inbatch_scores = local_user @ inbatch_cand.T
inbatch_pad = padding_mask[:, :C].reshape((1, local_B * C))
inbatch_scores = jnp.where(inbatch_pad, inbatch_scores, -INF)
else:
inbatch_cand = local_candidate[:, :C, :]
inbatch_scores = jnp.einsum("bd,bcd->bc", local_user, inbatch_cand)
inbatch_pad = padding_mask[:, :C]
inbatch_scores = jnp.where(inbatch_pad, inbatch_scores, -INF)
if N == 0:
global_neg_scores = jnp.array([[0]])
else:
global_cand = local_candidate[:, C:, :].reshape((local_B * N, -1))
global_neg_scores = local_user @ global_cand.T
global_pad = padding_mask[:, C:].reshape((1, local_B * N))
global_neg_scores = jnp.where(global_pad, global_neg_scores, -INF)
return inbatch_scores, global_neg_scores
@shard_map(
mesh=mesh,
in_specs=(P(data_axis), P(data_axis), P(data_axis), P(data_axis)),
out_specs=(P(data_axis), P(data_axis)),
check_vma=False,
)
def _apply_logq_correction(
local_batch: jax.Array,
local_neg: jax.Array,
local_batch_correction: jax.Array,
global_batch_correction: jax.Array,
) -> tuple[jax.Array, jax.Array]:
if use_in_batch_negatives:
local_batch_correction = local_batch_correction.reshape((1, -1))
local_batch += local_batch_correction
if N > 0:
local_neg += global_batch_correction.reshape((1, -1))
return local_batch, local_neg
candidate_padding_mask = batch["candidate_seq"]["post_hashes"][:, :, 0] != 0
candidate_safety_mask = batch["candidate_seq"].get("safety_label_mask")
retrieval_safety_stats = safety_filter_stats(
candidate_safety_mask,
candidate_padding_mask,
bits=safety_filter_bits,
prefix="safety_filter_candidates",
)
if safety_filter_apply_to_candidates and safety_filter_mode == "hard":
candidate_padding_mask, _ = apply_safety_filter(
candidate_safety_mask,
candidate_padding_mask,
None,
mode="hard",
bits=safety_filter_bits,
soft_weight=safety_filter_soft_weight,
)
ad_mask_candidates = jnp.ones((B, C), dtype=jnp.bool_)
if ads_only_candidates:
promoted_ids = batch["candidate_seq"]["promoted_ids"]
if promoted_ids is not None:
ad_mask = promoted_ids != 0
candidate_padding_mask = candidate_padding_mask & ad_mask
ad_mask_candidates = ad_mask[:, :C]
actions = batch["candidate_seq"]["actions"]
assert actions is not None
has_positive_actions = jnp.sum(actions[:, :C, positive_actions], axis=-1) > 0
has_hard_negative_actions = jnp.sum(actions[:, :C, hard_negative_actions], axis=-1) > 0
has_soft_negative_actions = jnp.sum(actions[:, :C, soft_negative_actions], axis=-1) > 0
if enable_fake_positives:
fake_positive_mask = jnp.sum(has_positive_actions, axis=-1, keepdims=True) == 0
fake_positive_mask = jnp.concatenate(
[fake_positive_mask, jnp.zeros((B, C - 1), dtype=jnp.bool_)], axis=-1
)
has_positive_actions = has_positive_actions | fake_positive_mask
valid_positive_mask = (
has_positive_actions
& ~has_hard_negative_actions
& ~has_soft_negative_actions
& ad_mask_candidates
& candidate_padding_mask[:, :C]
).astype(jnp.bool_)
raw_batch_scores, raw_global_neg_scores = _sharded_full_matmul(
user_representation, candidate_representation, candidate_padding_mask
)
metrics = {}
metrics.update(retrieval_safety_stats)
metrics["safety_filter_active"] = jnp.float32(1.0 if safety_filter_mode != "off" else 0.0)
warm_batch_scores = raw_batch_scores / temperature
warm_global_neg_scores = raw_global_neg_scores / temperature
metrics["temperature"] = temperature
if logq_correction_scale > 0.0:
tweet_counts = get_candidate_tweet_counts(
batch,
log_q_num_bins=100_000_000,
negative_sample_mask=jnp.ones((B, L), dtype=jnp.bool_),
)
sampling_weight = jnp.where(tweet_counts == 0.0, 1.0, 1.0 / tweet_counts)
logq_correction = jnp.log(sampling_weight)
batch_correction = logq_correction[:, :C] * logq_correction_scale
global_correction = logq_correction[:, C:] * logq_correction_scale
batch_scores, global_neg_scores = _apply_logq_correction(
warm_batch_scores, warm_global_neg_scores, batch_correction, global_correction
)
metrics["logq_max"] = jnp.max(batch_correction)
metrics["logq_min"] = jnp.min(batch_correction)
metrics["logq_mean"] = jnp.mean(batch_correction)
metrics["tweet_counts_max"] = jnp.max(tweet_counts[:, :C])
metrics["tweet_counts_min"] = jnp.min(tweet_counts[:, :C])
metrics["tweet_counts_mean"] = jnp.mean(tweet_counts[:, :C])
metrics["logq_max_mask"] = jnp.max(
batch_correction, where=candidate_padding_mask[:, :C], initial=-jnp.inf
)
metrics["logq_min_mask"] = jnp.min(
batch_correction, where=candidate_padding_mask[:, :C], initial=jnp.inf
)
metrics["logq_mean_mask"] = jnp.mean(batch_correction, where=candidate_padding_mask[:, :C])
metrics["tweet_counts_max_mask"] = jnp.max(
tweet_counts[:, :C], where=candidate_padding_mask[:, :C], initial=0
)
metrics["tweet_counts_min_mask"] = jnp.min(
tweet_counts[:, :C], where=candidate_padding_mask[:, :C], initial=1
)
metrics["tweet_counts_mean_mask"] = jnp.mean(
tweet_counts[:, :C], where=candidate_padding_mask[:, :C]
)
else:
batch_scores = warm_batch_scores
global_neg_scores = warm_global_neg_scores
@shard_map(
mesh=mesh,
in_specs=(P(data_axis), P(data_axis)),
out_specs=(P(data_axis), P(data_axis)),
check_vma=False,
)
def _rearrange_negatives(
batch_scores_shard: jax.Array, global_neg_scores_shard: jax.Array
) -> tuple[jax.Array, jax.Array]:
if not use_in_batch_negatives:
return batch_scores_shard, global_neg_scores_shard
b = batch_scores_shard.shape[0]
batch_scores_shard = batch_scores_shard.reshape((b, b, C))
self_cands = batch_scores_shard[jnp.arange(b), jnp.arange(b)]
off_diag_cols = (jnp.arange(b)[:, None] + jnp.arange(1, b)[None, :]) % b
off_diag_cols = jnp.sort(off_diag_cols, axis=1)
in_batch_negatives = batch_scores_shard[jnp.arange(b)[:, None], off_diag_cols].reshape(
b, (b - 1) * C
)
if N > 0:
return self_cands, jnp.concatenate(
[in_batch_negatives, global_neg_scores_shard], axis=1
)
else:
return self_cands, in_batch_negatives
self_scores, common_neg_scores = _rearrange_negatives(batch_scores, global_neg_scores)
assert isinstance(self_scores, jax.Array)
assert isinstance(common_neg_scores, jax.Array)
numerator_logits = self_scores
true_neg_scores = jnp.where(
has_hard_negative_actions | has_soft_negative_actions, self_scores, -INF
)
denominator_logits = jnp.concatenate([common_neg_scores, true_neg_scores], axis=-1)
tiled_denominator_logits = jnp.tile(denominator_logits[:, None, :], (1, C, 1))
tiled_denominator_logits = jnp.concatenate(
[numerator_logits[:, :, None], tiled_denominator_logits], axis=-1
)
if apply_u2u_and_i2i_loss:
@shard_map(
mesh=mesh,
in_specs=(P(data_axis), P(data_axis), P(data_axis), P(data_axis)),
out_specs=(P(data_axis), P(data_axis)),
check_vma=False,
)
def _sharded_u2u_and_i2i_matmul(
local_user: jax.Array,
local_candidate: jax.Array,
padding_mask: jax.Array,
numerator_logits: jax.Array,
) -> tuple[jax.Array, jax.Array]:
local_B = local_user.shape[0]
user_user_logits = (
jnp.where(
~jnp.eye(local_B, dtype=jnp.bool_),
jnp.matmul(local_user, local_user.T),
-1e12,
)
.reshape(local_B, 1, local_B)
.repeat(C, axis=1)
)
user_user_mask = user_user_logits < (0.1 + numerator_logits[:, :, None])
user_user_logits = jnp.where(user_user_mask, user_user_logits / temperature, -1e12)
item_item_logits = jnp.matmul(
(local_candidate[:, :C, :].reshape(local_B * C, -1)),
(local_candidate).reshape(local_B * L, -1).T,
)
item_item_mask = jnp.eye(local_B * C, local_B * L, dtype=jnp.bool_)
row_padding_mask = padding_mask[:, :C].reshape(-1, 1)
col_padding_mask = padding_mask.reshape(1, -1)
item_item_logits = jnp.where(
~item_item_mask & row_padding_mask & ~col_padding_mask,
item_item_logits / temperature,
-1e12,
)
item_item_logits = item_item_logits.reshape(local_B, C, -1)
return user_user_logits, item_item_logits
user_user_logits, item_item_logits = _sharded_u2u_and_i2i_matmul(
user_representation, candidate_representation, candidate_padding_mask, numerator_logits
)
log_denominator = jax.scipy.special.logsumexp(
jnp.concatenate(
[tiled_denominator_logits, user_user_logits, item_item_logits], axis=-1
),
axis=-1,
)
else:
log_denominator = jax.scipy.special.logsumexp(tiled_denominator_logits, axis=-1)
neg_log_probs = log_denominator - numerator_logits
neg_log_likelihood = jnp.where(valid_positive_mask, neg_log_probs, 0.0)
per_user_sum = jnp.sum(neg_log_likelihood, axis=-1)
per_user_count = jnp.sum(valid_positive_mask.astype(jnp.float32), axis=-1)
batch_mean = jnp.where(per_user_count > 0, per_user_sum / per_user_count, 0.0)
num_valid_users = jnp.sum((per_user_count > 0).astype(jnp.float32))
contrastive_loss = jnp.where(
num_valid_users > 0,
jnp.sum(batch_mean) / num_valid_users,
0.0,
)
loss = contrastive_loss
metrics.update(
_compute_retrieval_metrics(
C,
N,
raw_batch_scores,
raw_global_neg_scores,
self_scores,
global_neg_scores,
valid_positive_mask,
has_soft_negative_actions,
has_hard_negative_actions,
candidate_padding_mask,
actions,
contrastive_loss,
has_hard_negative_actions,
positive_actions,
hard_negative_actions,
soft_negative_actions,
use_in_batch_negatives,
data_axis,
mesh,
debug_mode,
)
)
return loss, metrics
@dataclass
class RecsysTwoTowerModel(hk.Module):
config: RecsysTwoTowerModelConfig
user_tower: RecsysAggregatedModel
candidate_tower: RecsysCandidateTower
sharding_context: ShardingContext
@property
def data_axis(self):
return ("stage", *self.config.model_config.data_axis)
@hk.transparent
def build_user_inputs(
self,
recsys_features_batch: RecsysFeaturesBatch,
recsys_embeddings: RecsysEmbeddings,
is_training: bool = True,
) -> tuple[jax.Array, jax.Array]:
_config = self.config.user_tower_config
assert _config.model_config.output_vocab_size is not None, "output_vocab_size is required"
if _config.feature_prep_enabled:
fp = _config.feature_prep
scale_multiplier = fp.scale_config.input_scale(fp.emb_size)
tokens, padding_mask, _ = build_feature_prep_inputs(
batch=recsys_features_batch,
recsys_embeddings=recsys_embeddings,
config=fp,
hash_keys=_config.hash_table.hash_keys,
input_scale=scale_multiplier,
output_vocab_size=_config.model_config.output_vocab_size,
is_training=is_training,
include_candidates=False,
)
tokens = with_sharding_constraint(
tokens, P(self.user_tower.data_axis, ("seq", "model"))
)
return tokens, padding_mask
history_actions = recsys_features_batch["history_seq"]["actions"]
assert history_actions is not None
self.action_embedding_table: jax.Array
history_actions_embeddings, self.action_embedding_table = (
self.user_tower.multi_hot_to_embeddings(
cast_jax(history_actions),
_config.model_config.output_vocab_size,
_config.emb_table_width,
_config.embed_init_scale,
"action_embedding_table",
)
)
ctx_config = _config.context_features
history_cat_features: jax.Array | None = None
if ctx_config.enabled:
raw_hist_cat = recsys_features_batch["history_seq"].get("categorical_features")
if raw_hist_cat is not None:
history_cat_features = cast_jax(raw_hist_cat)
history_unified_context = self.user_tower.build_unified_context_embedding(
product_surface=cast_jax(recsys_features_batch["history_seq"]["product_surface"]),
cat_features=history_cat_features,
)
_sid_post_emb_h = self._sid_token_or_zeros_init(
recsys_features_batch["history_seq"], _config
)
history_embeddings, history_padding_mask = block_history_reduce(
cast_jax(recsys_features_batch["history_seq"]["post_hashes"]),
cast_jax(recsys_features_batch["history_seq"]["auth_hashes"]),
recsys_embeddings.history_post_embeddings if _config.use_post_embedding else None,
recsys_embeddings.history_author_embeddings,
history_unified_context,
history_actions_embeddings,
_config.hash_table.hash_keys,
_config.model_config.scale_config.emb_lr_multiplier,
_config.embed_init_scale,
history_unified_context is not None,
sid_post_embeddings=_sid_post_emb_h,
)
if _config.use_seqpack:
layout = recsys_features_batch.get("packing_layout")
assert layout is not None, (
"use_seqpack=True but batch has no packing_layout; "
"run pack_batch on eval/training batches before the model."
)
num_devices, bs_per_device, _ = recsys_features_batch["user_hashes"].shape
total_batch = num_devices * bs_per_device
def _flatten_lead(x):
return None if x is None else cast_jax(x).reshape(total_batch, *x.shape[2:])
user_emb_result = self.user_tower._build_user_embedding(
cast_jax(recsys_features_batch["user_hashes"]),
recsys_embeddings,
reshape_for_seqpack=(num_devices, bs_per_device),
)
user_embeddings = user_emb_result[0] if user_emb_result is not None else None
uf = self.config.user_features
user_features_token = None
if uf.has_user_features:
flat_user_feature_keys = (
"user_categorical_features",
"user_bool_features",
"user_float_features",
"user_int64_features",
"user_installed_apps_multihot",
)
flat_batch = typing.cast(
RecsysFeaturesBatch,
{
**recsys_features_batch,
**{
k: _flatten_lead(recsys_features_batch[k])
for k in flat_user_feature_keys
},
},
)
user_features_token = build_user_features_token(
build_user_feature_parts(flat_batch, uf, self.sharding_context),
uf.user_features_concat_dim,
_config.emb_table_width,
DTYPE_BY_NAME[_config.fprop_dtype],
self.sharding_context,
use_mlp=uf.user_features_mlp,
pad=uf.user_features_concat_pad,
).reshape(num_devices, bs_per_device, -1)
padding_mask = cast_jax(layout.padding_mask)
seq_starts = cast_jax(layout.cu_seqlens[:, :-1])
device_idx = jnp.arange(num_devices, dtype=jnp.int32)[:, None]
embeddings = jnp.zeros(
(*padding_mask.shape, _config.emb_table_width),
dtype=DTYPE_BY_NAME[_config.fprop_dtype],
)
prefix_offset = 0
if user_embeddings is not None:
embeddings = embeddings.at[device_idx, seq_starts].set(user_embeddings)
prefix_offset = 1
if user_features_token is not None:
embeddings = embeddings.at[device_idx, seq_starts + prefix_offset].set(
user_features_token
)
embeddings = embeddings.at[device_idx, cast_jax(layout.history_positions)].add(
jnp.where(history_padding_mask[:, :, None], history_embeddings, 0)
)
embeddings *= self.config.model_config.scale_config.input_scale(
self.config.emb_table_width
)
embeddings = with_sharding_constraint(
embeddings, P(self.user_tower.data_axis, ("seq", "model"))
)
return self.user_tower.maybe_tfmr_project_embeddings(embeddings, _config), padding_mask
sequence_parts: list[jax.Array] = []