MOH749 commited on
Commit
23fcdf9
·
verified ·
1 Parent(s): dd8f4ca

Upload train_ears_granite.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. train_ears_granite.py +26 -54
train_ears_granite.py CHANGED
@@ -44,9 +44,9 @@ class Collator:
44
  import torch
45
  import soundfile as sf
46
  tok = self.processor.tokenizer
 
47
  sr_t = self.processor.audio_processor.sampling_rate
48
- pad = tok.pad_token_id if tok.pad_token_id is not None else 0
49
- ids_b, lab_b, attn_b, feat_b, fmask_b = [], [], [], [], []
50
  for ex in examples:
51
  try:
52
  arr, sr = sf.read(io.BytesIO(ex["audio"]["bytes"]), dtype="float32")
@@ -58,62 +58,34 @@ class Collator:
58
  import librosa
59
  arr = librosa.resample(arr, orig_sr=sr, target_sr=sr_t)
60
  arr = arr[: int(self.max_s * sr_t)]
61
- wav = torch.from_numpy(arr).unsqueeze(0)
62
- prompt = tok.apply_chat_template(
63
- [{"role": "user", "content": INSTR}], tokenize=False,
64
- add_generation_prompt=True)
65
- try:
66
- out = self.processor(prompt, wav, return_tensors="pt")
67
- except Exception as exc:
68
- print("[collator] processor error:", exc)
69
  continue
70
- iid = out["input_ids"].squeeze(0)
71
- am = out["attention_mask"].squeeze(0)
72
- tgt = tok(ex["text"], return_tensors="pt",
73
- add_special_tokens=False)["input_ids"].squeeze(0)
74
- if tok.eos_token_id is not None:
75
- tgt = torch.cat([tgt, torch.tensor([tok.eos_token_id], dtype=tgt.dtype)])
76
- full = torch.cat([iid, tgt])
77
- lab = torch.full_like(full, -100)
78
- lab[iid.shape[0]:] = tgt
79
- fattn = torch.cat([am, torch.ones(tgt.shape[0], dtype=am.dtype)])
80
- ids_b.append(full); lab_b.append(lab); attn_b.append(fattn)
81
- if "input_features" in out:
82
- feat_b.append(out["input_features"].squeeze(0))
83
- if "input_features_mask" in out:
84
- fmask_b.append(out["input_features_mask"].squeeze(0))
85
- import torch
86
- if not ids_b:
87
  return {"input_ids": torch.zeros((0, 1), dtype=torch.long),
88
  "attention_mask": torch.zeros((0, 1), dtype=torch.long),
89
  "labels": torch.full((0, 1), -100, dtype=torch.long)}
90
- ml = max(t.shape[0] for t in ids_b)
91
- pids = torch.full((len(ids_b), ml), pad, dtype=torch.long)
92
- plab = torch.full((len(ids_b), ml), -100, dtype=torch.long)
93
- pattn = torch.zeros((len(ids_b), ml), dtype=torch.long)
94
- for i, (a, b, c) in enumerate(zip(ids_b, lab_b, attn_b)):
95
- l = a.shape[0]
96
- pids[i, :l] = a; plab[i, :l] = b; pattn[i, :l] = c
97
- r = {"input_ids": pids, "attention_mask": pattn, "labels": plab}
98
- if feat_b:
99
- # Mel features are variable-length [T, n_mels] — pad to batch max along
100
- # time and carry a frame mask; granite-speech uses the mask to ignore
101
- # padded frames and to size each example's audio-token count.
102
- fmax = max(f.shape[0] for f in feat_b)
103
- fdim = feat_b[0].shape[-1]
104
- pf = torch.zeros((len(feat_b), fmax, fdim), dtype=feat_b[0].dtype)
105
- pm = torch.zeros((len(feat_b), fmax), dtype=torch.long)
106
- for i, f in enumerate(feat_b):
107
- t = f.shape[0]
108
- pf[i, :t] = f
109
- if i < len(fmask_b):
110
- m = fmask_b[i].reshape(-1)
111
- pm[i, : m.shape[0]] = m.to(torch.long)
112
- else:
113
- pm[i, :t] = 1
114
- r["input_features"] = pf
115
- r["input_features_mask"] = pm
116
- return r
117
 
118
 
119
  def main():
 
44
  import torch
45
  import soundfile as sf
46
  tok = self.processor.tokenizer
47
+ tok.padding_side = "right"
48
  sr_t = self.processor.audio_processor.sampling_rate
49
+ prompts, fulls, wavs = [], [], []
 
50
  for ex in examples:
51
  try:
52
  arr, sr = sf.read(io.BytesIO(ex["audio"]["bytes"]), dtype="float32")
 
58
  import librosa
59
  arr = librosa.resample(arr, orig_sr=sr, target_sr=sr_t)
60
  arr = arr[: int(self.max_s * sr_t)]
61
+ txt = (ex.get("text") or "").strip()
62
+ if not txt:
 
 
 
 
 
 
63
  continue
64
+ wavs.append(arr)
65
+ prompts.append(tok.apply_chat_template(
66
+ [{"role": "user", "content": INSTR}],
67
+ tokenize=False, add_generation_prompt=True))
68
+ fulls.append(tok.apply_chat_template(
69
+ [{"role": "user", "content": INSTR},
70
+ {"role": "assistant", "content": txt}], tokenize=False))
71
+ if not wavs:
 
 
 
 
 
 
 
 
 
72
  return {"input_ids": torch.zeros((0, 1), dtype=torch.long),
73
  "attention_mask": torch.zeros((0, 1), dtype=torch.long),
74
  "labels": torch.full((0, 1), -100, dtype=torch.long)}
75
+ # Let the processor batch + pad input_features and expand the <|audio|>
76
+ # placeholders consistently — hand-padding features desyncs the audio-token
77
+ # count from the placeholders (the 165-vs-4 failure). Recover labels by
78
+ # masking the prompt span, sized from a prompt-only pass (same audio → same
79
+ # placeholder expansion, right-padding keeps the prompt a clean prefix).
80
+ out = self.processor(text=fulls, audio=wavs, return_tensors="pt", padding=True)
81
+ pout = self.processor(text=prompts, audio=wavs, return_tensors="pt", padding=True)
82
+ labels = out["input_ids"].clone()
83
+ labels[out["attention_mask"] == 0] = -100
84
+ for i in range(len(fulls)):
85
+ plen = int(pout["attention_mask"][i].sum().item())
86
+ labels[i, :plen] = -100
87
+ out["labels"] = labels
88
+ return dict(out)
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
 
91
  def main():