-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExpG3Code.py
More file actions
1611 lines (1337 loc) · 88.9 KB
/
ExpG3Code.py
File metadata and controls
1611 lines (1337 loc) · 88.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Copyright (c) 2025 The ExpG3 Authors
All Rights Reserved.
PROPRIETARY AND CONFIDENTIAL
This software is the proprietary and confidential property of the copyright holder.
Possession and use of this software is strictly limited by the terms of a separate license agreement.
UNAUTHORIZED COPYING, DISTRIBUTION, OR USE OF THIS SOFTWARE, OR ANY PORTION OF IT, IS STRICTLY PROHIBITED.
This software is provided "as-is" without warranty of any kind, express or implied.
"""
# -*- coding: utf-8 -*-
"""
Experimental G3 Model Training Script
Refactored for cleaner code, better variable naming, and consistent Keras Model naming.
TPU-adapted, streaming FineWeb-Edu from Hugging Face Datasets, with text generation.
EOS token used for padding. Architectural change for memory gradient flow.
Memory-saving hyperparameters enabled for TPU testing.
Removed semicolons.
"""
import numpy as np
import tensorflow as tf
from tensorflow.keras import optimizers
import tqdm
from math import prod
import keras # Keras 3
keras.config.disable_traceback_filtering()
from tensorflow.keras import mixed_precision # Using tf.keras for mixed_precision
import time
import traceback
import os
import json
# Hugging Face Libraries
from datasets import load_dataset
from tokenizers import Tokenizer, models, trainers, pre_tokenizers, decoders, processors
from transformers import PreTrainedTokenizerFast
# --- Global flag to track TPU initialization ---
_TPU_INITIALIZED_IN_SESSION = False
_LAST_TPU_RESOLVER = None
def cleanup_tensorflow_runtimes():
"""Attempts to clean up TensorFlow and Keras states for re-running in same session."""
global _TPU_INITIALIZED_IN_SESSION, _LAST_TPU_RESOLVER
print("Attempting to clean up TensorFlow and Keras runtime state...")
try:
keras.backend.clear_session()
print("Keras session cleared.")
except Exception as e:
print(f"Error clearing Keras session: {e}")
try:
tf.compat.v1.reset_default_graph()
print("TensorFlow default graph reset.")
except Exception as e:
print(f"Error resetting default graph: {e}")
if _TPU_INITIALIZED_IN_SESSION and _LAST_TPU_RESOLVER is not None:
resolver_master_info = _LAST_TPU_RESOLVER.master() if _LAST_TPU_RESOLVER else 'N/A'
print(f"Note: Previous TPU resolver was {resolver_master_info}. "
"True TPU system shutdown from Python is complex and often not fully supported. "
"A kernel restart is the most reliable way to reset TPU state.")
_TPU_INITIALIZED_IN_SESSION = False
_LAST_TPU_RESOLVER = None
print("Cleanup attempt finished. For full reset, especially for TPUs, restart the kernel.")
# =========================================================================================
# = Mixed Precision Setup =
# =========================================================================================
policy_name = 'mixed_bfloat16'
try:
_ = tf.constant(1.0, dtype=tf.bfloat16)
print(f"Using {policy_name} policy.")
except Exception:
print(f"Warning: bfloat16 test failed. Falling back to mixed_float16.")
policy_name = 'mixed_float16'
policy = mixed_precision.Policy(policy_name)
mixed_precision.set_global_policy(policy)
print(f"Global mixed precision policy set to: {mixed_precision.global_policy().name}")
# Importing layers directly from keras (Keras 3)
from keras.layers import (
Input, LayerNormalization, Concatenate, TimeDistributed, DepthwiseConv1D, Conv2D,
Activation, Add, Dense, Lambda, Multiply, Conv1D, Embedding, AveragePooling1D
)
# =========================================================================================
# = Hyperparameters (TPU Adjusted) =
# =========================================================================================
VOCAB_SIZE_TARGET = 32000
EMBEDDING_DIM = 2048
MAX_SEQ_LEN = 512
NUM_REGISTERS = 512
MEMORY_DIM = EMBEDDING_DIM
# --- Memory Saving Configuration for TPU testing ---
NUM_MODEL_LAYERS = 6
NUM_MTP_HEADS = 0
SSM_STATE_DIM_MULTIPLIER = 1
# --- End Memory Saving Configuration ---
SSM_RANK_DIVISOR = 4
BATCH_SIZE_PER_REPLICA = 16
EPOCHS = 1
LEARNING_RATE = 1e-4
WARMUP_STEPS = 10
CLIP_NORM = 1.0
TOKENIZER_SAVE_DIR = "./housecat_tokenizer_hf_fineweb_eos_pad"
TOKENIZER_CONFIG_FILENAME = "tokenizer.json"
PAD_TOKEN_ID = 0
EOS_TOKEN_ID = 1
ACTUAL_VOCAB_SIZE = VOCAB_SIZE_TARGET
HF_DATASET_NAME = "HuggingFaceFW/fineweb-edu"
HF_DATASET_SPLIT = "train"
SAMPLES_FOR_TOKENIZER_TRAINING = 10000
FORCE_RETRAIN_TOKENIZER = False
TOTAL_TRAIN_STEPS_CONFIG = 1
# =========================================================================================
# = Tokenizer Training & Loading
# =========================================================================================
def get_text_iterator_from_hf_stream(dataset_name, split, num_samples=None, text_column="text"):
print(f"Setting up text iterator for '{dataset_name}/{split}' for {num_samples or 'all'} samples.")
streamed_dataset = load_dataset(dataset_name, streaming=True, split=split, trust_remote_code=True)
count = 0
for example in streamed_dataset:
if text_column in example and example[text_column]:
yield example[text_column]
count += 1
if num_samples is not None and count >= num_samples:
print(f"Reached specified {num_samples} samples for iterator.")
break
elif num_samples is not None and count >= num_samples:
print(f"Reached specified {num_samples} samples (iterator might have empty items).")
break
if num_samples is not None and count < num_samples:
print(f"Warning: Text iterator yielded only {count} samples, less than requested {num_samples}.")
def train_and_save_tokenizer_if_needed(
text_iterator_fn,
target_vocab_size,
tokenizer_output_dir,
tokenizer_filename,
force_retrain=False
):
global PAD_TOKEN_ID, EOS_TOKEN_ID
os.makedirs(tokenizer_output_dir, exist_ok=True)
config_file_path = os.path.join(tokenizer_output_dir, tokenizer_filename)
if not force_retrain and os.path.exists(config_file_path):
print(f"Tokenizer already trained. Loading from {config_file_path}")
try:
tokenizer_object = Tokenizer.from_file(config_file_path)
loaded_eos_id = tokenizer_object.token_to_id("[EOS]")
EOS_TOKEN_ID = loaded_eos_id if loaded_eos_id is not None else 2
PAD_TOKEN_ID = EOS_TOKEN_ID
print(f"Successfully loaded tokenizer. EOS ID: {EOS_TOKEN_ID}, PAD ID (set to EOS): {PAD_TOKEN_ID}")
return tokenizer_object
except Exception as e:
print(f"Error loading existing tokenizer from '{config_file_path}': {e}. Will attempt to retrain.")
print("--- Starting New Tokenizer Training ---")
tokenizer_object = Tokenizer(models.BPE())
tokenizer_object.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
tokenizer_object.decoder = decoders.ByteLevel()
tokenizer_object.post_processor = processors.ByteLevel(trim_offsets=True)
special_tokens_list = ["[UNK]", "[EOS]", "[MASK]", "[PAD]"]
bpe_trainer = trainers.BpeTrainer(
vocab_size=target_vocab_size,
min_frequency=2,
show_progress=True,
special_tokens=special_tokens_list
)
print("Requesting text corpus iterator for tokenizer training...")
text_corpus_iterator = text_iterator_fn()
print("Starting tokenizer.train_from_iterator()...")
training_start_time = time.time()
try:
tokenizer_object.train_from_iterator(text_corpus_iterator, trainer=bpe_trainer)
except Exception as e:
print(f"ERROR during tokenizer training from iterator: {e}")
print(traceback.format_exc())
return None
training_end_time = time.time()
print(f"Tokenizer training completed in {training_end_time - training_start_time:.2f} seconds.")
trained_eos_id = tokenizer_object.token_to_id("[EOS]")
if trained_eos_id is None:
print("Warning: [EOS] token not found in trained tokenizer vocab! Adding it.")
tokenizer_object.add_special_tokens(["[EOS]"])
trained_eos_id = tokenizer_object.token_to_id("[EOS]")
if trained_eos_id is None:
print("CRITICAL: Still cannot find [EOS] token after adding. Defaulting EOS ID to 2.")
EOS_TOKEN_ID = 2
else:
EOS_TOKEN_ID = trained_eos_id
else:
EOS_TOKEN_ID = trained_eos_id
PAD_TOKEN_ID = EOS_TOKEN_ID
print(f"EOS ID: {EOS_TOKEN_ID}, PAD ID (set to EOS): {PAD_TOKEN_ID} (from newly trained tokenizer)")
tokenizer_object.save(config_file_path)
print(f"Tokenizer saved to {config_file_path}")
return tokenizer_object
tokenizer = None # Global tokenizer instance, initialized by initialize_tokenizer()
def initialize_tokenizer():
global tokenizer, EOS_TOKEN_ID, PAD_TOKEN_ID, ACTUAL_VOCAB_SIZE
print("--- Tokenizer Initialization ---")
tokenizer_config_path = os.path.join(TOKENIZER_SAVE_DIR, TOKENIZER_CONFIG_FILENAME)
if SAMPLES_FOR_TOKENIZER_TRAINING > 0:
print(f"Attempting to train tokenizer on first {SAMPLES_FOR_TOKENIZER_TRAINING} samples from HF stream.")
hf_tokenizer_object = train_and_save_tokenizer_if_needed(
text_iterator_fn=lambda: get_text_iterator_from_hf_stream(
HF_DATASET_NAME, HF_DATASET_SPLIT, SAMPLES_FOR_TOKENIZER_TRAINING
),
target_vocab_size=VOCAB_SIZE_TARGET,
tokenizer_output_dir=TOKENIZER_SAVE_DIR,
tokenizer_filename=TOKENIZER_CONFIG_FILENAME,
force_retrain=FORCE_RETRAIN_TOKENIZER
)
else:
print("Skipping tokenizer training from stream as SAMPLES_FOR_TOKENIZER_TRAINING is not positive.")
hf_tokenizer_object = None
if os.path.exists(tokenizer_config_path):
try:
hf_tokenizer_object = Tokenizer.from_file(tokenizer_config_path)
loaded_eos_id = hf_tokenizer_object.token_to_id("[EOS]")
EOS_TOKEN_ID = loaded_eos_id if loaded_eos_id is not None else 2
PAD_TOKEN_ID = EOS_TOKEN_ID
print(f"Successfully loaded pre-trained tokenizer from {tokenizer_config_path}.")
except Exception as e:
print(f"Failed to load pre-trained tokenizer from {tokenizer_config_path}: {e}")
hf_tokenizer_object = None
else:
print(f"Pre-trained tokenizer file not found at {tokenizer_config_path}.")
if hf_tokenizer_object is None:
print("CRITICAL: Tokenizer object (from huggingface/tokenizers) is unavailable. Cannot proceed.")
return
tokenizer = PreTrainedTokenizerFast(
tokenizer_object=hf_tokenizer_object,
eos_token="[EOS]",
unk_token="[UNK]",
mask_token="[MASK]",
pad_token="[EOS]"
)
EOS_TOKEN_ID = tokenizer.eos_token_id if tokenizer.eos_token_id is not None else 2
PAD_TOKEN_ID = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else EOS_TOKEN_ID
ACTUAL_VOCAB_SIZE = tokenizer.vocab_size
if EOS_TOKEN_ID != PAD_TOKEN_ID:
print(f"Warning: EOS_TOKEN_ID ({EOS_TOKEN_ID}) != PAD_TOKEN_ID ({PAD_TOKEN_ID}) after PreTrainedTokenizerFast init.")
print("Forcing PAD_TOKEN_ID to be the same as EOS_TOKEN_ID for model consistency.")
PAD_TOKEN_ID = EOS_TOKEN_ID
print(f"Tokenizer (PreTrainedTokenizerFast) ready. Actual Vocab Size: {ACTUAL_VOCAB_SIZE}, EOS ID: {EOS_TOKEN_ID}, PAD ID: {PAD_TOKEN_ID}")
# =========================================================================================
# = Keras Layers
# =========================================================================================
class FourierFeatures(keras.layers.Layer):
def __init__(self, embedding_dimension, name="fourier_features", **kwargs):
super().__init__(name=name, **kwargs)
self.embedding_dimension = embedding_dimension
def call(self, inputs_tensor):
input_tensor_shape = tf.shape(inputs_tensor)
batch_size = input_tensor_shape[0]
sequence_length = input_tensor_shape[1]
position_indices = tf.range(sequence_length, dtype=tf.float32)[:, None]
half_embedding_dimension = self.embedding_dimension // 2
div_term_denominator = tf.cast(half_embedding_dimension, tf.float32)
div_term_values = tf.pow(10000.0, tf.range(0, half_embedding_dimension, dtype=tf.float32) / div_term_denominator)
angle_values = position_indices / div_term_values
fourier_components = tf.concat([tf.sin(angle_values), tf.cos(angle_values)], axis=-1)
if self.embedding_dimension % 2 != 0:
fourier_components = tf.pad(fourier_components, [[0, 0], [0, 1]])
expanded_fourier_components = tf.expand_dims(fourier_components, 0)
tiled_fourier_features = tf.tile(expanded_fourier_components, [batch_size, 1, 1])
return tf.cast(tiled_fourier_features, dtype=inputs_tensor.dtype)
def get_config(self):
config = super().get_config()
config.update({"embedding_dimension": self.embedding_dimension})
return config
class FusedPositionalEncoding(keras.layers.Layer):
def __init__(self, embedding_dimension, max_sequence_length, dynamic_rope=False, name="fused_positional_encoding", **kwargs):
super().__init__(name=name, **kwargs)
self.embedding_dimension = embedding_dimension
self.max_sequence_length = max_sequence_length
self.dynamic_rope = dynamic_rope
if self.embedding_dimension % 2 != 0:
raise ValueError(f"Embedding dimension ({self.embedding_dimension}) must be even for RoPE.")
def build(self, input_tensor_shape):
if not self.dynamic_rope:
inverse_frequencies = self._compute_inverse_frequencies()
positions_range = tf.range(self.max_sequence_length, dtype=inverse_frequencies.dtype)
scaled_time_values = tf.einsum('i,j->ij', positions_range, inverse_frequencies)
rope_embeddings_precomputed = tf.concat([tf.sin(scaled_time_values), tf.cos(scaled_time_values)], axis=-1)
self.static_rope_frequencies = self.add_weight(
name="static_rope_frequencies_weight",
shape=rope_embeddings_precomputed.shape,
dtype=self.dtype_policy.variable_dtype,
initializer=keras.initializers.Constant(tf.cast(rope_embeddings_precomputed, self.dtype_policy.variable_dtype)),
trainable=False
)
self.global_positional_embedding_layer = Embedding(
input_dim=self.max_sequence_length,
output_dim=self.embedding_dimension,
name="global_positional_embedding_lookup"
)
if not self.global_positional_embedding_layer.built:
self.global_positional_embedding_layer.build(tf.TensorShape((None, self.max_sequence_length)))
super().build(input_tensor_shape)
def _compute_inverse_frequencies(self):
half_dimension = self.embedding_dimension // 2
thermostat_base = 10000.0
exponent_values = (tf.range(0, half_dimension, dtype=tf.float32) * 2.0) / tf.cast(self.embedding_dimension, tf.float32)
return 1.0 / (thermostat_base ** exponent_values)
def _apply_rotary_embeddings(self, query_tensor, rope_embeddings_for_sequence):
query_dtype = query_tensor.dtype
rope_embeddings_for_sequence = tf.cast(rope_embeddings_for_sequence, query_dtype)
query_tf_shape = tf.shape(query_tensor)
batch_size, sequence_length = query_tf_shape[0], query_tf_shape[1]
half_dimension = self.embedding_dimension // 2
query_reshaped_for_rotation = tf.reshape(query_tensor, [batch_size, sequence_length, half_dimension, 2])
query_real_parts = query_reshaped_for_rotation[..., 0]
query_imag_parts = query_reshaped_for_rotation[..., 1]
sin_terms, cos_terms = tf.split(rope_embeddings_for_sequence, num_or_size_splits=2, axis=-1)
sin_terms_broadcast = sin_terms[None, :, :]
cos_terms_broadcast = cos_terms[None, :, :]
rotated_real_parts = query_real_parts * cos_terms_broadcast - query_imag_parts * sin_terms_broadcast
rotated_imag_parts = query_real_parts * sin_terms_broadcast + query_imag_parts * cos_terms_broadcast
rotated_query_stacked = tf.stack([rotated_real_parts, rotated_imag_parts], axis=-1)
return tf.reshape(rotated_query_stacked, query_tf_shape)
def call(self, sequence_input_tensor):
input_tf_shape = tf.shape(sequence_input_tensor)
batch_size, current_sequence_len = input_tf_shape[0], input_tf_shape[1]
if self.dynamic_rope:
inv_freqs = self._compute_inverse_frequencies()
pos_range = tf.range(current_sequence_len, dtype=inv_freqs.dtype)
scaled_time_vals = tf.einsum('i,j->ij', pos_range, inv_freqs)
rope_embeddings_current_seq = tf.concat([tf.sin(scaled_time_vals), tf.cos(scaled_time_vals)], axis=-1)
else:
rope_embeddings_current_seq = self.static_rope_frequencies[:current_sequence_len, :]
sequence_with_rope_applied = self._apply_rotary_embeddings(sequence_input_tensor, rope_embeddings_current_seq)
position_indices_for_gpe = tf.range(current_sequence_len)
batched_indices_for_gpe = tf.tile(position_indices_for_gpe[None, :], [batch_size, 1])
global_positional_values = self.global_positional_embedding_layer(batched_indices_for_gpe)
return sequence_with_rope_applied + tf.cast(global_positional_values, sequence_input_tensor.dtype)
def get_config(self):
config = super().get_config()
config.update({
"embedding_dimension": self.embedding_dimension,
"max_sequence_length": self.max_sequence_length,
"dynamic_rope": self.dynamic_rope
})
return config
class ConditionalAveragePooling1D(keras.layers.Layer):
def __init__(self, pool_size=2, strides=2, padding_if_pool='SAME', name="conditional_avg_pool", **kwargs):
super().__init__(name=name, **kwargs)
self.pool_size = pool_size
self.strides = strides
self.padding_if_pool = padding_if_pool.upper()
self.avg_pooling_layer = AveragePooling1D(
pool_size=self.pool_size,
strides=self.strides,
padding=self.padding_if_pool
)
def call(self, inputs_tensor):
current_sequence_length = tf.shape(inputs_tensor)[1]
if self.padding_if_pool == 'SAME':
condition_to_skip_pooling_op = current_sequence_length <= 1
else: # 'VALID'
condition_to_skip_pooling_op = current_sequence_length < self.pool_size
return tf.cond(
condition_to_skip_pooling_op,
lambda: inputs_tensor,
lambda: self.avg_pooling_layer(inputs_tensor)
)
def get_config(self):
config = super().get_config()
config.update({
"pool_size": self.pool_size,
"strides": self.strides,
"padding_if_pool": self.padding_if_pool
})
return config
class ExpandDimsLayer(keras.layers.Layer):
def __init__(self, axis, name="expand_dims_layer", **kwargs):
super().__init__(name=name, **kwargs)
self.axis_to_expand = axis
def call(self, inputs_tensor): return tf.expand_dims(inputs_tensor, self.axis_to_expand)
def get_config(self):
config = super().get_config()
config.update({"axis": self.axis_to_expand})
return config
class SqueezeLayer(keras.layers.Layer):
def __init__(self, axis=None, name="squeeze_layer", **kwargs):
super().__init__(name=name, **kwargs)
self.axis_to_squeeze = axis
def call(self, inputs_tensor): return tf.squeeze(inputs_tensor, self.axis_to_squeeze)
def get_config(self):
config = super().get_config()
config.update({"axis": self.axis_to_squeeze})
return config
class CausalPadding1D(keras.layers.Layer):
def __init__(self, kernel_size, dilation_rate=1, name="causal_padding_1d", **kwargs):
super().__init__(name=name, **kwargs)
self.kernel_size = kernel_size
self.dilation_rate = dilation_rate
self.left_padding_amount = dilation_rate * (kernel_size - 1)
def call(self, inputs_tensor):
return tf.pad(inputs_tensor,[[0,0],[self.left_padding_amount,0],[0,0]])
def get_config(self):
config = super().get_config()
config.update({"kernel_size": self.kernel_size, "dilation_rate": self.dilation_rate})
return config
class CausalPadding2D(keras.layers.Layer):
def __init__(self, kernel_size_tuple, name="causal_padding_2d", **kwargs):
super().__init__(name=name, **kwargs)
self.time_kernel_size = kernel_size_tuple[0]
self.feature_kernel_size = kernel_size_tuple[1]
self.time_padding_amount = self.time_kernel_size - 1
feature_padding_total = self.feature_kernel_size - 1
self.feature_pad_before = feature_padding_total // 2
self.feature_pad_after = feature_padding_total - self.feature_pad_before
def call(self, inputs_tensor):
return tf.pad(inputs_tensor, [
[0,0],
[self.time_padding_amount,0],
[self.feature_pad_before,self.feature_pad_after],
[0,0]
])
def get_config(self):
config = super().get_config()
config.update({"kernel_size_tuple":(self.time_kernel_size, self.feature_kernel_size)})
return config
class AutoNWayEmbedding(keras.layers.Layer):
def __init__(self, vocab_size, embedding_dimension, num_factors, name="autonway_embedding", **kwargs):
super().__init__(name=name, **kwargs)
self.vocab_size = vocab_size
self.embedding_dimension = embedding_dimension
self.num_factors = num_factors
if self.embedding_dimension < 0 or self.num_factors < 0: raise ValueError("Emb_dim/factors non-negative.")
if self.embedding_dimension > 0 and self.num_factors == 0: raise ValueError("Positive emb_dim with zero num_factors.")
if self.embedding_dimension == 0: self.factor_dimensions = tuple([0] * num_factors) if self.num_factors > 0 else tuple()
else: self.factor_dimensions = self._find_optimal_dimensions(self.embedding_dimension, self.num_factors)
current_product = prod(d for d in self.factor_dimensions if d > 0)
target_product = self.embedding_dimension if self.embedding_dimension > 0 else 1
if current_product != target_product:
if self.num_factors > 0 and self.embedding_dimension > 0:
base_dims = [1] * self.num_factors
base_dims[-1] = self.embedding_dimension
for i in range(self.num_factors - 1):
root_val = int(round(base_dims[-1]**(1.0 / (self.num_factors - i))))
if root_val > 1 and base_dims[-1] % root_val == 0:
base_dims[i] = root_val
base_dims[-1] //= root_val
self.factor_dimensions = tuple(base_dims)
current_product = prod(d for d in self.factor_dimensions if d > 0)
if current_product != target_product:
raise ValueError(f"Factorization fallback fail. Target:{self.embedding_dimension},NFactors:{self.num_factors},Got:{self.factor_dimensions},Prod:{current_product}")
self.embedding_factors_list = []
for i, factor_dim_value in enumerate(self.factor_dimensions):
if factor_dim_value > 0:
self.embedding_factors_list.append(
Embedding(self.vocab_size, factor_dim_value, name=f"{self.name}_factor_{i+1}")
)
def _find_optimal_dimensions(self, target_product_val, num_factors_to_find_val):
if num_factors_to_find_val <= 0: return tuple()
if target_product_val == 0: return tuple([0] * num_factors_to_find_val)
if num_factors_to_find_val == 1: return (target_product_val,)
dimensions_list = [1] * num_factors_to_find_val
prime_factors_map = {}
divisor = 2
n_temp = target_product_val
while divisor * divisor <= n_temp:
while n_temp % divisor == 0:
prime_factors_map[divisor] = prime_factors_map.get(divisor, 0) + 1
n_temp //= divisor
divisor += 1
if n_temp > 1:
prime_factors_map[n_temp] = prime_factors_map.get(n_temp, 0) + 1
for prime_factor_key in sorted(prime_factors_map.keys(), reverse=True):
for _ in range(prime_factors_map[prime_factor_key]):
dimensions_list.sort()
dimensions_list[0] *= prime_factor_key
dimensions_list.sort(reverse=True)
return tuple(dimensions_list)
def build(self, input_shape_for_ids):
for emb_layer_instance in self.embedding_factors_list:
if not emb_layer_instance.built:
emb_layer_instance.build(input_shape_for_ids)
super().build(input_shape_for_ids)
def call(self, token_ids_tensor_input):
token_ids_as_int32 = tf.cast(token_ids_tensor_input, tf.int32)
if not self.embedding_factors_list or self.embedding_dimension == 0:
shape_of_token_ids = tf.shape(token_ids_tensor_input)
return tf.zeros((shape_of_token_ids[0], shape_of_token_ids[1], self.embedding_dimension), dtype=self.compute_dtype)
list_of_factor_embeddings = [layer_instance(token_ids_as_int32) for layer_instance in self.embedding_factors_list]
if not list_of_factor_embeddings:
shape_of_token_ids = tf.shape(token_ids_tensor_input)
return tf.zeros((shape_of_token_ids[0], shape_of_token_ids[1], self.embedding_dimension), dtype=self.compute_dtype)
current_combined_embedding = list_of_factor_embeddings[0]
list_of_valid_factor_dims = [dim_val for dim_val in self.factor_dimensions if dim_val > 0]
product_of_dims_so_far = list_of_valid_factor_dims[0]
for i in range(1, len(list_of_factor_embeddings)):
next_factor_embedding_tensor = list_of_factor_embeddings[i]
expanded_current_combined = tf.expand_dims(current_combined_embedding, axis=-1)
expanded_next_factor = tf.expand_dims(next_factor_embedding_tensor, axis=-2)
current_combined_embedding = expanded_current_combined * expanded_next_factor
dimension_of_next_factor = list_of_valid_factor_dims[i]
new_total_product_dimension = product_of_dims_so_far * dimension_of_next_factor
shape_of_original_ids = tf.shape(token_ids_as_int32)
current_combined_embedding = tf.reshape(
current_combined_embedding,
(shape_of_original_ids[0], shape_of_original_ids[1], new_total_product_dimension)
)
product_of_dims_so_far = new_total_product_dimension
return tf.cast(current_combined_embedding, self.compute_dtype)
def compute_logits(self, hidden_states_input_tensor):
if not self.embedding_factors_list or self.embedding_dimension == 0:
return Lambda(
lambda h_states: tf.zeros((tf.shape(h_states)[0], tf.shape(h_states)[1], self.vocab_size), dtype=self.compute_dtype),
name=f"{self.name}_zeros_logits"
)(hidden_states_input_tensor)
list_of_factor_weight_matrices = [tf.cast(layer.embeddings, self.compute_dtype) for layer in self.embedding_factors_list]
if not list_of_factor_weight_matrices:
return Lambda(
lambda h_states: tf.zeros((tf.shape(h_states)[0], tf.shape(h_states)[1], self.vocab_size), dtype=self.compute_dtype),
name=f"{self.name}_zeros_logits_fallback"
)(hidden_states_input_tensor)
current_combined_weights_matrix = list_of_factor_weight_matrices[0]
list_of_valid_factor_dims = [dim_val for dim_val in self.factor_dimensions if dim_val > 0]
product_of_dims_so_far = list_of_valid_factor_dims[0]
for i in range(1, len(list_of_factor_weight_matrices)):
next_factor_matrix = list_of_factor_weight_matrices[i]
expanded_current_combined_weights = tf.expand_dims(current_combined_weights_matrix, axis=-1)
expanded_next_factor_weights = tf.expand_dims(next_factor_matrix, axis=-2)
current_combined_weights_matrix = expanded_current_combined_weights * expanded_next_factor_weights
dimension_of_next_factor = list_of_valid_factor_dims[i]
new_total_product_dimension = product_of_dims_so_far * dimension_of_next_factor
current_combined_weights_matrix = tf.reshape(
current_combined_weights_matrix,
(self.vocab_size, new_total_product_dimension)
)
product_of_dims_so_far = new_total_product_dimension
return Lambda(
lambda hidden_s: tf.matmul(hidden_s, current_combined_weights_matrix, transpose_b=True),
name=f"{self.name}_matmul_logits"
)(hidden_states_input_tensor)
def get_config(self):
config = super().get_config()
config.update({
"vocab_size":self.vocab_size,
"embedding_dimension":self.embedding_dimension,
"num_factors":self.num_factors
})
return config
class StatefulMemoryModule(keras.layers.Layer):
def __init__(self, memory_size_slots, memory_slot_dimension, name="stateful_memory_module", **kwargs):
super().__init__(name=name, **kwargs)
self.memory_size_slots = memory_size_slots
self.memory_slot_dimension = memory_slot_dimension
self.update_gate_dense_layer = Dense(memory_slot_dimension, activation='sigmoid', name=f"{self.name}_update_gate_dense")
self.reset_gate_dense_layer = Dense(memory_slot_dimension, activation='sigmoid', name=f"{self.name}_reset_gate_dense")
self.candidate_state_conv1d_layer = Conv1D(
filters=memory_slot_dimension,
kernel_size=1,
padding='same', # To maintain memory_size_slots dimension
activation='tanh',
name=f"{self.name}_candidate_state_conv1d"
)
def build(self, input_shapes_tuple): # Expects ((query_shape), (memory_state_shape))
# Shape for layers operating on each memory slot independently: (batch, memory_size_slots, memory_slot_dimension)
cell_input_output_tensor_shape = tf.TensorShape((None, self.memory_size_slots, self.memory_slot_dimension))
if not self.update_gate_dense_layer.built: self.update_gate_dense_layer.build(cell_input_output_tensor_shape)
if not self.reset_gate_dense_layer.built: self.reset_gate_dense_layer.build(cell_input_output_tensor_shape)
if not self.candidate_state_conv1d_layer.built: self.candidate_state_conv1d_layer.build(cell_input_output_tensor_shape)
super().build(input_shapes_tuple)
def _gru_cell_like_update_logic(self, tiled_query_tensor_per_slot, previous_memory_state_tensor_per_slot):
gate_input_tensor = tiled_query_tensor_per_slot + previous_memory_state_tensor_per_slot
update_gate_activations = self.update_gate_dense_layer(gate_input_tensor)
reset_gate_activations = self.reset_gate_dense_layer(gate_input_tensor)
candidate_generation_input_tensor = tiled_query_tensor_per_slot + (reset_gate_activations * previous_memory_state_tensor_per_slot)
candidate_memory_slot_values_tensor = self.candidate_state_conv1d_layer(candidate_generation_input_tensor)
new_memory_state_tensor = (1.0 - update_gate_activations) * previous_memory_state_tensor_per_slot + \
update_gate_activations * candidate_memory_slot_values_tensor
return new_memory_state_tensor
def read_from_memory_slots(self, query_input_tensor, current_memory_state_tensor):
attention_scores_unscaled_values = tf.matmul(query_input_tensor, current_memory_state_tensor, transpose_b=True)
scaling_value = tf.sqrt(tf.cast(self.memory_slot_dimension, query_input_tensor.dtype))
attention_scores_scaled_values = attention_scores_unscaled_values / tf.maximum(scaling_value, keras.backend.epsilon())
attention_distribution_weights_tensor = tf.nn.softmax(attention_scores_scaled_values, axis=-1)
retrieved_information_vector = tf.matmul(attention_distribution_weights_tensor, current_memory_state_tensor)
return retrieved_information_vector
def write_to_memory_slots(self, single_query_input_tensor, previous_memory_state_tensor):
# Tile single query (e.g., last sequence token) to all memory slots
tiling_multiples = tf.stack([1, self.memory_size_slots, 1])
tiled_query_for_all_slots = tf.tile(single_query_input_tensor, tiling_multiples)
updated_memory_state_tensor = self._gru_cell_like_update_logic(tiled_query_for_all_slots, previous_memory_state_tensor)
return updated_memory_state_tensor
def call(self, inputs_tuple, mode='write', training=None): # Add training arg for Keras convention
query_tensor, memory_state_tensor = inputs_tuple
query_tensor_casted = tf.cast(query_tensor, self.compute_dtype)
memory_state_tensor_casted = tf.cast(memory_state_tensor, self.compute_dtype)
if mode == 'read':
output_vector_from_read_op = self.read_from_memory_slots(query_tensor_casted, memory_state_tensor_casted)
output_memory_state_op = memory_state_tensor_casted # Read does not modify memory
elif mode == 'write':
output_memory_state_op = self.write_to_memory_slots(query_tensor_casted, memory_state_tensor_casted)
# For sequence processing, write op often returns a placeholder (like zeros) for the sequence path
output_vector_from_read_op = tf.zeros_like(query_tensor_casted, dtype=self.compute_dtype)
else:
raise ValueError(f"Invalid mode for {self.name}: '{mode}'. Must be 'read' or 'write'.")
return output_vector_from_read_op, output_memory_state_op
def get_config(self):
config = super().get_config()
config.update({
"memory_size_slots": self.memory_size_slots,
"memory_slot_dimension": self.memory_slot_dimension
})
return config
class SSMCore(keras.layers.Layer):
def __init__(self, model_dimension, state_dimension_config, ssm_rank_config, name="ssm_core", **kwargs): # Corrected ssm_rank_config usage
super().__init__(name=name, **kwargs)
self.model_dimension = model_dimension
self.s4_rank = ssm_rank_config # CORRECTED: ssm_rank_config IS the rank value
self.configured_state_dimension = state_dimension_config # Store user-provided value for get_config
assert state_dimension_config >= 0, "State dimension must be non-negative."
# Internal state dimension 'N', rounded up to power of 2 if > 0
if state_dimension_config > 0 and (state_dimension_config & (state_dimension_config - 1) != 0):
self.internal_state_dimension_N = 1 << (state_dimension_config - 1).bit_length()
else:
self.internal_state_dimension_N = state_dimension_config
self.num_butterfly_levels = int(np.log2(self.internal_state_dimension_N)) if self.internal_state_dimension_N > 0 else 0
self.A_butterfly_factors_list = [] # To store trainable (2,2) matrices for A
def build(self, input_tensor_shape_ignored): # input_shape not strictly needed for deferred building of sub-layers if shapes are fixed
variable_dtype_for_weights = self.dtype_policy.variable_dtype
if self.internal_state_dimension_N > 0:
for i in range(self.num_butterfly_levels):
factor_matrix_weight = self.add_weight(
name=f"{self.name}_A_butterfly_factor_{i}",
shape=(2, 2), initializer="orthogonal", trainable=True, dtype=variable_dtype_for_weights
)
self.A_butterfly_factors_list.append(factor_matrix_weight)
self.B_project_to_rank_dense = Dense(self.s4_rank, use_bias=False, name=f"{self.name}_B_project_to_rank")
self.B_expand_to_state_dense = Dense(self.internal_state_dimension_N, use_bias=False, name=f"{self.name}_B_expand_to_state")
self.C_project_to_rank_dense = Dense(self.s4_rank, use_bias=False, name=f"{self.name}_C_project_to_rank") if self.internal_state_dimension_N > 0 else None
self.C_expand_to_model_dense = Dense(self.model_dimension, use_bias=False, name=f"{self.name}_C_expand_to_model")
self.D_feedthrough_vector_weight = self.add_weight(
name=f"{self.name}_D_feedthrough_vector", shape=(self.model_dimension,),
initializer="zeros", trainable=True, dtype=variable_dtype_for_weights
)
# Ensure sub-layers are built (can also be done in first call)
if not self.B_project_to_rank_dense.built: self.B_project_to_rank_dense.build(tf.TensorShape((None, None, self.model_dimension)))
if not self.B_expand_to_state_dense.built: self.B_expand_to_state_dense.build(tf.TensorShape((None, None, self.s4_rank)))
if self.C_project_to_rank_dense and not self.C_project_to_rank_dense.built: self.C_project_to_rank_dense.build(tf.TensorShape((None, None, self.internal_state_dimension_N)))
if not self.C_expand_to_model_dense.built: self.C_expand_to_model_dense.build(tf.TensorShape((None, None, self.s4_rank)))
super().build(input_tensor_shape_ignored)
def _apply_butterfly_structured_matrix_A(self, state_tensor_S_input):
if self.num_butterfly_levels == 0 or self.internal_state_dimension_N == 0: return state_tensor_S_input
current_tensor_shape = tf.shape(state_tensor_S_input)
batch_size_val, sequence_length_val = current_tensor_shape[0], current_tensor_shape[1]
reshaped_tensor_for_butterfly = tf.reshape(state_tensor_S_input, tf.stack([batch_size_val, sequence_length_val] + [2] * self.num_butterfly_levels))
rank_of_reshaped_tensor = 2 + self.num_butterfly_levels # Batch, Seq, plus N levels of 2s
current_state_being_transformed = reshaped_tensor_for_butterfly
for level_index_val in range(self.num_butterfly_levels):
level_A_factor_matrix = tf.cast(self.A_butterfly_factors_list[level_index_val], current_state_being_transformed.dtype)
axis_for_current_level_processing = 2 + level_index_val # 0-indexed from batch dim
# Permute to bring the current processing axis to the end for matmul
permutation_order_list = [0, 1] + \
[axis_idx for axis_idx in range(2, rank_of_reshaped_tensor) if axis_idx != axis_for_current_level_processing] + \
[axis_for_current_level_processing]
inverse_permutation_order_list = tf.math.invert_permutation(tf.constant(permutation_order_list, tf.int32))
permuted_tensor_for_matmul = tf.transpose(current_state_being_transformed, perm=permutation_order_list)
shape_of_permuted_tensor = tf.shape(permuted_tensor_for_matmul)
# Flatten all dimensions except the last one (which is size 2)
flattened_dimension_size_for_matmul = tf.reduce_prod(shape_of_permuted_tensor[:-1])
flattened_tensor_input_to_matmul = tf.reshape(permuted_tensor_for_matmul, [flattened_dimension_size_for_matmul, 2])
multiplied_state_tensor = tf.matmul(flattened_tensor_input_to_matmul, level_A_factor_matrix)
reshaped_state_after_multiplication = tf.reshape(multiplied_state_tensor, shape_of_permuted_tensor)
current_state_being_transformed = tf.transpose(reshaped_state_after_multiplication, perm=inverse_permutation_order_list)
return tf.reshape(current_state_being_transformed, tf.stack([batch_size_val, sequence_length_val, self.internal_state_dimension_N]))
def call(self, input_sequence_tensor_u):
projected_B_to_rank_tensor = self.B_project_to_rank_dense(input_sequence_tensor_u)
expanded_B_to_state_tensor = self.B_expand_to_state_dense(projected_B_to_rank_tensor)
state_tensor_after_A_transform = self._apply_butterfly_structured_matrix_A(expanded_B_to_state_tensor)
if self.internal_state_dimension_N > 0 and self.C_project_to_rank_dense is not None:
projected_C_to_rank_tensor = self.C_project_to_rank_dense(state_tensor_after_A_transform)
else:
shape_of_input_u = tf.shape(input_sequence_tensor_u)
projected_C_to_rank_tensor = tf.zeros((shape_of_input_u[0], shape_of_input_u[1], self.s4_rank), dtype=input_sequence_tensor_u.dtype)
output_C_to_model_dim_tensor = self.C_expand_to_model_dense(projected_C_to_rank_tensor)
output_D_feedthrough_path = tf.cast(self.D_feedthrough_vector_weight, input_sequence_tensor_u.dtype) * input_sequence_tensor_u
return output_C_to_model_dim_tensor + output_D_feedthrough_path
def get_config(self):
config = super().get_config()
config.update({
"model_dimension": self.model_dimension,
"state_dimension_config": self.configured_state_dimension, # Original value
"ssm_rank_config": self.s4_rank # This now correctly refers to the actual rank value
})
return config
class OutputHead(keras.Model):
def __init__(self, shared_embedding_layer_ref, vocabulary_size, name="OutputHead_default", **kwargs):
super().__init__(name=name, **kwargs)
self.layer_norm = LayerNormalization(epsilon=1e-6, name=f"{self.name}_layer_norm")
self.shared_embedding_layer_ref = shared_embedding_layer_ref # Store reference
self.lambda_cast_to_float32 = Lambda(lambda x_tensor: tf.cast(x_tensor, tf.float32), name=f"{self.name}_cast_to_float32")
self.softmax_activation = Activation('softmax', name=f"{self.name}_final_softmax")
def call(self, input_hidden_states_tensor):
normalized_hidden_states = self.layer_norm(input_hidden_states_tensor)
output_logits_tensor = self.shared_embedding_layer_ref.compute_logits(normalized_hidden_states)
logits_as_float32_tensor = self.lambda_cast_to_float32(output_logits_tensor)
probabilities_output = self.softmax_activation(logits_as_float32_tensor)
return probabilities_output
def get_config(self):
config = super().get_config()
config.update({"vocabulary_size": self.shared_embedding_layer_ref.vocab_size})
return config
class Conv2DBlock(keras.Model):
def __init__(self, output_embedding_dimension, name="Conv2DBlock_default", **kwargs): # Name provided by caller
super().__init__(name=name, **kwargs)
self.output_embedding_dimension = output_embedding_dimension
self.expand_dims_norm_input = ExpandDimsLayer(axis=-1, name=f"{self.name}_expand_norm_input")
self.expand_dims_fourier_input = ExpandDimsLayer(axis=-1, name=f"{self.name}_expand_fourier_input")
self.concatenate_inputs_layer = Concatenate(axis=-1, name=f"{self.name}_concatenate_inputs")
self.convolution_path_layers_list = []
# Configuration for the Conv2D layers in the block
filters_config_list = [64, 128, 1]
kernels_config_list = [(7,7), (5,5), (3,3)]
activations_config_list = [tf.nn.swish, tf.nn.swish, None]
for i, (num_filters_val, kernel_dims_val, activation_fn_val) in enumerate(zip(filters_config_list, kernels_config_list, activations_config_list)):
self.convolution_path_layers_list.append(
CausalPadding2D(kernel_dims_val, name=f"{self.name}_causal_padding_2d_{i}")
)
self.convolution_path_layers_list.append(
Conv2D(
filters=num_filters_val, kernel_size=kernel_dims_val, padding='valid',
activation=activation_fn_val, name=f"{self.name}_conv2d_layer_{i}"
)
)
self.squeeze_channel_dim_layer = SqueezeLayer(axis=-1, name=f"{self.name}_squeeze_channel_dim")
self.projection_to_output_dim_dense_layer = Dense(units=output_embedding_dimension, name=f"{self.name}_projection_to_output_dim_dense")
self.time_distributed_final_projection_layer = TimeDistributed(self.projection_to_output_dim_dense_layer, name=f"{self.name}_time_distributed_projection")
def call(self, inputs_list_args):
normalized_sequence_input, fourier_features_input = inputs_list_args
expanded_normalized_seq = self.expand_dims_norm_input(normalized_sequence_input)
expanded_fourier_features = self.expand_dims_fourier_input(fourier_features_input)
concatenated_conv_input = self.concatenate_inputs_layer([expanded_normalized_seq, expanded_fourier_features])
current_tensor_in_convolution_path = concatenated_conv_input
for layer_in_path in self.convolution_path_layers_list:
current_tensor_in_convolution_path = layer_in_path(current_tensor_in_convolution_path)
squeezed_output_from_conv_path = self.squeeze_channel_dim_layer(current_tensor_in_convolution_path)
final_projected_output_sequence = self.time_distributed_final_projection_layer(squeezed_output_from_conv_path)
return final_projected_output_sequence
def get_config(self):
config = super().get_config()
config.update({"output_embedding_dimension": self.output_embedding_dimension})
return config
# =========================================================================================
# = G3Block and MTPG3Block (Main Architectural Components) =
# =========================================================================================
def G3Block(
embedding_dimension_val, shared_memory_module_inst, shared_fourier_layer_inst,
ssm_rank_val, ssm_state_dimension_multiplier_val, layer_idx, block_prefix_str="G3Block_"
):
current_block_name = f"{block_prefix_str}{layer_idx}"
input_sequence_tensor = Input(shape=(None, embedding_dimension_val), name=f"{current_block_name}_input_sequence_tensor")
input_memory_tensor = Input(shape=(NUM_REGISTERS, MEMORY_DIM), name=f"{current_block_name}_input_memory_tensor", dtype=shared_memory_module_inst.compute_dtype)
residual_connection_tensor = input_sequence_tensor
normalized_sequence_tensor = LayerNormalization(epsilon=1e-6, name=f"{current_block_name}_input_layer_norm")(input_sequence_tensor)
depthwise_conv_kernel_size = 4
padded_sequence_for_depthwise = CausalPadding1D(depthwise_conv_kernel_size, name=f"{current_block_name}_depthwise_causal_padding")(normalized_sequence_tensor)
depthwise_conv_output_tensor = DepthwiseConv1D(
kernel_size=depthwise_conv_kernel_size, padding='valid', activation=tf.nn.swish,
depth_multiplier=1, name=f"{current_block_name}_depthwise_conv_operation"
)(padded_sequence_for_depthwise)
sequence_after_depthwise_conv = Add()([normalized_sequence_tensor, depthwise_conv_output_tensor])
features_for_main_branches = LayerNormalization(epsilon=1e-6, name=f"{current_block_name}_features_layer_norm")(sequence_after_depthwise_conv)
fourier_features_for_conv2d = shared_fourier_layer_inst(normalized_sequence_tensor) # Note: Using original normalized_sequence_tensor
ssm_core_output_tensor = SSMCore(
model_dimension=embedding_dimension_val,
state_dimension_config=embedding_dimension_val * ssm_state_dimension_multiplier_val, # Corrected state_dimension to state_dimension_config
ssm_rank_config=ssm_rank_val,
name=f"{current_block_name}_ssm"
)(features_for_main_branches)
conv2d_block_output_tensor = Conv2DBlock(
output_embedding_dimension=embedding_dimension_val,
name=f"{current_block_name}_conv2d_block"
)([features_for_main_branches, fourier_features_for_conv2d])
combined_ssm_and_conv2d_tensor = Add()([ssm_core_output_tensor, conv2d_block_output_tensor])
lambda_for_slicing_last_token = Lambda(lambda x_input_tensor: x_input_tensor[:, -1:, :], name=f"{current_block_name}_slice")
query_tensor_for_memory_read = lambda_for_slicing_last_token(combined_ssm_and_conv2d_tensor)
read_signal_vector_from_memory, _ = shared_memory_module_inst([query_tensor_for_memory_read, input_memory_tensor], mode='read')
lambda_for_tiling_read_signal = Lambda(
lambda list_of_inputs: tf.tile(tf.cast(list_of_inputs[0], list_of_inputs[1].dtype), [1, tf.shape(list_of_inputs[1])[1], 1]),
name=f"{current_block_name}_lambda_tile_read_signal"
)
tiled_read_signal_sequence_tensor = lambda_for_tiling_read_signal([read_signal_vector_from_memory, combined_ssm_and_conv2d_tensor])
sequence_tensor_after_memory_read = Add()([combined_ssm_and_conv2d_tensor, tiled_read_signal_sequence_tensor])
query_tensor_for_memory_write = lambda_for_slicing_last_token(sequence_tensor_after_memory_read)
_, updated_memory_state_tensor = shared_memory_module_inst([query_tensor_for_memory_write, input_memory_tensor], mode='write')
output_sequence_before_pooling_tensor = Add(name=f"{current_block_name}_add_final_residual_connection")([residual_connection_tensor, sequence_tensor_after_memory_read])
pooled_output_sequence_tensor = ConditionalAveragePooling1D(
pool_size=2, strides=2, padding_if_pool='SAME', name=f"{current_block_name}_final_conditional_avg_pooling"
)(output_sequence_before_pooling_tensor)
return keras.Model(
inputs=[input_sequence_tensor, input_memory_tensor],
outputs=[pooled_output_sequence_tensor, updated_memory_state_tensor],
name=current_block_name
)
def MTPG3Block(
embedding_dimension_val, shared_memory_module_inst, shared_fourier_layer_inst,
ssm_rank_val, ssm_state_dimension_multiplier_val, layer_idx, block_prefix_str="MTPG3Block_" ):
current_block_name = f"{block_prefix_str}{layer_idx}"
input_sequence_tensor = Input(shape=(None, embedding_dimension_val), name=f"{current_block_name}_input_sequence_tensor")
input_memory_tensor = Input(shape=(NUM_REGISTERS, MEMORY_DIM), name=f"{current_block_name}_input_memory_tensor", dtype=shared_memory_module_inst.compute_dtype)
residual_connection_tensor = input_sequence_tensor
normalized_sequence_tensor = LayerNormalization(epsilon=1e-6, name=f"{current_block_name}_input_layer_norm")(input_sequence_tensor)
depthwise_conv_kernel_size = 4
padded_sequence_for_depthwise = CausalPadding1D(depthwise_conv_kernel_size, name=f"{current_block_name}_depthwise_causal_padding")(normalized_sequence_tensor)
depthwise_conv_output_tensor = DepthwiseConv1D(
kernel_size=depthwise_conv_kernel_size, padding='valid', activation=tf.nn.swish,
depth_multiplier=1, name=f"{current_block_name}_depthwise_conv_op"
)(padded_sequence_for_depthwise)
sequence_after_dw_residual = Add(name=f"{current_block_name}_add_residual_after_dw")([normalized_sequence_tensor, depthwise_conv_output_tensor])
features_for_main_branches = LayerNormalization(epsilon=1e-6, name=f"{current_block_name}_features_layer_norm")(sequence_after_dw_residual)
fourier_features_for_conv2d = shared_fourier_layer_inst(normalized_sequence_tensor) # Note: Using original normalized_sequence_tensor
ssm_core_output_tensor = SSMCore(
model_dimension=embedding_dimension_val,
state_dimension_config=embedding_dimension_val * ssm_state_dimension_multiplier_val, # Corrected state_dimension to state_dimension_config
ssm_rank_config=ssm_rank_val,
name=f"{current_block_name}_ssm"
)(features_for_main_branches)
conv2d_block_output_tensor = Conv2DBlock(
output_embedding_dimension=embedding_dimension_val,
name=f"{current_block_name}_conv2d_block"
)([features_for_main_branches, fourier_features_for_conv2d])
combined_ssm_and_conv2d_tensor = Add()([ssm_core_output_tensor, conv2d_block_output_tensor])
lambda_slice_last_token = Lambda(lambda x_tensor: x_tensor[:, -1:, :], name=f"{current_block_name}_slice")
memory_read_query_tensor = lambda_slice_last_token(combined_ssm_and_conv2d_tensor)
read_signal_vector_from_memory, _ = shared_memory_module_inst([memory_read_query_tensor, input_memory_tensor], mode='read')