kehanlu commited on
Commit
eded533
·
verified ·
1 Parent(s): d08f785

remove mirrored code/ (use the GitHub repo)

Browse files
Files changed (3) hide show
  1. code/data.py +0 -302
  2. code/inference.py +0 -201
  3. code/modeling.py +0 -171
code/data.py DELETED
@@ -1,302 +0,0 @@
1
- """
2
- Data pipeline for the minimal SpeechLLM.
3
-
4
- It sees a plain text token sequence in which every ``<|AUDIO|>`` has been replaced
5
- by exactly as many placeholder tokens as that audio will occupy after encoding.
6
- The model later overwrites those placeholders' *embeddings* with real speech
7
- features (see modeling.py). Nothing else about the LLM changes.
8
-
9
- Everything that turns "a manifest row" into "model inputs" happens in `Collator`.
10
- The `Dataset` is a dumb jsonl reader. Keeping it in one place matters here: the
11
- number of placeholders depends on the audio's true duration, which we only know
12
- once the waveform is loaded -- so the expansion has to happen next to the audio.
13
-
14
- Manifest format (one JSON object per line)::
15
-
16
- {
17
- "audios": [
18
- {"audio_filepath": "ESC50/1-103999-A-30.wav"}
19
- ],
20
- "messages": [
21
- {"role": "user", "content": "What do you hear? <|AUDIO|>"}
22
- ],
23
- "target": "A wooden door being knocked on."
24
- }
25
-
26
- `audio_filepath` is relative to `audio_root`. `target` may also be called
27
- `response` (both appear in the DeSTA3 manifests). Extra keys are ignored.
28
- """
29
-
30
- import json
31
- import logging
32
- import math
33
- import os
34
- import random
35
- from dataclasses import dataclass, field
36
- from typing import Any, List, Optional
37
-
38
- import librosa
39
- import torch
40
- from torch.utils.data import Dataset
41
-
42
- logger = logging.getLogger(__name__)
43
-
44
- SAMPLE_RATE = 16000
45
-
46
-
47
- # How many tokens will one audio occupy?
48
- #
49
- # Whisper's feature extractor always pads to 30 s, so we cannot use the padded
50
- # length -- a 5 s clip would reserve 25 s worth of slots. We ask the feature
51
- # extractor for an attention mask over the mel frames instead, and push the true
52
- # length through the same downsampling arithmetic the model uses.
53
-
54
- def whisper_frames(mel_len: int) -> int:
55
- """Whisper's encoder conv2 has stride 2. 3000 mel frames -> 1500 positions."""
56
- return (mel_len - 1) // 2 + 1
57
-
58
-
59
- def audio_token_count(mel_len: int, n_downsample: int) -> int:
60
- """mel frames -> number of LLM token slots this audio needs.
61
-
62
- The connector concatenates every `n_downsample` adjacent frames and right-pads to
63
- a multiple of that, so the count is ceil(frames / n_downsample), rounding up.
64
- """
65
- return -(-whisper_frames(mel_len) // n_downsample)
66
-
67
-
68
- def expand_audio_locator(tokens: List[str], audio_locator: str,
69
- placeholder_token: str, slot_sizes: List[int]):
70
- """Replace each `audio_locator` with `slot_sizes[i]` placeholder tokens.
71
-
72
- ``["a", "<|AUDIO|>", "b"]`` with ``slot_sizes=[3]`` becomes
73
- ``["a", "<|pad|>", "<|pad|>", "<|pad|>", "b"]`` and ``start_positions=[1]``.
74
- """
75
- out: List[str] = []
76
- starts: List[int] = []
77
- sizes = iter(slot_sizes)
78
- for token in tokens:
79
- if token == audio_locator:
80
- starts.append(len(out))
81
- out.extend([placeholder_token] * next(sizes))
82
- else:
83
- out.append(token)
84
- return out, starts
85
-
86
-
87
- def resolve_manifest(path: str) -> str:
88
- """Accept a local path or a huggingface.co/datasets/... resolve URL."""
89
- prefix = "https://huggingface.co/datasets/"
90
- if not path.startswith(prefix):
91
- return path
92
- from huggingface_hub import hf_hub_download
93
-
94
- parts = path[len(prefix):].split("/")
95
- repo_id, marker, revision = "/".join(parts[:2]), parts[2], parts[3]
96
- assert marker == "resolve", f"unsupported HF url: {path}"
97
- return hf_hub_download(repo_id=repo_id, filename="/".join(parts[4:]),
98
- revision=revision, repo_type="dataset")
99
-
100
-
101
- def resolve_audio_filepath(path: str) -> str:
102
- if os.path.exists(path):
103
- return path
104
- wav = os.path.splitext(path)[0] + ".wav"
105
- if os.path.exists(wav):
106
- return wav
107
- raise FileNotFoundError(path)
108
-
109
-
110
- def split_manifest_entries(entries):
111
- """Manifest entries are a path (ratio 1.0) or {"path": ..., "ratio": ...}.
112
-
113
- Returns (paths, ratios).
114
- """
115
- paths, ratios = [], []
116
- for entry in entries:
117
- if isinstance(entry, str):
118
- path, ratio = entry, 1.0
119
- else:
120
- unknown = set(entry) - {"path", "ratio"}
121
- assert "path" in entry and not unknown, f"bad manifest entry {entry!r}"
122
- path, ratio = entry["path"], float(entry.get("ratio", 1.0))
123
- assert ratio >= 0, f"{path}: ratio must be >= 0, got {ratio}"
124
- paths.append(path)
125
- ratios.append(ratio)
126
- return paths, ratios
127
-
128
-
129
- def manifest_name(path: str) -> str:
130
- return os.path.basename(path).removesuffix(".jsonl")
131
-
132
-
133
- class AudioTextDataset(Dataset):
134
- """Lazy jsonl reader with per-manifest mixing ratios.
135
- """
136
-
137
- def __init__(self, manifest_filepaths, audio_root: str, ratios=None, seed: int = 0):
138
- self.audio_root = audio_root
139
- self.paths = [resolve_manifest(p) for p in manifest_filepaths]
140
- self.ratios = list(ratios) if ratios is not None else [1.0] * len(self.paths)
141
- assert len(self.ratios) == len(self.paths)
142
- self.seed = seed
143
- self.rows = [] # per manifest: [(file_idx, byte_offset), ...]
144
- for file_idx, path in enumerate(self.paths):
145
- rows = []
146
- with open(path, "rb") as f:
147
- offset = 0
148
- for line in f:
149
- if line.strip():
150
- rows.append((file_idx, offset))
151
- offset += len(line)
152
- self.rows.append(rows)
153
- self._handles = {} # opened lazily, per dataloader worker
154
- self.resample(epoch=0, log=True)
155
-
156
- @property
157
- def needs_resampling(self) -> bool:
158
- """True when some ratio has a fractional part, i.e. a random subset is drawn."""
159
- return any(r != math.floor(r) for r in self.ratios)
160
-
161
- def resample(self, epoch: int, log: bool = False):
162
- self.index = [] # (file_idx, byte_offset)
163
- for file_idx, (rows, ratio) in enumerate(zip(self.rows, self.ratios)):
164
- whole = math.floor(ratio)
165
- n_extra = round((ratio - whole) * len(rows))
166
- # str seed: hashed with sha512, identical across processes and runs
167
- rng = random.Random(f"{self.seed}-{epoch}-{file_idx}")
168
- self.index += rows * whole + rng.sample(rows, n_extra)
169
- if log:
170
- logger.info(" %-32s ratio %.2f: %d of %d rows", manifest_name(self.paths[file_idx]),
171
- ratio, whole * len(rows) + n_extra, len(rows))
172
- if log:
173
- logger.info("loaded %d rows from %d manifest(s)", len(self.index), len(self.paths))
174
-
175
- def __len__(self):
176
- return len(self.index)
177
-
178
- def __getitem__(self, i):
179
- file_idx, offset = self.index[i]
180
- handle = self._handles.get(file_idx)
181
- if handle is None:
182
- handle = self._handles[file_idx] = open(self.paths[file_idx], "rb")
183
- handle.seek(offset)
184
- row = json.loads(handle.readline())
185
-
186
- # DeSTA3 manifests use either key; `response` wins when both are present.
187
- target = row.get("response") or row.get("target")
188
- assert target, f"row {i} has neither `response` nor `target`"
189
-
190
- audios = [{"audio_filepath": resolve_audio_filepath(
191
- os.path.join(self.audio_root, audio["audio_filepath"]))}
192
- for audio in row["audios"]]
193
- return {"messages": row["messages"], "target": target, "audios": audios}
194
-
195
-
196
- @dataclass
197
- class Collator:
198
- """Turns a list of rows into the tensors `SpeechLLM.forward` expects.
199
-
200
- Padding is on the **left** so that every sequence's answer ends at the same
201
- index -- that keeps `generate()` simple. It also means every position we
202
- record has to be shifted by that sequence's pad length.
203
- """
204
-
205
- tokenizer: Any
206
- feature_extractor: Any
207
- audio_locator: str = "<|AUDIO|>"
208
- placeholder_token: str = "<|vision_pad|>"
209
- max_seq_length: int = 1024
210
- max_audio_seconds: float = 30.0
211
- n_downsample: int = 2
212
- # inference: build the prompt only, with no answer appended and no labels.
213
- # Same slot arithmetic as training -- that is the whole point of reusing this
214
- # class rather than rebuilding the expansion in the demo script.
215
- for_generation: bool = False
216
-
217
- def __post_init__(self):
218
- assert self.tokenizer.padding_side == "left"
219
- assert self.placeholder_token in self.tokenizer.get_vocab(), (
220
- f"placeholder_token {self.placeholder_token!r} is not in the tokenizer "
221
- "vocabulary; pick a reserved/unused token of your LLM")
222
- self.placeholder_id = self.tokenizer.convert_tokens_to_ids(self.placeholder_token)
223
- self.pad_id = self.tokenizer.pad_token_id
224
-
225
- def __call__(self, batch):
226
- # 1. audio -> mel features, and the true (unpadded) length of each
227
- waveforms = []
228
- for row in batch:
229
- for audio in row["audios"]:
230
- wav, _ = librosa.load(audio["audio_filepath"], sr=SAMPLE_RATE, mono=True)
231
- waveforms.append(wav[:int(self.max_audio_seconds * SAMPLE_RATE)])
232
-
233
- features = self.feature_extractor(
234
- waveforms, sampling_rate=SAMPLE_RATE,
235
- return_tensors="pt", return_attention_mask=True,
236
- )
237
- mel_lengths = features["attention_mask"].sum(-1).tolist()
238
- audio_lengths = [audio_token_count(n, self.n_downsample) for n in mel_lengths]
239
-
240
- # 2. text -> token ids, with <|AUDIO|> expanded to placeholders
241
- context_ids, target_ids = [], []
242
- start_positions, audio_index = [], 0
243
-
244
- for row in batch:
245
- n_audios = len(row["audios"])
246
- # each audio reserves one slot per speech feature frame
247
- slot_sizes = audio_lengths[audio_index:audio_index + n_audios]
248
-
249
- prompt = self.tokenizer.apply_chat_template(
250
- row["messages"], tokenize=False, add_generation_prompt=True,
251
- enable_thinking=False,
252
- )
253
- tokens = self.tokenizer.tokenize(prompt)
254
- assert tokens.count(self.audio_locator) == n_audios, (
255
- f"{n_audios} audios but {tokens.count(self.audio_locator)} "
256
- f"{self.audio_locator} in the prompt")
257
-
258
- tokens, starts = expand_audio_locator(
259
- tokens, self.audio_locator, self.placeholder_token, slot_sizes)
260
-
261
- # straight to ids -- no convert_tokens_to_string round-trip, so the
262
- # placeholder can never be re-tokenized into something else
263
- ctx = self.tokenizer.convert_tokens_to_ids(tokens)
264
- if self.for_generation:
265
- tgt = [] # nothing to condition on; the model writes it
266
- else:
267
- tgt = self.tokenizer.encode(row["target"], add_special_tokens=False)
268
- tgt = tgt + [self.tokenizer.eos_token_id]
269
-
270
- assert len(ctx) < self.max_seq_length, (
271
- f"prompt alone is {len(ctx)} tokens (max_seq_length="
272
- f"{self.max_seq_length}); shorten the audio or raise the limit")
273
- tgt = tgt[:self.max_seq_length - len(ctx)] # only ever truncate the answer
274
-
275
- context_ids.append(ctx)
276
- target_ids.append(tgt)
277
- start_positions.append(starts)
278
- audio_index += n_audios
279
-
280
- # 3. left-pad, build labels, shift the recorded positions
281
- width = max(len(c) + len(t) for c, t in zip(context_ids, target_ids))
282
- input_ids = torch.full((len(batch), width), self.pad_id, dtype=torch.long)
283
- attention_mask = torch.zeros((len(batch), width), dtype=torch.long)
284
- labels = torch.full((len(batch), width), -100, dtype=torch.long)
285
- shifted_starts = []
286
-
287
- for i, (ctx, tgt) in enumerate(zip(context_ids, target_ids)):
288
- pad = width - len(ctx) - len(tgt)
289
- input_ids[i, pad:] = torch.tensor(ctx + tgt, dtype=torch.long)
290
- attention_mask[i, pad:] = 1
291
- labels[i, pad + len(ctx):] = torch.tensor(tgt, dtype=torch.long) # answer only
292
- for start in start_positions[i]:
293
- shifted_starts.append((i, start + pad))
294
-
295
- return {
296
- "input_ids": input_ids,
297
- "attention_mask": attention_mask,
298
- "labels": labels,
299
- "input_features": features["input_features"],
300
- "audio_lengths": audio_lengths, # per audio, after downsampling
301
- "start_positions": shifted_starts, # per audio, (row, first placeholder)
302
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
code/inference.py DELETED
@@ -1,201 +0,0 @@
1
- #!/usr/bin/env python
2
- """
3
- Inference for the minimal SpeechLLM -- the tutorial's demo entry point.
4
-
5
- # one file
6
- python inference.py --ckpt exp/run/checkpoints/last.ckpt --audio sample.flac
7
-
8
- # score a manifest: prints reference vs hypothesis side by side
9
- python inference.py --ckpt exp/run/checkpoints/last.ckpt \
10
- --manifest data/Librispeech-dev-test/test-clean_asr.jsonl \
11
- --audio-root /path/to/data --limit 20
12
-
13
- """
14
-
15
- import argparse
16
- import json
17
- import logging
18
- import os
19
-
20
- import torch
21
- from transformers import AutoFeatureExtractor, AutoTokenizer
22
-
23
- from data import Collator
24
- from modeling import SpeechLLM
25
-
26
- logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
27
- logger = logging.getLogger(__name__)
28
-
29
- DEFAULT_PROMPT = "<audio><|AUDIO|></audio>\n\nTranscribe the speech into text"
30
-
31
-
32
- class SpeechLLMForInference:
33
- """Checkpoint in, text out.
34
-
35
- `generate()` takes DeSTA3-style messages so the demo reads like a chat call:
36
-
37
- [{"role": "user",
38
- "content": "<audio><|AUDIO|></audio>\\n\\nTranscribe the speech into text",
39
- "audios": [{"audio": "sample.flac"}]}]
40
-
41
- Pass a list of those to batch several utterances in one forward pass.
42
- """
43
-
44
- def __init__(self, model, tokenizer, collator, device, dtype):
45
- self.model, self.tokenizer = model, tokenizer
46
- self.collator, self.device, self.dtype = collator, device, dtype
47
-
48
- # -- loading --
49
- @classmethod
50
- def from_checkpoint(cls, ckpt_path, device=None, dtype=None):
51
- device = device or ("cuda" if torch.cuda.is_available() else "cpu")
52
- ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False)
53
- hp = ckpt["hyper_parameters"]
54
- dtype = dtype or getattr(torch, hp["dtype"])
55
- logger.info("checkpoint %s (epoch %s, step %s)",
56
- os.path.basename(ckpt_path), ckpt.get("epoch"), ckpt.get("global_step"))
57
- # n_downsample used to be n_downsample_layers, an exponent: 1 meant 2 frames
58
- # per token. Map the old key so earlier checkpoints still load.
59
- n_downsample = hp.get("n_downsample") or 2 ** hp["n_downsample_layers"]
60
- logger.info(" llm=%s encoder=%s n_downsample=%d frozen_encoder=%s",
61
- hp["llm_id"], hp["encoder_id"],
62
- n_downsample, hp.get("freeze_encoder", False))
63
-
64
- # rebuilt exactly as SpeechLLMModule.__init__ does, or the ids shift
65
- tokenizer = AutoTokenizer.from_pretrained(hp["llm_id"])
66
- tokenizer.pad_token = tokenizer.eos_token
67
- tokenizer.padding_side = "left"
68
- tokenizer.add_tokens([hp["audio_locator"]])
69
- feature_extractor = AutoFeatureExtractor.from_pretrained(hp["encoder_id"])
70
-
71
- model = SpeechLLM(
72
- llm_id=hp["llm_id"], encoder_id=hp["encoder_id"],
73
- n_downsample=n_downsample, dtype=dtype,
74
- # .get(): older checkpoints predate these options
75
- adapter_hidden_dim=hp.get("adapter_hidden_dim", 0),
76
- freeze_encoder=hp.get("freeze_encoder", False), use_lora=True,
77
- lora_rank=hp["lora_rank"], lora_alpha=hp["lora_alpha"],
78
- lora_dropout=hp["lora_dropout"],
79
- lora_target_modules=hp["lora_target_modules"],
80
- )
81
- cls._load_trainable(model, ckpt["state_dict"])
82
- model.to(device).eval()
83
-
84
- collator = Collator(
85
- tokenizer=tokenizer, feature_extractor=feature_extractor,
86
- audio_locator=hp["audio_locator"], placeholder_token=hp["placeholder_token"],
87
- max_seq_length=hp["max_seq_length"], max_audio_seconds=hp["max_audio_seconds"],
88
- n_downsample=n_downsample,
89
- for_generation=True,
90
- )
91
- return cls(model, tokenizer, collator, device, dtype)
92
-
93
- @staticmethod
94
- def _load_trainable(model, state_dict):
95
- """Load the trainable-only checkpoint, and prove every tensor landed."""
96
- state = {k[len("model."):]: v for k, v in state_dict.items() if k.startswith("model.")}
97
- expected = {n for n, p in model.named_parameters() if p.requires_grad}
98
- missing, unexpected = expected - set(state), set(state) - expected
99
- assert not unexpected, (
100
- f"{len(unexpected)} tensors in the checkpoint match nothing in the model, "
101
- f"e.g. {sorted(unexpected)[:3]} -- the architecture does not match")
102
- assert not missing, (
103
- f"{len(missing)} trainable tensors were not in the checkpoint, "
104
- f"e.g. {sorted(missing)[:3]} -- they would stay randomly initialised")
105
- result = model.load_state_dict(state, strict=False)
106
- assert not result.unexpected_keys, result.unexpected_keys
107
- logger.info(" restored %d trainable tensors (%.1fM params)", len(state),
108
- sum(v.numel() for v in state.values()) / 1e6)
109
-
110
- # -- generation --
111
- def _to_rows(self, conversations):
112
- """DeSTA3-style messages -> the row dicts `Collator` consumes."""
113
- rows = []
114
- for conv in conversations:
115
- audios = []
116
- for message in conv:
117
- for audio in message.get("audios", []):
118
- path = audio["audio"] if isinstance(audio, dict) else audio
119
- assert os.path.exists(path), f"no such audio: {path}"
120
- audios.append({"audio_filepath": path})
121
- n_locators = sum(m["content"].count(self.collator.audio_locator) for m in conv)
122
- assert n_locators == len(audios), (
123
- f"{len(audios)} audios but {n_locators} {self.collator.audio_locator} "
124
- "in the conversation")
125
- # strip `audios` before the chat template ever sees it
126
- rows.append({"messages": [{"role": m["role"], "content": m["content"]} for m in conv],
127
- "audios": audios, "target": ""})
128
- return rows
129
-
130
- @torch.no_grad()
131
- def generate(self, conversations, max_new_tokens=200, do_sample=False, **generation_kwargs):
132
- if conversations and isinstance(conversations[0], dict):
133
- conversations = [conversations] # a single conversation
134
- batch = self.collator(self._to_rows(conversations))
135
-
136
- batch["input_ids"] = batch["input_ids"].to(self.device)
137
- batch["attention_mask"] = batch["attention_mask"].to(self.device)
138
- # SpeechLLM.encode_audio casts features to the encoder's own dtype
139
- batch["input_features"] = batch["input_features"].to(self.device)
140
-
141
- # The trainable tensors (connector, LoRA) stay in float32 while the frozen encoder and
142
- # LLM run in `dtype`, exactly as in training -- so the forward pass has to happen under
143
- # autocast, or layer_norm sees a float32 weight and a float16 activation and raises
144
- # "expected scalar type Half but found Float".
145
- # passing inputs_embeds means `generate` returns only the new tokens --
146
- # there is no prompt prefix to slice off
147
- with torch.autocast(self.device.split(":")[0], dtype=self.dtype,
148
- enabled=not self.device.startswith("cpu")):
149
- generated = self.model.generate(
150
- batch, self.tokenizer, max_new_tokens=max_new_tokens,
151
- do_sample=do_sample, **generation_kwargs)
152
- return [t.strip() for t in
153
- self.tokenizer.batch_decode(generated, skip_special_tokens=True)]
154
-
155
-
156
- # -- main --
157
-
158
- def main():
159
- ap = argparse.ArgumentParser(description=__doc__,
160
- formatter_class=argparse.RawDescriptionHelpFormatter)
161
- ap.add_argument("--ckpt", required=True)
162
- ap.add_argument("--audio", nargs="+", help="one or more audio files")
163
- ap.add_argument("--manifest", help="jsonl to run over instead of --audio")
164
- ap.add_argument("--audio-root", default="")
165
- ap.add_argument("--limit", type=int, default=10, help="rows to take from --manifest")
166
- ap.add_argument("--prompt", default=DEFAULT_PROMPT)
167
- ap.add_argument("--batch-size", type=int, default=4)
168
- ap.add_argument("--max-new-tokens", type=int, default=200)
169
- ap.add_argument("--device", default=None)
170
- args = ap.parse_args()
171
- assert args.audio or args.manifest, "give --audio or --manifest"
172
-
173
- pipe = SpeechLLMForInference.from_checkpoint(args.ckpt, device=args.device)
174
-
175
- if args.audio:
176
- items = [(os.path.join(args.audio_root, p), None) for p in args.audio]
177
- else:
178
- items = []
179
- with open(args.manifest) as f:
180
- for line in f:
181
- if len(items) >= args.limit:
182
- break
183
- row = json.loads(line)
184
- items.append((os.path.join(args.audio_root,
185
- row["audios"][0]["audio_filepath"]),
186
- row.get("response") or row.get("target")))
187
-
188
- for start in range(0, len(items), args.batch_size):
189
- chunk = items[start:start + args.batch_size]
190
- convs = [[{"role": "user", "content": args.prompt,
191
- "audios": [{"audio": path}]}] for path, _ in chunk]
192
- for (path, reference), hypothesis in zip(chunk, pipe.generate(
193
- convs, max_new_tokens=args.max_new_tokens)):
194
- print(f"\n--- {os.path.basename(path)}")
195
- if reference is not None:
196
- print(f" ref: {reference}")
197
- print(f" hyp: {hypothesis}")
198
-
199
-
200
- if __name__ == "__main__":
201
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
code/modeling.py DELETED
@@ -1,171 +0,0 @@
1
- """
2
- A minimal SpeechLLM: Whisper encoder + connector + LLM with LoRA.
3
-
4
- audio ──► Whisper encoder (trained or frozen) ──► connector (trained) ──┐
5
- ├──► LLM + LoRA ──► text
6
- text ────────────────────────────────────────► embedding table ────────┘
7
- """
8
-
9
- import logging
10
-
11
- import torch
12
- import torch.nn as nn
13
- from transformers import AutoModelForCausalLM, WhisperModel
14
-
15
- logger = logging.getLogger(__name__)
16
-
17
-
18
- class ConcatMLPConnector(nn.Module):
19
- """Whisper hidden states → LLM-width embeddings by frame concatenation.
20
- """
21
-
22
- def __init__(self, d_encoder: int, d_llm: int, n_downsample: int = 2,
23
- hidden_dim: int = 0):
24
- super().__init__()
25
- self.n_downsample = n_downsample
26
- hidden_dim = hidden_dim or d_llm
27
- self.proj = nn.Sequential(
28
- nn.LayerNorm(d_encoder * n_downsample),
29
- nn.Linear(d_encoder * n_downsample, hidden_dim),
30
- nn.GELU(),
31
- nn.Linear(hidden_dim, d_llm),
32
- )
33
-
34
- def forward(self, hidden_states): # (B, T, d_encoder)
35
- B, T, D = hidden_states.shape
36
- k = self.n_downsample
37
- pad = (-T) % k
38
- if pad:
39
- hidden_states = nn.functional.pad(hidden_states, (0, 0, 0, pad))
40
- stacked = hidden_states.reshape(B, (T + pad) // k, D * k)
41
- return self.proj(stacked) # (B, ceil(T/k), d_llm)
42
-
43
-
44
- class SpeechLLM(nn.Module):
45
- def __init__(self, llm_id: str, encoder_id: str,
46
- n_downsample: int = 2, dtype=torch.bfloat16,
47
- adapter_hidden_dim: int = 0,
48
- gradient_checkpointing: bool = False, cache_dir=None,
49
- freeze_encoder: bool = True, use_lora: bool = False,
50
- lora_rank: int = 32, lora_alpha: int = 64, lora_dropout: float = 0.05,
51
- lora_target_modules=("q_proj", "k_proj", "v_proj", "o_proj")):
52
- super().__init__()
53
- self.llm = AutoModelForCausalLM.from_pretrained(
54
- llm_id, torch_dtype=dtype, cache_dir=cache_dir)
55
- # We only ever need the encoder; loading WhisperModel and keeping .encoder
56
- # lets the decoder weights fall out of scope immediately.
57
- self.encoder = WhisperModel.from_pretrained(
58
- encoder_id, torch_dtype=dtype, cache_dir=cache_dir).encoder
59
-
60
- self.connector = ConcatMLPConnector(
61
- d_encoder=self.encoder.config.d_model,
62
- d_llm=self.llm.config.hidden_size,
63
- n_downsample=n_downsample,
64
- hidden_dim=adapter_hidden_dim,
65
- )
66
- logger.info("connector: %.1fM params",
67
- sum(p.numel() for p in self.connector.parameters()) / 1e6)
68
-
69
- for param in self.llm.parameters():
70
- param.requires_grad = False
71
-
72
- self.use_lora = use_lora
73
- if use_lora:
74
- from peft import LoraConfig ,get_peft_model
75
- lora_config = LoraConfig(
76
- r=lora_rank, lora_alpha=lora_alpha, lora_dropout=lora_dropout,
77
- target_modules=list(lora_target_modules), bias="none",
78
- task_type="CAUSAL_LM",
79
- )
80
-
81
- self.llm = get_peft_model(self.llm, lora_config).base_model.model
82
- n_lora = sum(p.numel() for n, p in self.llm.named_parameters() if "lora_" in n)
83
- assert n_lora > 0, f"LoRA matched no modules in {lora_target_modules}"
84
- logger.info("LoRA r=%d on %s: %.1fM adapter params",
85
- lora_rank, list(lora_target_modules), n_lora / 1e6)
86
-
87
- self.freeze_encoder = freeze_encoder
88
- for param in self.encoder.parameters():
89
- param.requires_grad = not freeze_encoder
90
-
91
- if not freeze_encoder:
92
- self.encoder.float()
93
-
94
- if gradient_checkpointing:
95
- ckpt_kwargs = {"use_reentrant": False}
96
- self.llm.gradient_checkpointing_enable(gradient_checkpointing_kwargs=ckpt_kwargs)
97
- if not freeze_encoder:
98
- self.encoder.gradient_checkpointing_enable(
99
- gradient_checkpointing_kwargs=ckpt_kwargs)
100
-
101
- dtypes = {}
102
- for name, param in self.named_parameters():
103
- if param.requires_grad:
104
- part = name.split(".")[0]
105
- dtypes.setdefault(part, set()).add(str(param.dtype).replace("torch.", ""))
106
- logger.info("trainable dtypes: %s", {k: sorted(v) for k, v in sorted(dtypes.items())})
107
-
108
- by_part = {}
109
- for name, param in self.named_parameters():
110
- if param.requires_grad:
111
- by_part[name.split(".")[0]] = by_part.get(name.split(".")[0], 0) + param.numel()
112
- trainable = sum(by_part.values())
113
- total = sum(p.numel() for p in self.parameters())
114
- logger.info("trainable %.1fM / %.1fM total (%.2f%%) -- %s",
115
- trainable / 1e6, total / 1e6, 100 * trainable / total,
116
- {k: f"{v/1e6:.1f}M" for k, v in sorted(by_part.items())})
117
-
118
- def encode_audio(self, input_features):
119
- """mel features → speech embeddings in the LLM's width.
120
- """
121
- input_features = input_features.to(self.encoder.conv1.weight.dtype)
122
- return self.connector(self.encoder(input_features).last_hidden_state)
123
-
124
- def build_inputs_embeds(self, input_ids, speech_features, audio_lengths, start_positions):
125
- """Overwrite each audio's placeholder embeddings with its speech features."""
126
- embed = self.llm.get_input_embeddings()
127
- inputs_embeds = embed(input_ids).clone()
128
-
129
- for k, (row, start) in enumerate(start_positions):
130
- segment = speech_features[k, :audio_lengths[k]]
131
- end = start + segment.size(0)
132
- assert end <= inputs_embeds.size(1), (
133
- f"audio {k} needs slots [{start}:{end}] but the sequence is "
134
- f"{inputs_embeds.size(1)} long")
135
- # outside autocast (inference) the float32 connector output must be
136
- # cast to the LLM's embedding dtype before the in-place write
137
- inputs_embeds[row, start:end] = segment.to(inputs_embeds.dtype)
138
-
139
- return inputs_embeds
140
-
141
- def forward(self, input_ids, attention_mask, input_features, audio_lengths,
142
- start_positions, labels=None):
143
- speech_features = self.encode_audio(input_features)
144
- inputs_embeds = self.build_inputs_embeds(
145
- input_ids, speech_features, audio_lengths, start_positions)
146
- return self.llm(inputs_embeds=inputs_embeds,
147
- attention_mask=attention_mask,
148
- labels=labels)
149
-
150
- @torch.no_grad()
151
- def generate(self, batch, tokenizer, **generation_kwargs):
152
- """Greedy/sampled decoding from the same batch dict used for training.
153
-
154
- Note we pass `inputs_embeds`, so `generate` returns only the newly
155
- generated ids -- there is no prompt prefix to strip.
156
- """
157
- speech_features = self.encode_audio(batch["input_features"])
158
- inputs_embeds = self.build_inputs_embeds(
159
- batch["input_ids"], speech_features, batch["audio_lengths"],
160
- batch["start_positions"])
161
- return self.llm.generate(
162
- inputs_embeds=inputs_embeds,
163
- attention_mask=batch["attention_mask"],
164
- pad_token_id=tokenizer.pad_token_id,
165
- **generation_kwargs,
166
- )
167
-
168
- def trainable_state_dict(self):
169
- """Only the connector -- a few tens of MB instead of the full ~11 GB."""
170
- return {name: param.detach().clone()
171
- for name, param in self.named_parameters() if param.requires_grad}