Pad the instances to the max sequence length in batch, and generate the corresponding position data and input mask.
(insts,
pad_idx=0,
return_pos=False,
return_input_mask=False,
return_max_len=False,
return_num_token=False)
| 138 | |
| 139 | |
| 140 | def pad_batch_data(insts, |
| 141 | pad_idx=0, |
| 142 | return_pos=False, |
| 143 | return_input_mask=False, |
| 144 | return_max_len=False, |
| 145 | return_num_token=False): |
| 146 | """ |
| 147 | Pad the instances to the max sequence length in batch, and generate the |
| 148 | corresponding position data and input mask. |
| 149 | """ |
| 150 | return_list = [] |
| 151 | max_len = max(len(inst) for inst in insts) |
| 152 | # Any token included in dict can be used to pad, since the paddings' loss |
| 153 | # will be masked out by weights and make no effect on parameter gradients. |
| 154 | |
| 155 | inst_data = np.array([ |
| 156 | list(inst) + list([pad_idx] * (max_len - len(inst))) for inst in insts |
| 157 | ]) |
| 158 | return_list += [inst_data.astype("int64").reshape([-1, max_len])] |
| 159 | |
| 160 | # position data |
| 161 | if return_pos: |
| 162 | inst_pos = np.array([ |
| 163 | list(range(0, len(inst))) + [pad_idx] * (max_len - len(inst)) |
| 164 | for inst in insts |
| 165 | ]) |
| 166 | |
| 167 | return_list += [inst_pos.astype("int64").reshape([-1, max_len])] |
| 168 | |
| 169 | if return_input_mask: |
| 170 | # This is used to avoid attention on paddings. |
| 171 | input_mask_data = np.array([[1] * len(inst) + [0] * |
| 172 | (max_len - len(inst)) for inst in insts]) |
| 173 | input_mask_data = np.expand_dims(input_mask_data, axis=-1) |
| 174 | return_list += [input_mask_data.astype("float32")] |
| 175 | |
| 176 | if return_max_len: |
| 177 | return_list += [max_len] |
| 178 | |
| 179 | if return_num_token: |
| 180 | num_token = 0 |
| 181 | for inst in insts: |
| 182 | num_token += len(inst) |
| 183 | return_list += [num_token] |
| 184 | |
| 185 | return return_list if len(return_list) > 1 else return_list[0] |
| 186 | |
| 187 | |
| 188 | if __name__ == "__main__": |
no outgoing calls
no test coverage detected