morpheuslord commited on
Commit
c0b0480
Β·
1 Parent(s): 4ef7c94

fix: remove broken len(n_test) log line, fix hub upload paths

Browse files
Files changed (1) hide show
  1. train_and_upgrade.py +110 -63
train_and_upgrade.py CHANGED
@@ -1,66 +1,62 @@
1
  """
2
- train_and_upgrade.py (v3)
3
  ==========================
4
  Self-improving upgrade pipeline for morpheuslord/rewrite
5
 
6
- CHANGES OVER v2:
7
- 1. Context window: 128 β†’ 256 tokens (T5 uses relative position bias,
8
- so the warm-start merge still works β€” no cold start required)
 
 
 
9
 
10
- 2. Data: added cointegrated/c4_200m-gec-filtered (~500k pairs, no
11
- registration needed). Falls back gracefully if unavailable.
12
- Total training data: ~600k pairs after augmentation vs ~80k in v2.
13
 
14
- 3. Beam search upgraded: num_beams=5, length_penalty=1.2,
15
- repetition_penalty=1.3, no_repeat_ngram_size=3
 
 
16
 
17
- 4. Evaluation cap removed on GPU: was [:200] always, now
18
- [:200] on CPU and full test set on GPU.
19
 
20
- 5. Human-pattern loss: now fully active on GPU. Loads the pretrained
21
- classifier from the Hub repo if present, otherwise skips gracefully.
 
22
 
23
- 6. Semantic faithfulness gate: after generation, outputs whose
24
- sentence-embedding cosine similarity to the input is below
25
- FAITHFULNESS_THRESHOLD (0.75) are replaced with the input as
26
- fallback. Prevents meaning-destroying corrections.
27
 
28
- 7. ERRANT F0.5: added as optional metric (requires `pip install errant`
29
- and `python -m spacy download en_core_web_sm`). Falls back silently
30
- if not installed.
 
31
 
32
- 8. Composite score now optionally includes ERRANT F0.5 when available:
33
- (GLEU + BERTScore_F1 + (1-WER) [+ ERRANT_F05]) / count
 
 
 
 
 
 
 
34
 
35
  DATASETS (priority order):
36
  Tier 1 β€” Local processed files (data/processed/*.jsonl)
37
- Already contains FCE + W&I+LOCNESS + JFLEG from original pipeline.
38
- Used as primary source β€” no re-downloading needed.
39
-
40
  Tier 2 β€” Local raw FCE JSON (data/raw/fce/json/*.json)
41
- Loaded directly if processed files are missing or as supplement.
42
- Covers fce.train.json, fce.dev.json, fce.test.json.
43
-
44
- Tier 3 β€” Local raw W&I+LOCNESS JSON (data/raw/wi+locness/json/*.json)
45
- Fallback if processed files missing.
46
-
47
- Tier 4 β€” HF Hub (JFLEG, W&I+LOCNESS)
48
- Only used if both local processed and local raw files are missing.
49
-
50
- Tier 5 β€” C4-200M GEC (cointegrated/c4_200m-gec-filtered, ~500k pairs)
51
- Always attempted on top of whatever local data was loaded.
52
- Falls back silently if unavailable.
53
-
54
- + Inline dyslexia augmentation (20% error rate) on all pairs.
55
-
56
- DATA_ROOT defaults to ./data (relative to script).
57
- Override with: DATA_ROOT=/path/to/data python train_and_upgrade.py
58
 
59
  USAGE:
60
  pip install -r requirements.txt
61
  HF_TOKEN=hf_xxx python train_and_upgrade.py
62
 
63
- requirements.txt (additions over v2):
64
  sentence-transformers>=2.7.0
65
  errant>=2.3.3 (optional β€” for ERRANT F0.5)
66
  """
@@ -108,25 +104,31 @@ log.info(f"Device: {DEVICE}")
108
  # ── Configuration ─────────────────────────────────────────────────────────────
109
  HF_TOKEN = os.environ.get("HF_TOKEN")
110
  MODEL_REPO = "morpheuslord/rewrite"
111
- BASE_MODEL_ID = "google/flan-t5-small"
 
 
 
 
112
  CHECKPOINT_DIR = "./checkpoints"
113
  MERGED_DIR = "./merged_model"
114
  BASELINE_FILE = "./baseline_score.json"
115
 
116
- # LoRA β€” warm-start from existing r=16 adapter, keep at r=16
117
- LORA_R = 16
118
- LORA_ALPHA = 32
 
 
119
  LORA_DROPOUT = 0.05
120
  TARGET_MODULES = ["q", "v", "k", "o", "wi_0", "wi_1", "wo"]
