๐ถ ํ์ต ๋ฒ์
- ์คํ ๋ค๋๋ฐ
- ๊ฐ์ธ ๊ณต๋ถ
๐ถ ํ์ต ๋ด์ฉ
โจ ๊ฐ์ธ ๊ณต๋ถ
โ๏ธ ์์น ์ธ์ฝ๋ฉ1. ์์น ์ธ์ฝ๋ฉ 1) ๋ด์ฉ - ํธ๋์คํฌ๋จธ์์๋ ๋ชจ๋ ์ ๋ ฅ์ ๋์์ ์ฒ๋ฆฌ - ๊ทธ ๊ณผ์ ์์ ์์ ์ ๋ณด๊ฐ ์ฌ๋ผ์ง - ์ด๋ ์์๋ฅผ ์ถ๊ฐํด์ฃผ๋ ์ญํ ์ ๋ด๋น 2. ์ ๋์ ์์น ์ธ์ฝ๋ฉ(absolute position encoding) 1) ๋ด์ฉ - ์ ๋ ฅ ํ ํฐ์ ์์น์ ๋ฐ๋ผ ๊ณ ์ ๋ ์๋ฒ ๋ฉ์ ๋ํจ - ํ ํฐ๊ณผ ํ ํฐ ์ฌ์ด์ ์๋์ ์ธ ์์น์ ๋ณด ํ์ฉํ์ง ๋ชปํจ - ๊ธด ํ ์คํธ๋ฅผ ์ถ๋ก ํ๋ ๊ฒฝ์ฐ์๋ ์ฑ๋ฅ์ด ๋จ์ด์ง
โ๏ธ ํ ํฐํ ์ํ ์ฝ๋# ํ ์คํธ๋ฅผ ์ ์ ํ ๋จ์๋ก ๋๋ (๋์ด์ฐ๊ธฐ ๊ธฐ์ค) input_text = "๋๋ ์ต๊ทผ ํ๋ฆฌ ์ฌํ์ ๋ค๋ ์๋ค" input_text_list = input_text.split() print(input_text_list) # ['๋๋', '์ต๊ทผ', 'ํ๋ฆฌ', '์ฌํ์', '๋ค๋ ์๋ค'] # ํ ํฐ (์ซ์ID ๋ถ์ฌ) # ์์ด๋ ๋์ ๋๋ฆฌ์ ์์ด๋ str2idx = {word:idx for idx, word in enumerate(input_text_list)} # ํ ํฐ ๋์ ๋๋ฆฌ ๋ง๋ค๊ธฐ idx2str = {idx:word for idx, word in enumerate(input_text_list)} print(str2idx) # {'๋๋': 0, '์ต๊ทผ': 1, 'ํ๋ฆฌ': 2, '์ฌํ์': 3, '๋ค๋ ์๋ค': 4} print(idx2str) # {0: '๋๋', 1: '์ต๊ทผ', 2: 'ํ๋ฆฌ', 3: '์ฌํ์', 4: '๋ค๋ ์๋ค'} # ํ ํฐ์ ํ ํฐ ์์ด๋๋ก ๋ณํ input_ids = [str2idx[word] for word in input_text_list] print(input_ids) # [0, 1, 2, 3, 4]
โ๏ธ ์ ๋์ ์์น ์ธ์ฝ๋ฉ
embedding_dim = 16 max_position = 12 # 1. ํ ํฐ ์๋ฒ ๋ฉ ์ธต ์์ฑ (5, 16) embed_layer = nn.Embedding(len(str2idx), embedding_dim) # 2. ์์น ์ธ์ฝ๋ฉ ์ธต ์์ฑ (12, 16) position_embed_layer = nn.Embedding(max_position, embedding_dim) # 3. ์์น ID ์์ฑ ๋ฐ ์ธ์ฝ๋ฉ # - torch.arange(len(input_ids)) :: ์ ๋ ฅ ํ ํฐ์ ๊ฐ์๋งํผ ์์น ID๋ฅผ ์์ฑ # - unsqueeze(0) :: ์ด ๋ฐฐ์ด์ ๋ฐฐ์น ์ฐจ์์ ์ถ๊ฐํ์ฌ ๋ชจ์์ (1, ์ํ์ค ๊ธธ์ด)๋ก ๋ง๋ฌ position_ids = torch.arange(len(input_ids), dtype=torch.long).unsqueeze(0) position_encodings = position_embed_layer(position_ids) # 4. ํ ํฐ ์๋ฒ ๋ฉ ์กฐํ ๋ฐ ์ฐจ์ ์กฐ์ token_embeddings = embed_layer(torch.tensor(input_ids)) # (5, 16) token_embeddings = token_embeddings.unsqueeze(0) # (1, 5, 16) # 5. ํ ํฐ ์๋ฒ ๋ฉ๊ณผ ์์น ์ธ์ฝ๋ฉ์ ๋ํด ์ต์ข ์ ๋ ฅ ์๋ฒ ๋ฉ ์์ฑ input_embeddings = token_embeddings + position_encodings input_embeddings.shape # torch.Size([1, 5, 16]))
๐ถ ๋๋์
1. ๊ณต๋ถํ ๊ฑด ๋ง๊ณ ์๊ฐ์ ๋ถ์กฑํ๋ค.
2. ๋ค ํ ์ ์๋ค. ๊ณต๋ถ ์ ๋ต์ ์ธ์ฐ์
'๊ต์ก > ์คํ๋ฅดํ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| [TIL] ๋ด์ผ๋ฐฐ์์บ ํ AI 9๊ธฐ - 22ํ (1) | 2025.02.05 |
|---|---|
| [TIL] ๋ด์ผ๋ฐฐ์์บ ํ AI 9๊ธฐ - 21ํ (4) | 2025.02.04 |
| [TIL] ๋ด์ผ๋ฐฐ์์บ ํ AI 9๊ธฐ - 20ํ (0) | 2025.02.03 |
| [TIL] ๋ด์ผ๋ฐฐ์์บ ํ AI 9๊ธฐ - 19ํ (0) | 2025.01.31 |
| [TIL] ๋ด์ผ๋ฐฐ์์บ ํ AI 9๊ธฐ - 18ํ (2) | 2025.01.09 |