-
Notifications
You must be signed in to change notification settings - Fork 71
/
bert.jl
1431 lines (1170 loc) · 52.4 KB
/
bert.jl
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
using ..Transformers: batchedmul, batched_triu!
# Bert specific initializers
FakeTHLinear(cfg::AbstractHGFConfig, args...; kwargs...) = FakeTHLinear(typeof(cfg), cfg, args...; kwargs...)
function FakeTHLinear(::Type{HGFBertConfig}, config, hi, ho; bias=true)
weight = randn(Float32, ho, hi) .* config.initializer_range
if bias
bias = zeros(Float32, ho)
else
bias = nothing
end
FakeTHLinear(weight, bias)
end
FakeTHEmbedding(cfg::AbstractHGFConfig, args...; kwargs...) = FakeTHEmbedding(typeof(cfg), cfg, args...; kwargs...)
function FakeTHEmbedding(::Type{HGFBertConfig}, config, num, dims; pad_idx=nothing)
weight = randn(Float32, dims, num) .* config.initializer_range
if !isnothing(pad_idx)
real_pad_idx = pad_idx+1
else
real_pad_idx = 0
end
FakeTHEmbedding(real_pad_idx, weight)
end
FakeTHLayerNorm(cfg::AbstractHGFConfig, args...; kwargs...) = FakeTHLayerNorm(typeof(cfg), cfg, args...; kwargs...)
function FakeTHLayerNorm(::Type{HGFBertConfig}, config, dims; eps::Float32=1e-05)
weight = ones(Float32, dims)
bias = zeros(Float32, dims)
FakeTHLayerNorm(eps, weight, bias)
end
# HGF Bert compounts
# embedding
struct HGFBertEmbeddings{
W<:FakeTHEmbedding,
P<:FakeTHEmbedding,
T<:FakeTHEmbedding,
L<:FakeTHLayerNorm
} <: THModule
LayerNorm::L
word_embeddings::W
position_embeddings::P
token_type_embeddings::T
end
@functor HGFBertEmbeddings
HGFBertEmbeddings(cfg::AbstractHGFConfig, args...; kwargs...) = HGFBertEmbeddings(typeof(cfg), cfg, args...; kwargs...)
function HGFBertEmbeddings(T::Type{HGFBertConfig}, config)
layernorm = FakeTHLayerNorm(T, config, config.hidden_size; eps=config.layer_norm_eps)
word_emb = FakeTHEmbedding(T, config, config.vocab_size,
config.hidden_size;
pad_idx=config.pad_token_id)
posi_emb = FakeTHEmbedding(T, config, config.max_position_embeddings,
config.hidden_size)
toke_emb = FakeTHEmbedding(T, config, config.type_vocab_size,
config.hidden_size)
HGFBertEmbeddings(layernorm, word_emb, posi_emb, toke_emb)
end
_arange(x, len) = cumsum(fill!(similar(x, Int, len), one(Int)))
Flux.@nograd _arange
@inline get_word_emb(be::HGFBertEmbeddings, input_ids::AbstractArray{<:Integer}) = be.word_embeddings(input_ids)
@inline get_word_emb(be::HGFBertEmbeddings, input_embed::AbstractArray{T}) where T = input_embed
@inline get_position_emb(be::HGFBertEmbeddings, inputs_embeds, ::Nothing) = get_position_emb(be, inputs_embeds, _arange(inputs_embeds, size(inputs_embeds)[end-1]))
@inline get_position_emb(be::HGFBertEmbeddings, inputs_embeds, position_ids) = be.position_embeddings(position_ids)
@inline get_token_type_emb(be::HGFBertEmbeddings, inputs_embeds, ::Nothing) = get_token_type_emb(be, inputs_embeds, fill!(similar(inputs_embeds, Int, Base.tail(size(inputs_embeds))), one(Int)))
@inline get_token_type_emb(be::HGFBertEmbeddings, inputs_embeds, token_type_ids) = be.token_type_embeddings(token_type_ids)
function (be::HGFBertEmbeddings)(input,
position_ids::Union{Nothing, AbstractArray{<:Integer}},
token_type_ids::Union{Nothing, AbstractArray{<:Integer}})
inputs_embeds = get_word_emb(be, input)
position_embeds = get_position_emb(be, inputs_embeds, position_ids)
token_type_embeds = get_token_type_emb(be, inputs_embeds, token_type_ids)
return be(inputs_embeds, position_embeds, token_type_embeds)
end
function (be::HGFBertEmbeddings)(inputs_embeds::AbstractArray{T},
position_embeds::AbstractArray{T},
token_type_embeds::AbstractArray{T}) where T
embeddings = (inputs_embeds .+ position_embeds) + token_type_embeds
embeddings = be.LayerNorm(embeddings)
return embeddings
end
(be::HGFBertEmbeddings)(input; position_ids=nothing, token_type_ids=nothing) = be(input, position_ids, token_type_ids)
# self attention part
struct HGFBertSelfAttention{
Q<:FakeTHLinear,
K<:FakeTHLinear,
V<:FakeTHLinear
} <: THModule
num_attention_heads::Int
query::Q
key::K
value::V
end
Functors.functor(::Type{<:HGFBertSelfAttention}, sa) = (query=sa.query, key=sa.key, value=sa.value), y->HGFBertSelfAttention(sa.num_attention_heads, y...)
function _split_tranpose_for_scores(x, num_head)
head_size = div(size(x, 1), num_head)
split_size = (head_size, num_head, size(x, 2), size(x, 3))
permute_order = (1, 3, 2, 4)
return reshape(x, split_size) |> Base.Fix2(permutedims, permute_order)
end
function _compute_attention_scores(query_layer, key_layer, attention_mask::Union{Nothing, <:AbstractArray})
attentions_scores = batchedmul(key_layer, query_layer; transA = true)
attentions_scores = attentions_scores ./ convert(eltype(attentions_scores), sqrt(size(key_layer, 1)))
!isnothing(attention_mask) &&
(attentions_scores = attentions_scores .+ attention_mask)
return attentions_scores
end
function _merge_transpose_for_output(x, num_head)
permute_order = (1, 3, 2, 4)
final_size = (:, size(x, 2), size(x, 4))
return permutedims(x, permute_order) |>
Base.Fix2(reshape, final_size)
end
function (sa::HGFBertSelfAttention)(hidden_states, attention_mask, output_attentions::Val)
mixed_query_layer = sa.query(hidden_states)
mixed_key_layer = sa.key(hidden_states)
mixed_value_layer = sa.value(hidden_states)
return sa(mixed_query_layer, mixed_key_layer, mixed_value_layer, attention_mask, output_attentions)
end
function (sa::HGFBertSelfAttention)(hidden_states, encoder_hidden_states, attention_mask, output_attentions::Val)
mixed_query_layer = sa.query(hidden_states)
mixed_key_layer = sa.key(encoder_hidden_states)
mixed_value_layer = sa.value(encoder_hidden_states)
return sa(mixed_query_layer, mixed_key_layer, mixed_value_layer, attention_mask, output_attentions)
end
function (sa::HGFBertSelfAttention)(mixed_query_layer, mixed_key_layer, mixed_value_layer,
attention_mask,
::Val{output_attentions}) where output_attentions
query_layer = _split_tranpose_for_scores(mixed_query_layer, sa.num_attention_heads)
key_layer = _split_tranpose_for_scores(mixed_key_layer, sa.num_attention_heads)
value_layer = _split_tranpose_for_scores(mixed_value_layer, sa.num_attention_heads)
attentions_scores = _compute_attention_scores(query_layer, key_layer, attention_mask)
attentions_probs = softmax(attentions_scores; dims=1)
mixed_context_layer = batchedmul(value_layer, attentions_probs)
context_layer = _merge_transpose_for_output(mixed_context_layer, sa.num_attention_heads)
if output_attentions
outputs = context_layer, attentions_probs
return outputs
else
return context_layer
end
end
HGFBertSelfAttention(cfg::AbstractHGFConfig, args...; kwargs...) = HGFBertSelfAttention(typeof(cfg), cfg, args...; kwargs...)
function HGFBertSelfAttention(T::Type{HGFBertConfig}, config)
attention_head_size = config.hidden_size ÷ config.num_attention_heads
all_head_size = config.num_attention_heads * attention_head_size
query = FakeTHLinear(T, config, config.hidden_size, all_head_size)
key = FakeTHLinear(T, config, config.hidden_size, all_head_size)
value = FakeTHLinear(T, config, config.hidden_size, all_head_size)
HGFBertSelfAttention(config.num_attention_heads, query, key, value)
end
# self attention output part
struct HGFBertSelfOutput{
L<:FakeTHLayerNorm,
D<:FakeTHLinear
} <: THModule
LayerNorm::L
dense::D
end
@functor HGFBertSelfOutput
function (so::HGFBertSelfOutput)(hidden_states, input_tensor)
hidden_states = so.dense(hidden_states)
hidden_states = so.LayerNorm(hidden_states + input_tensor)
return hidden_states
end
HGFBertSelfOutput(cfg::AbstractHGFConfig, args...; kwargs...) = HGFBertSelfOutput(typeof(cfg), cfg, args...; kwargs...)
function HGFBertSelfOutput(T::Type{HGFBertConfig}, config)
layernorm = FakeTHLayerNorm(T, config, config.hidden_size; eps=config.layer_norm_eps)
dense = FakeTHLinear(T, config, config.hidden_size, config.hidden_size)
HGFBertSelfOutput(layernorm, dense)
end
# self attention
struct HGFBertAttention{
S<:HGFBertSelfAttention,
O<:HGFBertSelfOutput
} <: THModule
self::S
output::O
end
@functor HGFBertAttention
function (a::HGFBertAttention)(hidden_states,
attention_mask::Union{Nothing, <:AbstractArray},
_output_attentions::Val{output_attentions}) where output_attentions
self_output = a.self(hidden_states, attention_mask, _output_attentions)
if output_attentions
output, attention_prob = self_output
attention_output = a.output(output, hidden_states)
return attention_output, attention_prob
else
attention_output = a.output(self_output, hidden_states)
return attention_output
end
end
HGFBertAttention(cfg::AbstractHGFConfig, args...; kwargs...) = HGFBertAttention(typeof(cfg), cfg, args...; kwargs...)
function HGFBertAttention(T::Type{HGFBertConfig}, config)
self = HGFBertSelfAttention(T, config)
output = HGFBertSelfOutput(T, config)
HGFBertAttention(self, output)
end
# positionwise first dense
struct HGFBertIntermediate{F, D<:FakeTHLinear} <: THModule
intermediate_act::F
dense::D
end
Functors.functor(::Type{<:HGFBertIntermediate}, intermediate) = (dense = intermediate.dense,), y->HGFBertIntermediate(intermediate.intermediate_act, y...)
(i::HGFBertIntermediate)(hidden_states) = i.intermediate_act.(i.dense(hidden_states))
HGFBertIntermediate(cfg::AbstractHGFConfig, args...; kwargs...) = HGFBertIntermediate(typeof(cfg), cfg, args...; kwargs...)
function HGFBertIntermediate(T::Type{HGFBertConfig}, config)
global ACT2FN
act = ACT2FN[Symbol(config.hidden_act)]
dense = FakeTHLinear(T, config, config.hidden_size, config.intermediate_size)
HGFBertIntermediate(act, dense)
end
# positionwise second dense
struct HGFBertOutput{
D<:FakeTHLinear,
L<:FakeTHLayerNorm
} <: THModule
dense::D
LayerNorm::L
end
@functor HGFBertOutput
function (o::HGFBertOutput)(hidden_states, input_tensor)
hidden_states = o.dense(hidden_states)
hidden_states = o.LayerNorm(hidden_states + input_tensor)
return hidden_states
end
HGFBertOutput(cfg::AbstractHGFConfig, args...; kwargs...) = HGFBertOutput(typeof(cfg), cfg, args...; kwargs...)
function HGFBertOutput(T::Type{HGFBertConfig}, config)
dense = FakeTHLinear(T, config, config.intermediate_size, config.hidden_size)
layernorm = FakeTHLayerNorm(T, config, config.hidden_size; eps=config.layer_norm_eps)
HGFBertOutput(dense, layernorm)
end
# transformer layer
struct HGFBertLayer{DEC<:Union{Nothing, HGFBertAttention},
A<:HGFBertAttention,
I<:HGFBertIntermediate,
O<:HGFBertOutput
} <: THModule
attention::A
crossattention::DEC
intermediate::I
output::O
end
HGFBertLayer(a, i, o) = HGFBertLayer(a, nothing, i, o)
_is_decode(::HGFBertLayer{Nothing}) = false
_is_decode(::HGFBertLayer) = true
Functors.functor(::Type{<:HGFBertLayer}, layer) = (!_is_decode(layer) ?
(attention = layer.attention, intermediate = layer.intermediate, output = layer.output) :
(attention = layer.attention, crossattention = layer.crossattention, intermediate = layer.intermediate, output = layer.output)),
y ->HGFBertLayer(y...)
function (l::HGFBertLayer{Nothing})(hidden_states, attention_mask::Union{Nothing, <:AbstractArray},
_output_attentions::Val{output_attentions}) where output_attentions
if output_attentions
attention_output, attention_prob = l.attention(hidden_states, attention_mask, _output_attentions)
else
attention_output = l.attention(hidden_states, attention_mask, _output_attentions)
end
intermediate_output = l.intermediate(attention_output)
layer_output = l.output(intermediate_output, attention_output)
if output_attentions
return layer_output, attention_prob
else
return layer_output
end
end
function (l::HGFBertLayer)(hidden_states, attention_mask,
encoder_hidden_states, encoder_attention_mask,
_output_attentions::Val{output_attentions}) where output_attentions
if output_attentions
attention_output, attention_prob = l.attention(hidden_states, attention_mask, _output_attentions)
attention_output, cross_attention_prob = l.crossattention(attention_output, encoder_attention_mask, _output_attentions)
else
attention_output = l.attention(hidden_states, attention_mask, _output_attentions)
attention_output = l.crossattention(attention_output, encoder_hidden_states, encoder_attention_mask, _output_attentions)
end
intermediate_output = l.intermediate(attention_output)
layer_output = l.output(intermediate_output, attention_output)
if output_attentions
return layer_output, attention_prob, cross_attention_prob
else
return layer_output
end
end
HGFBertLayer(cfg::AbstractHGFConfig, args...; kwargs...) = HGFBertLayer(typeof(cfg), cfg, args...; kwargs...)
function HGFBertLayer(T::Type{HGFBertConfig}, config)
attention = HGFBertAttention(T, config)
crossattention = config.is_decoder ?
HGFBertAttention(T, config) :
nothing
intermediate = HGFBertIntermediate(T, config)
output = HGFBertOutput(T, config)
HGFBertLayer(attention, crossattention, intermediate, output)
end
# stacked transformers
struct HGFBertEncoder{N, L<:FakeTHModuleList{N}} <: THModule
layer::L
end
@functor HGFBertEncoder
(e::HGFBertEncoder)(hidden_states;
attention_mask = nothing,
output_attentions = false,
output_hidden_states = false
) = e(hidden_states, attention_mask, Val(output_attentions), Val(output_hidden_states))
@generated function (e::HGFBertEncoder{N})(hidden_states, attention_mask,
_output_attentions::Val{output_attentions},
_output_hidden_states::Val{output_hidden_states}
) where {N, output_attentions, output_hidden_states}
if output_attentions
all_attentions = Expr(:tuple)
end
if output_hidden_states
all_hidden_states = Expr(:tuple, :hidden_states)
end
body = Expr[]
for i = 1:N
previous = i == 1 ? :hidden_states : Symbol(:hidden_states, i-1)
current = Symbol(:hidden_states, i)
if output_attentions
current_attention = Symbol(:attention_, i)
current_output = :($current, $current_attention)
else
current_output = current
end
expr = :($current_output = e.layer[$i]($previous, attention_mask, _output_attentions))
push!(body, expr)
if output_attentions
push!(all_attentions.args, current_attention)
end
if output_hidden_states
push!(all_hidden_states.args, current)
end
end
current = Symbol(:hidden_states, N)
if output_attentions
push!(body, :(all_attentions = $all_attentions))
else
push!(body, :(all_attentions = nothing))
end
if output_hidden_states
push!(body, :(all_hidden_states = $all_hidden_states))
else
push!(body, :(all_hidden_states = nothing))
end
return quote
$(body...)
return (
last_hidden_state = $current,
hidden_states = all_hidden_states,
attentions = all_attentions
)
end
end
(e::HGFBertEncoder)(hidden_states, encoder_hidden_states;
attention_mask = nothing,
encoder_mask = nothing,
output_attentions = false,
output_hidden_states = false
) = e(hidden_states, attention_mask,
encoder_hidden_states, encoder_mask,
Val(output_attentions), Val(output_hidden_states))
@generated function (e::HGFBertEncoder{N})(hidden_states, attention_mask,
encoder_hidden_states, encoder_mask,
_output_attentions::Val{output_attentions},
_output_hidden_states::Val{output_hidden_states}
) where {N, output_attentions, output_hidden_states}
if output_attentions
all_attentions = Expr(:tuple)
end
if output_hidden_states
all_hidden_states = Expr(:tuple, :hidden_states)
end
body = Expr[]
for i = 1:N
previous = i == 1 ? :hidden_states : Symbol(:hidden_states, i-1)
current = Symbol(:hidden_states, i)
if output_attentions
current_attention = Symbol(:attention_, i)
current_output = :($current, $current_attention)
else
current_output = current
end
expr = :($current_output = e.layer[$i]($previous, attention_mask,
encoder_hidden_states, encoder_mask,
_output_attentions))
push!(body, expr)
if output_attentions
push!(all_attentions.args, current_attention)
end
if output_hidden_states
push!(all_hidden_states.args, current)
end
end
current = Symbol(:hidden_states, N)
if output_attentions
push!(body, :(all_attentions = $all_attentions))
else
push!(body, :(all_attentions = nothing))
end
if output_hidden_states
push!(body, :(all_hidden_states = $all_hidden_states))
else
push!(body, :(all_hidden_states = nothing))
end
return quote
$(body...)
return (
last_hidden_state = $current,
hidden_states = all_hidden_states,
attentions = all_attentions
)
end
end
HGFBertEncoder(cfg::AbstractHGFConfig, args...; kwargs...) = HGFBertEncoder(typeof(cfg), cfg, args...; kwargs...)
function HGFBertEncoder(T::Type{HGFBertConfig}, config)
layer = FakeTHModuleList(
[HGFBertLayer(T, config) for _ in 1:config.num_hidden_layers]
)
HGFBertEncoder(layer)
end
# classify token projection
struct HGFBertPooler{D<:FakeTHLinear} <: THModule
dense::D
end
@functor HGFBertPooler
function (p::HGFBertPooler)(hidden_states)
first_token_tensor = hidden_states[:, 1, :]
pooled_output = tanh.(p.dense(first_token_tensor))
return pooled_output
end
HGFBertPooler(cfg::AbstractHGFConfig, args...; kwargs...) = HGFBertPooler(typeof(cfg), cfg, args...; kwargs...)
function HGFBertPooler(T::Type{HGFBertConfig}, config)
dense = FakeTHLinear(T, config, config.hidden_size, config.hidden_size)
HGFBertPooler(dense)
end
# label prediction layer
struct HGFBertPredictionHeadTransform{
F,
D<:FakeTHLinear,
L<:FakeTHLayerNorm
} <: THModule
transform_act_fn::F
dense::D
LayerNorm::L
end
@functor HGFBertPredictionHeadTransform
function (pht::HGFBertPredictionHeadTransform)(hidden_states)
hidden_states = pht.dense(hidden_states)
hidden_states = pht.transform_act_fn.(hidden_states)
hidden_states = pht.LayerNorm(hidden_states)
return hidden_states
end
function HGFBertPredictionHeadTransform(config::HGFBertConfig)
global ACT2FN
dense = FakeTHLinear(config, config.hidden_size, config.hidden_size)
act = ACT2FN[Symbol(config.hidden_act)]
layernorm = FakeTHLayerNorm(config, config.hidden_size; eps=config.layer_norm_eps)
return HGFBertPredictionHeadTransform(act, dense, layernorm)
end
# language model prediction layer
struct HGFBertLMPredictionHead{
B<:AbstractArray,
T<:HGFBertPredictionHeadTransform,
D<:FakeTHLinear
} <: THModule
transform::T
decoder::D
bias::B
end
@functor HGFBertLMPredictionHead
function (ph::HGFBertLMPredictionHead)(hidden_states)
hidden_states = ph.transform(hidden_states)
hidden_states = ph.decoder(hidden_states) .+ ph.bias
return hidden_states
end
function HGFBertLMPredictionHead(config::HGFBertConfig; input_embedding=nothing)
trans = HGFBertPredictionHeadTransform(config)
if isnothing(input_embedding)
decoder = FakeTHLinear(config, config.hidden_size, config.vocab_size; bias=false)
else
decoder = FakeTHLinear(Transpose(input_embedding), nothing)
end
bias = zeros(Float32, config.vocab_size)
return HGFBertLMPredictionHead(trans, decoder, bias)
end
# language model prediction wrapper
struct HGFBertOnlyMLMHead{P<:HGFBertLMPredictionHead} <: THModule
predictions::P
end
@functor HGFBertOnlyMLMHead
(h::HGFBertOnlyMLMHead)(sequence_output) = h.predictions(sequence_output)
function HGFBertOnlyMLMHead(config::HGFBertConfig; input_embedding=nothing)
predictions = HGFBertLMPredictionHead(config; input_embedding=input_embedding)
return HGFBertOnlyMLMHead(predictions)
end
# next sentence prediction layer
struct HGFBertOnlyNSPHead{S<:FakeTHLinear} <: THModule
seq_relationship::S
end
@functor HGFBertOnlyNSPHead
(h::HGFBertOnlyNSPHead)(pooled_output) = h.seq_relationship(pooled_output)
function HGFBertOnlyNSPHead(config::HGFBertConfig)
seq_relationship = FakeTHLinear(config, config.hidden_size, 2)
return HGFBertOnlyNSPHead(seq_relationship)
end
# pretrain prediction layers
struct HGFBertPreTrainingHeads{
P<:HGFBertLMPredictionHead,
S<:FakeTHLinear
} <: THModule
predictions::P
seq_relationship::S
end
@functor HGFBertPreTrainingHeads
(pth::HGFBertPreTrainingHeads)(sequence_output, pooled_output) = pth.predictions(sequence_output), pth.seq_relationship(pooled_output)
function HGFBertPreTrainingHeads(config::HGFBertConfig; input_embedding=nothing)
predictions = HGFBertLMPredictionHead(config; input_embedding=input_embedding)
seq_relationship = FakeTHLinear(config, config.hidden_size, 2)
return HGFBertPreTrainingHeads(predictions, seq_relationship)
end
# bert model without prediction
abstract type HGFBertPreTrainedModel <: HGFPreTrainedModel end
struct HGFBertModel{
E<:HGFBertEmbeddings,
T<:HGFBertEncoder,
P<:HGFBertPooler
} <: HGFBertPreTrainedModel
embeddings::E
encoder::T
pooler::P
end
@functor HGFBertModel
function maybe_prepare_mask(embedding_output, ::Nothing)
mask_size = size(embedding_output) |> Base.tail
fill!(similar(embedding_output, mask_size), 1) |> maybe_prepare_mask
end
maybe_prepare_mask(embedding_output, attention_mask) = maybe_prepare_mask(attention_mask)
maybe_prepare_mask(embedding_output, attention_mask::AbstractArray{T, 4}) where T = attention_mask
function maybe_prepare_mask(attention_mask::AbstractArray{T, 3}) where T
seq_len1, seq_len2, batch_size = size(attention_mask)
attention_mask = reshape(attention_mask, seq_len1, seq_len2, 1, batch_size)
return attention_mask
end
function maybe_prepare_mask(attention_mask::AbstractMatrix)
seq_len, batch_size = size(attention_mask)
attention_mask = reshape(attention_mask, seq_len, 1, 1, batch_size)
return attention_mask
end
function create_attention_mask(attention_mask::AbstractArray{T, 4}) where T
return (one(T) .- attention_mask) .* convert(T, -10000)
end
function create_attention_mask(embedding_output, attention_mask)
attention_mask = maybe_prepare_mask(embedding_output, attention_mask)
create_attention_mask(attention_mask)
end
maybe_prepare_causal_mask(embedding_output, attention_mask::AbstractArray{T, 4}) where T = attention_mask
maybe_prepare_causal_mask(embedding_output, attention_mask::AbstractArray{T, 3}) where T = maybe_prepare_mask(embedding_output, attention_mask)
function maybe_prepare_causal_mask(embedding_output, attention_mask::Union{Nothing, AbstractMatrix})
regular_mask = maybe_prepare_mask(embedding_output, attention_mask) # seq_len, 1, 1, b
attention_mask = permutedims(regular_mask, (2,1,3,4)) .* regular_mask # seq_len, seq_len, 1, b
return attention_mask
end
function create_causal_attention_mask(embedding_output, attention_mask)
attention_mask = maybe_prepare_causal_mask(embedding_output, attention_mask)
batched_triu!(attention_mask, 0)
return create_attention_mask(attention_mask)
end
Flux.@nograd create_attention_mask
Flux.@nograd create_causal_attention_mask
(bm::HGFBertModel)(input; position_ids = nothing, token_type_ids = nothing,
attention_mask = nothing,
output_attentions = false,
output_hidden_states = false
) = bm(input, position_ids, token_type_ids, attention_mask,
Val(output_attentions), Val(output_hidden_states))
function (bm::HGFBertModel)(
input, position_ids, token_type_ids,
attention_mask,
_output_attentions::Val{output_attentions},
_output_hidden_states::Val{output_hidden_states}
) where {output_attentions, output_hidden_states}
embedding_output = bm.embeddings(input, position_ids, token_type_ids)
attention_mask = create_attention_mask(embedding_output, attention_mask)
encoder_outputs = bm.encoder(embedding_output, attention_mask,
_output_attentions, _output_hidden_states)
sequence_output = encoder_outputs.last_hidden_state
pooled_output = bm.pooler(sequence_output)
return (
last_hidden_state = sequence_output,
pooler_output = pooled_output,
hidden_states = encoder_outputs.hidden_states,
attentions = encoder_outputs.attentions
)
end
(bm::HGFBertModel)(input, encoder_hidden_states;
position_ids = nothing, token_type_ids = nothing,
attention_mask = nothing, encoder_attention_mask = nothing,
output_attentions = false,
output_hidden_states = false
) = bm(input, encoder_hidden_states,
position_ids, token_type_ids,
attention_mask, encoder_attention_mask,
Val(output_attentions), Val(output_hidden_states))
function (bm::HGFBertModel)(
input, encoder_hidden_states, position_ids, token_type_ids,
attention_mask, encoder_attention_mask,
_output_attentions::Val{output_attentions},
_output_hidden_states::Val{output_hidden_states}
) where {output_attentions, output_hidden_states}
embedding_output = bm.embeddings(input, position_ids, token_type_ids)
attention_mask = create_causal_attention_mask(embedding_output, attention_mask)
encoder_attention_mask = create_attention_mask(encoder_hidden_states, encoder_attention_mask)
encoder_outputs = bm.encoder(embedding_output, attention_mask,
encoder_hidden_states, encoder_attention_mask,
_output_attentions, _output_hidden_states)
sequence_output = encoder_outputs.last_hidden_state
pooled_output = bm.pooler(sequence_output)
return (
last_hidden_state = sequence_output,
pooler_output = pooled_output,
hidden_states = encoder_outputs.hidden_states,
attentions = encoder_outputs.attentions
)
end
function HGFBertModel(config::HGFBertConfig)
embeddings = HGFBertEmbeddings(config)
encoder = HGFBertEncoder(config)
pooler = HGFBertPooler(config)
HGFBertModel(embeddings, encoder, pooler)
end
get_input_embedding(model::HGFBertModel) = model.embeddings.word_embeddings.weight
# bert models for different task
# pretrain
struct HGFBertForPreTraining{B<:HGFBertModel, C<:HGFBertPreTrainingHeads} <: HGFBertPreTrainedModel
bert::B
cls::C
end
@functor HGFBertForPreTraining
(self::HGFBertForPreTraining)(input;
position_ids = nothing, token_type_ids = nothing,
attention_mask = nothing,
output_attentions = false,
output_hidden_states = false
) = self(input, position_ids, token_type_ids,
attention_mask,
Val(output_attentions), Val(output_hidden_states))
function (self::HGFBertForPreTraining)(input, position_ids, token_type_ids,
attention_mask,
_output_attentions::Val{output_attentions},
_output_hidden_states::Val{output_hidden_states}
) where {output_attentions, output_hidden_states}
outputs = self.bert(input, position_ids, token_type_ids,
attention_mask, _output_attentions, _output_hidden_states)
sequence_output, pooled_output = outputs
prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)
total_loss = nothing
return (
loss = total_loss,
prediction_logits = prediction_scores,
seq_relationship_logits = seq_relationship_score,
hidden_states = outputs.hidden_states,
attentions = outputs.attentions
)
end
(self::HGFBertForPreTraining)(input, labels, next_sentence_label;
position_ids = nothing, token_type_ids = nothing,
attention_mask = nothing,
output_attentions = false,
output_hidden_states = false
) = self(input, labels, next_sentence_label,
position_ids, token_type_ids,
attention_mask,
Val(output_attentions), Val(output_hidden_states))
function (self::HGFBertForPreTraining)(input, labels, next_sentence_label,
position_ids, token_type_ids,
attention_mask,
_output_attentions::Val{output_attentions},
_output_hidden_states::Val{output_hidden_states}
) where {output_attentions, output_hidden_states}
outputs = self(input, position_ids, token_type_ids, attention_mask,
_output_attentions, _output_hidden_states)
prediction_scores = outputs.prediction_logits
seq_relationship_score = outputs.seq_relationship_logits
masked_lm_loss = Flux.logitcrossentropy(prediction_scores, labels)
next_sentence_loss = Flux.logitcrossentropy(seq_relationship_score, next_sentence_label)
total_loss = masked_lm_loss + next_sentence_loss
return (
loss = total_loss,
prediction_logits = prediction_scores,
seq_relationship_logits = seq_relationship_score,
hidden_states = outputs.hidden_states,
attentions = outputs.attentions
)
end
function HGFBertForPreTraining(config::HGFBertConfig)
bert = HGFBertModel(config)
input_embedding = get_input_embedding(bert)
cls = HGFBertPreTrainingHeads(config; input_embedding=input_embedding)
return HGFBertForPreTraining(bert, cls)
end
# clm finetune
struct HGFBertLMHeadModel{B<:HGFBertModel, C<:HGFBertOnlyMLMHead} <: HGFBertPreTrainedModel
bert::B
cls::C
end
@functor HGFBertLMHeadModel
(self::HGFBertLMHeadModel)(input;
position_ids = nothing, token_type_ids = nothing,
attention_mask = nothing,
output_attentions = false,
output_hidden_states = false
) = self(input, position_ids, token_type_ids,
attention_mask,
Val(output_attentions), Val(output_hidden_states))
function (self::HGFBertLMHeadModel)(input, position_ids, token_type_ids,
attention_mask,
_output_attentions::Val{output_attentions},
_output_hidden_states::Val{output_hidden_states}
) where {output_attentions, output_hidden_states}
outputs = self.bert(input, position_ids, token_type_ids,
attention_mask, _output_attentions, _output_hidden_states)
sequence_output = outputs[1]
prediction_scores = self.cls(sequence_output)
lm_loss = nothing
return (
loss = lm_loss,
prediction_logits = prediction_scores,
hidden_states = outputs.hidden_states,
attentions = outputs.attentions
)
end
(self::HGFBertLMHeadModel)(input, labels;
position_ids = nothing, token_type_ids = nothing,
attention_mask = nothing,
output_attentions = false,
output_hidden_states = false
) = self(input, labels,
position_ids, token_type_ids,
attention_mask,
Val(output_attentions), Val(output_hidden_states))
function (self::HGFBertLMHeadModel)(input, labels,
position_ids, token_type_ids,
attention_mask,
_output_attentions::Val{output_attentions},
_output_hidden_states::Val{output_hidden_states}
) where {output_attentions, output_hidden_states}
outputs = self(input, position_ids, token_type_ids, attention_mask,
_output_attentions, _output_hidden_states)
prediction_scores = outputs.prediction_logits
shifted_prediction_scores = prediction_scores[:, 1:end-1, :]
shifted_labels = labels[:, 2:end]
lm_loss = Flux.logitcrossentropy(shifted_prediction_scores, shifted_labels)
return (
loss = lm_loss,
prediction_logits = prediction_scores,
hidden_states = outputs.hidden_states,
attentions = outputs.attentions
)
end
function HGFBertLMHeadModel(config::HGFBertConfig)
bert = HGFBertModel(config)
input_embedding = get_input_embedding(bert)
cls = HGFBertOnlyMLMHead(config; input_embedding=input_embedding)
return HGFBertLMHeadModel(bert, cls)
end
# maked lm
struct HGFBertForMaskedLM{B<:HGFBertModel, C<:HGFBertOnlyMLMHead} <: HGFBertPreTrainedModel
bert::B
cls::C
end
@functor HGFBertForMaskedLM
(self::HGFBertForMaskedLM)(input;
position_ids = nothing, token_type_ids = nothing,
attention_mask = nothing,
output_attentions = false,
output_hidden_states = false
) = self(input, position_ids, token_type_ids,
attention_mask,
Val(output_attentions), Val(output_hidden_states))
function (self::HGFBertForMaskedLM)(input, position_ids, token_type_ids,
attention_mask,
_output_attentions::Val{output_attentions},
_output_hidden_states::Val{output_hidden_states}
) where {output_attentions, output_hidden_states}
outputs = self.bert(input, position_ids, token_type_ids,
attention_mask, _output_attentions, _output_hidden_states)
sequence_output = outputs[1]
prediction_scores = self.cls(sequence_output)
masked_lm_loss = nothing
return (
loss = masked_lm_loss,
logits = prediction_scores,
hidden_states = outputs.hidden_states,
attentions = outputs.attentions
)
end
(self::HGFBertForMaskedLM)(input, labels;
position_ids = nothing, token_type_ids = nothing,
attention_mask = nothing,
output_attentions = false,
output_hidden_states = false
) = self(input, labels,
position_ids, token_type_ids,
attention_mask,
Val(output_attentions), Val(output_hidden_states))
function (self::HGFBertForMaskedLM)(input, labels,
position_ids, token_type_ids,
attention_mask,