Speech transform for Gemma 4. Converts raw waveforms to log-mel spectrograms. Unlike Gemma 3N, this uses: - 20ms frames (320 samples) with 10ms hop (160 samples) - No FFT overdrive (fft_length=512) - No preemphasis - Mel range 0-8000 Hz - mel_floor=0.001
| 56 | |
| 57 | |
| 58 | class Gemma4SpeechTransformModel(nn.Module): |
| 59 | """ |
| 60 | Speech transform for Gemma 4. |
| 61 | |
| 62 | Converts raw waveforms to log-mel spectrograms. Unlike Gemma 3N, this uses: |
| 63 | - 20ms frames (320 samples) with 10ms hop (160 samples) |
| 64 | - No FFT overdrive (fft_length=512) |
| 65 | - No preemphasis |
| 66 | - Mel range 0-8000 Hz |
| 67 | - mel_floor=0.001 |
| 68 | """ |
| 69 | |
| 70 | def __init__( |
| 71 | self, |
| 72 | sample_rate: int = 16000, |
| 73 | frame_length: int = 320, |
| 74 | hop_length: int = 160, |
| 75 | fft_length: int = 512, |
| 76 | n_mels: int = 128, |
| 77 | f_min: float = 0.0, |
| 78 | f_max: float = 8000.0, |
| 79 | mel_floor: float = 0.001, |
| 80 | input_scale_factor: float = 1.0, |
| 81 | ) -> None: |
| 82 | super().__init__() |
| 83 | |
| 84 | self.sample_rate = sample_rate |
| 85 | self.frame_length = frame_length |
| 86 | self.hop_length = hop_length |
| 87 | self.fft_length = fft_length |
| 88 | self.n_mels = n_mels |
| 89 | self.mel_floor = mel_floor |
| 90 | self.input_scale_factor = input_scale_factor |
| 91 | |
| 92 | window = torch.hann_window(frame_length, periodic=True) |
| 93 | self.register_buffer("window", window) |
| 94 | |
| 95 | mel_filters = create_mel_filterbank( |
| 96 | n_freqs=fft_length // 2 + 1, |
| 97 | f_min=f_min, |
| 98 | f_max=f_max, |
| 99 | n_mels=n_mels, |
| 100 | sample_rate=sample_rate, |
| 101 | fft_length=fft_length, |
| 102 | ) |
| 103 | self.register_buffer("mel_filters", mel_filters) |
| 104 | |
| 105 | def forward(self, waveform: torch.Tensor) -> torch.Tensor: |
| 106 | """ |
| 107 | Convert waveform to log-mel spectrogram. |
| 108 | |
| 109 | Matches HuggingFace Gemma4AudioFeatureExtractor._extract_spectrogram(): |
| 110 | - Semicausal time padding (prepend frame_length//2 zeros) |
| 111 | - Frame size = frame_length + 1 (for preemphasis support), drop last sample |
| 112 | - log(mel + mel_floor) for log compression |
| 113 | |
| 114 | Args: |
| 115 | waveform: Shape [num_samples] (1D only). |
no outgoing calls