aoxo commited on
Commit
17f4e46
·
verified ·
1 Parent(s): 2d3a567

Update eduport_tts_mal.py

Browse files
Files changed (1) hide show
  1. eduport_tts_mal.py +81 -44
eduport_tts_mal.py CHANGED
@@ -113,6 +113,7 @@ decoder_config = GPT2Config(vocab_size=len(tokenizer))
113
  decoder_config.add_cross_attention=True
114
  decoder = GPT2LMHeadModel(config=decoder_config)
115
 
 
116
  class SpeechRecognitionModel(torch.nn.Module):
117
  def __init__(self, encoder, decoder):
118
  super().__init__()
@@ -120,57 +121,93 @@ class SpeechRecognitionModel(torch.nn.Module):
120
  self.decoder = decoder
121
 
122
  def forward(self, audio_input, text_input):
 
123
  encoder_output = self.encoder(audio_input).last_hidden_state
124
- decoder_output = self.decoder(text_input, encoder_hidden_states=encoder_output)
125
- return decoder_output
126
-
127
- # Instantiate the model
128
- model = SpeechRecognitionModel(encoder, decoder)
 
 
 
 
 
 
 
 
 
 
 
129
 
130
- # Optimizer and scheduler
131
- optimizer = torch.optim.Adam(model.parameters(), lr=1e-4)
132
- scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
 
134
- # Training Loop
135
- device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
136
- model.to(device)
 
137
 
138
- num_epochs = 10
 
139
 
140
- for epoch in range(num_epochs):
141
- model.train()
142
- train_loss = 0
143
- for audio_input, text_input in train_loader:
144
- optimizer.zero_grad()
145
 
146
- # Move tensors to the appropriate device
147
- audio_input = audio_input.squeeze(1).to(device)
148
- text_input = text_input.to(device)
149
 
150
- # Forward pass
151
- output = model(audio_input, text_input)
152
-
153
- # Compute loss
154
- loss = torch.nn.CrossEntropyLoss()(output.logits.view(-1, output.logits.size(-1)), text_input.view(-1))
155
- loss.backward()
156
- optimizer.step()
157
-
158
- train_loss += loss.item()
159
-
160
- # Validation step
161
- model.eval()
162
- val_loss = 0
163
- with torch.no_grad():
164
- for audio_input, text_input in val_loader:
165
- audio_input = audio_input.to(device)
166
- text_input = text_input.to(device)
167
- output = model(audio_input, text_input)
168
- loss = torch.nn.CrossEntropyLoss()(output.logits.view(-1, output.logits.size(-1)), text_input.view(-1))
169
- val_loss += loss.item()
170
 
171
- # Update scheduler
172
- scheduler.step(val_loss)
173
 
174
- print(f'Epoch {epoch}: Train Loss: {train_loss / len(train_loader)}, Val Loss: {val_loss / len(val_loader)}')
175
 
176
- # Inference (use the same process as the training loop to handle inference)
 
 
113
  decoder_config.add_cross_attention=True
114
  decoder = GPT2LMHeadModel(config=decoder_config)
115
 
116
+ # Model Architecture with Improved FP16 Support
117
  class SpeechRecognitionModel(torch.nn.Module):
118
  def __init__(self, encoder, decoder):
119
  super().__init__()
 
121
  self.decoder = decoder
122
 
123
  def forward(self, audio_input, text_input):
124
+ # Extract encoder hidden states
125
  encoder_output = self.encoder(audio_input).last_hidden_state
126
+
127
+ # Create an attention mask for the encoder output
128
+ encoder_attention_mask = torch.ones(
129
+ encoder_output.shape[:2],
130
+ dtype=torch.long,
131
+ device=encoder_output.device
132
+ )
133
+
134
+ # Forward pass through the decoder with cross-attention
135
+ outputs = self.decoder(
136
+ input_ids=text_input,
137
+ encoder_hidden_states=encoder_output,
138
+ encoder_attention_mask=encoder_attention_mask
139
+ )
140
+
141
+ return outputs
142
 
143
+ # Training Loop with Improved Mixed Precision
144
+ def train_model(num_epochs=10):
145
+ # Prepare the models
146
+ # Use float32 for most of the model, let autocast handle precision
147
+ encoder = Wav2Vec2Model.from_pretrained('facebook/wav2vec2-base-960h')
148
+
149
+ # Modify the decoder configuration
150
+ decoder_config = GPT2Config(
151
+ vocab_size=len(tokenizer),
152
+ add_cross_attention=True
153
+ )
154
+ decoder = GPT2LMHeadModel(config=decoder_config)
155
+
156
+ # Initialize the model
157
+ model = SpeechRecognitionModel(encoder, decoder)
158
+
159
+ # Move to GPU
160
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
161
+ model = model.to(device)
162
+
163
+ # Optimizer and learning rate scheduler
164
+ optimizer = torch.optim.Adam(model.parameters(), lr=1e-4)
165
+ scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min')
166
+
167
+ # Gradient scaler for mixed precision training
168
+ scaler = GradScaler()
169
+
170
+ # Training loop
171
+ for epoch in range(num_epochs):
172
+ model.train()
173
+ train_loss = 0
174
+ for audio_input, text_input in train_loader:
175
+ optimizer.zero_grad()
176
+
177
+ # Move tensors to device
178
+ audio_input = audio_input.squeeze(1).to(device)
179
+ text_input = text_input.to(device)
180
 
181
+ # Use autocast for mixed precision training
182
+ with autocast(dtype=torch.float16):
183
+ # Forward pass
184
+ output = model(audio_input, text_input)
185
 
186
+ # Compute loss
187
+ loss = torch.nn.CrossEntropyLoss()(output.logits.view(-1, output.logits.size(-1)), text_input.view(-1))
188
 
189
+ # Scaled loss for mixed precision
190
+ scaler.scale(loss).backward()
191
+ scaler.step(optimizer)
192
+ scaler.update()
 
193
 
194
+ train_loss += loss.item()
 
 
195
 
196
+ # Validation step
197
+ model.eval()
198
+ val_loss = 0
199
+ with torch.no_grad(), autocast(dtype=torch.float16):
200
+ for audio_input, text_input in val_loader:
201
+ audio_input = audio_input.to(device)
202
+ text_input = text_input.to(device)
203
+ output = model(audio_input, text_input)
204
+ loss = torch.nn.CrossEntropyLoss()(output.logits.view(-1, output.logits.size(-1)), text_input.view(-1))
205
+ val_loss += loss.item()
 
 
 
 
 
 
 
 
 
 
206
 
207
+ # Update scheduler
208
+ scheduler.step(val_loss)
209
 
210
+ print(f'Epoch {epoch}: Train Loss: {train_loss / len(train_loader)}, Val Loss: {val_loss / len(val_loader)}')
211
 
212
+ # Run the training
213
+ train_model()