홈으로 돌아가기

transformers용 ruGPT-3 XL 복원

이 글은 Megatron 형식의 레거시 ruGPT-3 XL을 HuggingFace로 변환하는 과정을 설명합니다. 상세한 가중치 매핑, 커스텀 클래스, RTX 4090에서의 테스트 및 MERA 벤치마크. 모델은 fine-tuning 및 GGUF 변환 준비 완료.

복원된 ruGPT-3 XL: Megatron에서 transformers로
Advertisement 728x90

ruGPT-3 XL을 현대 프레임워크로 변환하고 복원하기

2021년에 출시된 오래된 언어 모델 ai-forever/rugpt3xl(13억 파라미터)을 사용하는 개발자들은 여러 어려움을 겪었습니다. 이 모델은 러시아어 코퍼스에서 처음부터 학습한 GPT-2 계열 모델로, Megatron-LM 체크포인트 형식으로 저장되어 있으며 PyTorch 1.7과 transformers 3.5가 필요합니다. 이를 Hugging Face 형식으로 변환하면 최신 추론 및 미세조정 도구와의 호환성이 열립니다.

이 과정은 mp_rank_00_model_states.pt에서 가중치를 추출하고, GPT2Model 구조에 매핑한 후, transformers용 커스텀 클래스를 생성하는 것으로 구성됩니다.

가중치 구조: Megatron-LM vs HuggingFace

기존 가중치는 결합된 QKV 프로젝션 [6144, 2048]을 사용하며, 이를 각각 크기 [2048, 2048]의 Q, K, V 행렬로 분리해야 합니다. 전체 매핑은 다음과 같습니다:

Google AdInline article slot

| Megatron-LM | HuggingFace |

|-------------|-------------|

| word_embeddings.weight | model.embed_tokens.weight |

Google AdInline article slot

| position_embeddings.weight | model.embed_positions.weight |

| transformer.layers.{i}.input_layernorm. | model.layers.{i}.input_layernorm. |

| transformer.layers.{i}.attention.query_key_value.weight | model.layers.{i}.self_attn.{q,k,v}_proj.weight |

Google AdInline article slot

| transformer.layers.{i}.attention.query_key_value.bias | model.layers.{i}.self_attn.{q,k,v}_proj.bias |

| transformer.layers.{i}.attention.dense. | model.layers.{i}.self_attn.o_proj. |

| transformer.layers.{i}.post_attention_layernorm. | model.layers.{i}.post_attention_layernorm. |

| transformer.layers.{i}.mlp.dense_h_to_4h. | model.layers.{i}.mlp.up_proj. |

| transformer.layers.{i}.mlp.dense_4h_to_h. | model.layers.{i}.mlp.down_proj. |

| transformer.final_layernorm. | model.norm. |

| - | lm_head.weight (embed_tokens 복사본) |

convert.py 스크립트는 체크포인트를 transformers와 호환되는 safetensors 형식으로 변환합니다.

커스텀 모델 클래스

Megatron-LM 또는 DeepSpeed에 의존하지 않는 새로운 클래스를 구현했습니다:

  • RuGPT3XLConfig: PretrainedConfig를 상속하며, 파라미터는 (vocab_size=50264, hidden_size=2048, num_layers=24).
  • RuGPT3XLAttention: 별도의 Q/K/V와 DynamicCache를 지원하는 멀티헤드 어텐션.
  • RuGPT3XMLP: MLP 블록(업프로젝션 → GELU → 다운프로젝션).
  • RuGPT3XLDecoderLayer: 디코더 레이어(전처리 정규화 → 어텐션 → 후처리 정규화 → MLP).
  • RuGPT3XLModel: 임베딩 + 24층 + 최종 정규화.
  • RuGPT3XLForCausalLM: lm_head 포함.

주요 개선 사항:

  • SFTTrainer/LoRA용 표준 forward().
  • DynamicCache를 통한 KV 캐시.
  • 그래디언트 체크포인팅.
  • device_map="auto"로 CPU/GPU 모두에서 실행 가능.

이제 모델은 Hugging Face에서 evilfreelancer/ruGPT3XL로 이용할 수 있습니다.

테스트 결과

RTX 4090에서 float16으로 생성한 결과:

  • 평균 속도: 초당 66.7토큰 (batch_size=1)
  • 긴 프롬프트에서도 맥락 유지
  • 요리법, 역사적 서사 등 정확한 텍스트 생성

MERA 벤치마크 (총점: 0.198):

  • PARus (일반 지성): 0.500
  • ruHateSpeech: 0.558
  • BPS (코드/수학): 0.528
  • RWSD (추론): 0.488
  • ruTiE (대화): 0.502
  • ruMMLU: 0.252

수학 및 코드 성능은 기준 모델 수준에 근접해 있으며, 지시 조정 없이 기본 모델이므로 예상 가능한 결과입니다.

GGUF로 변환하여 llama.cpp 사용하기

HF 형식으로 변환한 후, convert_hf_to_gguf.py 스크립트를 ruGPT-3 XL용으로 수정했습니다. 이제 Megatron 의존 없이 llama.cpp에서 실행되며, KV 캐시 및 최신 추론을 지원합니다.

이를 통해 LoRA 또는 SFT를 통한 맞춤형 데이터셋 미세조정, 파이프라인 통합, 엣지 장치에서의 테스트가 가능해졌습니다.

핵심 요약

  • 호환성: transformers ≥4.x와 호환, 구형 스택 필요 없음.
  • 성능: RTX 4090에서 초당 66.7토큰, 생성 시 KV 캐시 지원.
  • 학습 가능성: 그래디언트 체크포인팅을 활용한 LoRA/SFTTrainer 준비 완료.
  • 벤치마크: 일반 지성 및 혐오 발언 탐지에서 강점 (>0.5), 수학/코드에서는 약점.
  • 포맷: 광범위한 생태계 지원을 위한 HF + GGUF 제공.

— Editorial Team

Advertisement 728x90

다음 읽기