(self)
| 725 | ) |
| 726 | |
| 727 | def test_beam_search_with_path_merger(self): |
| 728 | batch_size, num_decodes = 1, 4 |
| 729 | max_decode_len = 8 |
| 730 | vocab_size = 4 |
| 731 | num_expected_tokens = 5 |
| 732 | cache = dict(step=jnp.zeros([])) |
| 733 | |
| 734 | def tokens_to_scores(tokens, cache): |
| 735 | del tokens |
| 736 | step = cache["step"] |
| 737 | has_enough_tokens = step >= num_expected_tokens |
| 738 | eps = 1e-2 + 1e-3 * step |
| 739 | continue_log_probs = jax.nn.log_softmax( |
| 740 | # A mostly uniform distribution among tokens except for PAD(0) and EOS(1) with |
| 741 | # slight preference towards lower ids. |
| 742 | # |
| 743 | # [NEG_INF, NEG_INF, 0, -eps, -2 * eps, ...]. |
| 744 | jnp.pad( |
| 745 | jnp.arange(0, vocab_size - 2, dtype=jnp.float32) * -eps, |
| 746 | ((2, 0)), |
| 747 | constant_values=NEG_INF, |
| 748 | ) |
| 749 | ) |
| 750 | # Force EOS=1: [NEG_INF, 0, NEG_INF, NEG_INF, ...]. |
| 751 | finish_log_probs = (1 - jax.nn.one_hot(1, vocab_size)) * NEG_INF |
| 752 | log_probs = ( |
| 753 | has_enough_tokens * finish_log_probs + (1 - has_enough_tokens) * continue_log_probs |
| 754 | ) |
| 755 | return log_probs, dict(step=cache["step"] + 1) |
| 756 | |
| 757 | inputs = jnp.zeros([batch_size, max_decode_len], dtype=jnp.int32) |
| 758 | kwargs = dict( |
| 759 | inputs=inputs, |
| 760 | time_step=decoding.infer_initial_time_step(inputs, pad_id=0), |
| 761 | cache=cache, |
| 762 | tokens_to_scores=tokens_to_scores, |
| 763 | eos_id=1, |
| 764 | num_decodes=num_decodes, |
| 765 | ) |
| 766 | outputs_without_merger = decoding.beam_search_decode(**kwargs) |
| 767 | |
| 768 | prefix_merger = _TokenSumPrefixMerger() |
| 769 | outputs_with_merger = decoding.beam_search_decode(**kwargs, prefix_merger=prefix_merger) |
| 770 | |
| 771 | logging.info( |
| 772 | "scores_without_merger=%s scores_with_merger=%s", |
| 773 | outputs_without_merger.scores, |
| 774 | outputs_with_merger.scores, |
| 775 | ) |
| 776 | |
| 777 | np.testing.assert_array_equal( |
| 778 | jnp.asarray( |
| 779 | [ |
| 780 | [ |
| 781 | # Without prefix merging, we prefer sequences with mostly 2's. |
| 782 | [2, 2, 2, 2, 2, 1, 0, 0], |
| 783 | [3, 2, 2, 2, 2, 1, 0, 0], |
| 784 | [2, 3, 2, 2, 2, 1, 0, 0], |
nothing calls this directly
no test coverage detected