LogosAccessibleExpression commited on
Commit
8103614
Β·
verified Β·
1 Parent(s): 64ba922

Upload corrector_ft_job.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. corrector_ft_job.py +186 -0
corrector_ft_job.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.10"
3
+ # dependencies = [
4
+ # "torch",
5
+ # "transformers",
6
+ # "datasets",
7
+ # "peft",
8
+ # "accelerate",
9
+ # "bitsandbytes",
10
+ # "huggingface_hub",
11
+ # "numpy",
12
+ # ]
13
+ # ///
14
+ """
15
+ LoRA fine-tune a small causal LM (default Qwen2.5-3B) as an ASR n-best CORRECTOR,
16
+ on the SAP-Hypo5 dysarthric-speech dataset (xiuwenz2/SAP-Hypo5).
17
+
18
+ Follows the SAP-Hypo5 / Hypo2Trans "H2T-LoRA" recipe verbatim:
19
+ prompt = instruction + best-hypothesis + other-hypotheses -> reference
20
+ loss on the RESPONSE ONLY (train_on_inputs=False), done here by masking the
21
+ prompt tokens with -100 in `labels` (plain transformers.Trainer, no TRL β€” its
22
+ SFTTrainer API drifts between versions and this job can't be cheaply re-run).
23
+
24
+ NOTE the dataset's `output` is normalized (lowercase, no punctuation): this trains
25
+ pure WORD correction, not casing/punctuation. The model is the word-arbitration
26
+ stage; formatting stays a separate layer downstream.
27
+
28
+ Runs as an HF Job (uv run --script). Config via env vars:
29
+ BASE_MODEL base causal LM to LoRA-tune (default Qwen/Qwen2.5-3B)
30
+ DATASET HF dataset id (default xiuwenz2/SAP-Hypo5)
31
+ PUSH_REPO dataset repo to upload the adapter to (REQUIRED)
32
+ EPOCHS, MAX_LEN, LR, BATCH, GRAD_ACC, LORA_R (training hparams)
33
+ USE_4BIT "1" for QLoRA (bitsandbytes), else bf16 LoRA (default "0")
34
+ HF_TOKEN write token (job secret)
35
+ """
36
+ import os, logging
37
+ import torch
38
+ from datasets import load_dataset
39
+ from transformers import (AutoTokenizer, AutoModelForCausalLM,
40
+ BitsAndBytesConfig, Trainer, TrainingArguments)
41
+ from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
42
+ from huggingface_hub import HfApi, login
43
+
44
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
45
+ log = logging.getLogger("corrector_ft")
46
+
47
+ # ── Config ──────────────────────────────────────────────────────────────────
48
+ BASE_MODEL = os.environ.get("BASE_MODEL", "Qwen/Qwen2.5-3B")
49
+ DATASET = os.environ.get("DATASET", "xiuwenz2/SAP-Hypo5")
50
+ PUSH_REPO = os.environ["PUSH_REPO"] # e.g. org/qwen2.5-3b-corrector-sap-hypo5
51
+ EPOCHS = float(os.environ.get("EPOCHS", "2"))
52
+ MAX_LEN = int(os.environ.get("MAX_LEN", "512"))
53
+ LR = float(os.environ.get("LR", "2e-4"))
54
+ BATCH = int(os.environ.get("BATCH", "8"))
55
+ GRAD_ACC = int(os.environ.get("GRAD_ACC", "4"))
56
+ LORA_R = int(os.environ.get("LORA_R", "16"))
57
+ USE_4BIT = os.environ.get("USE_4BIT", "0") == "1"
58
+ HF_TOKEN = os.environ.get("HF_TOKEN")
59
+
60
+ # ── SAP-Hypo5 / H2T-LoRA prompt (verbatim from templates/H2T-LoRA.json) ───────
61
+ INSTRUCTION = ("Below is the best-hypotheses transcribed from speech recognition system. "
62
+ "Please try to revise it using the words which are only included into other-hypothesis, "
63
+ "and write the response for the true transcription.")
64
+
65
+ def build_prompt(best: str, others: str) -> str:
66
+ return (f"{INSTRUCTION}\n\n### Best-hypothesis:\n{best}\n\n"
67
+ f"### Other-hypothesis:\n{others}\n\n### Response:\n")
68
+
69
+ def build_others(hyps) -> str:
70
+ # SAP-Hypo5 inference.py build_prompts: ". ".join(others) + "."
71
+ return ". ".join(hyps[1:]) + "." if len(hyps) > 1 else ""
72
+
73
+
74
+ def main():
75
+ if HF_TOKEN:
76
+ login(token=HF_TOKEN)
77
+
78
+ tok = AutoTokenizer.from_pretrained(BASE_MODEL, use_fast=True)
79
+ if tok.pad_token_id is None:
80
+ tok.pad_token = tok.eos_token
81
+
82
+ def encode(ex):
83
+ hyps = ex["input"]
84
+ prompt = build_prompt(hyps[0], build_others(hyps))
85
+ ref = (ex["output"] or "").strip()
86
+ p_ids = tok(prompt, add_special_tokens=False)["input_ids"]
87
+ r_ids = tok(ref, add_special_tokens=False)["input_ids"] + [tok.eos_token_id]
88
+ ids = (p_ids + r_ids)[:MAX_LEN]
89
+ # train_on_inputs=False: mask the prompt, learn only the reference tokens.
90
+ labels = ([-100] * len(p_ids) + r_ids)[:MAX_LEN]
91
+ return {"input_ids": ids, "labels": labels, "attention_mask": [1] * len(ids)}
92
+
93
+ log.info("loading %s", DATASET)
94
+ ds = load_dataset(DATASET)
95
+ cols = ds["train"].column_names
96
+ train = ds["train"].map(encode, remove_columns=cols)
97
+ val = ds["validation"].map(encode, remove_columns=cols)
98
+ log.info("train=%d val=%d", len(train), len(val))
99
+
100
+ def collate(feats):
101
+ m = max(len(f["input_ids"]) for f in feats)
102
+ pad = tok.pad_token_id
103
+ def p(f, k, fill): return f[k] + [fill] * (m - len(f[k]))
104
+ return {
105
+ "input_ids": torch.tensor([p(f, "input_ids", pad) for f in feats]),
106
+ "labels": torch.tensor([p(f, "labels", -100) for f in feats]),
107
+ "attention_mask": torch.tensor([p(f, "attention_mask", 0) for f in feats]),
108
+ }
109
+
110
+ # ── model + LoRA ────────────────────────────��────────────────────────────
111
+ if USE_4BIT:
112
+ quant = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",
113
+ bnb_4bit_compute_dtype=torch.bfloat16,
114
+ bnb_4bit_use_double_quant=True)
115
+ model = AutoModelForCausalLM.from_pretrained(
116
+ BASE_MODEL, quantization_config=quant,
117
+ torch_dtype=torch.bfloat16, device_map={"": 0})
118
+ model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=True)
119
+ else:
120
+ model = AutoModelForCausalLM.from_pretrained(
121
+ BASE_MODEL, torch_dtype=torch.bfloat16, device_map={"": 0})
122
+ model.gradient_checkpointing_enable(
123
+ gradient_checkpointing_kwargs={"use_reentrant": False})
124
+ # With gradient checkpointing + a frozen base, gradients must be told to flow
125
+ # back to the LoRA adapters (the 4-bit path gets this via prepare_model_for_kbit_training).
126
+ model.enable_input_require_grads()
127
+
128
+ lora = LoraConfig(
129
+ r=LORA_R, lora_alpha=2 * LORA_R, lora_dropout=0.05, bias="none",
130
+ task_type="CAUSAL_LM",
131
+ target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
132
+ "gate_proj", "up_proj", "down_proj"])
133
+ model = get_peft_model(model, lora)
134
+ model.config.use_cache = False
135
+ model.print_trainable_parameters()
136
+
137
+ args = TrainingArguments(
138
+ output_dir="out",
139
+ num_train_epochs=EPOCHS,
140
+ per_device_train_batch_size=BATCH,
141
+ gradient_accumulation_steps=GRAD_ACC,
142
+ learning_rate=LR,
143
+ bf16=True,
144
+ warmup_ratio=0.03,
145
+ lr_scheduler_type="cosine",
146
+ logging_steps=25,
147
+ eval_strategy="steps",
148
+ eval_steps=250,
149
+ save_strategy="no",
150
+ optim="paged_adamw_8bit" if USE_4BIT else "adamw_torch",
151
+ report_to="none",
152
+ )
153
+ trainer = Trainer(model=model, args=args, train_dataset=train,
154
+ eval_dataset=val, data_collator=collate)
155
+ trainer.train()
156
+
157
+ # ── sanity: generate on a few val examples so the log shows what it learned ─
158
+ try:
159
+ model.config.use_cache = True
160
+ model.eval()
161
+ raw = load_dataset(DATASET, split="validation").select(range(5))
162
+ for ex in raw:
163
+ hyps = ex["input"]
164
+ prompt = build_prompt(hyps[0], build_others(hyps))
165
+ enc = tok(prompt, return_tensors="pt").to(model.device)
166
+ with torch.no_grad():
167
+ out = model.generate(**enc, max_new_tokens=64, do_sample=False,
168
+ pad_token_id=tok.pad_token_id)
169
+ gen = tok.decode(out[0][enc["input_ids"].shape[1]:], skip_special_tokens=True).strip()
170
+ log.info("BEST : %s", hyps[0])
171
+ log.info("PRED : %s", gen.splitlines()[0] if gen else "")
172
+ log.info("REF : %s\n", ex["output"])
173
+ except Exception as e:
174
+ log.warning("sanity generation skipped: %s", e)
175
+
176
+ # ── save adapter + push to a DATASET repo (org token can't create model repos) ─
177
+ model.save_pretrained("adapter")
178
+ tok.save_pretrained("adapter")
179
+ api = HfApi(token=HF_TOKEN)
180
+ api.create_repo(PUSH_REPO, repo_type="dataset", exist_ok=True)
181
+ api.upload_folder(folder_path="adapter", repo_id=PUSH_REPO, repo_type="dataset")
182
+ log.info("pushed adapter -> https://huggingface.co/datasets/%s", PUSH_REPO)
183
+
184
+
185
+ if __name__ == "__main__":
186
+ main()