--- language: - ko - en pipeline_tag: translation library_name: pytorch tags: - translation - korean - seq2seq - minrnn - mingru - document-translation - from-scratch license: apache-2.0 --- # minRNN Ko↔En Translator (268M) — 문서/문맥 단위 번역 PyTorch로 **바닥부터 직접 구현**한 한국어↔영어 번역 모델입니다. 어텐션 대신 **minGRU 선형 순환(minRNN)**을 쓰는 인코더-디코더 seq2seq로, 학습은 병렬 스캔으로 병렬화되고 디코딩은 스텝당 O(1)·메모리 O(L)입니다. 여러 문장을 문맥 윈도우로 묶어 통째로 번역하는 **문서 모드**를 지원합니다 — 문장별 번역에서 흔들리는 용어·대명사·문체 일관성을 문맥으로 유지합니다. *A 268M-parameter Korean↔English translation model implemented from scratch in PyTorch. Encoder-decoder seq2seq using minGRU linear recurrence (minRNN) instead of attention — parallel-scan training, O(1)/step decoding. Supports document-level translation by encoding a window of sentences jointly (k-to-k decoding), keeping terminology and style consistent across sentences.* - **코드/구현**: https://github.com/wndaasa/ko-en-translator - **아키텍처**: minRNN seq2seq — d_model 1024, enc/dec 각 8층, d_ff 4096, heads 16, vocab 32K (공용 BPE) - **positional embedding 없음**(순환이 위치를 담당) → max_len을 바꿔도 가중치 재사용 가능 ## 포함 모델 | 경로 | 용도 | 학습 | 지표 | |---|---|---|---| | `doc-paper/best.pt` | **논문/기술문서 문서모드 ko→en (권장)** | 문장 사전학습 → AI Hub 기술과학 60,483편(179K 문맥 윈도우) 파인튜닝 | val ppl **2.5**, 문서모드 BLEU **35.46** | | `sentence-base/best.pt` | 범용 문장 단위 ko↔en (양방향) | OPUS(NLLB·CCMatrix·OpenSubtitles·ParaCrawl) 17M쌍 | val ppl 12.6, ko→en BLEU ~26 | | `tokenizer.json` | 공용 ByteLevel BPE (32K, 방향 태그 포함) | — | — | ## 사용법 가중치는 자기완결형 체크포인트(`model`/`config`/`arch`)이며, 모델 코드는 GitHub 저장소에서 가져옵니다: ```bash git clone https://github.com/wndaasa/ko-en-translator cd ko-en-translator && pip install torch tokenizers huggingface_hub ``` ```python import torch from huggingface_hub import hf_hub_download from src.minrnn import MinRNNConfig, MinRNNSeq2Seq from src.tokenizer import load_tokenizer from src.data import CONTEXT_SEP from src.translate import greedy_translate, greedy_translate_context REPO = "Imsbee/ko-en-translator" device = "cuda" if torch.cuda.is_available() else "cpu" ckpt = torch.load(hf_hub_download(REPO, "doc-paper/best.pt"), map_location=device) model = MinRNNSeq2Seq(MinRNNConfig(**ckpt["config"])).to(device).eval() model.load_state_dict(ckpt["model"]) tok = load_tokenizer(hf_hub_download(REPO, "tokenizer.json")) # 문서 모드: 문장들을 CONTEXT_SEP("\x1f")로 이어 붙여 입력, k문장 → k문장 번역 doc = CONTEXT_SEP.join([ "본 연구에서는 화학 재활용 기술의 공정을 분석하였다.", "이 과정은 다음과 같다.", ]) print(greedy_translate_context(model, tok, doc, device, target_lang="en")) # 단일 문장 모드 (sentence-base/best.pt 는 양방향: target_lang="ko"도 가능) print(greedy_translate(model, tok, "한 명의 환자가 부분 반응을 보였다", device, target_lang="en")) ``` ## 학습 데이터·과정 1. **문장 사전학습**: OPUS moses(NLLB, CCMatrix, OpenSubtitles, ParaCrawl) 정제·전역 중복제거 16.99M쌍, 양방향(ko↔en), max_len 128. 2. **문맥 파인튜닝**: 문서 경계를 보존한 슬라이딩 윈도우로 연속 문장을 `` 구분자로 결합 (vocab 무변경), AI Hub '기술과학' 한영 논문 60,483편 → 179,136 문맥 윈도우, ko→en 단방향, max_len 640. RTX 4090 24GB 한 장으로 학습. 정성 샘플 (doc-paper): | 한국어 | 모델 출력 | |---|---| | 한 명의 환자가 부분 반응을 보였다 | one patient showed a partial response | | 이 화학 재활용 기술의 과정은 다음과 같다 | The process of this chemical recycling technology is as follows | | 꾸준한 구강 건강 관리 습관 형성이 중요하다 | It is important to form a steady oral health management habit | ## 왜 minRNN인가 268M 동일 모델 크기에서 디코더 forward를 길이별로 측정하면(batch 1), 긴 시퀀스일수록 트랜스포머(O(L²)) 대비 격차가 벌어집니다: | L | Transformer | minRNN | |---|---|---| | 128 | 1054 MB / 2.7 ms | 1038 MB / 2.4 ms | | 1024 | 1212 MB / 12.1 ms | 1083 MB / 9.5 ms | | 4096 | 3288 MB / 114 ms | 1239 MB / **39 ms** (메모리 2.65×, 속도 2.9×) | ## 한계 - 문서모드 BLEU는 짧은 문서 표본(20개) 기준 참고치입니다(긴 문서 전수 평가 미실행). - `doc-paper`는 논문/기술 문어체에 특화 — 구어·일상 도메인은 `sentence-base` 사용을 권장합니다. - greedy 디코딩만 구현되어 있습니다(beam search 없음). ## 학습 데이터 출처 (Attribution) - **본 모델은 [AI허브(aihub.or.kr)](https://www.aihub.or.kr)의 「한국어-영어 번역 말뭉치(기술과학)」 데이터를 활용하여 학습되었습니다. 해당 AI데이터는 한국지능정보사회진흥원(NIA)의 사업결과이며, 이 모델(2차적 저작물)에도 동일하게 이를 밝힙니다.** AI허브 데이터 이용정책에 따라 원 데이터는 재배포하지 않으며, 이 저장소는 학습된 가중치만 배포합니다. - OPUS 공개 병렬 코퍼스: NLLB, CCMatrix, OpenSubtitles, ParaCrawl — 각 코퍼스의 원 라이선스를 따릅니다.