121
 
122
- # Training
123
- EPOCHS = 10
124
- BATCH_SIZE = 2 if not ON_GPU else 8 # larger batch on GPU
125
- GRAD_ACCUM = 32 if not ON_GPU else 8 # effective batch stays ~64
126
- LR = 2e-4
127
- WARMUP_RATIO = 0.10
128
  LABEL_SMOOTHING = 0.1
129
- MAX_INPUT_LEN = 256 # was 128 β€” T5 relative bias handles longer seqs
130
  MAX_TARGET_LEN = 256
131
 
132
  # Combined loss weights
@@ -142,7 +144,7 @@ EVAL_CAP = None if ON_GPU else 200
142
  # to the input are replaced with the original input as fallback
143
  FAITHFULNESS_THRESHOLD = 0.75
144
 
145
- TASK_PREFIX = "Correct the grammar and spelling while preserving writing style: "
146
 
147
  # ── Dyslexia Simulator ────────────────────────────────────────────────────────
148
 
@@ -278,6 +280,45 @@ def load_and_prepare_data(
278
  "Consider manually downloading a GEC corpus and adding pairs."
279
  )
280
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
281
  log.info(f"Total real pairs before augmentation: {len(pairs)}")
282
 
283
  # ── Dyslexia augmentation ─────────────────────────────────────────────
@@ -717,12 +758,12 @@ def push_to_hub(adapter_dir: str, merged_dir: str, scores: Dict) -> bool:
717
  api = HfApi()
718
  errant_str = f" | ERRANT {scores['errant_f05']:.4f}" if scores.get("errant_f05") else ""
719
  commit_msg = (
720
- f"Auto-upgrade v3: composite {scores['composite']:.4f} | "
721
  f"GLEU {scores['gleu']:.4f} | "
722
  f"BERTScore {scores['bert_f1']:.4f} | "
723
  f"1-WER {scores['inv_wer']:.4f}"
724
  f"{errant_str} | "
725
- f"r=16, 256-token ctx, C4-GEC data, faithfulness gate"
726
  )
727
 
728
  log.info("Pushing LoRA adapter to Hub...")
@@ -760,7 +801,11 @@ def push_to_hub(adapter_dir: str, merged_dir: str, scores: Dict) -> bool:
760
 
761
  def main():
762
  log.info("=" * 60)
763
- log.info("Rewrite Model Upgrade Pipeline (v3)")
 
 
 
 
764
  log.info("=" * 60)
765
  log.info(f"Device: {DEVICE} | GPU: {ON_GPU}")
766
  log.info(f"Context window: {MAX_INPUT_LEN} tokens")
@@ -811,14 +856,16 @@ def main():
811
  human_classifier=human_clf,
812
  )
813
 
