File size: 55,477 Bytes
9e5c7bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
#                🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
#           This file was automatically generated from src/transformers/models/emo/modular_emo.py.
#               Do NOT edit this file manually as any edits will be overwritten by the generation of
#             the file from the modular. If any change should be done, please apply the change to the
#                          modular_emo.py file directly. One of our CI enforces this.
#                🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
# coding=utf-8
# Copyright 2025 the HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from dataclasses import dataclass
from typing import Callable, Optional, Union

import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers.activations import ACT2FN
from transformers.cache_utils import Cache, DynamicCache
from transformers.generation import GenerationMixin
from transformers.integrations import use_kernel_forward_from_hub
from transformers.masking_utils import create_causal_mask
from transformers.modeling_layers import GradientCheckpointingLayer
from transformers.modeling_outputs import MoeModelOutputWithPast
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
from transformers.processing_utils import Unpack
from transformers.utils import ModelOutput, TransformersKwargs, auto_docstring
from transformers.utils.deprecation import deprecate_kwarg
from transformers.utils.generic import OutputRecorder, check_model_inputs

from .configuration_emo import EmoConfig


@use_kernel_forward_from_hub("RMSNorm")
class EmoRMSNorm(nn.Module):
    def __init__(self, hidden_size, eps=1e-6):
        """
        EmoRMSNorm is equivalent to T5LayerNorm
        """
        super().__init__()
        self.weight = nn.Parameter(torch.ones(hidden_size))
        self.variance_epsilon = eps

    def forward(self, hidden_states):
        input_dtype = hidden_states.dtype
        hidden_states = hidden_states.to(torch.float32)
        variance = hidden_states.pow(2).mean(-1, keepdim=True)
        hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
        return (self.weight * hidden_states).to(input_dtype)

    def extra_repr(self):
        return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"


class EmoMLP(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.config = config
        self.hidden_size = config.hidden_size
        self.intermediate_size = config.intermediate_size
        self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
        self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
        self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
        self.act_fn = ACT2FN[config.hidden_act]
        # Some densefirst models were accidentally trained with bias=True on dense MLPs
        # (OLMo Core's FeedForwardConfig defaults bias to True when not explicitly set).
        # We support loading those weights here.
        dense_mlp_bias = getattr(config, "dense_mlp_bias", False)
        if dense_mlp_bias:
            del self.gate_proj
            del self.up_proj
            del self.down_proj
            self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=True)
            self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=True)
            self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=True)

    def forward(self, x):
        down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
        return down_proj


def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
    """
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    """
    batch, num_key_value_heads, slen, head_dim = hidden_states.shape
    if n_rep == 1:
        return hidden_states
    hidden_states = hidden_states[:, :, None, :, :].expand(
        batch, num_key_value_heads, n_rep, slen, head_dim
    )
    return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)


def eager_attention_forward(
    module: nn.Module,
    query: torch.Tensor,
    key: torch.Tensor,
    value: torch.Tensor,
    attention_mask: Optional[torch.Tensor],
    scaling: float,
    dropout: float = 0.0,
    **kwargs: Unpack[TransformersKwargs],
):
    key_states = repeat_kv(key, module.num_key_value_groups)
    value_states = repeat_kv(value, module.num_key_value_groups)

    attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
    if attention_mask is not None:
        causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
        attn_weights = attn_weights + causal_mask

    attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
    attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
    attn_output = torch.matmul(attn_weights, value_states)
    attn_output = attn_output.transpose(1, 2).contiguous()

    return attn_output, attn_weights


def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
    """Applies Rotary Position Embedding to the query and key tensors.

    Args:
        q (`torch.Tensor`): The query tensor.
        k (`torch.Tensor`): The key tensor.
        cos (`torch.Tensor`): The cosine part of the rotary embedding.
        sin (`torch.Tensor`): The sine part of the rotary embedding.
        position_ids (`torch.Tensor`, *optional*):
            Deprecated and unused.
        unsqueeze_dim (`int`, *optional*, defaults to 1):
            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
    Returns:
        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    """
    q_type, k_type = q.dtype, k.dtype
    cos = cos.unsqueeze(unsqueeze_dim)
    sin = sin.unsqueeze(unsqueeze_dim)
    q_embed = (q * cos) + (rotate_half(q) * sin)
    k_embed = (k * cos) + (rotate_half(k) * sin)
    return q_embed.to(q_type), k_embed.to(k_type)


