이 저장소에는 스크래치부터 구현한 Transformer와 그 위에 구축된 두 가지 실험 라인이 포함되어 있습니다:
- 언어 프리트레이닝 WikiText-103에서 간단한 GPT 스타일(디코더 전용) 및 BERT 스타일(인코더 전용) 모델로
- 멀티피처 시계열 예측 여기서 이질적인 피처(연속 + 범주형)가 임베딩되고, 연결되어 자기회귀 방식으로 예측됩니다.
# 0) conda 환경 생성
conda create -n transformer_from_sc python=3.9 -y
conda activate transformer_from_sc
# 1) 요구사항 설치
pip install -r requirements.txt참고: CUDA를 사용하는 경우, 로컬 CUDA 버전에 맞는 PyTorch 빌드를 설치하세요.
transformer/
├── checkpoint/ # 모델 체크포인트
├── src/
│ ├── data/ # 데이터 파일
│ ├── transformer_scratch.py # 코어 Transformer (스크래치부터)
│ └── model/
│ ├── gpt_style.py # 디코더 전용 장난감/프리트레이닝
│ ├── bert_style.py # 인코더 전용 MLM 프리트레이닝
│ ├── multifeature_forecast_v1.py # v1: 균일 dtype 피처
│ └── multifeature_forecast_v2.py # v2: 혼합 연속 + 범주형
└── README.md
직접 작성한 Transformer 모듈로 다음을 구현합니다:
MultiHeadAttention,PoswiseFeedForwardNet- 마스킹 유틸리티 (
attention_pad_mask,attention_decoder_mask) - 사인파 위치 인코딩 (
get_sinusoid_encoding_table) - 모든 다른 모델에서 사용되는 인코더/디코더 블록
이 파일은 언어 프리트레이닝과 멀티피처 예측 모델 모두의 기초입니다.
WikiText-103을 로드하기 위해 Hugging Face 데이터셋을 사용합니다:
from datasets import load_dataset
dataset = load_dataset("wikitext", "wikitext-103-v1")두 언어 모델 모두 transformer_scratch.py의 커스텀 Transformer 위에 구현됩니다:
- 커스텀 디코더 블록을 쌓아 구축된 디코더 전용(GPT 스타일) 모델
- 자기회귀 언어 모델링을 위해 훈련됨
- 커스텀 인코더 블록을 쌓아 구축된 인코더 전용(BERT 스타일) 모델
- 마스크드 언어 모델링(MLM)으로 훈련됨
# BERT 스타일 MLM 파인튜닝 / 프리트레이닝 예시
python -m src.model.bert_style
# 또는
python src/model/bert_style.py참고: 체크포인트 디렉토리는 기본적으로
checkpoint/입니다. 필요시 스크립트 내에서 조정하세요.
- 여러 피처가 시간 단계당 임베딩되고 단일 토큰 표현으로 연결됩니다
- 디코더 전용 Transformer가 시퀀스를 소비하고 모든 헤드에 대한 다음 단계 타겟을 예측합니다
- 추론은 슬라이딩 윈도우와 재귀 예측을 사용합니다
- 모든 피처가 동일한 dtype을 공유한다고 가정 (예: 모두 범주형 또는 균일하게 처리)
- 더 간단한 임베딩과 헤드 레이아웃
- 혼합 피처 타입: 연속 (예: Sales) + 범주형 (Open, Promo, StateHoliday, SchoolHoliday, EOS)
- 멀티헤드 예측 타겟:
sales: 회귀 (MSE)open,promo,school,eos: 이진 (BCE with logits)state: 다중 클래스 (크로스 엔트로피)
- 스토어별 z-score 정규화를 지원하고 생성 중 역정규화
- 시퀀스 종료를 모델링하기 위한 EOS 스트림 포함
# v2 (혼합 타입, 멀티태스크 예측)
python -m src.model.multifeature_forecast_v2
# v1 (균일 dtype)
python -m src.model.multifeature_forecast- 체크포인트: 각 스크립트의
CKPT_DIR확인 (checkpoint/기본) - GPU 선택:
CUDA_VISIBLE_DEVICES설정 또는 런처 구성 - 배치/시퀀스 길이: GPU 메모리 예산에 맞게 튜닝
- 경로:
DATA_PATH및 캐시/체크포인트 경로가 환경에 맞는지 확인
기본적으로 연구 및 교육용 사용.
상업적 사용의 경우, 데이터/모델 라이선스 및 준수를 확인하세요.
This repository contains a from-scratch Transformer implementation and two lines of experiments built on top of it:
- Language pretraining with simple GPT-style (decoder-only) and BERT-style (encoder-only) models on WikiText-103
- Multifeature time-series forecasting where heterogeneous features (continuous + categorical) are embedded, concatenated, and predicted in an autoregressive manner
# 0) Create conda environment
conda create -n transformer_from_sc python=3.9 -y
conda activate transformer_from_sc
# 1) Install requirements
pip install -r requirements.txtNote: If you use CUDA, install a PyTorch build that matches your local CUDA version.
transformer/
├── checkpoint/ # Model checkpoints
├── src/
│ ├── data/ # Data files
│ ├── transformer_scratch.py # Core Transformer (from scratch)
│ └── model/
│ ├── gpt_style.py # Decoder-only toy/pretraining
│ ├── bert_style.py # Encoder-only MLM pretraining
│ ├── multifeature_forecast_v1.py # v1: uniform dtype features
│ └── multifeature_forecast_v2.py # v2: mixed continuous + categorical
└── README.md
A hand-written Transformer module that implements:
MultiHeadAttention,PoswiseFeedForwardNet- Masking utilities (
attention_pad_mask,attention_decoder_mask) - Sinusoidal positional encodings (
get_sinusoid_encoding_table) - Encoder/decoder blocks used by all other models
This file is the foundation for both language pretraining and multifeature forecasting models.
We use Hugging Face datasets to load WikiText-103:
from datasets import load_dataset
dataset = load_dataset("wikitext", "wikitext-103-v1")Both language models are implemented on top of the custom Transformer in transformer_scratch.py:
- Decoder-only (GPT-style) model built by stacking the custom decoder blocks
- Trained for autoregressive language modeling
- Encoder-only (BERT-style) model built by stacking the custom encoder blocks
- Trained with Masked Language Modeling (MLM)
# BERT-style MLM fine-tuning / pretraining example
python -m src.model.bert_style
# or
python src/model/bert_style.pyNote: Checkpoint directory defaults to
checkpoint/. Adjust inside the script if needed.
- Multiple features are embedded per time step and concatenated into a single token representation
- A decoder-only Transformer consumes the sequence and predicts next-step targets for all heads
- Inference uses a sliding window with recursive forecasting
- Assumes all features share the same dtype (e.g., all categorical or all treated uniformly)
- Simpler embedding and head layout
- Mixed feature types: continuous (e.g., Sales) + categorical (Open, Promo, StateHoliday, SchoolHoliday, EOS)
- Multi-head prediction targets:
sales: regression (MSE)open,promo,school,eos: binary (BCE with logits)state: multi-class (cross-entropy)
- Supports per-store z-score normalization for Sales, and de-normalization during generation
- Includes an EOS stream to model sequence termination
# v2 (mixed type, multi-task forecasting)
python -m src.model.multifeature_forecast_v2
# v1 (uniform dtype)
python -m src.model.multifeature_forecast- Checkpoints: See
CKPT_DIRin each script (checkpoint/by default) - GPU selection: Set
CUDA_VISIBLE_DEVICESor configure your launcher - Batch/sequence length: Tune for your GPU memory budget
- Paths: Ensure
DATA_PATHand any cache/checkpoint paths match your environment
Research and educational use by default.
For commercial use, verify data/model licenses and compliance.