814
- # ── Step 5: Training arguments ─────────────────────────────────────────
815
- log.info(f"Step 5: Training for {EPOCHS} epochs (effective batch={BATCH_SIZE * GRAD_ACCUM})...")
 
 
816
  training_args = Seq2SeqTrainingArguments(
817
  output_dir=CHECKPOINT_DIR,
818
  num_train_epochs=EPOCHS,
819
- per_device_train_batch_size=BATCH_SIZE,
820
- per_device_eval_batch_size=BATCH_SIZE,
821
- gradient_accumulation_steps=GRAD_ACCUM,
822
  learning_rate=LR,
823
  lr_scheduler_type="cosine",
824
  warmup_ratio=WARMUP_RATIO,
 
1
  """
2
+ train_and_upgrade.py (v4)
3
  ==========================
4
  Self-improving upgrade pipeline for morpheuslord/rewrite
5
 
6
+ CHANGES OVER v3 (the big one):
7
+ 1. Base model upgraded: google/flan-t5-small (77M) β†’ grammarly/coedit-large (406M)
8
+ coedit-large is T5-large already fine-tuned specifically for Grammar Error
9
+ Correction (GEC) tasks. Starting from this specialist model instead of a
10
+ general-purpose small model is the single largest quality improvement possible.
11
+ Same T5 architecture = same LoRA target modules, no structural changes needed.
12
 
13
+ 2. LoRA rank: r=16, Ξ±=32 β†’ r=32, Ξ±=64
14
+ Larger model can absorb more trainable capacity. Still ~16M trainable params
15
+ (~4% of 406M) β€” fits comfortably in 16GB RAM.
16
 
17
+ 3. Training adjusted for already-specialized base:
18
+ - Epochs: 10 β†’ 5 (coedit-large already knows GEC; gentle fine-tuning)
19
+ - LR: 2e-4 β†’ 1e-4 (lower rate prevents catastrophic forgetting)
20
+ - Warmup ratio: 10% β†’ 5%
21
 
22
+ 4. Batch: per_device=1, grad_accum=64 (effective batch=64, CPU-safe for 406M model)
 
23
 
24
+ 5. Data: added grammarly/coedit dataset (~68k GEC pairs β€” the same data the
25
+ base model was trained on, so fine-tuning on it steers the model toward
26
+ our specific dyslexia+style preservation task without fighting its priors).
27
 
28
+ 6. Task prefix updated to match coedit-large's training format for better
29
+ prompt-model alignment.
 
 
30
 
31
+ 7. Warm-start: the existing morpheuslord/rewrite LoRA adapter was trained on
32
+ flan-t5-small (hidden_size=512). coedit-large has hidden_size=1024 β€”
33
+ incompatible dimensions. The existing try/except already handles this:
34
+ it logs a warning and cold-starts cleanly from coedit-large's weights.
35
 
36
+ 8. Commit message and baseline label updated to reflect v4.
37
+
38
+ All v3 features retained:
39
+ - 256-token context window
40
+ - Combined loss: CE + style + semantic (+ human-pattern on GPU)
41
+ - Semantic faithfulness gate (cosine sim < 0.75 β†’ revert to source)
42
+ - ERRANT F0.5 optional metric
43
+ - Composite score gating before Hub push
44
+ - C4-GEC data loading (with fallback)
45
 
46
  DATASETS (priority order):
47
  Tier 1 β€” Local processed files (data/processed/*.jsonl)
 
 
 
48
  Tier 2 β€” Local raw FCE JSON (data/raw/fce/json/*.json)
49
+ Tier 3 β€” Local raw W&I+LOCNESS JSON
50
+ Tier 4 β€” HF Hub: JFLEG + W&I+LOCNESS
51
+ Tier 5 β€” grammarly/coedit (~68k pairs, NEW in v4)
52
+ Tier 6 β€” C4-200M GEC / multilingual-gec fallback (~100k pairs)
53
+ + Dyslexia augmentation (20% error rate) on all pairs
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
  USAGE:
56
  pip install -r requirements.txt
57
  HF_TOKEN=hf_xxx python train_and_upgrade.py
58
 
59
+ requirements.txt (same as v3):
60
  sentence-transformers>=2.7.0
61
  errant>=2.3.3 (optional β€” for ERRANT F0.5)
62
  """
 
104
  # ── Configuration ─────────────────────────────────────────────────────────────
105
  HF_TOKEN = os.environ.get("HF_TOKEN")
106
  MODEL_REPO = "morpheuslord/rewrite"
107
+ # v4: upgraded from google/flan-t5-small (77M generalist) to
108
+ # grammarly/coedit-large (406M GEC specialist β€” T5-large fine-tuned
109
+ # specifically for Grammar Error Correction tasks).
110
+ # Same T5 architecture: same target modules, same tokenizer family.
111
+ BASE_MODEL_ID = "grammarly/coedit-large"
112
  CHECKPOINT_DIR = "./checkpoints"
113
  MERGED_DIR = "./merged_model"
114
  BASELINE_FILE = "./baseline_score.json"
115
 
116
+ # LoRA β€” cold start on coedit-large (existing adapter was flan-t5-small,
117
+ # hidden_size 512 vs 1024 β€” incompatible; try/except handles it).
118
+ # r=32 gives ~16M trainable params (~4% of 406M), fits in 16GB RAM.
119
+ LORA_R = 32
120
+ LORA_ALPHA = 64
121
  LORA_DROPOUT = 0.05
122
  TARGET_MODULES = ["q", "v", "k", "o", "wi_0", "wi_1", "wo"]
123
 
124
+ # Training β€” tuned for CPU + already-specialized base model
125
+ EPOCHS = 5 # coedit-large already knows GEC; gentle fine-tuning
126
+ BATCH_SIZE = 1 # CPU-safe for 406M model in float32
127
+ GRAD_ACCUM = 64 # effective batch = 64 (same as v3)
128
+ LR = 1e-4 # lower LR β€” prevents catastrophic forgetting
129
+ WARMUP_RATIO = 0.05
130
  LABEL_SMOOTHING = 0.1
131
+ MAX_INPUT_LEN = 256
132
  MAX_TARGET_LEN = 256
133
 
134
  # Combined loss weights
 
144
  # to the input are replaced with the original input as fallback
145
  FAITHFULNESS_THRESHOLD = 0.75
146
 
147
+ TASK_PREFIX = "Fix grammar and spelling while preserving writing style: "
148
 
149
  # ── Dyslexia Simulator ────────────────────────────────────────────────────────
150
 
 
280
  "Consider manually downloading a GEC corpus and adding pairs."
281
  )
