File size: 8,471 Bytes
8103614
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# /// script
# requires-python = ">=3.10"
# dependencies = [
#   "torch",
#   "transformers",
#   "datasets",
#   "peft",
#   "accelerate",
#   "bitsandbytes",
#   "huggingface_hub",
#   "numpy",
# ]
# ///
"""
LoRA fine-tune a small causal LM (default Qwen2.5-3B) as an ASR n-best CORRECTOR,
on the SAP-Hypo5 dysarthric-speech dataset (xiuwenz2/SAP-Hypo5).

Follows the SAP-Hypo5 / Hypo2Trans "H2T-LoRA" recipe verbatim:
  prompt = instruction + best-hypothesis + other-hypotheses  ->  reference
  loss on the RESPONSE ONLY (train_on_inputs=False), done here by masking the
  prompt tokens with -100 in `labels` (plain transformers.Trainer, no TRL β€” its
  SFTTrainer API drifts between versions and this job can't be cheaply re-run).

NOTE the dataset's `output` is normalized (lowercase, no punctuation): this trains
pure WORD correction, not casing/punctuation. The model is the word-arbitration
stage; formatting stays a separate layer downstream.

Runs as an HF Job (uv run --script). Config via env vars:
  BASE_MODEL   base causal LM to LoRA-tune          (default Qwen/Qwen2.5-3B)
  DATASET      HF dataset id                          (default xiuwenz2/SAP-Hypo5)
  PUSH_REPO    dataset repo to upload the adapter to  (REQUIRED)
  EPOCHS, MAX_LEN, LR, BATCH, GRAD_ACC, LORA_R       (training hparams)
  USE_4BIT     "1" for QLoRA (bitsandbytes), else bf16 LoRA (default "0")
  HF_TOKEN     write token (job secret)
"""
import os, logging
import torch
from datasets import load_dataset
from transformers import (AutoTokenizer, AutoModelForCausalLM,
                          BitsAndBytesConfig, Trainer, TrainingArguments)
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
from huggingface_hub import HfApi, login

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
log = logging.getLogger("corrector_ft")

# ── Config ──────────────────────────────────────────────────────────────────
BASE_MODEL = os.environ.get("BASE_MODEL", "Qwen/Qwen2.5-3B")
DATASET    = os.environ.get("DATASET", "xiuwenz2/SAP-Hypo5")
PUSH_REPO  = os.environ["PUSH_REPO"]                      # e.g. org/qwen2.5-3b-corrector-sap-hypo5
EPOCHS     = float(os.environ.get("EPOCHS", "2"))
MAX_LEN    = int(os.environ.get("MAX_LEN", "512"))
LR         = float(os.environ.get("LR", "2e-4"))
BATCH      = int(os.environ.get("BATCH", "8"))
GRAD_ACC   = int(os.environ.get("GRAD_ACC", "4"))
LORA_R     = int(os.environ.get("LORA_R", "16"))
USE_4BIT   = os.environ.get("USE_4BIT", "0") == "1"
HF_TOKEN   = os.environ.get("HF_TOKEN")

# ── SAP-Hypo5 / H2T-LoRA prompt (verbatim from templates/H2T-LoRA.json) ───────
INSTRUCTION = ("Below is the best-hypotheses transcribed from speech recognition system. "
    "Please try to revise it using the words which are only included into other-hypothesis, "
    "and write the response for the true transcription.")

def build_prompt(best: str, others: str) -> str:
    return (f"{INSTRUCTION}\n\n### Best-hypothesis:\n{best}\n\n"
            f"### Other-hypothesis:\n{others}\n\n### Response:\n")

def build_others(hyps) -> str:
    # SAP-Hypo5 inference.py build_prompts: ". ".join(others) + "."
    return ". ".join(hyps[1:]) + "." if len(hyps) > 1 else ""


