我有一个关于“飞行中”标记的问题。这个问题是通过阅读“如何从零开始使用变形金刚和托卡器来训练一个新的语言模型”这里提出的。最后有一句话:“如果您的数据集非常大,可以选择动态加载和标记示例,而不是作为预处理步骤”。我尝试了一种将datasets
和tokenizers
结合起来的解决方案,但是没有找到一个好的模式。
我想这个解决方案需要将一个数据集包装到Pytorch数据集中。
作为文档的一个具体例子
import torch
class SquadDataset(torch.utils.data.Dataset):
def __init__(self, encodings):
# instead of doing this beforehand, I'd like to do tokenization on the fly
self.encodings = encodings
def __getitem__(self, idx):
return {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}
def __len__(self):
return len(self.encodings.input_ids)
train_dataset = SquadDataset(train_encodings)
如何利用令牌程序的矢量化功能来实现“动态”令牌化?
发布于 2020-12-08 13:55:52
更新2021年2月
从v1.3.0开始,数据集支持通过set_transform
方法对函数进行延迟评估。因此,您可以像显示的这里那样直接应用动态标记化。
旧答案
最后,我接受了这个解决方案。我不喜欢batch_size现在被控制在dataset级别。然而,它做好了自己的工作。
通过这种方式,我们利用了两种美好的东西:
class CustomPytorchDataset(Dataset):
"""
This class wraps the HuggingFace dataset and allows for
batch indexing into the dataset. This allows exploiting
the capabilities of the tokenizer to work on batches.
NOTE: now we control batch_size at the Dataset level, not
in the DataLoader therefore the DataLoader should always be
used with `batch_size=1`.
"""
def __init__(self, batch_size: int):
self.batch_size = batch_size
self.dataset = train_ds # HuggingFace dataset
self.tokenizer = bert_tokenizer # HuggingFace tokenizer
def __getitem__(self, batch_idx: List[int]):
instance = self.dataset[batch_idx]
# tokenize on-the-fly
tokenized_instance = self.tokenizer(
instance[text_col],
truncation=True,
padding=True
)
return tokenized_instance
def __len__(self):
return len(self.dataset)
def sampler(self):
# shuffling can be controlled by the sampler,
# without touching the dataset
return BatchSampler(
SequentialSampler(self),
batch_size=self.batch_size,
drop_last=True
)
@staticmethod
def collate_fn(batches: List[Dict[str, int]]):
return {
k: torch.tensor(v, dtype=torch.int64)
for k, v in batches[0].items()
}
https://stackoverflow.com/questions/65159768
复制相似问题