282
 
283
+ # ── grammarly/coedit (NEW in v4) ──────────────────────────────────────
284
+ # ~68k GEC pairs β€” the same dataset coedit-large was trained on.
285
+ # Fine-tuning on it steers the model toward our specific dyslexia+style
286
+ # task without fighting its training priors.
287
+ COEDIT_SPLITS = [
288
+ ("train", "sentence", "target"),
289
+ ("validation", "sentence", "target"),
290
+ ]
291
+ coedit_loaded = False
292
+ try:
293
+ log.info("Trying grammarly/coedit dataset...")
294
+ for split_name, src_col, tgt_col in COEDIT_SPLITS:
295
+ try:
296
+ coedit_split = load_dataset("grammarly/coedit", split=split_name)
297
+ before = len(pairs)
298
+ for row in coedit_split:
299
+ src = row.get(src_col, "").strip()
300
+ tgt = row.get(tgt_col, "").strip()
301
+ # Strip any task prefix that coedit prepends (e.g. "Fix grammar: ")
302
+ for pfx in ("Fix grammar: ", "Fix grammaticality: ",
303
+ "Fix the grammar: ", "Improve the fluency: ",
304
+ "Make the text more formal: ", "Simplify this: "):
305
+ if src.startswith(pfx):
306
+ src = src[len(pfx):]
307
+ break
308
+ if src and tgt and src != tgt:
309
+ pairs.append({"input": src, "target": tgt})
310
+ added = len(pairs) - before
311
+ if added > 0:
312
+ log.info(f"grammarly/coedit ({split_name}): {added} pairs loaded")
313
+ coedit_loaded = True
314
+ except Exception as e:
315
+ log.warning(f"grammarly/coedit {split_name} failed: {e}")
316
+ except Exception as e:
317
+ log.warning(f"grammarly/coedit unavailable: {e}")
318
+
319
+ if not coedit_loaded:
320
+ log.warning("grammarly/coedit not loaded β€” training without coedit pairs")
321
+
322
  log.info(f"Total real pairs before augmentation: {len(pairs)}")
323
 
324
  # ── Dyslexia augmentation ─────────────────────────────────────────────
 
758
  api = HfApi()
759
  errant_str = f" | ERRANT {scores['errant_f05']:.4f}" if scores.get("errant_f05") else ""
760
  commit_msg = (
761
+ f"Auto-upgrade v4: composite {scores['composite']:.4f} | "
762
  f"GLEU {scores['gleu']:.4f} | "
763
  f"BERTScore {scores['bert_f1']:.4f} | "
764
  f"1-WER {scores['inv_wer']:.4f}"
765
  f"{errant_str} | "
766
+ f"base=coedit-large, r=32, 256-token ctx, coedit+GEC data, faithfulness gate"
767
  )
768
 
769
  log.info("Pushing LoRA adapter to Hub...")
 
801
 
802
  def main():
803
  log.info("=" * 60)
804
+ log.info("Rewrite Model Upgrade Pipeline (v4)")
805
+ log.info("=" * 60)
806
+ log.info(f"Device: {DEVICE} | GPU: {ON_GPU}")
807
+ log.info(f"Base model: {BASE_MODEL_ID}")
808
+ log.info(f"LoRA: r={LORA_R}, Ξ±={LORA_ALPHA}")
809
  log.info("=" * 60)
810
  log.info(f"Device: {DEVICE} | GPU: {ON_GPU}")
811
  log.info(f"Context window: {MAX_INPUT_LEN} tokens")
 
856
  human_classifier=human_clf,
857
  )
858
 
859
+ # On GPU we can use larger batches; on CPU stay at 1 per device.
860
+ _train_batch = 4 if ON_GPU else BATCH_SIZE
861
+ _grad_accum = 16 if ON_GPU else GRAD_ACCUM # effective batch = 64 either way
862
+ log.info(f"Step 5: Training for {EPOCHS} epochs (effective batch={_train_batch * _grad_accum})...")
863
  training_args = Seq2SeqTrainingArguments(
864
  output_dir=CHECKPOINT_DIR,
865
  num_train_epochs=EPOCHS,
866
+ per_device_train_batch_size=_train_batch,
867
+ per_device_eval_batch_size=_train_batch,
868
+ gradient_accumulation_steps=_grad_accum,
869
  learning_rate=LR,
870
  lr_scheduler_type="cosine",
871
  warmup_ratio=WARMUP_RATIO,