def rotate_half(x):
    """Rotates half the hidden dims of the input."""
    x1 = x[..., : x.shape[-1] // 2]
    x2 = x[..., x.shape[-1] // 2 :]
    return torch.cat((-x2, x1), dim=-1)


class EmoAttention(nn.Module):
    """Multi-headed attention from 'Attention Is All You Need' paper"""

    def __init__(self, config: EmoConfig, layer_idx: Optional[int] = None):
        super().__init__()
        self.config = config
        self.layer_idx = layer_idx
        self.head_dim = getattr(
            config, "head_dim", config.hidden_size // config.num_attention_heads
        )
        self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
        self.scaling = self.head_dim**-0.5
        self.attention_dropout = config.attention_dropout
        self.is_causal = True

        self.q_proj = nn.Linear(
            config.hidden_size,
            config.num_attention_heads * self.head_dim,
            bias=config.attention_bias,
        )
        self.k_proj = nn.Linear(
            config.hidden_size,
            config.num_key_value_heads * self.head_dim,
            bias=config.attention_bias,
        )
        self.v_proj = nn.Linear(
            config.hidden_size,
            config.num_key_value_heads * self.head_dim,
            bias=config.attention_bias,
        )
        self.o_proj = nn.Linear(
            config.num_attention_heads * self.head_dim,
            config.hidden_size,
            bias=config.attention_bias,
        )

    @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
    def forward(
        self,
        hidden_states: torch.Tensor,
        position_embeddings: tuple[torch.Tensor, torch.Tensor],
        attention_mask: Optional[torch.Tensor],
        past_key_values: Optional[Cache] = None,
        cache_position: Optional[torch.LongTensor] = None,
        **kwargs: Unpack[TransformersKwargs],
    ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
        input_shape = hidden_states.shape[:-1]
        hidden_shape = (*input_shape, -1, self.head_dim)

        query_states = self.q_proj(hidden_states)
        key_states = self.k_proj(hidden_states)
        value_states = self.v_proj(hidden_states)

        query_states = query_states.view(hidden_shape).transpose(1, 2)
        key_states = key_states.view(hidden_shape).transpose(1, 2)
        value_states = value_states.view(hidden_shape).transpose(1, 2)

        cos, sin = position_embeddings
        query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)

        if past_key_values is not None:
            # sin and cos are specific to RoPE models; cache_position needed for the static cache
            cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
            key_states, value_states = past_key_values.update(
                key_states, value_states, self.layer_idx, cache_kwargs
            )

        attention_interface: Callable = eager_attention_forward
        if self.config._attn_implementation != "eager":
            attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]

        attn_output, attn_weights = attention_interface(
            self,
            query_states,
            key_states,
            value_states,
            attention_mask,
            dropout=0.0 if not self.training else self.attention_dropout,
            scaling=self.scaling,
            **kwargs,
        )

        attn_output = attn_output.reshape(*input_shape, -1).contiguous()
        attn_output = self.o_proj(attn_output)
        return attn_output, attn_weights


class EmoSparseMoeBlock(nn.Module):
    def __init__(
        self,
        config,
        num_experts: int,
        num_shared_experts: int,
        always_active_experts: Optional[list[int]] = None,
    ):
        super().__init__()
        self.top_k = config.num_experts_per_tok
        self.norm_topk_prob = config.norm_topk_prob

        self.num_shared_experts = num_shared_experts
        self.always_active_experts = always_active_experts
        self.num_experts = num_experts
        self.gate = nn.Linear(config.hidden_size, self.num_experts, bias=False)
        # Expert MLPs should never use dense_mlp_bias (that's only for dense FFN layers)
        import copy

        expert_config = copy.copy(config)
        expert_config.dense_mlp_bias = False
        self.experts = nn.ModuleList([EmoMLP(expert_config) for _ in range(self.num_experts)])

    def _get_top_k_with_always_active(
        self, scores: torch.Tensor
    ) -> tuple[torch.Tensor, torch.Tensor]:
        """
        Select top-k experts where always_active_experts are always included.
        Softmax is computed over all experts, then always-active are masked out for topk selection.
        """
        always_active = self.always_active_experts
        assert always_active is not None
        num_always_active = len(always_active)
        routed_top_k = self.top_k - num_always_active

        # Mask out always-active experts so they aren't selected by topk.
        masked_scores = scores.clone()
        masked_scores[:, always_active] = float("-inf")

        # Select top-(top_k - num_always_active) from the remaining experts.
        if routed_top_k == 1:
            _, routed_indices = masked_scores.max(dim=-1, keepdim=True)
        else:
            _, routed_indices = torch.topk(masked_scores, routed_top_k, dim=-1)

        # Gather actual weights from original (unmasked) scores.
        routed_weights = scores.gather(-1, routed_indices)

        # Build always-active indices and weights.
        always_active_tensor = torch.tensor(
            always_active, device=scores.device, dtype=routed_indices.dtype
        )
        always_active_indices = always_active_tensor.unsqueeze(0).expand(
            scores.shape[0], num_always_active
        )
        always_active_weights = scores.gather(-1, always_active_indices)

        # Concatenate: always-active first, then routed.
        selected_experts = torch.cat([always_active_indices, routed_indices], dim=-1)
        routing_weights = torch.cat([always_active_weights, routed_weights], dim=-1)

        return routing_weights, selected_experts

    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
        batch_size, sequence_length, hidden_dim = hidden_states.shape
        hidden_states = hidden_states.view(-1, hidden_dim)
        # router_logits: (batch * sequence_length, n_experts)
        router_logits = self.gate(hidden_states)

        if self.always_active_experts is not None and len(self.always_active_experts) > 0:
            # Use masking approach: softmax over all experts, mask always-active for topk
            routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
            routing_weights, selected_experts = self._get_top_k_with_always_active(routing_weights)
        elif self.num_shared_experts > 0:
            # Legacy path: shared experts are the last N experts
            # split the router logits into shared and unshared experts
            router_logits_standard = router_logits[
                :, : -self.num_shared_experts
            ]  # (batch * sequence_length, n_experts - num_shared_experts)
            router_logits_shared = router_logits[
                :, -self.num_shared_experts :
            ]  # (batch * sequence_length, num_shared_experts)

            # compute the routing weights for the standard experts and shared experts separately
            routing_weights_standard = F.softmax(router_logits_standard, dim=1, dtype=torch.float)
            routing_weights_shared = F.softmax(router_logits_shared, dim=1, dtype=torch.float)

            # select the routing weights and experts for the standard experts and shared experts separately
            routing_weights_standard, selected_experts_standard = torch.topk(
                routing_weights_standard, self.top_k - self.num_shared_experts, dim=-1
            )
            routing_weights_shared, selected_experts_shared = torch.topk(
                routing_weights_shared, self.num_shared_experts, dim=-1
            )

            # concatenate the routing weights and selected experts for the standard experts and shared experts
            routing_weights = torch.cat([routing_weights_standard, routing_weights_shared], dim=1)
            selected_experts = torch.cat(
                [
                    selected_experts_standard,
                    selected_experts_shared + (self.num_experts - self.num_shared_experts),
                ],
                dim=1,
            )  # we need to add the offset to the selected experts for the shared experts since they are at the end of the router logits

            # make sure there are self.top_k experts selected in total
            assert (
                routing_weights.shape
                == selected_experts.shape
                == (batch_size * sequence_length, self.top_k)
            ), f"routing_weights and selected_experts should have the same shape of (batch_size * sequence_length, self.top_k), but got {routing_weights.shape} and {selected_experts.shape}"
        else:
            routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
            routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1)

        if self.norm_topk_prob:
            if self.num_shared_experts > 0 or (
                self.always_active_experts is not None and len(self.always_active_experts) > 0
            ):
                raise NotImplementedError(
                    "norm_topk_prob is not implemented for the case where num_shared_experts > 0 or always_active_experts is set"
                )
            routing_weights /= routing_weights.sum(dim=-1, keepdim=True)

        # we cast back to the input dtype
        routing_weights = routing_weights.to(hidden_states.dtype)

        final_hidden_states = torch.zeros(
            (batch_size * sequence_length, hidden_dim),
            dtype=hidden_states.dtype,
            device=hidden_states.device,
        )

        # One hot encode the selected experts to create an expert mask
        # this will be used to easily index which expert is going to be selected
        expert_mask = torch.nn.functional.one_hot(
            selected_experts, num_classes=self.num_experts
        ).permute(2, 1, 0)

        # Loop over all available experts in the model and perform the computation on each expert
        for expert_idx in range(self.num_experts):
            expert_layer = self.experts[expert_idx]
            idx, top_x = torch.where(expert_mask[expert_idx])

            # Index the correct hidden states and compute the expert hidden state for
            # the current expert. We need to make sure to multiply the output hidden
            # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
            current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)
            current_hidden_states = expert_layer(current_state) * routing_weights[top_x, idx, None]

            # However `index_add_` only support torch tensors for indexing so we'll use
            # the `top_x` tensor here.
            final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
        final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
        return final_hidden_states, router_logits


