GokseninYuksel commited on
Commit
fe17b0f
·
verified ·
1 Parent(s): 4a33ba7

Upload Speech-JEPA weights

Browse files
README.md ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language: en
3
+ license: bsd-3-clause
4
+ library_name: transformers
5
+ pipeline_tag: feature-extraction
6
+ datasets:
7
+ - openslr/librispeech_asr
8
+ tags:
9
+ - speech
10
+ - audio
11
+ - self-supervised-learning
12
+ - jepa
13
+ - speech-jepa
14
+ ---
15
+
16
+ # Speech-JEPA Base
17
+
18
+ [Code and recipes](https://github.com/labhamlet/SpeechJEPA)
19
+
20
+ The base model pretrained on 16 kHz sampled speech audio (LibriSpeech, 960 h). When using the model make
21
+ sure that your speech input is also sampled at 16 kHz.
22
+
23
+ **Note**: This model does not have a tokenizer as it was pretrained on audio alone. In order to use this
24
+ model for speech recognition, a tokenizer should be created and the model should be fine-tuned on labeled
25
+ text data. Fine-tuned checkpoints for the Libri-light splits are listed below.
26
+
27
+ ## Model description
28
+
29
+ Speech-JEPA is a Joint-Embedding Predictive Architecture for speech. A context encoder sees a partially
30
+ masked sequence of convolutional speech features and a light-weight convolutional decoder predicts the
31
+ latent representations of the masked spans produced by an exponential-moving-average teacher
32
+ (instance-normalised average of the top-8 teacher layers, as in data2vec 2.0). There is no
33
+ reconstruction of audio and no quantised targets.
34
+
35
+ | | |
36
+ |---|---|
37
+ | Parameters | 89.7 M |
38
+ | Feature encoder | 7-layer 1-D CNN (wav2vec 2.0 layout), 320× downsampling, 20 ms frames |
39
+ | Transformer | 12 layers, 768-d, 12 heads, rotary position embeddings, post-norm |
40
+ | Pretraining data | LibriSpeech 960 h |
41
+ | Pretraining updates | 370000 |
42
+
43
+ `jepa_pretraining_extras.safetensors` additionally holds the JEPA decoder, mask token and the EMA teacher encoder so that pre-training can be resumed with the original code.
44
+
45
+ ## Usage
46
+
47
+ ```python
48
+ import torch
49
+ from datasets import load_dataset
50
+ from transformers import AutoModel, Wav2Vec2FeatureExtractor
51
+
52
+ feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained("labhamlet/speech-jepa-base")
53
+ model = AutoModel.from_pretrained("labhamlet/speech-jepa-base", trust_remote_code=True)
54
+
55
+ ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
56
+ inputs = feature_extractor(ds[0]["audio"]["array"], sampling_rate=16000, return_tensors="pt")
57
+
58
+ with torch.no_grad():
59
+ hidden_states = model(**inputs).last_hidden_state # (1, frames, 768), one frame every 20 ms
60
+ ```
61
+
62
+ For batched input pass `padding=True` to the feature extractor; the returned `attention_mask` is used
63
+ by the model to ignore padded samples. `output_hidden_states=True` returns the input embedding and the
64
+ output of every Transformer layer.
65
+
66
+ The original training code can also load this repository:
67
+
68
+ ```python
69
+ from wavjepa.hub import load_pretrained # github.com/labhamlet/SpeechJEPA
70
+ model = load_pretrained("labhamlet/speech-jepa-base") # wavjepa.jepa_d2v2.JEPA, incl. decoder and EMA teacher
71
+ ```
72
+
73
+ ## Fine-tuned checkpoints (CTC, LibriSpeech character vocabulary)
74
+
75
+ | Labelled data | Repository |
76
+ |---|---|
77
+ | Libri-light 10 min | [labhamlet/speech-jepa-base-asr-10min](https://huggingface.co/labhamlet/speech-jepa-base-asr-10min) |
78
+ | Libri-light 1 h | [labhamlet/speech-jepa-base-asr-1h](https://huggingface.co/labhamlet/speech-jepa-base-asr-1h) |
79
+ | Libri-light 10 h | [labhamlet/speech-jepa-base-asr-10h](https://huggingface.co/labhamlet/speech-jepa-base-asr-10h) |
80
+ | LibriSpeech train-clean-100 | [labhamlet/speech-jepa-base-asr-100h](https://huggingface.co/labhamlet/speech-jepa-base-asr-100h) |
81
+
82
+ ## Files
83
+
84
+ * `model.safetensors`, `config.json` — `SpeechJEPAModel` weights and configuration
85
+ * `modeling_speech_jepa.py`, `configuration_speech_jepa.py` — model code (`trust_remote_code=True`)
86
+ * `preprocessor_config.json` — `Wav2Vec2FeatureExtractor` (16 kHz, per-utterance normalisation)
87
+ * `jepa_pretraining_extras.safetensors` — JEPA decoder, mask token and EMA teacher (original key names)
88
+ * `training_config.json` — hyper-parameters of the pretraining run
89
+
90
+ ## License
91
+
92
+ BSD-3-Clause.
config.json ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "activation_dropout": 0.1,
3
+ "apply_spec_augment": true,
4
+ "architectures": [
5
+ "SpeechJEPAModel"
6
+ ],
7
+ "attention_dropout": 0.1,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_speech_jepa.SpeechJEPAConfig",
10
+ "AutoModel": "modeling_speech_jepa.SpeechJEPAModel",
11
+ "AutoModelForCTC": "modeling_speech_jepa.SpeechJEPAForCTC"
12
+ },
13
+ "conv_bias": false,
14
+ "conv_dim": [
15
+ 512,
16
+ 512,
17
+ 512,
18
+ 512,
19
+ 512,
20
+ 512,
21
+ 512
22
+ ],
23
+ "conv_kernel": [
24
+ 10,
25
+ 3,
26
+ 3,
27
+ 3,
28
+ 3,
29
+ 2,
30
+ 2
31
+ ],
32
+ "conv_stride": [
33
+ 5,
34
+ 2,
35
+ 2,
36
+ 2,
37
+ 2,
38
+ 2,
39
+ 2
40
+ ],
41
+ "ctc_loss_reduction": "mean",
42
+ "ctc_zero_infinity": true,
43
+ "dtype": "float32",
44
+ "feat_extract_norm": "group",
45
+ "final_dropout": 0.1,
46
+ "hidden_act": "gelu",
47
+ "hidden_dropout": 0.1,
48
+ "hidden_size": 768,
49
+ "initializer_range": 0.02,
50
+ "intermediate_size": 3072,
51
+ "layer_norm_eps": 1e-06,
52
+ "layerdrop": 0.05,
53
+ "mask_feature_length": 64,
54
+ "mask_feature_min_masks": 0,
55
+ "mask_feature_prob": 0.0,
56
+ "mask_time_length": 10,
57
+ "mask_time_min_masks": 2,
58
+ "mask_time_prob": 0.065,
59
+ "max_position_embeddings": 8192,
60
+ "model_type": "speech_jepa",
61
+ "num_attention_heads": 12,
62
+ "num_hidden_layers": 12,
63
+ "pad_token_id": 0,
64
+ "rope_theta": 10000.0,
65
+ "transformers_version": "5.2.0",
66
+ "use_weighted_layer_sum": false,
67
+ "vocab_size": 29
68
+ }
configuration_speech_jepa.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Speech-JEPA model configuration (Hugging Face `transformers` format)."""
2
+ from transformers import PretrainedConfig
3
+
4
+
5
+ class SpeechJEPAConfig(PretrainedConfig):
6
+ r"""
7
+ Configuration of a Speech-JEPA model (a wav2vec 2.0 style convolutional feature encoder followed by a
8
+ post-norm Transformer encoder with rotary position embeddings). Field names follow
9
+ `Wav2Vec2Config` wherever the semantics are identical.
10
+ """
11
+
12
+ model_type = "speech_jepa"
13
+
14
+ def __init__(
15
+ self,
16
+ conv_dim=(512, 512, 512, 512, 512, 512, 512),
17
+ conv_kernel=(10, 3, 3, 3, 3, 2, 2),
18
+ conv_stride=(5, 2, 2, 2, 2, 2, 2),
19
+ conv_bias=False,
20
+ feat_extract_norm="group",
21
+ hidden_size=768,
22
+ num_hidden_layers=12,
23
+ num_attention_heads=12,
24
+ intermediate_size=3072,
25
+ hidden_act="gelu",
26
+ layer_norm_eps=1e-6,
27
+ rope_theta=10000.0,
28
+ max_position_embeddings=8192,
29
+ hidden_dropout=0.1,
30
+ activation_dropout=0.1,
31
+ attention_dropout=0.1,
32
+ final_dropout=0.1,
33
+ layerdrop=0.05,
34
+ apply_spec_augment=True,
35
+ mask_time_prob=0.065,
36
+ mask_time_length=10,
37
+ mask_time_min_masks=2,
38
+ mask_feature_prob=0.0,
39
+ mask_feature_length=64,
40
+ mask_feature_min_masks=0,
41
+ use_weighted_layer_sum=False,
42
+ vocab_size=29,
43
+ ctc_loss_reduction="mean",
44
+ ctc_zero_infinity=True,
45
+ pad_token_id=0,
46
+ initializer_range=0.02,
47
+ **kwargs,
48
+ ):
49
+ super().__init__(pad_token_id=pad_token_id, **kwargs)
50
+ self.conv_dim = list(conv_dim)
51
+ self.conv_kernel = list(conv_kernel)
52
+ self.conv_stride = list(conv_stride)
53
+ self.conv_bias = conv_bias
54
+ self.feat_extract_norm = feat_extract_norm
55
+ self.hidden_size = hidden_size
56
+ self.num_hidden_layers = num_hidden_layers
57
+ self.num_attention_heads = num_attention_heads
58
+ self.intermediate_size = intermediate_size
59
+ self.hidden_act = hidden_act
60
+ self.layer_norm_eps = layer_norm_eps
61
+ self.rope_theta = rope_theta
62
+ self.max_position_embeddings = max_position_embeddings
63
+ self.hidden_dropout = hidden_dropout
64
+ self.activation_dropout = activation_dropout
65
+ self.attention_dropout = attention_dropout
66
+ self.final_dropout = final_dropout
67
+ self.layerdrop = layerdrop
68
+ self.apply_spec_augment = apply_spec_augment
69
+ self.mask_time_prob = mask_time_prob
70
+ self.mask_time_length = mask_time_length
71
+ self.mask_time_min_masks = mask_time_min_masks
72
+ self.mask_feature_prob = mask_feature_prob
73
+ self.mask_feature_length = mask_feature_length
74
+ self.mask_feature_min_masks = mask_feature_min_masks
75
+ self.use_weighted_layer_sum = use_weighted_layer_sum
76
+ self.vocab_size = vocab_size
77
+ self.ctc_loss_reduction = ctc_loss_reduction
78
+ self.ctc_zero_infinity = ctc_zero_infinity
79
+ self.initializer_range = initializer_range
80
+
81
+ if not (len(self.conv_dim) == len(self.conv_kernel) == len(self.conv_stride)):
82
+ raise ValueError("conv_dim, conv_kernel and conv_stride must have the same length")
83
+
84
+ @property
85
+ def num_feat_extract_layers(self):
86
+ return len(self.conv_dim)
jepa_pretraining_extras.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5fb57333701bc9df7c8e2c95e18f8f29c2f3732f876768e525d93d0924daff64
3
+ size 342722472
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c74bd422e476a9cb1738a7314804db0ce00f89c99c26bc25819987052bf59780
3
+ size 358632360
modeling_speech_jepa.py ADDED
@@ -0,0 +1,401 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PyTorch Speech-JEPA model (Hugging Face `transformers` format).
2
+
3
+ Self-contained port of the encoder trained in https://github.com/labhamlet/SpeechJEPA
4
+ (`wavjepa/jepa_d2v2.py`, `wavjepa/modules.py`). Only `torch` and `transformers` are required.
5
+ """
6
+ from typing import Optional, Tuple, Union
7
+
8
+ import numpy as np
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+ from transformers import PreTrainedModel
13
+ from transformers.activations import ACT2FN
14
+ from transformers.modeling_outputs import BaseModelOutput, CausalLMOutput
15
+
16
+ from .configuration_speech_jepa import SpeechJEPAConfig
17
+
18
+
19
+ # --------------------------------------------------------------------------- #
20
+ # SpecAugment helper (identical to transformers' wav2vec2 implementation)
21
+ # --------------------------------------------------------------------------- #
22
+ def _compute_mask_indices(shape, mask_prob, mask_length, attention_mask=None, min_masks=0) -> np.ndarray:
23
+ batch_size, sequence_length = shape
24
+ if mask_length < 1:
25
+ raise ValueError("`mask_length` has to be bigger than 0.")
26
+ if mask_length > sequence_length:
27
+ raise ValueError(f"`mask_length` ({mask_length}) must be <= `sequence_length` ({sequence_length})")
28
+
29
+ epsilon = np.random.rand(1).item()
30
+
31
+ def compute_num_masked_span(input_length):
32
+ num_masked_span = int(mask_prob * input_length / mask_length + epsilon)
33
+ num_masked_span = max(num_masked_span, min_masks)
34
+ if num_masked_span * mask_length > sequence_length:
35
+ num_masked_span = sequence_length // mask_length
36
+ if input_length - (mask_length - 1) < num_masked_span:
37
+ num_masked_span = max(input_length - (mask_length - 1), 0)
38
+ return num_masked_span
39
+
40
+ input_lengths = (
41
+ attention_mask.detach().sum(-1).tolist() if attention_mask is not None else [sequence_length] * batch_size
42
+ )
43
+ spec_aug_mask = np.zeros((batch_size, sequence_length), dtype=bool)
44
+ spec_aug_mask_idxs = []
45
+ max_num_masked_span = compute_num_masked_span(sequence_length)
46
+ if max_num_masked_span == 0:
47
+ return spec_aug_mask
48
+
49
+ for input_length in input_lengths:
50
+ num_masked_span = compute_num_masked_span(input_length)
51
+ idx = np.random.choice(np.arange(input_length - (mask_length - 1)), num_masked_span, replace=False)
52
+ dummy = sequence_length - 1 if len(idx) == 0 else idx[0]
53
+ idx = np.concatenate([idx, np.ones(max_num_masked_span - num_masked_span, dtype=np.int32) * dummy])
54
+ spec_aug_mask_idxs.append(idx)
55
+
56
+ spec_aug_mask_idxs = np.array(spec_aug_mask_idxs)
57
+ spec_aug_mask_idxs = np.broadcast_to(spec_aug_mask_idxs[:, :, None], (batch_size, max_num_masked_span, mask_length))
58
+ spec_aug_mask_idxs = spec_aug_mask_idxs.reshape(batch_size, max_num_masked_span * mask_length)
59
+ offsets = np.broadcast_to(np.arange(mask_length)[None, None, :], (batch_size, max_num_masked_span, mask_length))
60
+ spec_aug_mask_idxs = spec_aug_mask_idxs + offsets.reshape(batch_size, max_num_masked_span * mask_length)
61
+ spec_aug_mask_idxs[spec_aug_mask_idxs > sequence_length - 1] = sequence_length - 1
62
+ np.put_along_axis(spec_aug_mask, spec_aug_mask_idxs, 1, -1)
63
+ return spec_aug_mask
64
+
65
+
66
+ # --------------------------------------------------------------------------- #
67
+ # convolutional feature encoder
68
+ # --------------------------------------------------------------------------- #
69
+ class SpeechJEPAConvLayer(nn.Module):
70
+ def __init__(self, config: SpeechJEPAConfig, layer_id: int):
71
+ super().__init__()
72
+ in_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
73
+ out_dim = config.conv_dim[layer_id]
74
+ self.conv = nn.Conv1d(in_dim, out_dim, config.conv_kernel[layer_id],
75
+ stride=config.conv_stride[layer_id], bias=config.conv_bias)
76
+ self.layer_norm = None
77
+ if config.feat_extract_norm == "group" and layer_id == 0:
78
+ self.layer_norm = nn.GroupNorm(out_dim, out_dim, affine=True)
79
+ self.activation = ACT2FN[config.hidden_act]
80
+
81
+ def forward(self, hidden_states):
82
+ hidden_states = self.conv(hidden_states)
83
+ if self.layer_norm is not None:
84
+ hidden_states = self.layer_norm(hidden_states)
85
+ return self.activation(hidden_states)
86
+
87
+
88
+ class SpeechJEPAFeatureEncoder(nn.Module):
89
+ def __init__(self, config: SpeechJEPAConfig):
90
+ super().__init__()
91
+ self.conv_layers = nn.ModuleList([SpeechJEPAConvLayer(config, i) for i in range(config.num_feat_extract_layers)])
92
+ self._requires_grad = True
93
+
94
+ def _freeze_parameters(self):
95
+ for p in self.parameters():
96
+ p.requires_grad = False
97
+ self._requires_grad = False
98
+
99
+ def forward(self, input_values):
100
+ hidden_states = input_values[:, None] # (B, 1, T)
101
+ for layer in self.conv_layers:
102
+ hidden_states = layer(hidden_states)
103
+ return hidden_states # (B, C, T')
104
+
105
+
106
+ class SpeechJEPAFeatureProjection(nn.Module):
107
+ """LayerNorm(conv features) -> Linear -> LayerNorm(hidden)."""
108
+
109
+ def __init__(self, config: SpeechJEPAConfig):
110
+ super().__init__()
111
+ self.layer_norm = nn.LayerNorm(config.conv_dim[-1])
112
+ self.projection = nn.Linear(config.conv_dim[-1], config.hidden_size)
113
+ self.post_layer_norm = nn.LayerNorm(config.hidden_size)
114
+
115
+ def forward(self, hidden_states):
116
+ hidden_states = self.layer_norm(hidden_states)
117
+ hidden_states = self.projection(hidden_states)
118
+ return self.post_layer_norm(hidden_states)
119
+
120
+
121
+ # --------------------------------------------------------------------------- #
122
+ # Transformer encoder with rotary position embeddings
123
+ # --------------------------------------------------------------------------- #
124
+ def apply_rotary(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
125
+ """Interleaved-pair RoPE (same convention as torchtune's RotaryPositionalEmbeddings).
126
+
127
+ x: (B, S, H, D); cos/sin: (S, D // 2).
128
+ """
129
+ dtype = x.dtype
130
+ x = x.float().reshape(*x.shape[:-1], -1, 2)
131
+ cos = cos[None, :, None, :]
132
+ sin = sin[None, :, None, :]
133
+ out = torch.stack([x[..., 0] * cos - x[..., 1] * sin, x[..., 1] * cos + x[..., 0] * sin], dim=-1)
134
+ return out.flatten(3).to(dtype)
135
+
136
+
137
+ class SpeechJEPARotaryEmbedding(nn.Module):
138
+ """cos/sin tables for interleaved RoPE. Computed on the fly (and cached as plain attributes, not buffers,
139
+ so that meta-device instantiation in `from_pretrained` cannot leave them uninitialised)."""
140
+
141
+ def __init__(self, dim: int, max_seq_len: int, base: float):
142
+ super().__init__()
143
+ self.dim, self.base, self.max_seq_len = dim, base, max_seq_len
144
+ self._cache = {}
145
+
146
+ def forward(self, seq_len: int, device):
147
+ key = (seq_len, str(device))
148
+ if key not in self._cache:
149
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, device=device).float() / self.dim))
150
+ pos = torch.arange(seq_len, dtype=torch.float32, device=device)
151
+ freqs = torch.outer(pos, inv_freq)
152
+ self._cache = {key: (freqs.cos(), freqs.sin())}
153
+ return self._cache[key]
154
+
155
+
156
+ class SpeechJEPAAttention(nn.Module):
157
+ def __init__(self, config: SpeechJEPAConfig):
158
+ super().__init__()
159
+ self.num_heads = config.num_attention_heads
160
+ self.head_dim = config.hidden_size // config.num_attention_heads
161
+ self.dropout = config.attention_dropout
162
+ self.q_proj = nn.Linear(config.hidden_size, config.hidden_size)
163
+ self.k_proj = nn.Linear(config.hidden_size, config.hidden_size)
164
+ self.v_proj = nn.Linear(config.hidden_size, config.hidden_size)
165
+ self.out_proj = nn.Linear(config.hidden_size, config.hidden_size)
166
+
167
+ def forward(self, hidden_states, cos, sin, attention_mask=None):
168
+ B, S, _ = hidden_states.shape
169
+ q = self.q_proj(hidden_states).view(B, S, self.num_heads, self.head_dim)
170
+ k = self.k_proj(hidden_states).view(B, S, self.num_heads, self.head_dim)
171
+ v = self.v_proj(hidden_states).view(B, S, self.num_heads, self.head_dim)
172
+ q = apply_rotary(q, cos, sin).transpose(1, 2)
173
+ k = apply_rotary(k, cos, sin).transpose(1, 2)
174
+ v = v.transpose(1, 2)
175
+ out = F.scaled_dot_product_attention(q, k, v, attn_mask=attention_mask,
176
+ dropout_p=self.dropout if self.training else 0.0, is_causal=False)
177
+ return self.out_proj(out.transpose(1, 2).reshape(B, S, -1))
178
+
179
+
180
+ class SpeechJEPAFeedForward(nn.Module):
181
+ def __init__(self, config: SpeechJEPAConfig):
182
+ super().__init__()
183
+ self.intermediate_dense = nn.Linear(config.hidden_size, config.intermediate_size)
184
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
185
+ self.intermediate_dropout = nn.Dropout(config.activation_dropout)
186
+ self.output_dense = nn.Linear(config.intermediate_size, config.hidden_size)
187
+ self.output_dropout = nn.Dropout(config.hidden_dropout)
188
+
189
+ def forward(self, hidden_states):
190
+ hidden_states = self.intermediate_dropout(self.intermediate_act_fn(self.intermediate_dense(hidden_states)))
191
+ return self.output_dropout(self.output_dense(hidden_states))
192
+
193
+
194
+ class SpeechJEPAEncoderLayer(nn.Module):
195
+ """Post-norm Transformer layer: LN(x + attn(x)) -> LN(h + ffn(h))."""
196
+
197
+ def __init__(self, config: SpeechJEPAConfig):
198
+ super().__init__()
199
+ self.attention = SpeechJEPAAttention(config)
200
+ self.dropout = nn.Dropout(config.hidden_dropout)
201
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
202
+ self.feed_forward = SpeechJEPAFeedForward(config)
203
+ self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
204
+
205
+ def forward(self, hidden_states, cos, sin, attention_mask=None):
206
+ hidden_states = self.layer_norm(hidden_states + self.dropout(self.attention(hidden_states, cos, sin, attention_mask)))
207
+ return self.final_layer_norm(hidden_states + self.feed_forward(hidden_states))
208
+
209
+
210
+ class SpeechJEPAEncoder(nn.Module):
211
+ def __init__(self, config: SpeechJEPAConfig):
212
+ super().__init__()
213
+ self.config = config
214
+ self.rotary = SpeechJEPARotaryEmbedding(config.hidden_size // config.num_attention_heads,
215
+ config.max_position_embeddings, config.rope_theta)
216
+ self.layers = nn.ModuleList([SpeechJEPAEncoderLayer(config) for _ in range(config.num_hidden_layers)])
217
+
218
+ def forward(self, hidden_states, attention_mask=None, output_hidden_states=False, return_dict=True):
219
+ B, S, _ = hidden_states.shape
220
+ sdpa_mask = None
221
+ if attention_mask is not None:
222
+ # (B, S) 1 = real frame -> (B, 1, 1, S) bool, True = may attend to key
223
+ sdpa_mask = attention_mask.bool()[:, None, None, :]
224
+ cos, sin = self.rotary(S, hidden_states.device)
225
+
226
+ all_hidden_states = (hidden_states,) if output_hidden_states else None
227
+ for layer in self.layers:
228
+ if self.training and torch.rand(1).item() < self.config.layerdrop:
229
+ continue
230
+ hidden_states = layer(hidden_states, cos, sin, sdpa_mask)
231
+ if output_hidden_states:
232
+ all_hidden_states = all_hidden_states + (hidden_states,)
233
+
234
+ if not return_dict:
235
+ return tuple(v for v in (hidden_states, all_hidden_states) if v is not None)
236
+ return BaseModelOutput(last_hidden_state=hidden_states, hidden_states=all_hidden_states)
237
+
238
+
239
+ # --------------------------------------------------------------------------- #
240
+ # pretrained-model wrappers
241
+ # --------------------------------------------------------------------------- #
242
+ class SpeechJEPAPreTrainedModel(PreTrainedModel):
243
+ config_class = SpeechJEPAConfig
244
+ base_model_prefix = "speech_jepa"
245
+ main_input_name = "input_values"
246
+ supports_gradient_checkpointing = False
247
+
248
+ def _init_weights(self, module):
249
+ if isinstance(module, nn.Linear):
250
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
251
+ if module.bias is not None:
252
+ module.bias.data.zero_()
253
+ elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):
254
+ module.bias.data.zero_()
255
+ module.weight.data.fill_(1.0)
256
+ elif isinstance(module, nn.Conv1d):
257
+ nn.init.kaiming_normal_(module.weight)
258
+ if module.bias is not None:
259
+ module.bias.data.zero_()
260
+ elif isinstance(module, SpeechJEPAModel):
261
+ module.masked_spec_embed.data.uniform_()
262
+
263
+ def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor):
264
+ for kernel, stride in zip(self.config.conv_kernel, self.config.conv_stride):
265
+ input_lengths = torch.div(input_lengths - kernel, stride, rounding_mode="floor") + 1
266
+ return input_lengths
267
+
268
+ def _get_feature_vector_attention_mask(self, feature_vector_length: int, attention_mask: torch.LongTensor):
269
+ output_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(-1)).to(torch.long)
270
+ batch_size = attention_mask.shape[0]
271
+ mask = torch.zeros((batch_size, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device)
272
+ mask[(torch.arange(batch_size, device=mask.device), output_lengths - 1)] = 1
273
+ return mask.flip([-1]).cumsum(-1).flip([-1]).bool()
274
+
275
+
276
+ class SpeechJEPAModel(SpeechJEPAPreTrainedModel):
277
+ def __init__(self, config: SpeechJEPAConfig):
278
+ super().__init__(config)
279
+ self.config = config
280
+ self.feature_extractor = SpeechJEPAFeatureEncoder(config)
281
+ self.feature_projection = SpeechJEPAFeatureProjection(config)
282
+ self.masked_spec_embed = nn.Parameter(torch.Tensor(config.hidden_size).uniform_())
283
+ self.dropout = nn.Dropout(config.hidden_dropout)
284
+ self.encoder = SpeechJEPAEncoder(config)
285
+ self.post_init()
286
+
287
+ def freeze_feature_encoder(self):
288
+ self.feature_extractor._freeze_parameters()
289
+
290
+ def _mask_hidden_states(self, hidden_states, mask_time_indices=None, attention_mask=None):
291
+ if not getattr(self.config, "apply_spec_augment", True):
292
+ return hidden_states
293
+ batch_size, sequence_length, hidden_size = hidden_states.size()
294
+ if mask_time_indices is not None:
295
+ hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
296
+ elif self.config.mask_time_prob > 0 and self.training:
297
+ idx = _compute_mask_indices((batch_size, sequence_length), self.config.mask_time_prob,
298
+ self.config.mask_time_length, attention_mask=attention_mask,
299
+ min_masks=self.config.mask_time_min_masks)
300
+ idx = torch.tensor(idx, device=hidden_states.device, dtype=torch.bool)
301
+ hidden_states[idx] = self.masked_spec_embed.to(hidden_states.dtype)
302
+ if self.config.mask_feature_prob > 0 and self.training:
303
+ idx = _compute_mask_indices((batch_size, hidden_size), self.config.mask_feature_prob,
304
+ self.config.mask_feature_length, min_masks=self.config.mask_feature_min_masks)
305
+ idx = torch.tensor(idx, device=hidden_states.device, dtype=torch.bool)[:, None].expand(-1, sequence_length, -1)
306
+ hidden_states[idx] = 0
307
+ return hidden_states
308
+
309
+ def forward(
310
+ self,
311
+ input_values: torch.Tensor,
312
+ attention_mask: Optional[torch.Tensor] = None,
313
+ mask_time_indices: Optional[torch.BoolTensor] = None,
314
+ output_hidden_states: Optional[bool] = None,
315
+ return_dict: Optional[bool] = None,
316
+ ) -> Union[Tuple, BaseModelOutput]:
317
+ """``input_values``: (B, T) waveform at 16 kHz, normalised to zero mean / unit variance per utterance
318
+ (use ``Wav2Vec2FeatureExtractor`` with ``do_normalize=True``). ``attention_mask``: (B, T), 1 = real sample."""
319
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
320
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
321
+
322
+ features = self.feature_extractor(input_values).transpose(1, 2) # (B, T', C)
323
+ hidden_states = self.feature_projection(features)
324
+
325
+ frame_mask = None
326
+ if attention_mask is not None:
327
+ frame_mask = self._get_feature_vector_attention_mask(hidden_states.shape[1], attention_mask)
328
+
329
+ hidden_states = self._mask_hidden_states(hidden_states, mask_time_indices=mask_time_indices, attention_mask=frame_mask)
330
+ hidden_states = self.dropout(hidden_states)
331
+
332
+ encoder_outputs = self.encoder(hidden_states, attention_mask=frame_mask,
333
+ output_hidden_states=output_hidden_states, return_dict=return_dict)
334
+ if not return_dict:
335
+ return encoder_outputs
336
+ return BaseModelOutput(last_hidden_state=encoder_outputs.last_hidden_state, hidden_states=encoder_outputs.hidden_states)
337
+
338
+
339
+ class SpeechJEPAForCTC(SpeechJEPAPreTrainedModel):
340
+ def __init__(self, config: SpeechJEPAConfig):
341
+ super().__init__(config)
342
+ self.speech_jepa = SpeechJEPAModel(config)
343
+ self.dropout = nn.Dropout(config.final_dropout)
344
+ if config.vocab_size is None:
345
+ raise ValueError("`config.vocab_size` must be set for SpeechJEPAForCTC")
346
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size)
347
+ if config.use_weighted_layer_sum:
348
+ self.layer_weights = nn.Parameter(torch.ones(config.num_hidden_layers + 1) / (config.num_hidden_layers + 1))
349
+ self.post_init()
350
+
351
+ def freeze_feature_encoder(self):
352
+ self.speech_jepa.feature_extractor._freeze_parameters()
353
+
354
+ def freeze_base_model(self):
355
+ for p in self.speech_jepa.parameters():
356
+ p.requires_grad = False
357
+
358
+ def forward(
359
+ self,
360
+ input_values: torch.Tensor,
361
+ attention_mask: Optional[torch.Tensor] = None,
362
+ labels: Optional[torch.Tensor] = None,
363
+ output_hidden_states: Optional[bool] = None,
364
+ return_dict: Optional[bool] = None,
365
+ ) -> Union[Tuple, CausalLMOutput]:
366
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
367
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
368
+
369
+ outputs = self.speech_jepa(input_values, attention_mask=attention_mask,
370
+ output_hidden_states=output_hidden_states, return_dict=True)
371
+ if self.config.use_weighted_layer_sum:
372
+ hidden_states = torch.stack(outputs.hidden_states, dim=1)
373
+ norm_weights = F.softmax(self.layer_weights, dim=-1)
374
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
375
+ else:
376
+ hidden_states = outputs.last_hidden_state
377
+
378
+ logits = self.lm_head(self.dropout(hidden_states))
379
+
380
+ loss = None
381
+ if labels is not None:
382
+ if labels.max() >= self.config.vocab_size:
383
+ raise ValueError(f"Label values must be <= vocab_size: {self.config.vocab_size}")
384
+ attention_mask = attention_mask if attention_mask is not None else torch.ones_like(input_values, dtype=torch.long)
385
+ input_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(-1)).to(torch.long)
386
+ labels_mask = labels >= 0
387
+ target_lengths = labels_mask.sum(-1)
388
+ flattened_targets = labels.masked_select(labels_mask)
389
+ log_probs = F.log_softmax(logits, dim=-1, dtype=torch.float32).transpose(0, 1)
390
+ with torch.backends.cudnn.flags(enabled=False):
391
+ loss = F.ctc_loss(log_probs, flattened_targets, input_lengths, target_lengths,
392
+ blank=self.config.pad_token_id, reduction=self.config.ctc_loss_reduction,
393
+ zero_infinity=self.config.ctc_zero_infinity)
394
+
395
+ if not return_dict:
396
+ output = (logits,) + ((outputs.hidden_states,) if output_hidden_states else ())
397
+ return ((loss,) + output) if loss is not None else output
398
+ return CausalLMOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states if output_hidden_states else None)
399
+
400
+
401
+ __all__ = ["SpeechJEPAConfig", "SpeechJEPAPreTrainedModel", "SpeechJEPAModel", "SpeechJEPAForCTC"]
preprocessor_config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "do_normalize": true,
3
+ "feature_extractor_type": "Wav2Vec2FeatureExtractor",
4
+ "feature_size": 1,
5
+ "padding_side": "right",
6
+ "padding_value": 0.0,
7
+ "return_attention_mask": true,
8
+ "sampling_rate": 16000
9
+ }
training_config.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "transformer_encoder_layers_cfg": {
3
+ "d_model": 768,
4
+ "nhead": 12,
5
+ "batch_first": true,
6
+ "norm_first": false,
7
+ "bias": true,
8
+ "dim_feedforward": 3072,
9
+ "dropout": 0.0,
10
+ "activation": "GELU(approximate='none')",
11
+ "layer_norm_eps": 1e-06
12
+ },
13
+ "transformer_encoder_cfg": {
14
+ "num_layers": 12,
15
+ "enable_nested_tensor": false,
16
+ "mask_check": true
17
+ },
18
+ "lr": 0.0004,
19
+ "adam_betas": [
20
+ 0.9,
21
+ 0.98
22
+ ],
23
+ "adam_eps": 1e-06,
24
+ "adam_weight_decay": 0.01,
25
+ "ema_decay": 0.999,
26
+ "ema_end_decay": 0.99999,
27
+ "ema_anneal_end_step": 100000,
28
+ "warmup_steps": 100000,
29
+ "average_top_k_layers": 8,
30
+ "resample_sr": 16000,
31
+ "original_sr": 16000,
32
+ "use_gradient_checkpointing": false,
33
+ "compile_modules": false,
34
+ "size": "base",
35
+ "clean_audio_ratio": 0.0
36
+ }