def main():
    if HF_TOKEN:
        login(token=HF_TOKEN)

    tok = AutoTokenizer.from_pretrained(BASE_MODEL, use_fast=True)
    if tok.pad_token_id is None:
        tok.pad_token = tok.eos_token

    def encode(ex):
        hyps = ex["input"]
        prompt = build_prompt(hyps[0], build_others(hyps))
        ref = (ex["output"] or "").strip()
        p_ids = tok(prompt, add_special_tokens=False)["input_ids"]
        r_ids = tok(ref, add_special_tokens=False)["input_ids"] + [tok.eos_token_id]
        ids = (p_ids + r_ids)[:MAX_LEN]
        # train_on_inputs=False: mask the prompt, learn only the reference tokens.
        labels = ([-100] * len(p_ids) + r_ids)[:MAX_LEN]
        return {"input_ids": ids, "labels": labels, "attention_mask": [1] * len(ids)}

    log.info("loading %s", DATASET)
    ds = load_dataset(DATASET)
    cols = ds["train"].column_names
    train = ds["train"].map(encode, remove_columns=cols)
    val   = ds["validation"].map(encode, remove_columns=cols)
    log.info("train=%d val=%d", len(train), len(val))

    def collate(feats):
        m = max(len(f["input_ids"]) for f in feats)
        pad = tok.pad_token_id
        def p(f, k, fill): return f[k] + [fill] * (m - len(f[k]))
        return {
            "input_ids":      torch.tensor([p(f, "input_ids", pad) for f in feats]),
            "labels":         torch.tensor([p(f, "labels", -100) for f in feats]),
            "attention_mask": torch.tensor([p(f, "attention_mask", 0) for f in feats]),
        }

    # ── model + LoRA ─────────────────────────────────────────────────────────
    if USE_4BIT:
        quant = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",
                                   bnb_4bit_compute_dtype=torch.bfloat16,
                                   bnb_4bit_use_double_quant=True)
        model = AutoModelForCausalLM.from_pretrained(
            BASE_MODEL, quantization_config=quant,
            torch_dtype=torch.bfloat16, device_map={"": 0})
        model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=True)
    else:
        model = AutoModelForCausalLM.from_pretrained(
            BASE_MODEL, torch_dtype=torch.bfloat16, device_map={"": 0})
        model.gradient_checkpointing_enable(
            gradient_checkpointing_kwargs={"use_reentrant": False})
        # With gradient checkpointing + a frozen base, gradients must be told to flow
        # back to the LoRA adapters (the 4-bit path gets this via prepare_model_for_kbit_training).
        model.enable_input_require_grads()

    lora = LoraConfig(
        r=LORA_R, lora_alpha=2 * LORA_R, lora_dropout=0.05, bias="none",
        task_type="CAUSAL_LM",
        target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
                        "gate_proj", "up_proj", "down_proj"])
    model = get_peft_model(model, lora)
    model.config.use_cache = False
    model.print_trainable_parameters()

    args = TrainingArguments(
        output_dir="out",
        num_train_epochs=EPOCHS,
        per_device_train_batch_size=BATCH,
        gradient_accumulation_steps=GRAD_ACC,
        learning_rate=LR,
        bf16=True,
        warmup_ratio=0.03,
        lr_scheduler_type="cosine",
        logging_steps=25,
        eval_strategy="steps",
        eval_steps=250,
        save_strategy="no",
        optim="paged_adamw_8bit" if USE_4BIT else "adamw_torch",
        report_to="none",
    )
    trainer = Trainer(model=model, args=args, train_dataset=train,
                      eval_dataset=val, data_collator=collate)
    trainer.train()

    # ── sanity: generate on a few val examples so the log shows what it learned ─
    try:
        model.config.use_cache = True
        model.eval()
        raw = load_dataset(DATASET, split="validation").select(range(5))
        for ex in raw:
            hyps = ex["input"]
            prompt = build_prompt(hyps[0], build_others(hyps))
            enc = tok(prompt, return_tensors="pt").to(model.device)
            with torch.no_grad():
                out = model.generate(**enc, max_new_tokens=64, do_sample=False,
                                     pad_token_id=tok.pad_token_id)
            gen = tok.decode(out[0][enc["input_ids"].shape[1]:], skip_special_tokens=True).strip()
            log.info("BEST : %s", hyps[0])
            log.info("PRED : %s", gen.splitlines()[0] if gen else "")
            log.info("REF  : %s\n", ex["output"])
    except Exception as e:
        log.warning("sanity generation skipped: %s", e)

    # ── save adapter + push to a DATASET repo (org token can't create model repos) ─
    model.save_pretrained("adapter")
    tok.save_pretrained("adapter")
    api = HfApi(token=HF_TOKEN)
    api.create_repo(PUSH_REPO, repo_type="dataset", exist_ok=True)
    api.upload_folder(folder_path="adapter", repo_id=PUSH_REPO, repo_type="dataset")
    log.info("pushed adapter -> https://huggingface.co/datasets/%s", PUSH_REPO)


if __name__ == "__main__":
    main()