class EmoDecoderLayer(GradientCheckpointingLayer):
    def __init__(
        self,
        config: EmoConfig,
        layer_idx: int,
        num_experts: int,
        num_shared_experts: int,
        always_active_experts: Optional[list[int]] = None,
    ):
        super().__init__()
        self.hidden_size = config.hidden_size
        self.self_attn = EmoAttention(config=config, layer_idx=layer_idx)

        self.num_experts = num_experts

        if num_experts == 0:
            # Dense layer: use MLP with dense_intermediate_size
            dense_intermediate_size = getattr(config, "dense_intermediate_size", None)
            if dense_intermediate_size is None:
                raise ValueError(
                    "num_experts=0 (dense layer) but config.dense_intermediate_size is not set. "
                    "Please set dense_intermediate_size in the config."
                )
            import copy

            dense_config = copy.copy(config)
            dense_config.intermediate_size = dense_intermediate_size
            dense_config.dense_mlp_bias = getattr(config, "dense_mlp_bias", False)
            self.mlp = EmoMLP(dense_config)
        else:
            self.mlp = EmoSparseMoeBlock(
                config, num_experts, num_shared_experts, always_active_experts
            )

        self.pre_attention_layernorm = EmoRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
        self.pre_feedforward_layernorm = EmoRMSNorm(config.hidden_size, eps=config.rms_norm_eps)

    @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
    def forward(
        self,
        hidden_states: torch.Tensor,
        attention_mask: Optional[torch.Tensor] = None,
        position_ids: Optional[torch.LongTensor] = None,
        past_key_values: Optional[Cache] = None,
        cache_position: Optional[torch.LongTensor] = None,
        position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
        **kwargs,
    ) -> torch.FloatTensor:
        """
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`, *optional*):
                attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
                query_sequence_length, key_sequence_length)` if default attention is used.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            output_router_logits (`bool`, *optional*):
                Whether or not to return the logits of all the routers. They are useful for computing the router loss,
                and should not be returned during inference.
            use_cache (`bool`, *optional*):
                If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
                (see `past_key_values`).
            past_key_values (`Cache`, *optional*): cached past key and value projection states
            cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
                Indices depicting the position of the input sequence tokens in the sequence
            position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
                Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
                with `head_dim` being the embedding dimension of each attention head.
            kwargs (`dict`, *optional*):
                Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
                into the model
        """
        residual = hidden_states
        # apply norm before attention
        hidden_states = self.pre_attention_layernorm(hidden_states)
        # Self Attention
        hidden_states, _ = self.self_attn(
            hidden_states=hidden_states,
            attention_mask=attention_mask,
            position_ids=position_ids,
            past_key_values=past_key_values,
            cache_position=cache_position,
            position_embeddings=position_embeddings,
            **kwargs,
        )
        hidden_states = residual + hidden_states

        # Fully Connected
        residual = hidden_states
        # apply norm before feedforward
        hidden_states = self.pre_feedforward_layernorm(hidden_states)
        mlp_output = self.mlp(hidden_states)
        if isinstance(mlp_output, tuple):
            hidden_states, _ = mlp_output
        else:
            hidden_states = mlp_output
        hidden_states = residual + hidden_states
        return hidden_states


