| 118 | |
| 119 | |
| 120 | class AbstractSeq2SeqDataset(Dataset): |
| 121 | def __init__( |
| 122 | self, |
| 123 | tokenizer, |
| 124 | data_dir, |
| 125 | max_source_length, |
| 126 | max_target_length, |
| 127 | type_path="train", |
| 128 | n_obs=None, |
| 129 | prefix="", |
| 130 | **dataset_kwargs |
| 131 | ): |
| 132 | super().__init__() |
| 133 | self.src_file = Path(data_dir).joinpath(type_path + ".source") |
| 134 | self.tgt_file = Path(data_dir).joinpath(type_path + ".target") |
| 135 | self.len_file = Path(data_dir).joinpath(type_path + ".len") |
| 136 | if os.path.exists(self.len_file): |
| 137 | self.src_lens = pickle_load(self.len_file) |
| 138 | self.used_char_len = False |
| 139 | else: |
| 140 | self.src_lens = self.get_char_lens(self.src_file) |
| 141 | self.used_char_len = True |
| 142 | self.max_source_length = max_source_length |
| 143 | self.max_target_length = max_target_length |
| 144 | assert min(self.src_lens) > 0, f"found empty line in {self.src_file}" |
| 145 | self.tokenizer = tokenizer |
| 146 | self.prefix = prefix if prefix is not None else "" |
| 147 | |
| 148 | if n_obs is not None: |
| 149 | self.src_lens = self.src_lens[:n_obs] |
| 150 | self.pad_token_id = self.tokenizer.pad_token_id |
| 151 | self.dataset_kwargs = dataset_kwargs |
| 152 | dataset_kwargs.update({"add_prefix_space": True} if isinstance(self.tokenizer, BartTokenizer) else {}) |
| 153 | |
| 154 | def __len__(self): |
| 155 | return len(self.src_lens) |
| 156 | |
| 157 | @staticmethod |
| 158 | def get_char_lens(data_file): |
| 159 | return [len(x) for x in Path(data_file).open().readlines()] |
| 160 | |
| 161 | @cached_property |
| 162 | def tgt_lens(self): |
| 163 | """Length in characters of target documents""" |
| 164 | return self.get_char_lens(self.tgt_file) |
| 165 | |
| 166 | def make_sortish_sampler(self, batch_size, distributed=False, shuffle=True, **kwargs): |
| 167 | if distributed: |
| 168 | return DistributedSortishSampler(self, batch_size, shuffle=shuffle, **kwargs) |
| 169 | else: |
| 170 | return SortishSampler(self.src_lens, batch_size, shuffle=shuffle) |
| 171 | |
| 172 | def make_dynamic_sampler(self, max_tokens_per_batch=1024, **kwargs): |
| 173 | assert FAIRSEQ_AVAILABLE, "Dynamic batch size requires `pip install fairseq`" |
| 174 | assert not self.used_char_len, "You must call python make_len_file.py before calling make_dynamic_sampler" |
| 175 | sorted_indices = list(self.make_sortish_sampler(1024, shuffle=False)) |
| 176 | |
| 177 | def num_tokens_in_example(i): |
nothing calls this directly
no outgoing calls
no test coverage detected