|
| 1 | +import random |
| 2 | +from functools import partial |
| 3 | + |
| 4 | +import numpy as np |
| 5 | + |
| 6 | +import paddle |
| 7 | +import paddle.distributed as dist |
| 8 | +from paddle.io import DataLoader, DistributedBatchSampler, BatchSampler |
| 9 | +from paddlenlp.data import Pad |
| 10 | + |
| 11 | + |
| 12 | +def print_args(args): |
| 13 | + print('----------- Configuration Arguments -----------') |
| 14 | + for arg, value in sorted(vars(args).items()): |
| 15 | + print('%s: %s' % (arg, value)) |
| 16 | + print('------------------------------------------------') |
| 17 | + |
| 18 | + |
| 19 | +def set_seed(seed): |
| 20 | + # Use the same data seed(for data shuffle) for all procs to guarantee data |
| 21 | + # consistency after sharding. |
| 22 | + random.seed(seed) |
| 23 | + np.random.seed(seed) |
| 24 | + # Maybe different op seeds(for dropout) for different procs is better. |
| 25 | + paddle.seed(seed + dist.get_rank()) |
| 26 | + |
| 27 | + |
| 28 | +def convert_example(example, |
| 29 | + tokenizer, |
| 30 | + max_seq_len=512, |
| 31 | + max_target_len=128, |
| 32 | + max_title_len=256, |
| 33 | + mode='train'): |
| 34 | + """Convert all examples into necessary features.""" |
| 35 | + source = example['source'] |
| 36 | + title = None |
| 37 | + if 'title' in example.keys(): |
| 38 | + title = example['title'] |
| 39 | + |
| 40 | + if mode != 'test': |
| 41 | + tokenized_example = tokenizer.gen_encode( |
| 42 | + source, |
| 43 | + title=title, |
| 44 | + target=example['target'], |
| 45 | + max_seq_len=max_seq_len, |
| 46 | + max_target_len=max_target_len, |
| 47 | + max_title_len=max_title_len, |
| 48 | + return_position_ids=True, |
| 49 | + return_length=True) |
| 50 | + target_start = tokenized_example['input_ids'].index( |
| 51 | + tokenizer.cls_token_id, 1) |
| 52 | + target_end = tokenized_example['seq_len'] |
| 53 | + # Use to gather the logits corresponding to the labels during training |
| 54 | + tokenized_example['masked_positions'] = list( |
| 55 | + range(target_start, target_end - 1)) |
| 56 | + tokenized_example['labels'] = tokenized_example['input_ids'][ |
| 57 | + target_start + 1:target_end] |
| 58 | + |
| 59 | + return tokenized_example |
| 60 | + else: |
| 61 | + tokenized_example = tokenizer.gen_encode( |
| 62 | + source, |
| 63 | + title=title, |
| 64 | + max_seq_len=max_seq_len, |
| 65 | + max_title_len=max_title_len, |
| 66 | + add_start_token_for_decoding=True, |
| 67 | + return_position_ids=True) |
| 68 | + |
| 69 | + if 'target' in example: |
| 70 | + tokenized_example['target'] = example['target'] |
| 71 | + return tokenized_example |
| 72 | + |
| 73 | + |
| 74 | +def batchify_fn(batch_examples, pad_val, mode): |
| 75 | + def pad_mask(batch_attention_mask): |
| 76 | + batch_size = len(batch_attention_mask) |
| 77 | + max_len = max(map(len, batch_attention_mask)) |
| 78 | + attention_mask = np.ones( |
| 79 | + (batch_size, max_len, max_len), dtype='float32') * -1e9 |
| 80 | + for i, mask_data in enumerate(attention_mask): |
| 81 | + seq_len = len(batch_attention_mask[i]) |
| 82 | + mask_data[-seq_len:, -seq_len:] = np.array( |
| 83 | + batch_attention_mask[i], dtype='float32') |
| 84 | + # In order to ensure the correct broadcasting mechanism, expand one |
| 85 | + # dimension to the second dimension (n_head of Transformer). |
| 86 | + attention_mask = np.expand_dims(attention_mask, axis=1) |
| 87 | + return attention_mask |
| 88 | + |
| 89 | + pad_func = Pad(pad_val=pad_val, pad_right=False, dtype='int64') |
| 90 | + |
| 91 | + input_ids = pad_func([example['input_ids'] for example in batch_examples]) |
| 92 | + token_type_ids = pad_func( |
| 93 | + [example['token_type_ids'] for example in batch_examples]) |
| 94 | + position_ids = pad_func( |
| 95 | + [example['position_ids'] for example in batch_examples]) |
| 96 | + |
| 97 | + attention_mask = pad_mask( |
| 98 | + [example['attention_mask'] for example in batch_examples]) |
| 99 | + |
| 100 | + if mode != 'test': |
| 101 | + max_len = max([example['seq_len'] for example in batch_examples]) |
| 102 | + masked_positions = np.concatenate([ |
| 103 | + np.array(example['masked_positions']) + |
| 104 | + (max_len - example['seq_len']) + i * max_len |
| 105 | + for i, example in enumerate(batch_examples) |
| 106 | + ]) |
| 107 | + labels = np.concatenate([ |
| 108 | + np.array( |
| 109 | + example['labels'], dtype='int64') for example in batch_examples |
| 110 | + ]) |
| 111 | + return input_ids, token_type_ids, position_ids, attention_mask, masked_positions, labels |
| 112 | + else: |
| 113 | + return input_ids, token_type_ids, position_ids, attention_mask |
| 114 | + |
| 115 | + |
| 116 | +def create_data_loader(dataset, tokenizer, args, mode): |
| 117 | + trans_func = partial( |
| 118 | + convert_example, |
| 119 | + tokenizer=tokenizer, |
| 120 | + max_seq_len=args.max_seq_len, |
| 121 | + max_target_len=args.max_target_len, |
| 122 | + max_title_len=args.max_title_len, |
| 123 | + mode=mode) |
| 124 | + dataset = dataset.map(trans_func, lazy=True) |
| 125 | + if mode == 'train': |
| 126 | + batch_sampler = DistributedBatchSampler( |
| 127 | + dataset, batch_size=args.batch_size, shuffle=True) |
| 128 | + else: |
| 129 | + batch_sampler = BatchSampler( |
| 130 | + dataset, batch_size=args.batch_size // 2, shuffle=False) |
| 131 | + collate_fn = partial(batchify_fn, pad_val=tokenizer.pad_token_id, mode=mode) |
| 132 | + data_loader = DataLoader( |
| 133 | + dataset, |
| 134 | + batch_sampler=batch_sampler, |
| 135 | + collate_fn=collate_fn, |
| 136 | + return_list=True) |
| 137 | + return dataset, data_loader |
| 138 | + |
| 139 | + |
| 140 | +def post_process_sum(token_ids, tokenizer): |
| 141 | + """Post-process the decoded sequence. Truncate from the first <eos>.""" |
| 142 | + eos_pos = len(token_ids) |
| 143 | + for i, tok_id in enumerate(token_ids): |
| 144 | + if tok_id == tokenizer.mask_token_id: |
| 145 | + eos_pos = i |
| 146 | + break |
| 147 | + token_ids = token_ids[:eos_pos] |
| 148 | + tokens = tokenizer.convert_ids_to_tokens(token_ids) |
| 149 | + tokens = tokenizer.merge_subword(tokens) |
| 150 | + special_tokens = ['[UNK]'] |
| 151 | + tokens = [token for token in tokens if token not in special_tokens] |
| 152 | + return token_ids, tokens |
| 153 | + |
| 154 | + |
| 155 | +def select_sum(ids, scores, tokenizer, max_dec_len=None, |
| 156 | + num_return_sequences=1): |
| 157 | + ids = ids.numpy() |
| 158 | + scores = scores.numpy() |
| 159 | + |
| 160 | + if len(ids) != len(scores) or (len(ids) % num_return_sequences) != 0: |
| 161 | + raise ValueError( |
| 162 | + "the length of `ids` is {}, but the `num_return_sequences` is {}". |
| 163 | + format(len(ids), num_return_sequences)) |
| 164 | + |
| 165 | + group = [] |
| 166 | + tmp = [] |
| 167 | + for pred, score in zip(ids, scores): |
| 168 | + pred_token_ids, pred_tokens = post_process_sum(pred, tokenizer) |
| 169 | + num_token = len(pred_token_ids) |
| 170 | + |
| 171 | + target = "".join(pred_tokens) |
| 172 | + |
| 173 | + # not ending |
| 174 | + if max_dec_len is not None and num_token >= max_dec_len: |
| 175 | + score -= 1e3 |
| 176 | + |
| 177 | + tmp.append([target, score]) |
| 178 | + if len(tmp) == num_return_sequences: |
| 179 | + group.append(tmp) |
| 180 | + tmp = [] |
| 181 | + |
| 182 | + results = [] |
| 183 | + for preds in group: |
| 184 | + preds = sorted(preds, key=lambda x: -x[1]) |
| 185 | + results.append(preds[0][0]) |
| 186 | + return results |
0 commit comments