@auto_docstring
class EmoPreTrainedModel(PreTrainedModel):
    config: EmoConfig
    base_model_prefix = "model"
    supports_gradient_checkpointing = True
    _no_split_modules = ["EmoDecoderLayer"]
    _skip_keys_device_placement = ["past_key_values"]
    _supports_flash_attn = True
    _supports_sdpa = True
    _supports_flex_attn = True
    _can_compile_fullgraph = (
        False  # MoE models don't work with torch.compile (`torch.where(condition)` not supported)
    )
    _supports_attention_backend = True
    _can_record_outputs = {
        "router_logits": OutputRecorder(EmoSparseMoeBlock, index=1),
        "hidden_states": EmoDecoderLayer,
        "attentions": EmoAttention,
    }
    config_class = EmoConfig


class EmoRotaryEmbedding(nn.Module):
    inv_freq: torch.Tensor  # fix linting for `register_buffer`

    def __init__(self, config: EmoConfig, device=None):
        super().__init__()
        # BC: "rope_type" was originally "type"
        if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
            self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
        else:
            self.rope_type = "default"
        self.max_seq_len_cached = config.max_position_embeddings
        self.original_max_seq_len = config.max_position_embeddings

        self.config = config
        self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]

        inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
        self.register_buffer("inv_freq", inv_freq, persistent=False)
        self.original_inv_freq = self.inv_freq

    @torch.no_grad()
    @dynamic_rope_update  # power user: used with advanced RoPE types (e.g. dynamic rope)
    def forward(self, x, position_ids):
        inv_freq_expanded = (
            self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
        )
        position_ids_expanded = position_ids[:, None, :].float()

        device_type = (
            x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
        )
        with torch.autocast(device_type=device_type, enabled=False):  # Force float32
            freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
            emb = torch.cat((freqs, freqs), dim=-1)
            cos = emb.cos() * self.attention_scaling
            sin = emb.sin() * self.attention_scaling
            return cos, sin


