model.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. import torch
  2. from typing import List, Union
  3. from SwissArmyTransformer.generation.autoregressive_sampling import update_mems, get_masks_and_position_ids_default
  4. def batch_filling_sequence(
  5. model,
  6. seqs,
  7. context_lengths,
  8. strategy,
  9. max_memory_length=100000,
  10. get_masks_and_position_ids=get_masks_and_position_ids_default,
  11. mems=None,
  12. **kw_args
  13. ):
  14. '''
  15. seq: [2, 3, 5, ..., -1(to be generated), -1, ...]
  16. mems: [num_layers, batch_size, len_mems(index), mem_hidden_size]
  17. cache, should be first mems.shape[1] parts of context_tokens.
  18. mems are the first-level citizens here, but we don't assume what is memorized.
  19. input mems are used when multi-phase generation.
  20. '''
  21. assert len(seqs.shape) == 2
  22. # building the initial tokens, attention_mask, and position_ids
  23. batch_size, context_length = seqs.shape
  24. seqs, attention_mask, position_ids = get_masks_and_position_ids(seqs)
  25. tokens = seqs[..., :context_length]
  26. if attention_mask.dtype != torch.bool:
  27. attention_mask = attention_mask.type_as(next(model.parameters())) # if fp16
  28. # initialize generation
  29. counter = context_length - 1 # Last fixed index is ``counter''
  30. index = 0 if mems is None else mems.shape[2] # Next forward starting index, also the length of cache.
  31. num_beams = 1
  32. # step-by-step generation
  33. while counter < seqs.shape[1] - 1:
  34. # Now, we want to generate seq[counter + 1],
  35. # token[:, index: counter+1] needs forwarding.
  36. # forward
  37. if num_beams > 1:
  38. tokens = tokens.reshape(batch_size * num_beams, -1)
  39. mems = mems.reshape(mems.shape[0], batch_size * num_beams, mems.shape[-2], mems.shape[-1])
  40. logits, *output_per_layers = model(
  41. tokens[:, index:],
  42. position_ids[..., index: counter+1],
  43. attention_mask[..., index: counter+1, :counter+1], # TODO memlen
  44. mems=mems,
  45. **kw_args
  46. )
  47. mem_kv = [o['mem_kv'] for o in output_per_layers]
  48. mems = update_mems(mem_kv, mems, max_memory_length=max_memory_length)
  49. if counter == context_length - 1:
  50. logits = logits[torch.arange(batch_size), context_lengths - 1]
  51. else:
  52. logits = logits[:, -1]
  53. # if torch.distributed.get_rank() == 0:
  54. # breakpoint()
  55. # torch.distributed.barrier()
  56. counter += 1
  57. index = counter
  58. # sampling
  59. if num_beams > 1:
  60. logits = logits.reshape(batch_size, num_beams, -1)
  61. tokens = tokens.reshape(batch_size, num_beams, -1)
  62. mems = mems.reshape(mems.shape[0], batch_size, num_beams, mems.shape[-2], mems.shape[-1])
  63. tokens, mems = strategy.forward(logits, tokens, mems)
  64. if len(tokens.shape) == 3:
  65. num_beams = tokens.shape[1]
  66. position_ids = position_ids.unsqueeze(1).expand(batch_size, num_beams, -1).reshape(batch_size * num_beams, -1)
  67. attention_mask = attention_mask.unsqueeze(1).expand(batch_size, num_beams, -1, -1, -1).reshape(
  68. batch_size * num_beams, -1, -1, -1)
  69. if strategy.is_done:
  70. break
  71. return strategy.finalize(tokens, mems)
  72. class ModelForEvaluation(torch.nn.Module):
  73. def __init__(self, model):
  74. super().__init__()
  75. self.model = model
  76. @staticmethod
  77. def process_data(batch):
  78. return (
  79. batch["tokens"].to(device=torch.cuda.current_device()).long(),
  80. batch["position_ids"].to(device=torch.cuda.current_device()).long(),
  81. batch["attention_mask"].to(device=torch.cuda.current_device()).bool().unsqueeze(1),
  82. )
  83. def cond_log_prob(self, batch) -> List[List[float]]:
  84. """
  85. @return: Conditional log probability of each option
  86. """
  87. tokens, position_ids, attention_mask = self.process_data(batch)
  88. choices_batch, choice_target_ids_batch = batch["choices"], batch["choice_target_ids"]
  89. is_single_token = batch["is_single_token"]
  90. self.model.eval()
  91. with torch.no_grad():
  92. logits, *output_per_layers = self.model(tokens, position_ids, attention_mask, log_attention_weights=None)
  93. logits_batch = torch.nn.functional.log_softmax(logits, dim=-1)
  94. # output: [b, sq, vocab]
  95. log_probs = []
  96. if is_single_token: # Single token
  97. for logits, choices, choice_target_ids in zip(logits_batch, choices_batch, choice_target_ids_batch):
  98. log_probs.append(logits[choice_target_ids[0], choices].tolist())
  99. else: # Multi token
  100. for output, choices, choice_target_ids in zip(logits_batch, choices_batch, choice_target_ids_batch):
  101. log_probs_single = []
  102. for choice, choice_target_id in zip(choices, choice_target_ids):
  103. tmp = output[choice_target_id, choice]
  104. log_probs_single.append(tmp.sum().tolist())
  105. log_probs.append(log_probs_single)
  106. return log_probs
  107. def generate_text(self, sample, strategy, return_all_beams=False, max_gen_length=128) -> Union[
  108. List[int], List[List[int]]]:
  109. """
  110. @return: A list of text model generated, sorted by score in descending order
  111. """
  112. seqs = sample["tokens"].to(device=torch.cuda.current_device()).long()
  113. context_lengths = sample["context_length"].long()
  114. def get_masks_and_position_ids(seq):
  115. batch_size = seq.shape[0]
  116. tokens = torch.nn.functional.pad(seq, (0, max_gen_length), mode='constant', value=-1)
  117. position_ids = torch.cat((sample['position_ids'], sample['target_position_ids']), dim=-1)
  118. position_ids = position_ids.to(device=torch.cuda.current_device()).long()
  119. attention_mask = sample["attention_mask"].to(device=torch.cuda.current_device())
  120. context_mask = attention_mask[torch.arange(batch_size), context_lengths - 1].unsqueeze(1).repeat(1,
  121. max_gen_length,
  122. 1)
  123. causal_mask = torch.tril(context_mask.new_ones((batch_size, max_gen_length, max_gen_length))) < 0.5
  124. generation_mask = torch.cat(
  125. (context_mask, causal_mask), dim=-1)
  126. attention_mask = torch.nn.functional.pad(attention_mask, (0, max_gen_length), mode='constant', value=1)
  127. attention_mask = torch.cat((attention_mask, generation_mask), dim=1)
  128. attention_mask = attention_mask.bool().unsqueeze(1)
  129. return tokens, attention_mask, position_ids
  130. self.model.eval()
  131. with torch.no_grad():
  132. output = batch_filling_sequence(
  133. self.model,
  134. seqs,
  135. context_lengths,
  136. get_masks_and_position_ids=get_masks_and_position_ids,
  137. strategy=strategy,
  138. )[0]
  139. if isinstance(output, torch.Tensor): # different strategies
  140. output = list(output)
  141. output_targets = []
  142. context_length = seqs.shape[1]
  143. for line in output:
  144. line = line.tolist()
  145. unfinished = line.index(-1) if -1 in line else len(line)
  146. if line[unfinished - 1] in strategy.end_tokens:
  147. unfinished -= 1
  148. line = line[context_length:unfinished]
  149. output_targets.append(line)
  150. return output_targets