M8: GPU 파인튜닝 시험 학습 (large-v3-turbo LoRA, CER 4.8% → 1.8%)
- train_lora: GPU 에서 원본 가중치 bf16 적재(VRAM 절반, 최대 2.7GB), 라벨 절반을 타임스탬프 형식으로 (notimestamps 로만 학습하면 앱의 타임스탬프 모드에서 끝맺음을 잊고 문장 뒤에 말을 지어냄) - evaluate: 앱과 같은 타임스탬프 모드로 측정 - finetune-e2e: GVR_FT_BASE/STEPS/SYNTH - README·테스트 기록: M7·M8 완료 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -78,6 +78,9 @@ uv pip install --python .venv-ft/bin/python -r gvr_worker/finetune/requirements.
|
||||
- 단계: `synth.py`(edge-tts SunHi/InJoon/Hyunsu, 속도·피치 변화, 30% 확률 배경 잡음) → `build_dataset.py`(문장 해시로 고정 검증 세트) →
|
||||
`evaluate.py`(학습 전 CER) → `train_lora.py`(LoRA r=32, q/k/v/out_proj, CUDA bf16 autocast / CPU fp32, gradient checkpointing) →
|
||||
`evaluate.py`(학습 후 CER) → `export_ct2.py`(병합 → CTranslate2 float16 → `models/<이름>-ft-<YYYYMMDD>/` + `gvr-model.json`).
|
||||
- GPU 에서는 얼려 둔 원본 가중치를 bf16 으로 올린다(LoRA 만 fp32). large-v3-turbo, 배치 4 기준 최대 VRAM 2.7GB.
|
||||
- 라벨의 절반은 `<|0.00|> 문장 <|말끝|>` 타임스탬프 형식이다. 앱은 타임스탬프 모드로 변환하므로, `<|notimestamps|>` 로만 학습하면
|
||||
끝맺음을 잊고 문장 뒤에 말을 지어낸다(M8 시험 학습에서 확인). `evaluate.py` 도 같은 이유로 타임스탬프 모드로 잰다.
|
||||
- `adopt = cer_after < cer_before` 일 때만 내보낸다(`--export-always` 로 강제). 앱은 `models` 의 `meta` 를 보고 교체/되돌리기.
|
||||
- 중지 파일(기본 `GVR-Data/finetune.stop`)이 있으면 시작하지 않고, 학습 중 생기면 어댑터를 저장하고 `stopped:true` 로 끝난다.
|
||||
- 사용자 교정 jsonl: `{"audio":"<training/xxx.ogg>","text":"<고친 문장>"}`.
|
||||
@@ -91,7 +94,7 @@ CPU 스모크 테스트(openai/whisper-tiny, 합성 30개, `--max-steps 3`)는
|
||||
- r3dlog 채팅 형식은 2024년 이전 보고 기준 추정이다. `r3dlog_check` 로 실제 로그를 확인해야 한다.
|
||||
- 잡음 판정 기준값은 추정치다. 실제 녹음으로 `noise_sensitivity` 와 `noise.py` 임계값을 조정해야 한다.
|
||||
- 정규화 음량은 16kHz 로 디코딩한 신호에서 잰다(48k 원본과 소폭 차이 가능).
|
||||
- CUDA 경로(GPU 추론, cuDNN/cuBLAS DLL 다운로드·로딩)는 이 개발 머신에서 실행하지 않았다(M0 에서 게임 PC 로 확인).
|
||||
- GPU 추론·학습은 개발 서버 RTX 5050(리눅스, CUDA float16)에서 확인했다(M7·M8, `docs/dev/test-results.md`). Windows 의 cuDNN/cuBLAS DLL 다운로드·로딩은 게임 PC 진단으로 확인한다.
|
||||
|
||||
## Windows 주의: pywinrt 의 오래된 MSVC 런타임
|
||||
|
||||
|
||||
@@ -43,7 +43,9 @@ def main() -> None:
|
||||
feats = processor.feature_extractor(audios, sampling_rate=16000, return_tensors="np").input_features
|
||||
x = torch.tensor(np.asarray(feats), dtype=dtype, device=model.device)
|
||||
with torch.inference_mode():
|
||||
ids = model.generate(input_features=x, language="ko", task="transcribe", max_new_tokens=128)
|
||||
# 앱과 같은 타임스탬프 모드로 잰다 (그래야 끝맺음을 잊은 모델을 걸러낸다)
|
||||
ids = model.generate(input_features=x, language="ko", task="transcribe", max_new_tokens=128,
|
||||
return_timestamps=True)
|
||||
hyps += [t.strip() for t in processor.batch_decode(ids, skip_special_tokens=True)]
|
||||
refs += [r["text"] for r in chunk]
|
||||
progress(stage, min(i + a.batch, len(rows)), len(rows))
|
||||
|
||||
@@ -20,6 +20,18 @@ import numpy as np
|
||||
from common import emit, load_audio, log, progress, read_jsonl
|
||||
|
||||
MAX_SAMPLES = 30 * 16000
|
||||
TS_PROB = 0.5 # 이 비율만큼은 타임스탬프가 붙은 라벨로 학습한다
|
||||
|
||||
|
||||
def speech_end_s(audio: np.ndarray, sr: int = 16000) -> float:
|
||||
"""끝의 무음을 뺀 말소리 끝 시각(초). 20ms 프레임 RMS 가 최대값 대비 -40dB 이상인 마지막 프레임."""
|
||||
hop = sr // 50
|
||||
n = len(audio) // hop
|
||||
if n == 0:
|
||||
return 0.0
|
||||
rms = np.sqrt(np.mean(audio[: n * hop].reshape(n, hop) ** 2, axis=1))
|
||||
loud = np.nonzero(rms > rms.max() * 0.01)[0]
|
||||
return float((loud[-1] + 1) * hop / sr) if len(loud) else len(audio) / sr
|
||||
|
||||
|
||||
def main() -> None:
|
||||
@@ -51,7 +63,9 @@ def main() -> None:
|
||||
|
||||
processor = WhisperProcessor.from_pretrained(a.base)
|
||||
processor.tokenizer.set_prefix_tokens(language="korean", task="transcribe")
|
||||
model = WhisperForConditionalGeneration.from_pretrained(a.base, dtype=torch.float32)
|
||||
# GPU(bf16)에서는 얼려 둘 원본 가중치를 bf16 으로 올려 VRAM 을 절반으로 줄인다 (large-v3-turbo: 3.2GB → 1.6GB).
|
||||
# 학습하는 LoRA 가중치만 fp32 로 둔다 (아래). CPU 는 fp32 그대로.
|
||||
model = WhisperForConditionalGeneration.from_pretrained(a.base, dtype=torch.bfloat16 if bf16 else torch.float32)
|
||||
model.config.use_cache = False
|
||||
model.generation_config.language = "ko"
|
||||
model.generation_config.task = "transcribe"
|
||||
@@ -62,6 +76,9 @@ def main() -> None:
|
||||
r=a.rank, lora_alpha=a.rank * 2, lora_dropout=0.05, bias="none",
|
||||
target_modules=["q_proj", "k_proj", "v_proj", "out_proj"],
|
||||
))
|
||||
for p in model.parameters():
|
||||
if p.requires_grad:
|
||||
p.data = p.data.float()
|
||||
model.print_trainable_parameters()
|
||||
model.to(device)
|
||||
|
||||
@@ -70,12 +87,26 @@ def main() -> None:
|
||||
raise SystemExit("학습 데이터가 없습니다")
|
||||
start_id = model.config.decoder_start_token_id
|
||||
|
||||
tok = processor.tokenizer
|
||||
eot = tok.convert_tokens_to_ids("<|endoftext|>")
|
||||
ts_prefix = [tok.convert_tokens_to_ids(t) for t in ("<|ko|>", "<|transcribe|>")]
|
||||
|
||||
def ts_token(t: float) -> int:
|
||||
return tok.convert_tokens_to_ids(f"<|{min(round(t / 0.02) * 0.02, 30.0):.2f}|>")
|
||||
|
||||
def featurize(row: dict) -> tuple[np.ndarray, list[int]]:
|
||||
audio = load_audio(row["audio"])[:MAX_SAMPLES]
|
||||
feats = processor.feature_extractor(audio, sampling_rate=16000, return_tensors="np").input_features[0]
|
||||
labels = processor.tokenizer(row["text"]).input_ids
|
||||
if labels and labels[0] == start_id: # 모델이 decoder_start 를 앞에 붙이므로 뺀다
|
||||
labels = labels[1:]
|
||||
if random.random() < TS_PROB:
|
||||
# 앱(faster-whisper)은 타임스탬프 모드로 변환한다. <|notimestamps|> 라벨로만 학습하면 그 모드에서 끝맺음
|
||||
# (끝 타임스탬프 → endoftext)을 잊어 문장 뒤에 "끝", "댕댕댕" 같은 말을 지어낸다 (시험 학습에서 확인).
|
||||
# 그래서 절반은 <|0.00|> 문장 <|말끝|> 형식으로 학습해 그 능력을 지킨다.
|
||||
text_ids = tok(row["text"], add_special_tokens=False).input_ids
|
||||
labels = [*ts_prefix, ts_token(0.0), *text_ids, ts_token(speech_end_s(audio)), eot]
|
||||
else:
|
||||
labels = tok(row["text"]).input_ids
|
||||
if labels and labels[0] == start_id: # 모델이 decoder_start 를 앞에 붙이므로 뺀다
|
||||
labels = labels[1:]
|
||||
return feats, labels
|
||||
|
||||
def batches():
|
||||
@@ -131,7 +162,8 @@ def main() -> None:
|
||||
processor.save_pretrained(str(out))
|
||||
meta = {"base": a.base, "steps": step, "total": total, "stopped": stopped, "train_samples": len(rows),
|
||||
"last_loss": None if math.isnan(last_loss) else last_loss, "seconds": round(time.time() - t0, 1),
|
||||
"device": str(device), "bf16": bf16}
|
||||
"device": str(device), "bf16": bf16,
|
||||
"peak_vram_mb": round(torch.cuda.max_memory_allocated() / 2**20) if cuda else None}
|
||||
(out / "train_meta.json").write_text(json.dumps(meta, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
emit({"result": {"adapter": str(out), **meta}})
|
||||
|
||||
|
||||
Reference in New Issue
Block a user