@auto_docstring
class EmoModel(EmoPreTrainedModel):
    def __init__(self, config):
        super().__init__(config)
        self.padding_idx = config.pad_token_id
        self.vocab_size = config.vocab_size

        self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
        self.norm = EmoRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
        self.rotary_emb = EmoRotaryEmbedding(config=config)
        self.gradient_checkpointing = False

        # Check if per-layer expert counts are specified
        num_experts_per_layer = getattr(config, "num_experts_per_layer", None)
        num_shared_experts_per_layer = getattr(config, "num_shared_experts_per_layer", None)
        always_active_experts_per_layer = getattr(config, "always_active_experts_per_layer", None)
        always_active_experts = getattr(config, "always_active_experts", None)

        # Resolve always_active_experts to a per-layer list
        if always_active_experts_per_layer is None and always_active_experts is not None:
            always_active_experts_per_layer = [always_active_experts] * config.num_hidden_layers

        if num_experts_per_layer is not None:
            # Use per-layer expert counts
            assert (
                len(num_experts_per_layer) == config.num_hidden_layers
            ), f"num_experts_per_layer has length {len(num_experts_per_layer)} but model has {config.num_hidden_layers} layers"
            if num_shared_experts_per_layer is None:
                # Default: use config.num_shared_experts for all layers, but cap at layer's num_experts
                num_shared_experts_per_layer = [
                    min(config.num_shared_experts, num_experts_per_layer[i])
                    for i in range(config.num_hidden_layers)
                ]
            self.layers = nn.ModuleList(
                [
                    EmoDecoderLayer(
                        config,
                        layer_idx,
                        num_experts_per_layer[layer_idx],
                        num_shared_experts_per_layer[layer_idx],
                        always_active_experts=always_active_experts_per_layer[layer_idx]
                        if always_active_experts_per_layer is not None
                        else None,
                    )
                    for layer_idx in range(config.num_hidden_layers)
                ]
            )
        else:
            # Fall back to original behavior: all layers use config.num_experts
            self.layers = nn.ModuleList(
                [
                    EmoDecoderLayer(
                        config,
                        layer_idx,
                        config.num_experts,
                        config.num_shared_experts,
                        always_active_experts=always_active_experts_per_layer[layer_idx]
                        if always_active_experts_per_layer is not None
                        else None,
                    )
                    for layer_idx in range(config.num_hidden_layers)
                ]
            )

        # Initialize weights and apply final processing
        self.post_init()

    @check_model_inputs
    @auto_docstring
    def forward(
        self,
        input_ids: Optional[torch.LongTensor] = None,
        attention_mask: Optional[torch.Tensor] = None,
        position_ids: Optional[torch.LongTensor] = None,
        past_key_values: Optional[Cache] = None,
        inputs_embeds: Optional[torch.FloatTensor] = None,
        use_cache: Optional[bool] = None,
        cache_position: Optional[torch.LongTensor] = None,
        **kwargs: Unpack[TransformersKwargs],
    ) -> MoeModelOutputWithPast:
        if (input_ids is None) ^ (inputs_embeds is not None):
            raise ValueError("You must specify exactly one of input_ids or inputs_embeds")

        if use_cache and past_key_values is None:
            past_key_values = DynamicCache(config=self.config)

        if inputs_embeds is None:
            inputs_embeds = self.embed_tokens(input_ids)

        if cache_position is None:
            past_seen_tokens = (
                past_key_values.get_seq_length() if past_key_values is not None else 0
            )
            cache_position = torch.arange(
                past_seen_tokens,
                past_seen_tokens + inputs_embeds.shape[1],
                device=inputs_embeds.device,
            )
        if position_ids is None:
            position_ids = cache_position.unsqueeze(0)

        causal_mask = create_causal_mask(
            config=self.config,
            input_embeds=inputs_embeds,
            attention_mask=attention_mask,
            cache_position=cache_position,
            past_key_values=past_key_values,
            position_ids=position_ids,
        )

        hidden_states = inputs_embeds

        # create position embeddings to be shared across the decoder layers
        position_embeddings = self.rotary_emb(hidden_states, position_ids)

        for decoder_layer in self.layers[: self.config.num_hidden_layers]:
            hidden_states = decoder_layer(
                hidden_states,
                position_embeddings=position_embeddings,
                attention_mask=causal_mask,
                position_ids=position_ids,
                past_key_values=past_key_values,
                use_cache=use_cache,
                cache_position=cache_position,
                **kwargs,
            )

        hidden_states = self.norm(hidden_states)

        return MoeModelOutputWithPast(  # only diff with Mistral is the output type, we need MoE
            last_hidden_state=hidden_states,
            past_key_values=past_key_values,
        )


@dataclass
class MoeCausalLMOutputWithPast(ModelOutput):
    """
    Base class for causal language model (or autoregressive) with mixture of experts outputs.

    Args:
        loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
            Language modeling loss (for next-token prediction).

        logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
            Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).

        aux_loss (`torch.FloatTensor`, *optional*, returned when `labels` is provided):
            aux_loss for the sparse modules.

        router_logits (`tuple(torch.FloatTensor)`, *optional*, returned when `output_router_probs=True` and `config.add_router_probs=True` is passed or when `config.output_router_probs=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, sequence_length, num_experts)`.

            Raw router logtis (post-softmax) that are computed by MoE routers, these terms are used to compute the auxiliary
            loss for Mixture of Experts models.

        past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).

            Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
            `past_key_values` input) to speed up sequential decoding.
        hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
            one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
        attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
    """

    loss: Optional[torch.FloatTensor] = None
    aux_loss: Optional[torch.FloatTensor] = None
    lb_loss: Optional[torch.FloatTensor] = None
    ce_loss: Optional[torch.FloatTensor] = None
    logits: Optional[torch.FloatTensor] = None
    past_key_values: Optional[Cache] = None
    hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
    attentions: Optional[tuple[torch.FloatTensor, ...]] = None
    router_logits: Optional[tuple[torch.FloatTensor]] = None


