C.W.K.
Stream
Lesson 04 of 08 · published

dataset.map(): 캐시되는 변환

~30 min · datasets, map

Level 0스카우트
0 XP0/50 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

map() 이 일꾼인 이유

ds.map(fn) 이 함수를 row-by-row (또는 batch-by-batch) 로 적용, 새 데이터셋 돌려줌. Pandas .apply() 처럼 보이는데 두 결정적 차이: cached (함수 source 기반으로 디스크에 결과 memoize) + multi-process (num_proc=N).

Batched + unbatched

디폴트는 row 별. 토크나이즈, NLP 전처리, 무거운 op 대부분에 batched=True 가 극적으로 빠름 — 함수가 컬럼 리스트 dict 받고 같은 모양 돌려줌. 라이브러리가 batch 자동 split.

remove_columns gotcha

map 함수가 새 컬럼 추가하면 (전형적: text 컬럼을 input_ids + attention_mask 로 토크나이즈), remove_columns=['text'] 셋 안 하면 원본 컬럼 남아. Trainer 가 추가 string 컬럼 안 받아서 “trainer 깨짐” 티켓의 가장 흔한 원인.

Code

Batched 토크나이즈·python
from datasets import load_dataset
from transformers import AutoTokenizer

tok = AutoTokenizer.from_pretrained("distilbert-base-uncased")
ds = load_dataset("stanfordnlp/imdb", split="train")

def tokenize(batch):
    return tok(batch["text"], padding="max_length", truncation=True, max_length=512)

tokenized = ds.map(
    tokenize,
    batched=True,
    batch_size=1000,
    num_proc=4,
    remove_columns=["text"],   # trainer 호환에 critical
)
print(tokenized)
print(tokenized[0].keys())  # input_ids, attention_mask, label
함수 바꿀 때 캐시 invalidation·python
# datasets 가 함수 source 로 캐시 키.
# 함수 살짝 tweak 하고 kwargs 안 바꾸면 결과 STILL stale.
# load_from_cache_file=False 로 강제 재실행:

tokenized = ds.map(tokenize, batched=True, load_from_cache_file=False)

# 또는 캐시 상태 inspect:
print(ds.cache_files)  # (filename, range) 튜플 리스트

External links

Exercise

stanfordnlp/imdb train split 을 batched=Falsebatched=True, batch_size=1000 둘 다로 토크나이즈. 시간 측정. 다시 돌려 캐시 hit 확인 (거의 instant 여야). 토크나이저 max_length 수정, 재실행, 캐시 invalidate 확인.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.