def load_balancing_loss_func_olmoe(
    gate_logits: Union[torch.Tensor, tuple[torch.Tensor], None],
    num_experts: Optional[int] = None,
    top_k=2,
    attention_mask: Optional[torch.Tensor] = None,
    labels: Optional[torch.Tensor] = None,
    num_items_in_batch: Optional[
        torch.Tensor
    ] = None,  # the number of tokens within a global batch (including across dp ranks)
    ignore_index=-100,
    num_shared_experts=0,
    num_experts_per_layer: Optional[list[int]] = None,
    num_shared_experts_per_layer: Optional[list[int]] = None,
    always_active_experts: Optional[list[int]] = None,
    always_active_experts_per_layer: Optional[list[list[int]]] = None,
) -> Union[torch.Tensor, int]:
    r"""
    Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.

    This version supports variable per-layer expert counts by computing the loss
    per-layer individually and averaging across layers.

    See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
    function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
    experts is too unbalanced.

    Args:
        gate_logits:
            Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
            shape [batch_size X sequence_length, num_experts]. This has not been softmaxed yet.
            Note: each layer may have a different num_experts if num_experts_per_layer is set.
        num_experts:
            Number of experts (used as fallback if num_experts_per_layer is None)
        top_k:
            The number of experts to route per-token, can be also interpreted as the `top-k` routing
            parameter.
        attention_mask (`torch.Tensor`, *optional*):
            The attention_mask used in forward function
            shape [batch_size X sequence_length] if not None.
        num_experts_per_layer:
            List of expert counts per layer. If None, uses num_experts for all layers.
        num_shared_experts_per_layer:
            List of shared expert counts per layer. If None, uses num_shared_experts for all layers.

    Returns:
        The auxiliary loss.
    """
    if gate_logits is None or not isinstance(gate_logits, tuple):
        return 0

    compute_device = gate_logits[0].device
    num_hidden_layers = len(gate_logits)

    # Resolve always_active_experts for the uniform path
    if always_active_experts_per_layer is None and always_active_experts is not None:
        always_active_experts_per_layer = [always_active_experts] * num_hidden_layers

    # Check if we have variable expert counts
    has_variable_experts = num_experts_per_layer is not None and len(set(num_experts_per_layer)) > 1

    if not has_variable_experts:
        # All layers have the same expert count - use the original stacking approach
        concatenated_gate_logits = torch.stack(
            [layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0
        )  # shape: (num_hidden_layers, batch_size * sequence_length, num_experts)

        # remove the shared experts from the gate logits since they are not used for routing in the loss function
        if num_shared_experts > 0:
            concatenated_gate_logits = concatenated_gate_logits[:, :, :-num_shared_experts]
            # adjust the num_experts and top_k accordingly for the loss computation
            num_experts = num_experts - num_shared_experts
            top_k = top_k - num_shared_experts

        routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)

        # Exclude always-active experts from the LB loss by removing their
        # columns entirely so that num_experts matches the last dimension.
        if (
            always_active_experts_per_layer is not None
            and len(always_active_experts_per_layer[0]) > 0
        ):
            assert num_experts is not None
            aa_experts = always_active_experts_per_layer[0]  # uniform across layers in this path
            routed_mask = torch.ones(num_experts, dtype=torch.bool, device=compute_device)
            routed_mask[aa_experts] = False
            routing_weights = routing_weights[:, :, routed_mask]
            num_experts = num_experts - len(aa_experts)
            top_k = top_k - len(aa_experts)

        _, selected_experts = torch.topk(
            routing_weights, top_k, dim=-1
        )  # shape: (num_hidden_layers, batch_size * sequence_length, top_k)

        expert_counts_onehot = torch.nn.functional.one_hot(
            selected_experts, num_experts
        )  # shape: (num_hidden_layers, batch_size * sequence_length, top_k, num_experts)

        if attention_mask is None and labels is None:
            # Compute the percentage of tokens routed to each experts
            counts_per_expert = torch.mean(
                expert_counts_onehot.float(), dim=(1, 2)
            )  # shape: (num_hidden_layers, num_experts)

            # Compute the average probability of routing to these experts
            prob_per_expert = torch.mean(
                routing_weights, dim=1
            )  # shape: (num_hidden_layers, num_experts)
        else:
            # if there are labels, then we want to ignore the indices that are in the prompt as well (if there is any)
            if labels is not None:
                attention_mask = labels != ignore_index
            assert attention_mask is not None
            batch_size, sequence_length = attention_mask.shape

            # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
            expert_attention_mask = (
                attention_mask[None, :, :, None, None]
                .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
                .reshape(num_hidden_layers, -1, top_k, num_experts)
                .to(compute_device)
            )

            # Compute the percentage of tokens routed to each experts
            counts_per_expert = torch.sum(
                expert_counts_onehot.float() * expert_attention_mask, dim=(1, 2)
            )

            # Compute the mask that masks all padding tokens as 0 with the same shape of frequency_per_expert
            router_per_expert_attention_mask = (
                attention_mask[None, :, :, None]
                .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
                .reshape(num_hidden_layers, -1, num_experts)
                .to(compute_device)
            )

            # average the probability across valid tokens
            prob_per_expert = torch.sum(
                routing_weights * router_per_expert_attention_mask, dim=1
            ) / torch.sum(
                attention_mask
            )  # shape: (num_hidden_layers, num_experts)

        overall_loss = torch.sum(counts_per_expert * prob_per_expert)

        # Fallback when num_items_in_batch isn't provided (e.g., manual forward calls)
        if num_items_in_batch is None:
            if labels is not None:
                num_items_in_batch = (labels != ignore_index).sum()
            elif attention_mask is not None:
                num_items_in_batch = attention_mask.sum()
            else:
                # fall back to total tokens in batch/seq from gate logits
                num_items_in_batch = gate_logits[0].shape[0]

            if torch.is_tensor(num_items_in_batch):
                num_items_in_batch = num_items_in_batch.to(compute_device)

        # we follow olmo-core and use counts for dot product instead of frequency, and divide by total number token across gradient accumulation steps
        overall_loss = overall_loss / (num_items_in_batch * top_k)

        overall_loss = (
            overall_loss * num_experts / num_hidden_layers
        )  # times num_experts according to lb equation, divide by num_hidden_layers to get average over layers

        return overall_loss

    else:
        # Variable expert counts - compute loss per layer and average
        if num_shared_experts_per_layer is None:
            num_shared_experts_per_layer = [num_shared_experts] * num_hidden_layers

        # Compute attention mask once
        if labels is not None:
            attention_mask = labels != ignore_index

        if attention_mask is not None:
            batch_size, sequence_length = attention_mask.shape

        # Fallback when num_items_in_batch isn't provided
        if num_items_in_batch is None:
            if labels is not None:
                num_items_in_batch = (labels != ignore_index).sum()
            elif attention_mask is not None:
                num_items_in_batch = attention_mask.sum()
            else:
                num_items_in_batch = gate_logits[0].shape[0]

            if torch.is_tensor(num_items_in_batch):
                num_items_in_batch = num_items_in_batch.to(compute_device)

        layer_losses = []

        assert num_experts_per_layer is not None
        for layer_idx, layer_gate in enumerate(gate_logits):
            layer_gate = layer_gate.to(compute_device)
            layer_num_experts = num_experts_per_layer[layer_idx]
            layer_num_shared = num_shared_experts_per_layer[layer_idx]

            # Remove shared experts from logits
            if layer_num_shared > 0:
                layer_gate = layer_gate[:, :-layer_num_shared]
                effective_num_experts = layer_num_experts - layer_num_shared
                effective_top_k = top_k - layer_num_shared
            else:
                effective_num_experts = layer_num_experts
                effective_top_k = top_k

            # Compute routing weights
            routing_weights = torch.nn.functional.softmax(layer_gate, dim=-1)

            # Exclude always-active experts from the LB loss by removing their columns
            layer_aa = (
                always_active_experts_per_layer[layer_idx]
                if always_active_experts_per_layer is not None
                else None
            )
            if layer_aa is not None and len(layer_aa) > 0:
                routed_mask = torch.ones(
                    effective_num_experts, dtype=torch.bool, device=compute_device
                )
                routed_mask[layer_aa] = False
                routing_weights = routing_weights[:, routed_mask]
                effective_num_experts = effective_num_experts - len(layer_aa)
                effective_top_k = effective_top_k - len(layer_aa)

            _, selected_experts = torch.topk(
                routing_weights, effective_top_k, dim=-1
            )  # shape: (batch_size * sequence_length, top_k)

            expert_counts_onehot = torch.nn.functional.one_hot(
                selected_experts, effective_num_experts
            )  # shape: (batch_size * sequence_length, top_k, num_experts)

            if attention_mask is None:
                counts_per_expert = torch.mean(
                    expert_counts_onehot.float(), dim=(0, 1)
                )  # shape: (num_experts,)
                prob_per_expert = torch.mean(routing_weights, dim=0)  # shape: (num_experts,)
            else:
                # Reshape for masking
                expert_attention_mask = (
                    attention_mask[:, :, None, None]
                    .expand((batch_size, sequence_length, effective_top_k, effective_num_experts))
                    .reshape(-1, effective_top_k, effective_num_experts)
                    .to(compute_device)
                )

                counts_per_expert = torch.sum(
                    expert_counts_onehot.float() * expert_attention_mask, dim=(0, 1)
                )

                router_attention_mask = (
                    attention_mask[:, :, None]
                    .expand((batch_size, sequence_length, effective_num_experts))
                    .reshape(-1, effective_num_experts)
                    .to(compute_device)
                )

                prob_per_expert = torch.sum(
                    routing_weights * router_attention_mask, dim=0
                ) / torch.sum(attention_mask)

            layer_loss = torch.sum(counts_per_expert * prob_per_expert)
            layer_loss = layer_loss / (num_items_in_batch * effective_top_k)
            layer_loss = layer_loss * effective_num_experts

            layer_losses.append(layer_loss)

        # Average across layers
        overall_loss = torch.stack(layer_losses).mean()

        return overall_loss


class EmoForCausalLM(EmoPreTrainedModel, GenerationMixin):
    _tied_weights_keys = ["lm_head.weight"]

    def __init__(self, config):
        super().__init__(config)
        self.model = EmoModel(config)
        self.vocab_size = config.vocab_size
        self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)

        self.router_aux_loss_coef = config.router_aux_loss_coef
        self.num_experts = config.num_experts
        self.num_experts_per_tok = config.num_experts_per_tok
        # Initialize weights and apply final processing
        self.post_init()

    @auto_docstring
    def forward(
        self,
        input_ids: Optional[torch.LongTensor] = None,
        attention_mask: Optional[torch.Tensor] = None,
        position_ids: Optional[torch.LongTensor] = None,
        past_key_values: Optional[Cache] = None,
        inputs_embeds: Optional[torch.FloatTensor] = None,
        labels: Optional[torch.LongTensor] = None,
        use_cache: Optional[bool] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        output_router_logits: Optional[bool] = None,
        return_dict: Optional[bool] = None,
        cache_position: Optional[torch.LongTensor] = None,
        logits_to_keep: Union[int, torch.Tensor] = 0,
        **kwargs,
    ) -> Union[tuple, MoeCausalLMOutputWithPast]:
        r"""
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
            config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
            (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

        Example:

        ```python
        >>> from transformers import AutoTokenizer, EmoForCausalLM

        >>> model = EmoForCausalLM.from_pretrained("allenai/Emo-1B-7B-0924")
        >>> tokenizer = AutoTokenizer.from_pretrained("allenai/Emo-1B-7B-0924")

        >>> prompt = "Hey, are you conscious? Can you talk to me?"
        >>> inputs = tokenizer(prompt, return_tensors="pt")

        >>> # Generate
        >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
        >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
        'Hey, are you conscious? Can you talk to me?\nI’m not sure if you’re conscious of this, but I’m'
        ```
        """
        output_attentions = (
            output_attentions if output_attentions is not None else self.config.output_attentions
        )
        output_router_logits = (
            output_router_logits
            if output_router_logits is not None
            else self.config.output_router_logits
        )
        output_hidden_states = (
            output_hidden_states
            if output_hidden_states is not None
            else self.config.output_hidden_states
        )
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
        outputs = self.model(
            input_ids=input_ids,
            attention_mask=attention_mask,
            position_ids=position_ids,
            past_key_values=past_key_values,
            inputs_embeds=inputs_embeds,
            use_cache=use_cache,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            output_router_logits=output_router_logits,
            return_dict=return_dict,
            cache_position=cache_position,
        )

        hidden_states = outputs[0]
        # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
        slice_indices = (
            slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
        )
        logits = self.lm_head(hidden_states[:, slice_indices, :])

        loss = None
        ce_loss = None
        if labels is not None:
            ce_loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
            loss = ce_loss

        lb_loss = None

        if output_router_logits:
            # Get per-layer expert counts if available
            num_experts_per_layer = getattr(self.config, "num_experts_per_layer", None)
            num_shared_experts_per_layer = getattr(
                self.config, "num_shared_experts_per_layer", None
            )

            # Filter out dense layers (num_experts == 0) since they produce no router_logits
            if num_experts_per_layer is not None:
                moe_mask = [i for i, n in enumerate(num_experts_per_layer) if n > 0]
                num_experts_per_layer = [num_experts_per_layer[i] for i in moe_mask]
                if num_shared_experts_per_layer is not None:
                    num_shared_experts_per_layer = [
                        num_shared_experts_per_layer[i] for i in moe_mask
                    ]

            # Resolve always_active_experts for LB loss
            always_active_experts_per_layer_for_loss = getattr(
                self.config, "always_active_experts_per_layer", None
            )
            always_active_experts_for_loss = getattr(self.config, "always_active_experts", None)
            # Filter out dense layers if needed
            if (
                num_experts_per_layer is not None
                and always_active_experts_per_layer_for_loss is not None
            ):
                always_active_experts_per_layer_for_loss = [
                    always_active_experts_per_layer_for_loss[i] for i in moe_mask
                ]

            lb_loss = load_balancing_loss_func_olmoe(
                outputs.router_logits if return_dict else outputs[-1],
                self.num_experts,
                self.num_experts_per_tok,
                attention_mask,
                labels,
                num_shared_experts=self.config.num_shared_experts,
                num_experts_per_layer=num_experts_per_layer,
                num_shared_experts_per_layer=num_shared_experts_per_layer,
                always_active_experts=always_active_experts_for_loss,
                always_active_experts_per_layer=always_active_experts_per_layer_for_loss,
                **kwargs,
            )
            if labels is not None:
                assert isinstance(lb_loss, torch.Tensor)
                assert loss is not None
                loss += self.router_aux_loss_coef * lb_loss.to(
                    loss.device
                )  # make sure to reside in the same device

        if not return_dict:
            output = (logits,) + outputs[1:]
            if output_router_logits:
                output = (lb_loss,) + output
            return (loss,) + output if loss is not None else output

        return MoeCausalLMOutputWithPast(
            loss=loss,
            aux_loss=lb_loss,
            lb_loss=lb_loss.detach().clone()
            if isinstance(lb_loss, torch.Tensor)
            else None,  # for logging callback
            ce_loss=ce_loss.detach().clone()
            if ce_loss is not None
            else None,  # for logging callback
            logits=logits,
            past_key_values=outputs.past_key_values,
            hidden_states=outputs.hidden_states,
            attentions=outputs.attentions,
            router_logits=outputs.router_logits,
        )


__all__ = [
    "EmoForCausalLM",
    "EmoModel",
    "EmoPreTrainedModel",
]